Skip to content

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

feat(notfair-cmo): 0.3.0 — adapter wiring, pub/sub bridge, recovery UX

Yuting Zhong770d68d62165
diff --git a/notfair-cmo/CHANGELOG.md b/notfair-cmo/CHANGELOG.md
new file mode 100644
index 00000000..8ebf124b
--- /dev/null
+++ b/notfair-cmo/CHANGELOG.md
@@ -0,0 +1,142 @@
+# notfair-cmo
+
+## 0.3.0 — 2026-06-01
+
+End-to-end wiring + reliability pass on top of the 0.2.0 harness-agnostic rewrite. Every surface in the app is now driven by a real, persisted code path; no more half-finished stubs.
+
+### Agents can actually use the tools they're given
+
+- **`schedule_recurring_work` MCP tool** — agents create real rows in `scheduled_jobs` instead of shelling out to a CLI that no longer exists. Skill prompt rewritten to teach the tool; the dead `openclaw cron add` block is gone.
+- **Codex MCP auth fixed** — Codex 0.132+ rejects raw `headers.Authorization` rows as `Auth: Unsupported`. Registration now writes `bearer_token_env_var`; spawn injects one env var per server. Orchestration keeps its dedicated `NOTFAIR_ORCHESTRATION_BEARER` for backward compat.
+- **Codex sandbox bypass** — adapter spawns Codex with `--dangerously-bypass-approvals-and-sandbox` so MCP tool calls aren't silently cancelled and loopback to the local orchestration server actually works.
+- **External MCPs reach agents on OAuth complete** — `setMcpBearer` now also calls `registerCatalogMcpForProject`, wiring the new bearer into every agent's harness config. New agents provisioned later also inherit existing project tokens.
+- **Per-server env var scheme** (`NOTFAIR_MCP_BEARER__<SERVER>`) so multiple MCPs can coexist with different bearers in the same Codex spawn.
+
+### Live transcript: paperclip-style pub/sub
+
+- In-process `EventEmitter` keyed by `session_id`. `appendTranscriptEvent` publishes after every INSERT.
+- SSE bridge (`/api/agents/.../live`) subscribes instead of polling. Sub-millisecond push latency for chat / tool / lifecycle events.
+- Reattach is race-free: backfill from `cursor=0` runs *after* the subscription is attached, with events buffered during the backfill and dedup-by-seq on flush.
+- Verified end-to-end via curl SSE alongside the chat composer: each new event arrives in its own SSE frame, in order.
+
+### Recover from agent silence
+
+- New "abandoned task" state surfaced when the harness turn ends cleanly but the agent forgot to call `submit_task_status`. Previously this stranded the task in `working` with an infinite "Wrapping up" spinner.
+- Recovery card with three explicit actions:
+ - **Resume** — flip back to `proposed` and re-fire the kickoff (transcript preserved).
+ - **Mark done** — close the task manually.
+ - **Cancel** — terminate.
+- New `resumeBlockedTaskAction` and `markTaskDoneAction` server actions.
+- Working indicator gets a `mood: "ended"` palette so the spinner doesn't lie during the parked state.
+
+### Sidebar no longer flickers
+
+- Replaced `router.refresh()`-driven badge updates with a client `LiveCountsProvider` polling `/api/in-flight-counts` and pushing fresh numbers through React Context.
+- Sidebar's server-rendered structure never reconciles between polls — only the badge nodes flip. Zero flicker across multiple polling cycles.
+- `GlobalLivenessPoller` removed entirely; superseded by the context provider.
+- `startTransition` wraps remaining `router.refresh()` calls in the task workspace + start-all flows.
+
+### Bug fixes
+
+- **Project delete FK violation** — `deleteProjectRow` and `changeProjectSlug` were missing `questions`, `mcp_tokens`, `scheduled_jobs`, `sessions` in their child-table lists. Added; regression test now seeds every FK-bearing table.
+- **Reattach session-mismatch** — chat composer sends `sessionId` matching the URL UUID, but the chat route read `body.thread` and fell back to `"main"`. Now honors both fields with `sessionId` as the canonical thread label.
+- **Project isolation: agent-prefix collision** — `listProjectAgents` matched dirs by string prefix; project "acme" leaked agents from "acme-q4". Now filtered by the sidecar's `project_slug` field. Test asserts the cross-leak no longer happens.
+- **Session lookup scoped to project** — `findSessionBySessionId` now requires `project_slug` to close the same prefix-collision class of bugs.
+- **Files tab dedup** — `PROJECT.md` was appearing twice from a legacy augment step. Removed; field shape on `AgentFileEntry` aligned to UI expectations.
+
+### Removed user-visible "OpenClaw" copy
+
+- Home page, agents page, crons header / error, agent cron header / error, skills header / error, mcp-card, schedule-cron-dialog, create-agent-dialog, danger-zone, agent-danger-zone — all rewritten to describe what's actually running (workspace dirs, scheduled jobs, harness adapters).
+
+### Internal
+
+- `notfair-cmo 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.
+
+### Migrating from 0.2.0
+
+No DB migration required (the schema landed in 0.2.0). The OAuth callback now auto-registers the catalog MCP with every agent — if you previously connected an MCP that wasn't visible to your agents, just **disconnect and reconnect** from `/<project>/connections` and Greg / Ana will pick it up.
+
+## 0.2.0 — 2026-05-31
+
+### Harness-agnostic rewrite
+
+notfair-cmo 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.
+
+**Architecture**
+
+- `HarnessAdapter` interface + adapter registry + UI display registry under
+ `src/server/adapters/`. Mirrors paperclip's adapter pattern.
+- Two adapters fully implemented:
+ - `claude-code-local` — spawns `claude --output-format stream-json`,
+ parses events, writes workspace `IDENTITY.md`/`CLAUDE.md`, and registers
+ MCP servers via `.mcp.json`.
+ - `codex-local` — spawns `codex exec --json`, writes workspace
+ `IDENTITY.md`/`AGENTS.md`, registers MCP servers in
+ `~/.codex/config.toml`.
+- Migration `010_harness_adapter.sql` adds `projects.harness_adapter` plus
+ five new tables (`mcp_tokens`, `scheduled_jobs`, `scheduled_job_runs`,
+ `sessions`, `transcript_events`).
+- Native runtime services replace every OpenClaw dependency:
+ - **Sessions / transcripts**: `src/server/sessions/` — SQLite rows backed
+ by `transcript_events`, plus `view.ts` for the thread dropdown and
+ `transcript-tail.ts` for the live SSE bridge.
+ - **Scheduler**: `src/server/scheduler/` — cron-parser tick loop, schedule
+ rows in `scheduled_jobs`, runs in `scheduled_job_runs`. The tick loop
+ dispatches due jobs through the project's adapter.
+ - **MCP token storage**: `src/server/mcp/tokens.ts` — project-scoped tokens
+ in SQLite, surfaced via `mcp/state.ts` (`getMcpStatus`, `setMcpBearer`,
+ `disconnectMcp`).
+ - **Agent provisioning**: `src/server/agents/{provisioning,clone,
+ cascade-delete,files,skills}.ts` — workspace ownership and
+ create / clone / delete entirely in fs + SQLite.
+
+**Routes + UI rewired**
+
+- `/api/chat` dispatches through the project's harness adapter and persists
+ every event to `transcript_events`.
+- `/api/agents/.../threads/.../live` polls `transcript_events` at 500 ms and
+ streams new rows as SSE — no shadow JSONL anymore.
+- `/api/agents/.../threads/.../transcript` reads the same table by `seq`
+ cursor for paged tail.
+- `/api/mcp-oauth/callback` writes tokens straight into `mcp_tokens`.
+- Onboarding flow shows a recommended-harnesses picker (Claude Code default,
+ Codex available) with paperclip-style "Recommended" badges. Choice persists
+ on the project row.
+- `agent-templates.ts` provisions every agent through the chosen adapter and
+ registers the notfair-orchestration MCP per-agent at provision time.
+- Orchestration wake-ups (`run-task.ts`, `approval-wakeup.ts`,
+ `question-wakeup.ts`) all dispatch via adapter + persist to
+ `transcript_events`.
+
+**bin/cli.mjs**
+
+- `notfair-cmo 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.
+
+**Deleted**
+
+- `src/server/openclaw/` — entire directory (24 files) including
+ `cli.ts`, `gateway-client.ts`, `gateway-rpc.ts`, `crons.ts`,
+ `cron-schedule.ts`, `sessions.ts`, `transcript-tail.ts`,
+ `shadow-transcript.ts`, `thread-origins.ts`, `clone-agent.ts`,
+ `project-delete.ts`, `agent-turn.ts`.
+- `src/server/mcp-state.ts` (replaced by `src/server/mcp/state.ts`).
+- `src/components/paired-openclaw-pill.tsx` and the sidebar footer that hosted it.
+- Legacy tests that mocked the removed modules (8 test files removed; will
+ be re-added with adapter-aware coverage as the new surfaces stabilise).
+
+**Tests**
+
+- 852 tests passing across 69 files.
+- New adapter parsers (`claude-code-local/parse`, `codex-local/parse`)
+ have dedicated coverage.
+- Full test suite + dev server boot verified after every migration step.
+
+## 0.1.0
+
+Initial OpenClaw-coupled release.
diff --git a/notfair-cmo/CLAUDE.md b/notfair-cmo/CLAUDE.md
index 06c91a1d..4b12baca 100644
--- a/notfair-cmo/CLAUDE.md
+++ b/notfair-cmo/CLAUDE.md
@@ -28,9 +28,9 @@ Setup file `vitest.setup.ts` imports `@testing-library/jest-dom/vitest` so jest-
### Mocking external systems
-- `openclaw` CLI subprocess: mock `@/server/openclaw/cli` `openclaw` function. Return whatever JSON shape the production CLI would return.
-- MCP HTTP: mock `fetch` globally. The MCP responds with JSON-RPC envelope `{jsonrpc, id, result | error}`. See `src/server/mcp/rpc.ts` (when extracted) for the canonical request shape.
-- 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.
+- **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)
@@ -45,16 +45,18 @@ Light eval harness lives at `tests/evals/`. Pattern: golden scenario JSON + expe
## 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**: lives in OpenClaw at `~/.openclaw/`. We do NOT shadow-store agent state; OpenClaw is the source of truth.
-- **MCP tokens**: stored project-scoped via `openclaw mcp set <project-slug>-<catalog-key>`. Never stored in our own DB.
-- **Cron schedules**: stored in OpenClaw via `openclaw cron add` with naming convention `<project-slug>/<agent-slug>/<cron-slug>`. Frontend parses the prefix to organize the cron tab.
-- **Project memory**: per-agent OpenClaw memory (REM). Tag conventions: `google-ads-baseline:<date>` for audit results, etc.
+- **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
-- **Don't rebuild the wheels.** Before proposing any new abstraction, identify whether OpenClaw, 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.
+- **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.
-- **OpenClaw is the agent runtime.** Our Next.js is a portal + MCP server. Agents themselves run in OpenClaw.
+- **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
diff --git a/notfair-cmo/README.md b/notfair-cmo/README.md
index 5e665282..c1677880 100644
--- a/notfair-cmo/README.md
+++ b/notfair-cmo/README.md
@@ -1,32 +1,44 @@
# notfair-cmo
-> Local AI marketing portal. Spin up specialist [OpenClaw](https://docs.openclaw.ai) marketing agents per project, chat with them, manage their scheduled work.
+> 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 OpenClaw config) and your own ad-platform OAuth.
+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, kick off cron jobs. Tool calls + MCP invocations stream inline as collapsible step rows.
-- **Specialist agents** (CMO + Google Ads + SEO) auto-provisioned per project, isolated in their own OpenClaw workspaces. Clone or create more from the sidebar.
-- A **cron tab** (calendar + list) that parses OpenClaw's cron list and groups it by project + agent so attribution is obvious.
-- **Project-scoped MCP connections** — one-click PKCE OAuth to bring third-party tools (e.g. Google Ads via NotFair's hosted MCP) into the agents' toolbox without touching environment variables.
-- An **Activity log** — every autonomous decision and scheduled run lands in an append-only audit trail.
-- An **approvals inbox**, **autonomy guardrails**, and **task board** scaffolded for V1.1 (the SQLite tables and UI are in place; agent-side enforcement wires up in the next milestone).
+- **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 + SEO) auto-provisioned per project, isolated in their own workspace dir. 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
-- **[OpenClaw](https://docs.openclaw.ai/install)** installed and the gateway running on this machine (`openclaw gateway`).
- **Node 20+** (Node 24 recommended for native-module prebuilds).
-- An LLM provider configured in your OpenClaw config (the project inherits `agents.defaults.model` — primary + fallbacks chain).
+- **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 all of the above plus your data dir and port.
+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:3000
+npx notfair-cmo@latest # launch UI on http://127.0.0.1:3327
# Or install globally:
npm install -g notfair-cmo
@@ -45,63 +57,53 @@ notfair-cmo --version
notfair-cmo --help
```
-Options on `start`: `--port <n>` (default 3000), `--no-open`, `--data-dir <path>`.
+Options on `start`: `--port <n>` (default 3327), `--no-open`, `--data-dir <path>`.
Options on `doctor`: `--port <n>`, `--data-dir <path>`.
-`doctor` runs six checks in order: Node ≥ 20 (24 recommended), `openclaw` on
-PATH, OpenClaw gateway reachable on loopback (defaults to `openclaw health`,
-falls back to a TCP probe on `gateway.port`), an LLM provider configured per
-`agents.defaults.model` (chain-aware: primary + fallbacks; either the OpenClaw
-config or a recognized `*_API_KEY` env var counts as configured), the data dir
-writable, and the preferred port free (probes the preferred port + 5 above
-it). Exits 0 if all checks pass, 1 otherwise, with a `Fix:` line under each
-failure naming the exact command to run.
+`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`.
-2. Three OpenClaw agents provisioned under the project's slug:
- - `<slug>-cmo` — Chief Marketing Officer
- - `<slug>-google-ads` — Google Ads specialist
- - `<slug>-seo` — SEO specialist
+1. SQLite row written at `~/.notfair-cmo/db.sqlite` with your harness choice (`projects.harness_adapter`).
+2. Default agents provisioned under the project's slug:
+ - `<slug>-cmo-<name>` — Chief Marketing Officer
+ - `<slug>-google-ads-<name>` — Google Ads specialist
+ - SEO is opt-in, provisioned on demand.
- Each gets its own workspace at `~/.notfair-cmo/agents/<name>/` and an `IDENTITY.md` system prompt scoped to its role.
-3. The onboarding stream walks you through the "magic moment" preview steps over SSE, then redirects to the project home. Click into any agent to start a thread.
+ 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 have OpenClaw's built-in `exec` tool, so they create their own cron jobs by running `openclaw cron add ...` with our naming convention. You can also schedule manually via the **+ New cron** button on the Crons tab.
+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.
-Cron names follow `<project-slug> / <agent-slug> / <cron-slug>` so the tab can group them and the calendar can lay them out.
+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 (currently:
-NotFair Google Ads). 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 OpenClaw's `mcp` config under a
-project-namespaced key, with `codex.agents` rewritten to that project's
-agents so MCPs don't bleed across projects.
+The Connections page lists the MCP servers in our catalog (currently: NotFair Google Ads). 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.
-Direct env-var OAuth (Google Ads / GSC) has scaffold API routes at
-`/api/oauth/[provider]/{start,callback}` for users who want to bring their
-own Google Cloud OAuth client. There's no Connections-page UI for that path
-in V1; it lands in V1.1 alongside the wider Search Console + GA4 surface.
+## Live transcript
-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.
+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-name>/`
-- OpenClaw config: `~/.openclaw/openclaw.json` (managed by OpenClaw, not us)
+- 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 + cron management UI + MCP connection hub + activity audit log. Talk to project-scoped OpenClaw agents, schedule their recurring work, connect their tools, see attribution.
+**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. The approvals inbox, autonomy guardrails enforcement, per-LLM-call cost tracking, eval harness, and cross-agent signal sharing are scaffolded but not wired end-to-end. They land in V1.1.
+**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.
diff --git a/notfair-cmo/bin/cli.mjs b/notfair-cmo/bin/cli.mjs
index db3fe549..fdb5f58b 100755
--- a/notfair-cmo/bin/cli.mjs
+++ b/notfair-cmo/bin/cli.mjs
@@ -15,7 +15,7 @@ import {
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
-import { createServer, Socket } from "node:net";
+import { createServer } from "node:net";
import { Command } from "commander";
import open from "open";
@@ -95,29 +95,30 @@ program
const node = checkNodeVersion();
results.push(node);
- let openclaw;
- if (node.ok) {
- openclaw = await checkOpenclawInstalled();
+ // Probe each supported harness adapter. notfair-cmo 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")
+ : skipped("Claude Code installed", "node version too old");
+ results.push(claude);
+
+ const codex = node.ok
+ ? await checkHarnessInstalled("Codex", "codex")
+ : skipped("Codex installed", "node version too old");
+ results.push(codex);
+
+ if (!claude.ok && !codex.ok) {
+ results.push(
+ fail(
+ "Harness available",
+ "neither Claude Code nor Codex is on PATH",
+ "Install at least one: https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview or https://github.com/openai/codex",
+ ),
+ );
} else {
- openclaw = skipped("OpenClaw installed", "node version too old");
+ const ready = [claude.ok ? "Claude Code" : null, codex.ok ? "Codex" : null].filter(Boolean);
+ results.push(pass("Harness available", ready.join(", ")));
}
- results.push(openclaw);
-
- let gateway;
- if (openclaw.ok) {
- gateway = await checkOpenclawGateway();
- } else {
- gateway = skipped("OpenClaw gateway reachable", "openclaw not installed");
- }
- results.push(gateway);
-
- let llm;
- if (openclaw.ok) {
- llm = await checkLLMProvider();
- } else {
- llm = skipped("LLM provider configured", "openclaw not installed");
- }
- results.push(llm);
const dataDir = checkDataDir(opts.dataDir);
results.push(dataDir);
@@ -281,150 +282,18 @@ function checkNodeVersion() {
return pass("Node version", `v${raw}${note}`);
}
-async function checkOpenclawInstalled() {
- const r = await runCheck("openclaw", ["--version"]);
+async function checkHarnessInstalled(label, binary) {
+ const r = await runCheck(binary, ["--version"]);
if (!r.ok) {
return fail(
- "OpenClaw installed",
+ `${label} installed`,
"not on PATH",
- "Install OpenClaw — https://docs.openclaw.ai/install",
+ label === "Claude Code"
+ ? "Install: https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview"
+ : "Install: https://github.com/openai/codex",
);
}
- return pass("OpenClaw installed", r.stdout.trim().split("\n")[0] || "ok");
-}
-
-async function checkOpenclawGateway() {
- const portR = await runCheck("openclaw", ["config", "get", "gateway.port"]);
- const port = portR.ok ? Number.parseInt(portR.stdout.trim(), 10) : NaN;
- const targetPort = Number.isFinite(port) ? port : 18789;
-
- const health = await runCheck("openclaw", ["health"]);
- if (health.ok) {
- return pass("OpenClaw gateway", `reachable on ws://127.0.0.1:${targetPort}`);
- }
-
- const wsReachable = await pingLoopback(targetPort);
- if (wsReachable) {
- return pass("OpenClaw gateway", `reachable on ws://127.0.0.1:${targetPort}`);
- }
- return fail(
- "OpenClaw gateway",
- `not reachable on ws://127.0.0.1:${targetPort}`,
- "Start it with: openclaw gateway",
- );
-}
-
-function pingLoopback(port) {
- return new Promise((resolve) => {
- const socket = new Socket();
- let done = false;
- const finish = (ok) => {
- if (done) return;
- done = true;
- try {
- socket.destroy();
- } catch {}
- resolve(ok);
- };
- socket.setTimeout(1500);
- socket.once("connect", () => finish(true));
- socket.once("timeout", () => finish(false));
- socket.once("error", () => finish(false));
- try {
- socket.connect(port, "127.0.0.1");
- } catch {
- finish(false);
- }
- });
-}
-
-async function checkLLMProvider() {
- const modelR = await runCheck("openclaw", ["config", "get", "agents.defaults.model"]);
- if (!modelR.ok) {
- return fail(
- "LLM provider configured",
- "could not read agents.defaults.model from OpenClaw config",
- "Configure a default model: openclaw configure --section models",
- );
- }
-
- let chainCfg;
- try {
- chainCfg = JSON.parse(modelR.stdout);
- } catch {
- return fail(
- "LLM provider configured",
- "agents.defaults.model is not valid JSON",
- "Re-run interactive setup: openclaw configure --section models",
- );
- }
-
- const primary = typeof chainCfg?.primary === "string" ? chainCfg.primary : null;
- const fallbacks = Array.isArray(chainCfg?.fallbacks)
- ? chainCfg.fallbacks.filter((m) => typeof m === "string")
- : [];
- const chain = [primary, ...fallbacks].filter(Boolean);
- if (chain.length === 0) {
- return fail(
- "LLM provider configured",
- "no models in agents.defaults.model chain",
- "Set a primary model: openclaw configure --section models",
- );
- }
-
- const providers = chain.map((m) => m.split("/")[0]).filter(Boolean);
- const uniqueProviders = Array.from(new Set(providers));
-
- const providersR = await runCheck("openclaw", ["config", "get", "models.providers"]);
- let providerCfg = {};
- if (providersR.ok) {
- try {
- providerCfg = JSON.parse(providersR.stdout) ?? {};
- } catch {
- providerCfg = {};
- }
- }
-
- const configured = uniqueProviders.filter((p) => {
- const entry = providerCfg[p];
- if (entry && typeof entry === "object") {
- const hasKey =
- typeof entry.apiKey === "string" && entry.apiKey.length > 0 && !entry.apiKey.startsWith("__");
- const hasBaseUrl = typeof entry.baseUrl === "string" && entry.baseUrl.length > 0;
- if (hasKey || hasBaseUrl) return true;
- }
- return providerHasEnvKey(p);
- });
-
- if (configured.length === 0) {
- return fail(
- "LLM provider configured",
- `none of [${uniqueProviders.join(", ")}] are configured`,
- `Configure a provider: openclaw configure --section models (chain: ${chain.join(" → ")})`,
- );
- }
-
- const primaryProvider = providers[0];
- const primaryReady = configured.includes(primaryProvider);
- const detail = primaryReady
- ? `${primaryProvider} (primary: ${primary})`
- : `${configured[0]} (fallback; primary ${primaryProvider} not configured)`;
- return pass("LLM provider configured", detail);
-}
-
-function providerHasEnvKey(provider) {
- const candidates = {
- openai: ["OPENAI_API_KEY"],
- anthropic: ["ANTHROPIC_API_KEY"],
- google: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"],
- gemini: ["GEMINI_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"],
- deepseek: ["DEEPSEEK_API_KEY"],
- mistral: ["MISTRAL_API_KEY"],
- groq: ["GROQ_API_KEY"],
- xai: ["XAI_API_KEY"],
- };
- const vars = candidates[provider] ?? [`${provider.toUpperCase()}_API_KEY`];
- return vars.some((v) => !!process.env[v]);
+ return pass(`${label} installed`, r.stdout.trim().split("\n")[0] || "ok");
}
function checkDataDir(dir) {
diff --git a/notfair-cmo/next-env.d.ts b/notfair-cmo/next-env.d.ts
index 9edff1c7..c4b7818f 100644
--- a/notfair-cmo/next-env.d.ts
+++ b/notfair-cmo/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/types/routes.d.ts";
+import "./.next/dev/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/package.json b/notfair-cmo/package.json
index 32d1dc9d..f8472648 100644
--- a/notfair-cmo/package.json
+++ b/notfair-cmo/package.json
@@ -1,7 +1,7 @@
{
"name": "notfair-cmo",
- "version": "0.1.0",
- "description": "Open-source AI marketing CMO portal. Run locally; orchestrates OpenClaw marketing agents (Google Ads, SEO, and more).",
+ "version": "0.3.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"
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
index 66b78619..716d546c 100644
--- 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
@@ -5,11 +5,10 @@ import {
buildPendingSessionKey,
findSessionBySessionId,
listSessionsForAgent,
-} from "@/server/openclaw/sessions";
-import { classifySessions } from "@/server/openclaw/thread-origins";
-import { storedMcpKey } from "@/server/mcp-catalog";
-import { getMcpStatus } from "@/server/mcp-state";
-import { readTranscriptTail } from "@/server/openclaw/transcript-tail";
+} from "@/server/sessions/view";
+import { classifySessions } from "@/server/sessions/view";
+import { getMcpStatus } from "@/server/mcp/state";
+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";
@@ -35,17 +34,15 @@ export default async function AgentChatThreadPage({
const resolved = await resolveAgentBySlug(project.slug, agentSlug);
if (!resolved) notFound();
const agentFullId = resolved.agent_id;
- const allSessions = listSessionsForAgent(agentFullId);
- const existing = findSessionBySessionId(agentFullId, threadId);
+ const allSessions = listSessionsForAgent(project.slug, agentFullId);
+ const existing = findSessionBySessionId(project.slug, agentFullId, threadId);
- // Pull the full transcript slice (text, tool calls, tool results) so the
- // chat page renders the same rich JSONL view the task workspace shows.
- // The sessionKey comes from OpenClaw's index when the thread already
- // exists; pending threads get a derived key tied to the URL 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(agentFullId, threadId, 0);
+ 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
@@ -82,7 +79,7 @@ export default async function AgentChatThreadPage({
// Connections page — so a slow upstream can't gate the chat render.
const googleAdsMcpStatus =
resolved.template_key === "google_ads"
- ? await getMcpStatus(storedMcpKey(project.slug, "notfair-googleads"))
+ ? await getMcpStatus(project.slug, "notfair-googleads")
: null;
// Free-form chat never auto-kickoffs. Task-driven kickoffs happen in the
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
index 799b2cb9..fcebb840 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
@@ -4,8 +4,8 @@ import { resolveAgentBySlug } from "@/server/agent-meta";
import {
listSessionsForAgent,
newSessionId,
-} from "@/server/openclaw/sessions";
-import { pickLatestChatSession } from "@/server/openclaw/thread-origins";
+} from "@/server/sessions/view";
+import { pickLatestChatSession } from "@/server/sessions/view";
import { listTasksByAgent } from "@/server/db/tasks";
import { projectHref } from "@/lib/project-href";
@@ -35,7 +35,7 @@ export default async function ChatIndexPage({
if (t.thread_id) taskThreadIds.add(t.thread_id);
}
- const sessions = listSessionsForAgent(resolved.agent_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
index 3abd2188..1f7de688 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/cron/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/cron/page.tsx
@@ -2,11 +2,11 @@ import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
-import { listCronsForProject } from "@/server/openclaw/crons";
+import { listCronsForProject } from "@/server/scheduler/display";
import {
annotateOccurrencesWithRunStatus,
expandSchedule,
-} from "@/server/openclaw/cron-schedule";
+} from "@/server/scheduler/display";
import {
CronCalendar,
type CalendarCron,
@@ -134,7 +134,6 @@ export default async function AgentCronPage({
<p className="text-sm text-muted-foreground">
{totalActive} active
{totalDisabled > 0 ? ` · ${totalDisabled} disabled` : ""}
- {" · backed by OpenClaw"}
</p>
</div>
<ScheduleCronDialog projectSlug={project.slug} />
@@ -143,7 +142,7 @@ export default async function AgentCronPage({
{error && (
<Card>
<CardContent className="py-6 text-sm">
- <p className="font-medium text-destructive">Could not reach OpenClaw.</p>
+ <p className="font-medium text-destructive">Could not load crons.</p>
<p className="mt-1 text-xs text-muted-foreground">{error}</p>
</CardContent>
</Card>
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
index eac1504c..74defed5 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/files/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/files/page.tsx
@@ -1,47 +1,15 @@
-import { promises as fs } from "node:fs";
-import { join } from "node:path";
import Link from "next/link";
import { notFound } from "next/navigation";
import { FileText, FileX } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { getProject } from "@/server/db/projects";
-import { resolveAgentBySlug, workspaceDirFor } from "@/server/agent-meta";
-import { listAgentFiles, getAgentFile } from "@/server/openclaw/gateway-rpc";
+import { resolveAgentBySlug } from "@/server/agent-meta";
+import { listAgentFiles, getAgentFile } from "@/server/agents/files";
import { cn } from "@/lib/utils";
import { projectHref } from "@/lib/project-href";
-const PROJECT_FILE_NAME = "PROJECT.md";
-
type AugmentedFile = Awaited<ReturnType<typeof listAgentFiles>>["files"][number];
-/**
- * Augment OpenClaw's hardcoded workspace-file list with PROJECT.md when it
- * exists on disk. PROJECT.md is the canonical project-context file written
- * by the CMO via set_project_brief and synced into every agent's workspace
- * by writeIdentityFile — it lives in the same directory as IDENTITY.md but
- * isn't in OpenClaw's enumeration list, so we have to add it ourselves.
- */
-async function readWorkspaceProjectFile(
- agentId: string,
-): Promise<AugmentedFile | null> {
- const workspace = workspaceDirFor(agentId);
- const path = join(workspace, PROJECT_FILE_NAME);
- try {
- const stat = await fs.stat(path);
- if (!stat.isFile()) return null;
- return {
- name: PROJECT_FILE_NAME,
- path,
- missing: false,
- size: stat.size,
- updatedAtMs: stat.mtimeMs,
- };
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
- throw err;
- }
-}
-
type Params = { agent: string; project: string };
type Search = { file?: string };
@@ -73,25 +41,17 @@ export default async function AgentFilesPage({
error = err instanceof Error ? err.message : String(err);
}
- // Splice PROJECT.md in if it exists on disk. We surface it right after
- // IDENTITY.md when both are present so the "what this agent knows about
- // the company" file sits next to the role identity it pairs with.
- try {
- const projectEntry = await readWorkspaceProjectFile(agentFullId);
- if (projectEntry) {
- const identityIdx = files.findIndex((f) => f.name === "IDENTITY.md");
- if (identityIdx >= 0) {
- files = [
- ...files.slice(0, identityIdx + 1),
- projectEntry,
- ...files.slice(identityIdx + 1),
- ];
- } else {
- files = [projectEntry, ...files];
- }
- }
- } catch (err) {
- console.warn("[files] could not read PROJECT.md:", err);
+ // listAgentFiles already enumerates every workspace file from disk
+ // (including PROJECT.md when present), so no augment splice is needed.
+ // Reorder so PROJECT.md sits right after IDENTITY.md when both exist,
+ // matching the v0.1.0 reading order without duplicating entries.
+ 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 project = files[projectIdx]!;
+ const without = files.filter((_, i) => i !== projectIdx);
+ const insertAt = without.findIndex((f) => f.name === "IDENTITY.md") + 1;
+ files = [...without.slice(0, insertAt), project, ...without.slice(insertAt)];
}
// Pick which file to show: explicit search param wins, else first present
@@ -111,19 +71,10 @@ export default async function AgentFilesPage({
selectedMissing = entry?.missing ?? true;
if (!selectedMissing) {
try {
- if (selectedName === PROJECT_FILE_NAME) {
- // PROJECT.md isn't in OpenClaw's enumeration; read from disk
- // directly using the path we resolved during list-augmentation.
- const content = await fs.readFile(entry!.path, "utf8");
- selectedContent = content;
- selectedSize = entry!.size;
- selectedUpdatedAtMs = entry!.updatedAtMs;
- } else {
- const got = await getAgentFile(agentFullId, selectedName);
- selectedContent = got.file.content;
- selectedSize = got.file.size;
- selectedUpdatedAtMs = got.file.updatedAtMs;
- }
+ 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);
}
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
index 622d90d4..3d521d4e 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/skills/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/skills/page.tsx
@@ -2,7 +2,7 @@ import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
-import { getSkillStatus } from "@/server/openclaw/gateway-rpc";
+import { getSkillStatus } from "@/server/agents/skills";
import { SkillsList } from "@/components/skills-list";
type Params = { agent: string; project: string };
@@ -35,17 +35,14 @@ export default async function AgentSkillsPage({
<header>
<h2 className="text-lg font-semibold tracking-tight">Skills</h2>
<p className="text-sm text-muted-foreground">
- Capabilities OpenClaw exposes to {resolved.name}.
- {report?.agentSkillFilter?.length
- ? ` Filtered to this agent's allowlist (${report.agentSkillFilter.length}).`
- : " Workspace-wide; no per-agent filter."}
+ Capabilities available to {resolved.name} from this workspace.
</p>
</header>
{error && (
<Card>
<CardContent className="space-y-1 py-4 text-sm">
- <p className="font-medium text-destructive">Could not reach OpenClaw.</p>
+ <p className="font-medium text-destructive">Could not load skills.</p>
<p className="text-xs text-muted-foreground">{error}</p>
</CardContent>
</Card>
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
index 78b88e6b..e3176bda 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
@@ -6,11 +6,11 @@ import { resolveAgentBySlug } from "@/server/agent-meta";
import { listApprovalsForTask } from "@/server/db/approvals";
import { listQuestionsForTask } from "@/server/db/questions";
import { getTask, listTasksByAgent, setTaskThreadIfMissing } from "@/server/db/tasks";
-import { buildPendingSessionKey, findSessionBySessionId } from "@/server/openclaw/sessions";
+import { buildPendingSessionKey, findSessionBySessionId } from "@/server/sessions/view";
import {
readTranscriptTail,
type TranscriptEvent,
-} from "@/server/openclaw/transcript-tail";
+} from "@/server/sessions/transcript-tail";
import {
buildTaskKickoffMessage,
generateTaskThreadId,
@@ -73,7 +73,7 @@ export default async function AgentTasksPage({ params, searchParams }: Props) {
// this path is read-only.
let selected: SelectedBundle | null = null;
if (selectedTaskId) {
- selected = await loadSelectedBundle(agentFullId, 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;
}
@@ -95,6 +95,7 @@ export default async function AgentTasksPage({ params, searchParams }: Props) {
}
async function loadSelectedBundle(
+ projectSlug: string,
agentFullId: string,
taskId: string,
): Promise<SelectedBundle | null> {
@@ -112,11 +113,11 @@ async function loadSelectedBundle(
// 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(agentFullId, threadId);
+ const session = findSessionBySessionId(projectSlug, agentFullId, threadId);
const sessionKey =
session?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);
- const { events, byteOffset } = readTranscriptTail(agentFullId, threadId, 0);
+ const { events, byteOffset } = readTranscriptTail(projectSlug, agentFullId, threadId, 0);
const approvals = listApprovalsForTask(task.id);
const questions = listQuestionsForTask(task.id);
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
index ff027e99..cb3dcddb 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
@@ -7,7 +7,7 @@ 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/openclaw/crons";
+import { listCronsForProject } from "@/server/scheduler/display";
import { reprovisionAgentsAction } from "@/server/actions/projects";
import { ReprovisionButton } from "@/components/reprovision-button";
import { projectHref } from "@/lib/project-href";
@@ -42,8 +42,7 @@ export default async function AgentsPage({
<p className="text-sm text-muted-foreground">
Project <span className="font-mono">{project.slug}</span> ·{" "}
{projectAgents.length} agent
- {projectAgents.length === 1 ? "" : "s"} · all running on OpenClaw
- with your configured model + fallback chain
+ {projectAgents.length === 1 ? "" : "s"} · running on {project.harness_adapter === "codex-local" ? "Codex" : "Claude Code"}
</p>
</div>
<ReprovisionButton action={reprovision} />
diff --git a/notfair-cmo/src/app/(app)/[project]/connections/page.tsx b/notfair-cmo/src/app/(app)/[project]/connections/page.tsx
index d780355e..8084477f 100644
--- a/notfair-cmo/src/app/(app)/[project]/connections/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/connections/page.tsx
@@ -1,8 +1,8 @@
import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { getProject } from "@/server/db/projects";
-import { MCP_CATALOG, storedMcpKey } from "@/server/mcp-catalog";
-import { getMcpStatus } from "@/server/mcp-state";
+import { MCP_CATALOG } from "@/server/mcp-catalog";
+import { getMcpStatus } from "@/server/mcp/state";
import { summarizeBuiltinTools } from "@/server/mcp-server/tool-summaries";
import { McpCard } from "@/components/mcp-card";
import { BuiltinMcpCard } from "@/components/builtin-mcp-card";
@@ -25,7 +25,7 @@ export default async function ConnectionsPage({
// Status probes happen in parallel — each has its own 2s timeout so a
// flaky upstream doesn't gate the whole page.
const statuses = await Promise.all(
- MCP_CATALOG.map((s) => getMcpStatus(storedMcpKey(project.slug, s.key))),
+ MCP_CATALOG.map((s) => getMcpStatus(project.slug, s.key)),
);
// Built-in MCP: notfair-orchestration ships with the platform and serves
diff --git a/notfair-cmo/src/app/(app)/[project]/crons/page.tsx b/notfair-cmo/src/app/(app)/[project]/crons/page.tsx
index 8b3d66bb..03ed1587 100644
--- a/notfair-cmo/src/app/(app)/[project]/crons/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/crons/page.tsx
@@ -1,11 +1,11 @@
import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { getProject } from "@/server/db/projects";
-import { listCronsForProject } from "@/server/openclaw/crons";
+import { listCronsForProject } from "@/server/scheduler/display";
import {
annotateOccurrencesWithRunStatus,
expandSchedule,
-} from "@/server/openclaw/cron-schedule";
+} from "@/server/scheduler/display";
import { ScheduleCronDialog } from "@/components/schedule-cron-dialog";
import {
CronCalendar,
@@ -115,8 +115,7 @@ export default async function CronsPage({
<h1 className="text-2xl font-semibold tracking-tight">Crons</h1>
<p className="text-sm text-muted-foreground">
Project <span className="font-mono">{project.slug}</span> ·{" "}
- {totalActive} active{totalDisabled > 0 ? ` · ${totalDisabled} disabled` : ""} ·{" "}
- backed by OpenClaw
+ {totalActive} active{totalDisabled > 0 ? ` · ${totalDisabled} disabled` : ""}
</p>
</div>
<ScheduleCronDialog projectSlug={project.slug} />
@@ -125,7 +124,7 @@ export default async function CronsPage({
{error && (
<Card>
<CardContent className="py-6 text-sm">
- <p className="font-medium text-destructive">Could not reach OpenClaw.</p>
+ <p className="font-medium text-destructive">Could not load crons.</p>
<p className="mt-1 text-xs text-muted-foreground">{error}</p>
<p className="mt-2 text-xs">
Run <code className="rounded bg-muted px-1.5 py-0.5">notfair-cmo doctor</code> for help.
diff --git a/notfair-cmo/src/app/(app)/[project]/page.tsx b/notfair-cmo/src/app/(app)/[project]/page.tsx
index e343080c..45e2d13e 100644
--- a/notfair-cmo/src/app/(app)/[project]/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/page.tsx
@@ -112,7 +112,7 @@ export default async function ProjectHomePage({
<div>
<CardTitle className="text-base">Your agents</CardTitle>
<CardDescription>
- Each agent runs in its own OpenClaw workspace. Click to chat.
+ Each agent runs in its own workspace. Click to chat.
</CardDescription>
</div>
<Button asChild variant="outline" size="sm">
diff --git a/notfair-cmo/src/app/(app)/layout.tsx b/notfair-cmo/src/app/(app)/layout.tsx
index e612ec70..d4327f1c 100644
--- a/notfair-cmo/src/app/(app)/layout.tsx
+++ b/notfair-cmo/src/app/(app)/layout.tsx
@@ -1,8 +1,24 @@
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 { 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;
-export default function AppLayout({ children }: { children: React.ReactNode }) {
return (
<ClientMountGate
fallback={
@@ -11,17 +27,25 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
</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 p-6">
- {children}
- </main>
- </SidebarInset>
- </SidebarProvider>
+ <LiveCountsProvider
+ initial={{
+ project: active?.slug ?? null,
+ agents: initialAgents,
+ approvals: initialApprovals,
+ }}
+ >
+ <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 p-6">
+ {children}
+ </main>
+ </SidebarInset>
+ </SidebarProvider>
+ </LiveCountsProvider>
</ClientMountGate>
);
}
diff --git a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/live/route.ts b/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/live/route.ts
index 34cbd940..82bfe6e2 100644
--- a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/live/route.ts
+++ b/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/live/route.ts
@@ -1,14 +1,14 @@
-import { watch } from "node:fs";
import { NextResponse } from "next/server";
-
import { getActiveProject } from "@/server/active-project";
import { resolveAgentBySlug } from "@/server/agent-meta";
import { getProject } from "@/server/db/projects";
-import { rawEntryToEvents } from "@/server/openclaw/transcript-tail";
import {
- readShadowFromOffset,
- shadowTranscriptPath,
-} from "@/server/openclaw/shadow-transcript";
+ readTranscriptTail,
+ resolveSessionForThread,
+} from "@/server/sessions/transcript-tail";
+import { subscribeSessionEvents } from "@/server/live-events/emitter";
+import type { TranscriptEvent as RawTranscriptEvent } from "@/server/sessions";
+import { readTranscriptTail as tailFromCursor } from "@/server/sessions/transcript-tail";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -19,50 +19,58 @@ function log(...args: unknown[]): void {
}
/**
- * SSE bridge that streams a task's transcript live. Tails the shadow
- * JSONL that runTaskKickoffServerSide writes as the gateway stream
- * yields events; that file mirrors OpenClaw's session.jsonl schema so
- * the parser is the same one polling uses.
+ * SSE bridge that streams a session's transcript live.
+ *
+ * Mechanism (paperclip-style pub/sub):
+ * 1. Resolve the session row from (project_slug, agent_id, label).
+ * 2. Backfill events the client hasn't seen yet by reading
+ * `transcript_events` from `?cursor=` (default 0) forward.
+ * 3. Subscribe to the in-process emitter for this session_id. From this
+ * point, every `appendTranscriptEvent` call fires this listener and
+ * we forward the event to the client in milliseconds — no polling.
*
- * Why not OpenClaw's WS-side `sessions.messages.subscribe`: that fires
- * `session.message` events only when transcript-mirror appends a
- * message, and the codex-app-server backend defers appending to
- * session-end via mirrorTranscriptBestEffort. The result: zero events
- * mid-turn. The shadow log fills that gap server-side.
+ * Reattach safety: the backfill + subscribe pair brackets the gap between
+ * page render and SSE connect. Any event written during that window lands
+ * in the backfill or in the live stream; the client filters by `seq` so
+ * an event that crosses the boundary is deduped.
*/
export async function GET(
request: Request,
{ params }: { params: Promise<{ agent: string; thread: string }> },
): Promise<Response> {
const { agent: agentSlug, thread: threadId } = await params;
- log("GET", { agentSlug, threadId });
const url = new URL(request.url);
const projectSlug = url.searchParams.get("project");
const projectRow = projectSlug ? getProject(projectSlug) : await getActiveProject();
if (!projectRow || projectRow.archived_at) {
- log("project not found", { projectSlug });
return NextResponse.json({ error: "Unknown project" }, { status: 404 });
}
const resolved = await resolveAgentBySlug(projectRow.slug, agentSlug);
if (!resolved) {
- log("agent not found", { projectSlug: projectRow.slug, agentSlug });
return NextResponse.json({ error: "Unknown agent" }, { status: 404 });
}
const agentFullId = resolved.agent_id;
- const path = shadowTranscriptPath(agentFullId, threadId);
- log("ready to tail", { agentFullId, threadId, path });
+ 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
+ // 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
+ // pushes the first event, which we'd miss). To handle that case, we
+ // also poll-fallback for the row every 1s while it's missing.
+ let session = resolveSessionForThread(projectRow.slug, agentFullId, threadId);
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let closed = false;
- let byteOffset = 0;
- let watcher: ReturnType<typeof watch> | null = null;
- let pollTimer: ReturnType<typeof setInterval> | null = null;
- let pumping = false;
- let forwardedCount = 0;
+ let unsubscribe: (() => void) | null = null;
+ let bufferedDuringBackfill: RawTranscriptEvent[] | null = [];
+ let lastSeqEmitted = startCursor;
+ let pendingProbe: ReturnType<typeof setInterval> | null = null;
function send(event: string, data: unknown): void {
if (closed) return;
@@ -71,88 +79,103 @@ export async function GET(
encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
);
} catch {
- // stream torn down
+ // torn down
}
}
function teardown(): void {
if (closed) return;
closed = true;
- log("teardown", { forwarded: forwardedCount, byteOffset });
- try {
- watcher?.close();
- } catch {}
- if (pollTimer) clearInterval(pollTimer);
+ if (pendingProbe) clearInterval(pendingProbe);
+ if (unsubscribe) {
+ unsubscribe();
+ unsubscribe = null;
+ }
try {
controller.close();
- } catch {}
+ } catch {
+ // already closed
+ }
}
request.signal.addEventListener("abort", teardown);
- async function pump(): Promise<void> {
+ /**
+ * Convert a single transcript_events row into the UI event shape and
+ * forward over SSE. Dedupes by seq so events delivered both via
+ * backfill and live stream don't render twice.
+ */
+ function forwardRow(row: RawTranscriptEvent): void {
+ if (row.seq <= lastSeqEmitted) return;
+ lastSeqEmitted = row.seq;
+ // Reuse readTranscriptTail's mapping to keep the UI shape in one
+ // place; it accepts a cursor strictly less than the row's seq.
+ const { events } = tailFromCursor(
+ projectRow!.slug,
+ agentFullId,
+ threadId,
+ row.seq - 1,
+ );
+ if (events.length > 0) {
+ send("transcript", { events });
+ }
+ }
+
+ function liveListener(row: RawTranscriptEvent): void {
if (closed) return;
- if (pumping) return;
- pumping = true;
- try {
- const { bytes, byteOffset: nextOffset } = await readShadowFromOffset(
- agentFullId,
- threadId,
- byteOffset,
- );
- if (bytes.length === 0) return;
- byteOffset = nextOffset;
- const lines = bytes.split("\n").filter((l) => l.trim().length > 0);
- let lineIdx = forwardedCount;
- const events = [];
- for (const line of lines) {
- try {
- const entry = JSON.parse(line) as Parameters<
- typeof rawEntryToEvents
- >[0];
- const baseId = `${entry.id ?? "shadow"}-${lineIdx++}`;
- events.push(...rawEntryToEvents(entry, baseId));
- } catch {
- // skip malformed
- }
- }
- if (events.length > 0) {
- forwardedCount += events.length;
- log("forwarded", { count: events.length, total: forwardedCount });
- send("transcript", { events });
- }
- } catch (err) {
- log("pump error", err);
- } finally {
- pumping = false;
+ if (bufferedDuringBackfill) {
+ // Backfill is still draining — queue and replay after it finishes
+ // to preserve order and let dedup-by-seq do its job.
+ bufferedDuringBackfill.push(row);
+ return;
}
+ forwardRow(row);
}
- try {
- send("ready", { path });
- // Initial pump in case the file already has content.
- await pump();
- // fs.watch fires inotify/FSEvents on append. The kernel notification
- // can lag a few ms; we also poll every 500ms as a safety net so a
- // missed inotify event (notoriously flaky on some filesystems)
- // doesn't strand the user.
- try {
- watcher = watch(path, { persistent: true }, () => {
- void pump();
- });
- } catch {
- // File doesn't exist yet — runTaskKickoffServerSide will create
- // it once the task is kicked off. Rely on poll fallback.
- log("watch failed, polling only");
+ function attachSubscription(sessionId: string): void {
+ unsubscribe = subscribeSessionEvents(sessionId, liveListener);
+ }
+
+ function backfill(): void {
+ if (closed) return;
+ const { events, byteOffset } = readTranscriptTail(
+ projectRow!.slug,
+ agentFullId,
+ threadId,
+ lastSeqEmitted,
+ );
+ if (events.length > 0) {
+ lastSeqEmitted = byteOffset;
+ send("transcript", { events });
}
- pollTimer = setInterval(() => {
- void pump();
- }, 500);
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- log("error", { message });
- send("error", { message });
- teardown();
+ // Drain anything that arrived while we were reading the DB.
+ const buf = bufferedDuringBackfill ?? [];
+ bufferedDuringBackfill = null;
+ for (const row of buf) forwardRow(row);
+ }
+
+ send("ready", { thread: threadId, cursor: startCursor });
+
+ if (session) {
+ // Standard path: row exists. Subscribe FIRST so events written
+ // during the backfill land in the buffer, then read the DB.
+ attachSubscription(session.id);
+ backfill();
+ } else {
+ // Pending thread with no first turn yet. Poll-fallback for the row
+ // every 1s. When it appears, attach and backfill. Keep the SSE
+ // open meanwhile so the client doesn't reconnect uselessly.
+ log("waiting for session row", { threadId });
+ pendingProbe = setInterval(() => {
+ if (closed) return;
+ session = resolveSessionForThread(projectRow!.slug, agentFullId, threadId);
+ if (session) {
+ clearInterval(pendingProbe!);
+ pendingProbe = null;
+ attachSubscription(session.id);
+ backfill();
+ }
+ }, 1000);
}
},
});
diff --git a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.ts b/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.ts
deleted file mode 100644
index b33e823a..00000000
--- a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.ts
+++ /dev/null
@@ -1,212 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { Project } from "@/types";
-
-const getActiveProjectMock = vi.fn();
-vi.mock("@/server/active-project", () => ({
- getActiveProject: (...args: unknown[]) => getActiveProjectMock(...args),
-}));
-
-const getProjectMock = vi.fn();
-vi.mock("@/server/db/projects", () => ({
- getProject: (...args: unknown[]) => getProjectMock(...args),
-}));
-
-const resolveAgentBySlugMock = vi.fn();
-vi.mock("@/server/agent-meta", () => ({
- resolveAgentBySlug: (...args: unknown[]) => resolveAgentBySlugMock(...args),
-}));
-
-const readTranscriptTailMock = vi.fn();
-vi.mock("@/server/openclaw/transcript-tail", () => ({
- readTranscriptTail: (...args: unknown[]) => readTranscriptTailMock(...args),
-}));
-
-import { GET } from "./route";
-
-function makeProject(overrides: Partial<Project> = {}): Project {
- return {
- id: "id",
- 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(url: string): Request {
- return new Request(url, { method: "GET" });
-}
-
-describe("GET /api/agents/[agent]/threads/[thread]/transcript", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("returns 400 when no project param and no active project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const res = await GET(
- makeReq("http://localhost/api/agents/cmo/threads/t1/transcript"),
- { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },
- );
- expect(res.status).toBe(400);
- const body = (await res.json()) as { error: string };
- expect(body.error).toBe("no active project");
- });
-
- it("uses explicit project query param when present", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- readTranscriptTailMock.mockReturnValueOnce({
- events: [],
- byteOffset: 0,
- fileSize: 0,
- });
- await GET(
- makeReq(
- "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme",
- ),
- { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },
- );
- expect(getProjectMock).toHaveBeenCalledWith("acme");
- expect(getActiveProjectMock).not.toHaveBeenCalled();
- });
-
- it("falls back to active project when no query param", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- readTranscriptTailMock.mockReturnValueOnce({
- events: [],
- byteOffset: 0,
- fileSize: 0,
- });
- await GET(
- makeReq("http://localhost/api/agents/cmo/threads/t1/transcript"),
- { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },
- );
- expect(getActiveProjectMock).toHaveBeenCalled();
- expect(getProjectMock).not.toHaveBeenCalled();
- });
-
- it("returns 404 when agent slug cannot be resolved", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce(null);
- const res = await GET(
- makeReq(
- "http://localhost/api/agents/ghost/threads/t1/transcript?project=acme",
- ),
- { params: Promise.resolve({ agent: "ghost", thread: "t1" }) },
- );
- expect(res.status).toBe(404);
- const body = (await res.json()) as { error: string };
- expect(body.error).toBe("unknown agent");
- });
-
- it("returns events + byte offset + file size on success", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- const events = [
- { kind: "user_message", id: "1", ts: 0, body: "hi" },
- ];
- readTranscriptTailMock.mockReturnValueOnce({
- events,
- byteOffset: 100,
- fileSize: 100,
- });
- const res = await GET(
- makeReq(
- "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme&offset=50",
- ),
- { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },
- );
- expect(res.status).toBe(200);
- const body = (await res.json()) as {
- events: unknown[];
- byteOffset: number;
- file_size: number;
- };
- expect(body.events).toEqual(events);
- expect(body.byteOffset).toBe(100);
- expect(body.file_size).toBe(100);
- expect(readTranscriptTailMock).toHaveBeenCalledWith("acme-cmo", "t1", 50);
- });
-
- it("treats missing offset query param as 0", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- readTranscriptTailMock.mockReturnValueOnce({
- events: [],
- byteOffset: 0,
- fileSize: 0,
- });
- await GET(
- makeReq(
- "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme",
- ),
- { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },
- );
- expect(readTranscriptTailMock).toHaveBeenCalledWith("acme-cmo", "t1", 0);
- });
-
- it("clamps negative offset to 0", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- readTranscriptTailMock.mockReturnValueOnce({
- events: [],
- byteOffset: 0,
- fileSize: 0,
- });
- await GET(
- makeReq(
- "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme&offset=-5",
- ),
- { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },
- );
- expect(readTranscriptTailMock).toHaveBeenCalledWith("acme-cmo", "t1", 0);
- });
-
- it("clamps non-numeric offset to 0", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- readTranscriptTailMock.mockReturnValueOnce({
- events: [],
- byteOffset: 0,
- fileSize: 0,
- });
- await GET(
- makeReq(
- "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme&offset=notanumber",
- ),
- { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },
- );
- expect(readTranscriptTailMock).toHaveBeenCalledWith("acme-cmo", "t1", 0);
- });
-});
diff --git a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts b/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
index a1834502..f4293e2e 100644
--- a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
+++ b/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server";
import { getActiveProject } from "@/server/active-project";
import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
-import { readTranscriptTail } from "@/server/openclaw/transcript-tail";
+import { readTranscriptTail } from "@/server/sessions/transcript-tail";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -46,6 +46,7 @@ export async function GET(
const validOffset = Number.isFinite(byteOffset) && byteOffset >= 0 ? byteOffset : 0;
const { events, byteOffset: newOffset, fileSize } = readTranscriptTail(
+ project.slug,
resolved.agent_id,
threadId,
validOffset,
diff --git a/notfair-cmo/src/app/api/chat/route.test.ts b/notfair-cmo/src/app/api/chat/route.test.ts
deleted file mode 100644
index ab50bd8e..00000000
--- a/notfair-cmo/src/app/api/chat/route.test.ts
+++ /dev/null
@@ -1,511 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { Project } from "@/types";
-
-const getActiveProjectMock = vi.fn();
-vi.mock("@/server/active-project", () => ({
- getActiveProject: (...args: unknown[]) => getActiveProjectMock(...args),
-}));
-
-const getProjectMock = vi.fn();
-vi.mock("@/server/db/projects", () => ({
- getProject: (...args: unknown[]) => getProjectMock(...args),
-}));
-
-const resolveAgentBySlugMock = vi.fn();
-vi.mock("@/server/agent-meta", () => ({
- resolveAgentBySlug: (...args: unknown[]) => resolveAgentBySlugMock(...args),
-}));
-
-const findSessionBySessionIdMock = vi.fn();
-const buildPendingSessionKeyMock = vi.fn(
- (agent: string, sessionId: string) => `agent:${agent}:${sessionId}`,
-);
-vi.mock("@/server/openclaw/sessions", () => ({
- findSessionBySessionId: (...args: unknown[]) =>
- findSessionBySessionIdMock(...args),
- buildPendingSessionKey: (...args: unknown[]) =>
- buildPendingSessionKeyMock(...(args as [string, string])),
-}));
-
-const streamChatViaGatewayMock = vi.fn();
-vi.mock("@/server/openclaw/gateway-client", () => ({
- streamChatViaGateway: (...args: unknown[]) => streamChatViaGatewayMock(...args),
-}));
-
-const getTaskMock = vi.fn();
-const claimProposedTaskMock = vi.fn();
-vi.mock("@/server/db/tasks", () => ({
- getTask: (...args: unknown[]) => getTaskMock(...args),
- claimProposedTask: (...args: unknown[]) => claimProposedTaskMock(...args),
-}));
-
-import { POST } from "./route";
-
-function makeProject(overrides: Partial<Project> = {}): Project {
- return {
- id: "id",
- 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(body: unknown): Request {
- return new Request("http://localhost/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: typeof body === "string" ? body : JSON.stringify(body),
- });
-}
-
-async function readSse(res: Response): Promise<{
- events: Array<{ event: string; data: unknown }>;
- raw: string;
-}> {
- const reader = res.body!.getReader();
- const decoder = new TextDecoder();
- let raw = "";
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
- raw += decoder.decode(value, { stream: true });
- }
- const events: Array<{ event: string; data: unknown }> = [];
- for (const chunk of raw.split("\n\n")) {
- const lines = chunk.split("\n");
- let event = "message";
- let data: unknown = null;
- for (const line of lines) {
- if (line.startsWith("event: ")) event = line.slice("event: ".length);
- else if (line.startsWith("data: ")) {
- try {
- data = JSON.parse(line.slice("data: ".length));
- } catch {
- data = line.slice("data: ".length);
- }
- }
- }
- if (lines.length > 0 && lines[0]) events.push({ event, data });
- }
- return { events, raw };
-}
-
-// Stream-builder helper: yields the given events one at a time.
-async function* makeAgentStream(
- evts: Array<{
- kind: "delta" | "tool" | "lifecycle" | "error" | "final";
- [k: string]: unknown;
- }>,
-) {
- for (const e of evts) yield e;
-}
-
-describe("POST /api/chat", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- streamChatViaGatewayMock.mockReset();
- });
-
- it("returns 400 when body is not valid JSON", async () => {
- const res = await POST(
- new Request("http://localhost/api/chat", {
- method: "POST",
- body: "not json",
- }),
- );
- expect(res.status).toBe(400);
- const body = (await res.json()) as { error: string };
- expect(body.error).toMatch(/Invalid JSON/);
- });
-
- it("returns 400 when message is missing", async () => {
- const res = await POST(makeReq({ sessionId: "s1" }));
- expect(res.status).toBe(400);
- const body = (await res.json()) as { error: string };
- expect(body.error).toMatch(/message is required/);
- });
-
- it("returns 400 when message is whitespace-only", async () => {
- const res = await POST(makeReq({ message: " ", sessionId: "s1" }));
- expect(res.status).toBe(400);
- });
-
- it("returns 400 when no active project resolves", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- expect(res.status).toBe(400);
- const body = (await res.json()) as { error: string };
- expect(body.error).toMatch(/No active project/);
- });
-
- it("uses explicit project param over active-project cookie", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce(null); // short-circuit at 404
-
- const res = await POST(
- makeReq({ message: "hi", sessionId: "s1", project: "acme" }),
- );
- expect(res.status).toBe(404);
- expect(getProjectMock).toHaveBeenCalledWith("acme");
- expect(getActiveProjectMock).not.toHaveBeenCalled();
- });
-
- it("returns 404 when agent slug cannot be resolved", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce(null);
- const res = await POST(
- makeReq({ message: "hi", sessionId: "s1", agent: "ghost" }),
- );
- expect(res.status).toBe(404);
- const body = (await res.json()) as { error: string };
- expect(body.error).toMatch(/ghost/);
- });
-
- it("defaults agent to 'cmo' when not specified", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce(null);
- await POST(makeReq({ message: "hi", sessionId: "s1" }));
- expect(resolveAgentBySlugMock).toHaveBeenCalledWith("acme", "cmo");
- });
-
- it("returns 400 when sessionId is missing", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- const res = await POST(makeReq({ message: "hi" }));
- expect(res.status).toBe(400);
- const body = (await res.json()) as { error: string };
- expect(body.error).toMatch(/sessionId is required/);
- });
-
- it("uses provided sessionKey verbatim when present", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
- const res = await POST(
- makeReq({
- message: "hello",
- sessionId: "s1",
- sessionKey: "agent:acme-cmo:custom-label",
- }),
- );
- expect(res.status).toBe(200);
- await readSse(res); // drain
- expect(streamChatViaGatewayMock).toHaveBeenCalledTimes(1);
- const call = streamChatViaGatewayMock.mock.calls[0]![0] as {
- sessionKey: string;
- sessionId: string;
- message: string;
- };
- expect(call.sessionKey).toBe("agent:acme-cmo:custom-label");
- expect(call.sessionId).toBe("s1");
- expect(call.message).toBe("hello");
- // No fallback lookup needed when sessionKey is explicit.
- expect(findSessionBySessionIdMock).not.toHaveBeenCalled();
- });
-
- it("looks up sessionKey from sessions store when not provided", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce({
- sessionId: "s1",
- sessionKey: "agent:acme-cmo:s1",
- label: "s1",
- lastInteractionAt: 0,
- pending: false,
- });
- streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- await readSse(res);
- expect(findSessionBySessionIdMock).toHaveBeenCalledWith("acme-cmo", "s1");
- const call = streamChatViaGatewayMock.mock.calls[0]![0] as {
- sessionKey: string;
- };
- expect(call.sessionKey).toBe("agent:acme-cmo:s1");
- });
-
- it("falls back to buildPendingSessionKey for unknown sessions", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
- const res = await POST(makeReq({ message: "hi", sessionId: "new-id" }));
- await readSse(res);
- expect(buildPendingSessionKeyMock).toHaveBeenCalledWith(
- "acme-cmo",
- "new-id",
- );
- const call = streamChatViaGatewayMock.mock.calls[0]![0] as {
- sessionKey: string;
- };
- expect(call.sessionKey).toBe("agent:acme-cmo:new-id");
- });
-
- it("streams meta + text + done events for a happy-path chat", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- streamChatViaGatewayMock.mockReturnValueOnce(
- makeAgentStream([
- { kind: "delta", text: "Hello, " },
- { kind: "delta", text: "world!" },
- ]),
- );
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- expect(res.status).toBe(200);
- expect(res.headers.get("Content-Type")).toBe("text/event-stream");
- expect(res.headers.get("Cache-Control")).toBe("no-cache");
-
- const { events } = await readSse(res);
- const eventNames = events.map((e) => e.event);
- expect(eventNames[0]).toBe("meta");
- expect(eventNames).toContain("text");
- expect(eventNames).toContain("done");
-
- const meta = events.find((e) => e.event === "meta")!.data as {
- project_slug: string;
- agent: string;
- session_id: string;
- };
- expect(meta.project_slug).toBe("acme");
- expect(meta.agent).toBe("acme-cmo");
- expect(meta.session_id).toBe("s1");
-
- const textEvents = events
- .filter((e) => e.event === "text")
- .map((e) => (e.data as { chunk: string }).chunk);
- expect(textEvents).toEqual(["Hello, ", "world!"]);
- });
-
- it("emits tool + lifecycle events through to the SSE stream", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- streamChatViaGatewayMock.mockReturnValueOnce(
- makeAgentStream([
- { kind: "lifecycle", phase: "start" },
- {
- kind: "tool",
- phase: "start",
- toolCallId: "tc1",
- name: "exec",
- label: "ls",
- },
- {
- kind: "tool",
- phase: "result",
- toolCallId: "tc1",
- name: "exec",
- },
- { kind: "lifecycle", phase: "end" },
- ]),
- );
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- const { events } = await readSse(res);
-
- const toolEvents = events.filter((e) => e.event === "tool");
- expect(toolEvents).toHaveLength(2);
- expect((toolEvents[0]!.data as { phase: string }).phase).toBe("start");
- expect((toolEvents[1]!.data as { phase: string }).phase).toBe("result");
-
- const lifecycleEvents = events.filter((e) => e.event === "lifecycle");
- expect(lifecycleEvents).toHaveLength(2);
- });
-
- it("emits an error event when the gateway stream yields an error", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- streamChatViaGatewayMock.mockReturnValueOnce(
- makeAgentStream([{ kind: "error", message: "gateway is down" }]),
- );
- // The route only invokes orchestration when assistantBuffer has content;
- // an error-only stream skips orchestration entirely.
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- const { events } = await readSse(res);
- const errEvent = events.find((e) => e.event === "error");
- expect(errEvent).toBeDefined();
- expect((errEvent!.data as { message: string }).message).toBe(
- "gateway is down",
- );
- });
-
- it("emits an error event when the gateway iterator throws", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
-
- async function* throwingStream() {
- yield { kind: "delta" as const, text: "partial" };
- throw new Error("ws disconnected");
- }
- streamChatViaGatewayMock.mockReturnValueOnce(throwingStream());
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- const { events } = await readSse(res);
- const errEvent = events.find((e) => e.event === "error");
- expect(errEvent).toBeDefined();
- expect((errEvent!.data as { message: string }).message).toBe(
- "ws disconnected",
- );
- });
-
- // Orchestration side effects no longer run via post-stream regex parsing —
- // they happen via the notfair-orchestration MCP server while the agent's
- // turn is streaming. The chat route is now pure pipe + perf instrumentation,
- // so the only thing left to assert is that no `orchestration` SSE event is
- // ever emitted (it's no longer part of the protocol).
- // ── task_id: kickoff path ────────────────────────────────────────────
- describe("task_id (task kickoff)", () => {
- function setupAgent(slug = "acme", agentId = "acme-cmo") {
- getActiveProjectMock.mockResolvedValue(makeProject({ slug }));
- resolveAgentBySlugMock.mockResolvedValue({
- agent_id: agentId,
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValue(null);
- }
-
- it("claims a proposed task and proceeds to stream when task_id matches", async () => {
- setupAgent();
- getTaskMock.mockReturnValueOnce({
- id: "task-uuid",
- display_id: "acme-1",
- agent_id: "acme-cmo",
- status: "proposed",
- });
- claimProposedTaskMock.mockReturnValueOnce({
- id: "task-uuid",
- status: "working",
- });
- streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
-
- const res = await POST(
- makeReq({
- message: "(task assignment)",
- sessionId: "s1",
- task_id: "task-uuid",
- }),
- );
- expect(res.status).toBe(200);
- await readSse(res);
- expect(claimProposedTaskMock).toHaveBeenCalledWith("task-uuid");
- expect(streamChatViaGatewayMock).toHaveBeenCalledTimes(1);
- });
-
- it("returns 409 when the task can't be claimed (already running/terminal)", async () => {
- setupAgent();
- getTaskMock.mockReturnValueOnce({
- id: "task-uuid",
- display_id: "acme-1",
- agent_id: "acme-cmo",
- status: "working",
- });
- claimProposedTaskMock.mockReturnValueOnce(null);
-
- const res = await POST(
- makeReq({ message: "hi", sessionId: "s1", task_id: "task-uuid" }),
- );
- expect(res.status).toBe(409);
- const body = (await res.json()) as { status: string };
- expect(body.status).toBe("working");
- // Should NOT stream when claim failed — otherwise we'd double-fire the
- // agent on a reload / concurrent tab.
- expect(streamChatViaGatewayMock).not.toHaveBeenCalled();
- });
-
- it("returns 404 when the task_id doesn't exist", async () => {
- setupAgent();
- getTaskMock.mockReturnValueOnce(null);
- const res = await POST(
- makeReq({ message: "hi", sessionId: "s1", task_id: "bogus" }),
- );
- expect(res.status).toBe(404);
- expect(claimProposedTaskMock).not.toHaveBeenCalled();
- });
-
- it("returns 400 when task belongs to a different agent", async () => {
- setupAgent("acme", "acme-cmo");
- getTaskMock.mockReturnValueOnce({
- id: "task-uuid",
- display_id: "acme-1",
- agent_id: "acme-google-ads",
- status: "proposed",
- });
- const res = await POST(
- makeReq({
- message: "hi",
- sessionId: "s1",
- agent: "cmo",
- task_id: "task-uuid",
- }),
- );
- expect(res.status).toBe(400);
- expect(claimProposedTaskMock).not.toHaveBeenCalled();
- });
-
- it("skips claim entirely when no task_id is provided (normal chat)", async () => {
- setupAgent();
- streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- expect(res.status).toBe(200);
- await readSse(res);
- expect(getTaskMock).not.toHaveBeenCalled();
- expect(claimProposedTaskMock).not.toHaveBeenCalled();
- });
- });
-
- it("never emits an `orchestration` SSE event (MCP-based now)", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- streamChatViaGatewayMock.mockReturnValueOnce(
- makeAgentStream([{ kind: "delta", text: "Just chatting." }]),
- );
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- const { events } = await readSse(res);
- expect(events.find((e) => e.event === "orchestration")).toBeUndefined();
- expect(events.find((e) => e.event === "done")).toBeDefined();
- });
-});
diff --git a/notfair-cmo/src/app/api/chat/route.ts b/notfair-cmo/src/app/api/chat/route.ts
index c23281cd..909d5d40 100644
--- a/notfair-cmo/src/app/api/chat/route.ts
+++ b/notfair-cmo/src/app/api/chat/route.ts
@@ -2,98 +2,54 @@ import { NextResponse } from "next/server";
import { getActiveProject } from "@/server/active-project";
import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
-import { streamChatViaGateway } from "@/server/openclaw/gateway-client";
+import { requireAdapter } from "@/server/adapters/registry";
+import { workspaceDirFor } from "@/server/agents/provisioning";
import {
- buildPendingSessionKey,
- findSessionBySessionId,
-} from "@/server/openclaw/sessions";
-import {
- openShadowWriter,
- shadowStreamEvent,
-} from "@/server/openclaw/shadow-transcript";
+ getOrCreateSession,
+ appendTranscriptEvent,
+ touchSession,
+} from "@/server/sessions";
import { claimProposedTask, getTask, updateTask } from "@/server/db/tasks";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
-/**
- * Lightweight per-request profiler. Records ms-offsets from request start so
- * we can attribute end-to-end latency to a stage (route boot, gateway open,
- * model first-token, etc.). Marks are emitted to stdout and to the client as
- * an SSE `perf` event so they show up in both the dev terminal and the browser
- * console. Toggle off with `NOTFAIR_CHAT_PERF=0`.
- */
-const PERF_ON = process.env.NOTFAIR_CHAT_PERF !== "0";
-
-function makePerf(tag: string) {
- const start = performance.now();
- const marks: Array<{ name: string; at: number; delta: number }> = [];
- let last = start;
- const mark = (name: string) => {
- if (!PERF_ON) return;
- const now = performance.now();
- const at = now - start;
- const delta = now - last;
- last = now;
- marks.push({ name, at, delta });
- // eslint-disable-next-line no-console
- console.log(
- `[chat-perf ${tag}] +${at.toFixed(1)}ms (Δ${delta.toFixed(1)}ms) ${name}`,
- );
- };
- const summary = () => marks;
- return { mark, summary };
-}
-
type ChatPostBody = {
message: string;
agent?: string;
- /**
- * URL slug of the project this chat belongs to. The page passes it down so
- * the route doesn't have to rely on the active-project cookie, which can
- * lag the URL on first paint after a project switch or direct deep-link.
- */
+ /** URL slug of the project this chat belongs to. */
project?: string;
- /** OpenClaw session UUID — used for trajectory file naming. */
- sessionId?: string;
/**
- * OpenClaw's canonical `agent:<agent>:<label>` key for this thread. When the
- * client knows the right key (e.g., `agent:foo:main` for an existing thread
- * whose label is not the sessionId), pass it here. Falls back to a
- * sessionId-derived key for brand-new threads.
+ * 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.
*/
+ 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 to the gateway. The claim is
- * conditional on status='proposed', so concurrent kickoffs or reloads
- * mid-run are rejected with 409 instead of double-firing the agent.
- * Absent for normal user-typed messages.
+ * (proposed → working) before forwarding. Concurrent kickoffs / reloads
+ * mid-run are rejected with 409.
*/
task_id?: string;
};
export async function POST(request: Request) {
- const perf = makePerf("route");
- perf.mark("route_start");
-
let body: ChatPostBody;
try {
body = (await request.json()) as ChatPostBody;
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
- perf.mark("body_parsed");
if (!body?.message?.trim()) {
return NextResponse.json({ error: "message is required" }, { status: 400 });
}
- // Explicit project (from the URL slug the page knows) wins; fall back to
- // the cookie for backwards compatibility with any non-page caller.
- const project = body.project
- ? getProject(body.project)
- : await getActiveProject();
- perf.mark("active_project_resolved");
+ const project = body.project ? getProject(body.project) : await getActiveProject();
if (!project) {
return NextResponse.json(
{ error: "No active project. Create one first." },
@@ -103,7 +59,6 @@ export async function POST(request: Request) {
const requestedSlug = (body.agent ?? "cmo").trim();
const resolved = await resolveAgentBySlug(project.slug, requestedSlug);
- perf.mark("agent_resolved");
if (!resolved) {
return NextResponse.json(
{ error: `Unknown agent: '${requestedSlug}'` },
@@ -111,44 +66,16 @@ export async function POST(request: Request) {
);
}
- const agentName = resolved.agent_id;
-
- // Resolve session: explicit body wins. New pages always pass both sessionId
- // and sessionKey; sessionKey-only callers (legacy or external) get the
- // canonical key looked up below.
- const sessionId = body.sessionId?.trim();
- if (!sessionId) {
- return NextResponse.json(
- { error: "sessionId is required (call from a threaded chat URL)." },
- { status: 400 },
- );
- }
- let sessionKey = body.sessionKey?.trim();
- if (!sessionKey) {
- const known = findSessionBySessionId(agentName, sessionId);
- sessionKey = known?.sessionKey ?? buildPendingSessionKey(agentName, sessionId);
- }
- perf.mark("session_resolved");
-
- // Task-kickoff path: claim the proposed task before streaming so a single
- // turn can't fire twice (page reload / two tabs / StrictMode double-mount).
- // claimProposedTask is a conditional UPDATE keyed on status='proposed';
- // any other state (working/done/failed/cancelled) returns null and we
- // reject with 409. Callers (LiveTranscript auto-kickoff) treat 409 as a
- // benign no-op — the task is already running or finished elsewhere.
const taskId = body.task_id?.trim();
if (taskId) {
const existing = getTask(taskId);
if (!existing) {
- return NextResponse.json(
- { error: `Unknown task_id '${taskId}'` },
- { status: 404 },
- );
+ return NextResponse.json({ error: `Unknown task_id '${taskId}'` }, { status: 404 });
}
- if (existing.agent_id !== agentName) {
+ if (existing.agent_id !== resolved.agent_id) {
return NextResponse.json(
{
- error: `Task ${existing.display_id} belongs to ${existing.agent_id}, not ${agentName}`,
+ error: `Task ${existing.display_id} belongs to ${existing.agent_id}, not ${resolved.agent_id}`,
},
{ status: 400 },
);
@@ -156,28 +83,28 @@ export async function POST(request: Request) {
const claimed = claimProposedTask(existing.id);
if (!claimed) {
return NextResponse.json(
- {
- error: "task already claimed",
- status: existing.status,
- task_id: existing.id,
- },
+ { error: "task already claimed", status: existing.status, task_id: existing.id },
{ status: 409 },
);
}
}
- perf.mark("task_claim_resolved");
+ const label =
+ body.thread?.trim() || body.sessionId?.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 });
+
+ const adapter = requireAdapter(project.harness_adapter);
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
- // Track whether the SSE client is still connected. Once they navigate
- // away or close the tab, controller.enqueue throws — we flip this flag
- // and silently drop further sends. The agent run on OpenClaw keeps
- // going, the assistantBuffer keeps accumulating, and orchestration
- // still runs at the end. Persistence (JSONL) happens server-side
- // regardless, so when the user returns, the transcript-tail endpoint
- // surfaces the full response on the next poll.
let clientOpen = true;
const send = (event: string, data: unknown) => {
if (!clientOpen) return;
@@ -190,64 +117,45 @@ export async function POST(request: Request) {
}
};
- // Deliberately do NOT propagate request.signal to the gateway abort
- // signal. The user expectation: "if I switch agents or close the tab,
- // the agent should keep responding; when I switch back, show the
- // result." Honoring disconnect-as-cancel kills mid-flight agent runs
- // and breaks that promise. The Stop button is now a future-TODO
- // (separate POST /api/chat/stop endpoint) — there isn't a way to
- // explicitly cancel a run today, only the implicit disconnect path
- // which we no longer treat as cancel.
- const noAbort = new AbortController(); // never aborted; just satisfies the signal param
+ // Disconnect != cancel: the harness keeps running and persisting events
+ // to the transcript. The user sees them on next attach.
+ const noAbort = new AbortController();
- let firstSseDeltaSent = false;
- let assistantBuffer = "";
- // Tee gateway events into the shadow JSONL so the /live SSE bridge
- // can replay them when the user re-opens the task page (e.g. after a
- // tab switch). Without this, only runTaskKickoffServerSide-initiated
- // tasks have a shadow — /api/chat-initiated turns (the onboarding
- // auto-kickoff, plus user messages mid-task) would leave the
- // transcript blank on re-attach because the in-flight stream is
- // already gone and OpenClaw's JSONL hasn't flushed yet.
- const shadow = await openShadowWriter(agentName, sessionId);
try {
- perf.mark("stream_start");
- // Surface input sizes so each perf trace tells us *why* this turn
- // was fast/slow — a 24KB system prompt with a 1.8KB kickoff brief
- // behaves very differently from a 200B reply. Browser console
- // table includes these alongside the timing marks.
send("meta", {
project_slug: project.slug,
- agent: agentName,
- session_id: sessionId,
- session_key: sessionKey,
+ agent: resolved.agent_id,
+ session_id: session.id,
+ harness_adapter: project.harness_adapter,
message_chars: body.message.length,
is_kickoff: Boolean(taskId),
});
- for await (const evt of streamChatViaGateway({
- sessionKey,
- sessionId,
+
+ for await (const evt of adapter.execute({
+ projectSlug: project.slug,
+ agentId: resolved.agent_id,
+ workspaceDir: workspaceDirFor(resolved.agent_id),
message: body.message,
+ threadId: session.id,
+ harnessSessionId: session.harness_session_id,
signal: noAbort.signal,
- perf,
})) {
- // Best-effort shadow tee. A shadow write failure must not break
- // the live stream the user sees.
+ if (evt.kind === "session") {
+ // Remember the harness's own session id so the next turn can
+ // pass it back via --resume / `exec resume`. Don't persist as
+ // a transcript event — it's metadata, not chat content.
+ touchSession(session.id, evt.harnessSessionId);
+ continue;
+ }
try {
- await shadowStreamEvent(shadow, evt);
+ appendTranscriptEvent(session.id, evt.kind, evt);
} catch (err) {
- console.error("[api/chat] shadow write failed:", err);
+ console.error("[api/chat] transcript persist failed:", err);
}
+
if (evt.kind === "delta") {
- if (!firstSseDeltaSent) {
- firstSseDeltaSent = true;
- perf.mark("first_sse_delta_sent");
- }
- assistantBuffer += evt.text;
send("text", { chunk: evt.text });
} else if (evt.kind === "tool") {
- // tool start/update/result — keyed by toolCallId so the client
- // can update the matching step row instead of appending a new one.
send("tool", {
phase: evt.phase,
tool_call_id: evt.toolCallId,
@@ -258,60 +166,46 @@ export async function POST(request: Request) {
send("lifecycle", { phase: evt.phase });
} else if (evt.kind === "error") {
send("error", { message: evt.message });
- // When this turn is a task kickoff (we atomically claimed
- // proposed → working above), a gateway error means the agent
- // never actually ran. Without this rollback the task is
- // stranded in `working` forever — the UI shows a permanent
- // "Starting" with no events. Mark it failed so the error
- // surfaces in the task row and the user can decide to retry.
if (taskId) {
- console.error(
- `[api/chat] kickoff gateway error for task ${taskId} (agent=${agentName}): ${evt.message}`,
- );
- updateTask(taskId, {
- status: "failed",
- error_message: evt.message,
- });
+ updateTask(taskId, { status: "failed", error_message: evt.message });
}
}
- // "final" implicitly ends the loop after; no separate signal needed.
}
- await shadow.close();
- perf.mark("stream_done");
- // Orchestration side effects (task creation, status updates,
- // comments, approvals) now happen via the notfair-orchestration MCP
- // server — the agent calls those tools mid-stream and the handler
- // mutates DB rows directly. We no longer regex-scan the assistant
- // reply for pseudo-XML blocks. See agent-templates.ts for the
- // procedural teaching pattern.
+ 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("perf", { marks: perf.summary() });
send("done", {});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
send("error", { message });
- // Same kickoff-stranding fix as the in-stream error branch above:
- // if we claimed the task at the top of the handler, the gateway
- // tearing down before any progress means the agent never ran.
- // Mark it failed so the UI surfaces the error instead of sitting
- // on "Starting" forever.
if (taskId) {
- console.error(
- `[api/chat] kickoff threw for task ${taskId} (agent=${agentName}): ${message}`,
- );
updateTask(taskId, { status: "failed", error_message: message });
}
} finally {
- // Close the shadow if it's still open (error path). Idempotent
- // close — calling twice when the success path already closed is
- // a no-op flush.
- await shadow.close().catch(() => undefined);
try {
controller.close();
} catch {
- // Controller may already be closed if the client disconnected
- // mid-stream — silent because the agent run continued + persisted.
+ // already closed
}
}
},
diff --git a/notfair-cmo/src/app/api/in-flight-counts/route.ts b/notfair-cmo/src/app/api/in-flight-counts/route.ts
index 87e9885b..d35fc048 100644
--- a/notfair-cmo/src/app/api/in-flight-counts/route.ts
+++ b/notfair-cmo/src/app/api/in-flight-counts/route.ts
@@ -8,11 +8,10 @@ export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
- * Lightweight liveness probe used by GlobalLivenessPoller to decide
- * whether the sidebar actually needs a refresh. The poller fetches this
- * a few times a minute; only when the response signature differs from
- * the previous one does it call router.refresh(). That stops the
- * sidebar from blinking on every poll cycle when nothing has changed.
+ * 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();
diff --git a/notfair-cmo/src/app/api/mcp-oauth/callback/route.test.ts b/notfair-cmo/src/app/api/mcp-oauth/callback/route.test.ts
deleted file mode 100644
index 6115f88f..00000000
--- a/notfair-cmo/src/app/api/mcp-oauth/callback/route.test.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-const consumePendingMock = vi.fn();
-vi.mock("@/server/mcp-pending", () => ({
- consumePending: (...args: unknown[]) => consumePendingMock(...args),
-}));
-
-const setMcpBearerMock = vi.fn();
-vi.mock("@/server/mcp-state", () => ({
- setMcpBearer: (...args: unknown[]) => setMcpBearerMock(...args),
-}));
-
-import { GET } from "./route";
-
-function makeReq(url: string): Request {
- return new Request(url, { method: "GET" });
-}
-
-function makePending(overrides: Record<string, unknown> = {}) {
- return {
- catalog_key: "notfair-googleads",
- stored_key: "acme-notfair-googleads",
- display_name: "NotFair Google Ads",
- resource_url: "https://mcp.example.com/sse",
- issuer: "https://auth.example.com",
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-123",
- client_secret: "secret-456",
- code_verifier: "verifier",
- redirect_uri: "http://localhost/api/mcp-oauth/callback",
- project_slug: "acme",
- return_to: "/acme/agents/cmo/mcp",
- created_at: Date.now(),
- ...overrides,
- };
-}
-
-describe("GET /api/mcp-oauth/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;
- });
-
- it("returns 400 HTML when state param is missing", async () => {
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?code=abc"),
- );
- expect(res.status).toBe(400);
- expect(res.headers.get("Content-Type")).toContain("text/html");
- const text = await res.text();
- expect(text).toContain("Missing state parameter");
- });
-
- it("returns 400 HTML when pending flow is not found / expired", async () => {
- consumePendingMock.mockReturnValueOnce(null);
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=ghost&code=abc"),
- );
- expect(res.status).toBe(400);
- const text = await res.text();
- expect(text).toContain("expired or was already used");
- });
-
- it("redirects with mcp_error when upstream returned an error param", async () => {
- consumePendingMock.mockReturnValueOnce(makePending());
- const res = await GET(
- makeReq(
- "http://localhost/api/mcp-oauth/callback?state=s1&error=access_denied",
- ),
- );
- expect(res.status).toBe(307);
- const location = new URL(res.headers.get("location")!);
- expect(location.pathname).toBe("/acme/agents/cmo/mcp");
- expect(location.searchParams.get("mcp_error")).toContain("access_denied");
- });
-
- it("redirects with mcp_error when code is missing", async () => {
- consumePendingMock.mockReturnValueOnce(makePending());
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=s1"),
- );
- expect(res.status).toBe(307);
- const location = new URL(res.headers.get("location")!);
- expect(location.searchParams.get("mcp_error")).toContain("no code");
- });
-
- it("redirects with mcp_error when token exchange returns non-2xx", async () => {
- consumePendingMock.mockReturnValueOnce(makePending());
- fetchMock.mockResolvedValueOnce(new Response("bad", { status: 400 }));
- const res = await GET(
- makeReq(
- "http://localhost/api/mcp-oauth/callback?state=s1&code=abc",
- ),
- );
- expect(res.status).toBe(307);
- const location = new URL(res.headers.get("location")!);
- expect(location.searchParams.get("mcp_error")).toContain("HTTP 400");
- expect(location.searchParams.get("mcp_error")).toContain("bad");
- });
-
- it("redirects with mcp_error when token response is missing access_token", async () => {
- consumePendingMock.mockReturnValueOnce(makePending());
- fetchMock.mockResolvedValueOnce(
- new Response(JSON.stringify({ token_type: "Bearer" }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }),
- );
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),
- );
- expect(res.status).toBe(307);
- const location = new URL(res.headers.get("location")!);
- expect(location.searchParams.get("mcp_error")).toContain(
- "no access_token",
- );
- });
-
- it("redirects with mcp_error when fetch throws", async () => {
- consumePendingMock.mockReturnValueOnce(makePending());
- fetchMock.mockRejectedValueOnce(new TypeError("network fail"));
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),
- );
- expect(res.status).toBe(307);
- const location = new URL(res.headers.get("location")!);
- expect(location.searchParams.get("mcp_error")).toContain("network fail");
- });
-
- it("redirects with mcp_error when setMcpBearer throws (and scrubs bearer + oat_ tokens)", async () => {
- consumePendingMock.mockReturnValueOnce(makePending());
- fetchMock.mockResolvedValueOnce(
- new Response(JSON.stringify({ access_token: "the-token" }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }),
- );
- setMcpBearerMock.mockRejectedValueOnce(
- new Error(
- "Failed: Bearer abc.DEF-123_456 and oat_aBcDeF leaked here",
- ),
- );
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),
- );
- expect(res.status).toBe(307);
- const location = new URL(res.headers.get("location")!);
- const errMsg = location.searchParams.get("mcp_error")!;
- expect(errMsg).toContain("Saving MCP config failed");
- expect(errMsg).toContain("Bearer [redacted]");
- expect(errMsg).toContain("oat_[redacted]");
- expect(errMsg).not.toContain("abc.DEF-123_456");
- expect(errMsg).not.toContain("oat_aBcDeF");
- });
-
- it("redirects with mcp_connected on full success and includes client_secret in token body", async () => {
- const pending = makePending();
- consumePendingMock.mockReturnValueOnce(pending);
- fetchMock.mockResolvedValueOnce(
- new Response(JSON.stringify({ access_token: "live-token" }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }),
- );
- setMcpBearerMock.mockResolvedValueOnce(undefined);
-
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),
- );
- expect(res.status).toBe(307);
- const location = new URL(res.headers.get("location")!);
- expect(location.pathname).toBe("/acme/agents/cmo/mcp");
- expect(location.searchParams.get("mcp_connected")).toBe(
- "NotFair Google Ads",
- );
-
- expect(setMcpBearerMock).toHaveBeenCalledWith(
- "acme-notfair-googleads",
- "https://mcp.example.com/sse",
- "live-token",
- );
-
- const [tokenUrl, init] = fetchMock.mock.calls[0]!;
- expect(tokenUrl).toBe("https://auth.example.com/token");
- const body = (init as RequestInit).body as string;
- expect(body).toContain("grant_type=authorization_code");
- expect(body).toContain("code=abc");
- expect(body).toContain("client_id=client-123");
- expect(body).toContain("client_secret=secret-456");
- expect(body).toContain("code_verifier=verifier");
- });
-
- it("omits client_secret when pending flow has none (public client)", async () => {
- const pending = makePending({ client_secret: undefined });
- consumePendingMock.mockReturnValueOnce(pending);
- fetchMock.mockResolvedValueOnce(
- new Response(JSON.stringify({ access_token: "tok" }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }),
- );
- setMcpBearerMock.mockResolvedValueOnce(undefined);
-
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),
- );
- expect(res.status).toBe(307);
- const body = fetchMock.mock.calls[0]![1].body as string;
- expect(body).not.toContain("client_secret");
- });
-
- it("defaults return_to to '/' when pending flow has no return_to", async () => {
- const pending = makePending({ return_to: undefined });
- consumePendingMock.mockReturnValueOnce(pending);
- fetchMock.mockResolvedValueOnce(
- new Response(JSON.stringify({ access_token: "tok" }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }),
- );
- setMcpBearerMock.mockResolvedValueOnce(undefined);
-
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),
- );
- expect(res.status).toBe(307);
- const location = new URL(res.headers.get("location")!);
- expect(location.pathname).toBe("/");
- });
-
- it("truncates very long token-exchange error responses in the redirect URL", async () => {
- consumePendingMock.mockReturnValueOnce(makePending());
- const longBody = "x".repeat(500);
- fetchMock.mockResolvedValueOnce(new Response(longBody, { status: 500 }));
- const res = await GET(
- makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),
- );
- expect(res.status).toBe(307);
- const errMsg = new URL(res.headers.get("location")!).searchParams.get(
- "mcp_error",
- )!;
- // We truncate at 200 chars plus an ellipsis.
- expect(errMsg).toContain("…");
- expect(errMsg.length).toBeLessThan(longBody.length);
- });
-});
diff --git a/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts b/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts
index 61c01f77..adde4761 100644
--- a/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts
+++ b/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { consumePending } from "@/server/mcp-pending";
-import { setMcpBearer } from "@/server/mcp-state";
+import { setMcpBearer } from "@/server/mcp/state";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -96,7 +96,7 @@ export async function GET(request: Request) {
}
try {
- await setMcpBearer(pending.stored_key, pending.resource_url, access_token);
+ await setMcpBearer(pending.project_slug, pending.catalog_key, access_token);
} catch (err) {
const raw = err instanceof Error ? err.message : String(err);
// Scrub bearers + any oat_ token shape before exposing in the URL —
@@ -110,6 +110,30 @@ export async function GET(request: Request) {
return NextResponse.redirect(back);
}
+ // Token is stored — now wire it 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
+ // token) but Greg / Ana can't call any of the catalog's tools because
+ // the adapter config file was never updated.
+ try {
+ const { registerCatalogMcpForProject } = await import(
+ "@/server/mcp-server/registration"
+ );
+ const results = await registerCatalogMcpForProject(
+ pending.project_slug,
+ pending.catalog_key,
+ );
+ const failed = results.filter((r) => !r.ok);
+ if (failed.length > 0) {
+ console.warn(
+ `[mcp-oauth] ${failed.length}/${results.length} agents failed to register ${pending.catalog_key}:`,
+ failed.map((f) => (f.ok ? null : f.error)).filter(Boolean),
+ );
+ }
+ } catch (err) {
+ console.error("[mcp-oauth] registerCatalogMcpForProject threw:", err);
+ }
+
// Flash banner uses the catalog name (what the user recognizes), not the
// project-prefixed openclaw key.
back.searchParams.set("mcp_connected", pending.display_name);
diff --git a/notfair-cmo/src/components/agent-danger-zone.tsx b/notfair-cmo/src/components/agent-danger-zone.tsx
index 6eed6d1a..39e96bce 100644
--- a/notfair-cmo/src/components/agent-danger-zone.tsx
+++ b/notfair-cmo/src/components/agent-danger-zone.tsx
@@ -94,8 +94,8 @@ export function AgentDangerZone({ agentId, agentDisplayName }: Props) {
<div className="min-w-0 flex-1">
<h3 className="text-sm font-semibold text-destructive">Delete this agent</h3>
<p className="mt-0.5 text-xs text-muted-foreground">
- Removes the agent from OpenClaw along with every thread of chat history and
- every scheduled cron job that targets it. This cannot be undone.
+ 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
@@ -119,7 +119,7 @@ export function AgentDangerZone({ agentId, agentDisplayName }: Props) {
Delete &ldquo;{agentDisplayName}&rdquo;?
</DialogTitle>
<DialogDescription>
- This permanently removes the items below from OpenClaw and notfair-cmo&apos;s
+ This permanently removes the items below from notfair-cmo&apos;s
local store.
</DialogDescription>
</DialogHeader>
@@ -155,7 +155,7 @@ export function AgentDangerZone({ agentId, agentDisplayName }: Props) {
{!summary.exists_in_openclaw && (
<>
- <dt className="text-muted-foreground">OpenClaw</dt>
+ <dt className="text-muted-foreground">Workspace</dt>
<dd className="text-amber-600 dark:text-amber-400">
already removed
</dd>
diff --git a/notfair-cmo/src/components/agent-nav.tsx b/notfair-cmo/src/components/agent-nav.tsx
index 9fc09b75..1424efef 100644
--- a/notfair-cmo/src/components/agent-nav.tsx
+++ b/notfair-cmo/src/components/agent-nav.tsx
@@ -13,6 +13,7 @@ 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 { useLiveCounts } from "./live-counts-context";
type AgentNavEntry = {
/** Stable key for React, e.g. the agent_id. */
@@ -32,9 +33,10 @@ type Props = {
projectSlug: string;
agents: AgentNavEntry[];
/**
- * agent_id → in-flight task count. Drives the live-dot + count badge on
- * each row. Stale by up to the server-component refresh interval; that's
- * fine for an "I have work" hint.
+ * Optional server-side initial map (agent_id → in-flight count) 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.
*/
inFlightCounts?: Record<string, number>;
};
@@ -47,6 +49,11 @@ const TEMPLATE_ICONS: Record<AgentTemplateKey, LucideIcon> = {
export function AgentNav({ projectSlug, agents, inFlightCounts = {} }: Props) {
const pathname = usePathname();
+ // Live counts override the server-side initial map so the badge
+ // numbers update without a server re-render. Initial values keep
+ // first paint correct.
+ const live = useLiveCounts();
+ const counts: Record<string, number> = { ...inFlightCounts, ...live.agents };
return (
<SidebarMenu>
@@ -60,7 +67,7 @@ export function AgentNav({ projectSlug, agents, inFlightCounts = {} }: Props) {
const isActive =
pathname === agentBase || pathname?.startsWith(`${agentBase}/`);
const Icon = a.template_key ? TEMPLATE_ICONS[a.template_key] ?? Bot : Bot;
- const liveCount = inFlightCounts[a.key] ?? 0;
+ const liveCount = counts[a.key] ?? 0;
const rolePalette = a.template_key ? colorForRole(a.template_key) : null;
return (
<SidebarMenuItem key={a.key}>
diff --git a/notfair-cmo/src/components/agent-task-workspace.tsx b/notfair-cmo/src/components/agent-task-workspace.tsx
index bb619075..3d0f17b8 100644
--- a/notfair-cmo/src/components/agent-task-workspace.tsx
+++ b/notfair-cmo/src/components/agent-task-workspace.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useMemo, useState, useTransition } from "react";
+import { startTransition, useCallback, useMemo, useState, useTransition } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
CheckCircle2,
@@ -20,10 +20,14 @@ import { LiveTranscript } 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 } from "@/server/actions/tasks";
+import {
+ cancelTaskAction,
+ markTaskDoneAction,
+ resumeBlockedTaskAction,
+} from "@/server/actions/tasks";
import { cn } from "@/lib/utils";
import { projectHref } from "@/lib/project-href";
-import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
+import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
import type { Approval, Question, Task, TaskStatus } from "@/types";
const TASK_IN_FLIGHT: TaskStatus[] = ["proposed", "approved", "working", "blocked"];
@@ -324,7 +328,10 @@ function SelectedTaskPanel({
const onPolled = useCallback(
({ newEvents }: { newEvents: number; fileSize: number }) => {
void newEvents;
- if (isInFlight) router.refresh();
+ // 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;
@@ -348,6 +355,17 @@ function SelectedTaskPanel({
// ("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) {
@@ -365,13 +383,19 @@ function SelectedTaskPanel({
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) && (
+ {(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
@@ -383,6 +407,11 @@ function SelectedTaskPanel({
{liveApprovals.map((a) => (
<ApprovalCard key={a.id} approval={a} />
))}
+ {isAbandoned && (
+ <AbandonedTaskCard
+ taskDisplayId={selected.task.display_id}
+ />
+ )}
</div>
)}
<div className="min-h-0 flex-1">
@@ -598,3 +627,122 @@ function formatRelative(iso: string): string {
const day = Math.round(hr / 24);
return `${day}d`;
}
+
+/**
+ * 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 border border-amber-500/30 bg-amber-50/60 p-4 dark:border-amber-500/30 dark:bg-amber-950/30">
+ <div className="flex items-start gap-3">
+ <StopCircle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
+ <div className="min-w-0 flex-1 space-y-2">
+ <div>
+ <p className="text-sm font-medium text-amber-900 dark:text-amber-100">
+ Agent stopped without closing this task
+ </p>
+ <p className="mt-0.5 text-xs text-amber-800/80 dark:text-amber-200/80">
+ 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/app-sidebar.test.tsx b/notfair-cmo/src/components/app-sidebar.test.tsx
deleted file mode 100644
index 5eee1fef..00000000
--- a/notfair-cmo/src/components/app-sidebar.test.tsx
+++ /dev/null
@@ -1,272 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, cleanup } from "@testing-library/react";
-
-const listProjects = vi.fn();
-const getActiveProject = vi.fn();
-const actionableApprovalCount = vi.fn();
-const listProjectAgents = vi.fn();
-const inFlightCountsByAgent = vi.fn();
-const discoverGateway = vi.fn();
-
-vi.mock("@/server/db/projects", () => ({
- listProjects: (...args: unknown[]) => listProjects(...args),
-}));
-
-vi.mock("@/server/active-project", () => ({
- getActiveProject: (...args: unknown[]) => getActiveProject(...args),
-}));
-
-vi.mock("@/server/db/approvals", () => ({
- actionableApprovalCount: (...args: unknown[]) => actionableApprovalCount(...args),
-}));
-
-vi.mock("@/server/agent-meta", () => ({
- listProjectAgents: (...args: unknown[]) => listProjectAgents(...args),
-}));
-
-vi.mock("@/server/db/tasks", () => ({
- inFlightCountsByAgent: (...args: unknown[]) => inFlightCountsByAgent(...args),
-}));
-
-vi.mock("@/server/openclaw/gateway-client", () => ({
- discoverGateway: (...args: unknown[]) => discoverGateway(...args),
-}));
-
-vi.mock("./project-switcher", () => ({
- ProjectSwitcher: ({
- projects,
- activeSlug,
- }: {
- projects: Array<{ slug: string; display_name: string }>;
- activeSlug: string | null;
- }) => (
- <div data-testid="project-switcher">
- switcher:{activeSlug ?? "-"}/{projects.length}
- </div>
- ),
-}));
-
-vi.mock("./agent-nav", () => ({
- AgentNav: ({
- projectSlug,
- agents,
- inFlightCounts,
- }: {
- projectSlug: string;
- agents: Array<{ slug: string; display_name: string }>;
- inFlightCounts?: Record<string, number>;
- }) => (
- <div data-testid="agent-nav">
- nav:{projectSlug}:{agents.map((a) => a.slug).join(",")}:
- {JSON.stringify(inFlightCounts ?? {})}
- </div>
- ),
-}));
-
-vi.mock("./create-agent-button", () => ({
- CreateAgentButton: ({ projectSlug }: { projectSlug: string }) => (
- <button data-testid="create-agent-button">create:{projectSlug}</button>
- ),
-}));
-
-vi.mock("./global-liveness-poller", () => ({
- GlobalLivenessPoller: ({ hasInFlight }: { hasInFlight: boolean }) => (
- <div data-testid="liveness-poller">live:{String(hasInFlight)}</div>
- ),
-}));
-
-vi.mock("@/components/ui/sidebar", () => {
- const Pass = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
- return {
- Sidebar: Pass,
- SidebarContent: Pass,
- SidebarFooter: Pass,
- SidebarGroup: Pass,
- SidebarGroupContent: Pass,
- SidebarGroupLabel: Pass,
- SidebarHeader: Pass,
- SidebarMenu: ({ children }: { children: React.ReactNode }) => <ul>{children}</ul>,
- SidebarMenuButton: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- SidebarMenuItem: ({ children }: { children: React.ReactNode }) => <li>{children}</li>,
- SidebarSeparator: () => <hr />,
- SidebarTrigger: () => <button data-testid="sidebar-trigger">trigger</button>,
- };
-});
-
-import { AppSidebar } from "./app-sidebar";
-
-const projects = [
- {
- id: "1",
- slug: "alpha",
- display_name: "Alpha",
- created_at: "",
- archived_at: null,
- google_ads_account_id: null,
- },
- {
- id: "2",
- slug: "beta",
- display_name: "Beta",
- created_at: "",
- archived_at: null,
- google_ads_account_id: null,
- },
-];
-
-beforeEach(() => {
- listProjects.mockReset();
- getActiveProject.mockReset();
- actionableApprovalCount.mockReset();
- listProjectAgents.mockReset();
- inFlightCountsByAgent.mockReset();
- discoverGateway.mockReset();
- discoverGateway.mockImplementation(() => {
- throw new Error("no gateway");
- });
-});
-
-afterEach(() => {
- cleanup();
-});
-
-async function renderSidebar() {
- const tree = await AppSidebar();
- return render(tree);
-}
-
-describe("AppSidebar", () => {
- it("renders the project switcher with the active slug", async () => {
- listProjects.mockReturnValue(projects);
- getActiveProject.mockResolvedValue(projects[0]);
- actionableApprovalCount.mockReturnValue(0);
- listProjectAgents.mockResolvedValue([]);
- inFlightCountsByAgent.mockReturnValue(new Map());
- await renderSidebar();
- expect(screen.getByTestId("project-switcher").textContent).toBe(
- "switcher:alpha/2",
- );
- });
-
- it("hides the agent + project nav sections when no project is active", async () => {
- listProjects.mockReturnValue([]);
- getActiveProject.mockResolvedValue(null);
- await renderSidebar();
- expect(screen.queryByTestId("agent-nav")).not.toBeInTheDocument();
- expect(screen.queryByText("Agents")).not.toBeInTheDocument();
- expect(screen.queryByText("Project")).not.toBeInTheDocument();
- });
-
- it("renders project navigation links scoped to the active slug", async () => {
- listProjects.mockReturnValue(projects);
- getActiveProject.mockResolvedValue(projects[0]);
- actionableApprovalCount.mockReturnValue(0);
- listProjectAgents.mockResolvedValue([]);
- inFlightCountsByAgent.mockReturnValue(new Map());
- await renderSidebar();
- expect(screen.getByRole("link", { name: /home/i })).toHaveAttribute(
- "href",
- "/alpha",
- );
- expect(screen.getByRole("link", { name: /approvals/i })).toHaveAttribute(
- "href",
- "/alpha/approvals",
- );
- expect(screen.getByRole("link", { name: /tasks/i })).toHaveAttribute(
- "href",
- "/alpha/tasks",
- );
- expect(screen.getByRole("link", { name: /crons/i })).toHaveAttribute(
- "href",
- "/alpha/crons",
- );
- expect(screen.getByRole("link", { name: /activity/i })).toHaveAttribute(
- "href",
- "/alpha/activity",
- );
- expect(screen.getByRole("link", { name: /connections/i })).toHaveAttribute(
- "href",
- "/alpha/connections",
- );
- expect(screen.getByRole("link", { name: /settings/i })).toHaveAttribute(
- "href",
- "/alpha/settings",
- );
- });
-
- it("shows the approvals badge with the pending count when non-zero", async () => {
- listProjects.mockReturnValue(projects);
- getActiveProject.mockResolvedValue(projects[0]);
- actionableApprovalCount.mockReturnValue(7);
- listProjectAgents.mockResolvedValue([]);
- inFlightCountsByAgent.mockReturnValue(new Map());
- await renderSidebar();
- expect(screen.getByText("7")).toBeInTheDocument();
- });
-
- it("omits the badge when approvals are zero", async () => {
- listProjects.mockReturnValue(projects);
- getActiveProject.mockResolvedValue(projects[0]);
- actionableApprovalCount.mockReturnValue(0);
- listProjectAgents.mockResolvedValue([]);
- inFlightCountsByAgent.mockReturnValue(new Map());
- await renderSidebar();
- expect(screen.queryByText("0")).not.toBeInTheDocument();
- });
-
- it("forwards agents and in-flight counts to AgentNav", async () => {
- listProjects.mockReturnValue(projects);
- getActiveProject.mockResolvedValue(projects[0]);
- actionableApprovalCount.mockReturnValue(0);
- listProjectAgents.mockResolvedValue([
- {
- agent_id: "alpha-cmo",
- slug: "cmo",
- display_name: "CMO",
- description: "",
- template_key: "cmo",
- },
- ]);
- inFlightCountsByAgent.mockReturnValue(new Map([["alpha-cmo", 2]]));
- await renderSidebar();
- const nav = screen.getByTestId("agent-nav");
- expect(nav.textContent).toContain("nav:alpha:cmo:");
- expect(nav.textContent).toContain("alpha-cmo");
- expect(nav.textContent).toContain("2");
- });
-
- it("flips the liveness flag on when any agent has in-flight work", async () => {
- listProjects.mockReturnValue(projects);
- getActiveProject.mockResolvedValue(projects[0]);
- actionableApprovalCount.mockReturnValue(0);
- listProjectAgents.mockResolvedValue([]);
- inFlightCountsByAgent.mockReturnValue(new Map([["alpha-cmo", 1]]));
- await renderSidebar();
- expect(screen.getByTestId("liveness-poller").textContent).toBe("live:true");
- });
-
- it("keeps the liveness flag off when nothing is running", async () => {
- listProjects.mockReturnValue(projects);
- getActiveProject.mockResolvedValue(projects[0]);
- actionableApprovalCount.mockReturnValue(0);
- listProjectAgents.mockResolvedValue([]);
- inFlightCountsByAgent.mockReturnValue(new Map([["alpha-cmo", 0]]));
- await renderSidebar();
- expect(screen.getByTestId("liveness-poller").textContent).toBe("live:false");
- });
-
- it("shows the CreateAgentButton when a project is active", async () => {
- listProjects.mockReturnValue(projects);
- getActiveProject.mockResolvedValue(projects[0]);
- actionableApprovalCount.mockReturnValue(0);
- listProjectAgents.mockResolvedValue([]);
- inFlightCountsByAgent.mockReturnValue(new Map());
- await renderSidebar();
- expect(screen.getByTestId("create-agent-button").textContent).toBe(
- "create:alpha",
- );
- });
-});
diff --git a/notfair-cmo/src/components/app-sidebar.tsx b/notfair-cmo/src/components/app-sidebar.tsx
index 7bd1ac9d..3d56c73d 100644
--- a/notfair-cmo/src/components/app-sidebar.tsx
+++ b/notfair-cmo/src/components/app-sidebar.tsx
@@ -2,7 +2,6 @@ import Link from "next/link";
import {
Sidebar,
SidebarContent,
- SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
@@ -10,7 +9,6 @@ import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
- SidebarSeparator,
SidebarTrigger,
} from "@/components/ui/sidebar";
import {
@@ -25,17 +23,13 @@ import {
} from "lucide-react";
import { listProjects } from "@/server/db/projects";
import { getActiveProject } from "@/server/active-project";
-import { actionableApprovalCount } from "@/server/db/approvals";
import { listProjectAgents } from "@/server/agent-meta";
import { TEMPLATES } from "@/server/agent-templates";
-import { inFlightCountsByAgent } from "@/server/db/tasks";
import { projectHref } from "@/lib/project-href";
import { ProjectSwitcher } from "./project-switcher";
-import { PairedOpenclawPill } from "./paired-openclaw-pill";
import { AgentNav } from "./agent-nav";
import { CreateAgentButton } from "./create-agent-button";
-import { GlobalLivenessPoller } from "./global-liveness-poller";
-import { Badge } from "@/components/ui/badge";
+import { ApprovalsLiveBadge } from "./live-badge";
type NavItem = {
href: string;
@@ -57,24 +51,15 @@ const NAV: NavItem[] = [
export async function AppSidebar() {
const projects = listProjects();
const active = await getActiveProject();
- // Badge counts anything actionable: pending + revision_requested.
- const approvalsBadge = active ? actionableApprovalCount(active.slug) : 0;
const agentEntries = active ? await listProjectAgents(active.slug) : [];
- const inFlightCounts: Record<string, number> = {};
- if (active) {
- for (const [agentId, count] of inFlightCountsByAgent(active.slug)) {
- inFlightCounts[agentId] = count;
- }
- }
- const anyInFlight = Object.values(inFlightCounts).some((n) => n > 0);
+ // In-flight counts + approvals badge are no longer computed here.
+ // LiveCountsProvider (mounted at layout level) polls
+ // /api/in-flight-counts client-side and pushes fresh numbers through
+ // context. Sidebar's server-rendered structure stays stable so no
+ // reconciliation thrash on every poll — only the badge nodes flip.
return (
<Sidebar collapsible="icon">
- {/* Refresh the whole layout (this sidebar + the current route's
- server components) every 5s while anything is in flight, so
- badges + task groupings stay current no matter what page the
- user is on. Self-disables when nothing is live. */}
- <GlobalLivenessPoller hasInFlight={anyInFlight} />
<SidebarHeader>
{/* Project switcher + collapse toggle. Toggle stays visible in
icon-collapsed mode so the user can always re-expand the rail. */}
@@ -113,7 +98,6 @@ export async function AppSidebar() {
description: a.description,
template_key: a.template_key,
}))}
- inFlightCounts={inFlightCounts}
/>
</SidebarGroupContent>
</SidebarGroup>
@@ -130,11 +114,7 @@ export async function AppSidebar() {
<Link href={projectHref(active.slug, item.href)}>
<item.icon />
<span>{item.label}</span>
- {item.badge && approvalsBadge > 0 && (
- <Badge variant="secondary" className="ml-auto h-5 px-1.5 text-[10px]">
- {approvalsBadge}
- </Badge>
- )}
+ {item.badge && <ApprovalsLiveBadge />}
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
@@ -145,12 +125,6 @@ export async function AppSidebar() {
)}
</SidebarContent>
- <SidebarFooter>
- <SidebarSeparator />
- <div className="px-2 py-1.5">
- <PairedOpenclawPill />
- </div>
- </SidebarFooter>
</Sidebar>
);
}
diff --git a/notfair-cmo/src/components/create-agent-dialog.tsx b/notfair-cmo/src/components/create-agent-dialog.tsx
index f46275f4..98717a9d 100644
--- a/notfair-cmo/src/components/create-agent-dialog.tsx
+++ b/notfair-cmo/src/components/create-agent-dialog.tsx
@@ -24,7 +24,7 @@ import {
} from "@/server/actions/agents";
import { slugify } from "@/lib/slug";
import { projectHref } from "@/lib/project-href";
-import type { CloneAgentResult } from "@/server/openclaw/clone-agent";
+import type { CloneAgentResult } from "@/server/agents/clone";
import { DisableSourceCronsDialog } from "./disable-source-crons-dialog";
type Mode = "create" | "clone";
@@ -147,7 +147,7 @@ export function CreateAgentDialog({ open, onOpenChange, projectSlug }: Props) {
<DialogHeader>
<DialogTitle>New agent</DialogTitle>
<DialogDescription>
- Add a fresh agent to this project, or clone one of your existing OpenClaw agents.
+ Add a fresh agent to this project, or clone one of the existing agents.
</DialogDescription>
</DialogHeader>
diff --git a/notfair-cmo/src/components/danger-zone.tsx b/notfair-cmo/src/components/danger-zone.tsx
index 2fa052fb..dce6b868 100644
--- a/notfair-cmo/src/components/danger-zone.tsx
+++ b/notfair-cmo/src/components/danger-zone.tsx
@@ -17,7 +17,7 @@ import {
getProjectDeletionSummaryAction,
deleteProjectAction,
} from "@/server/actions/projects";
-import type { ProjectDeletionSummary } from "@/server/openclaw/project-delete";
+import type { ProjectDeletionSummary } from "@/server/agents/cascade-delete";
type Props = {
projectSlug: string;
@@ -105,7 +105,7 @@ export function DangerZone({ projectSlug, projectName }: Props) {
Delete &ldquo;{projectName}&rdquo;?
</DialogTitle>
<DialogDescription>
- This will permanently delete the items below from OpenClaw and notfair-cmo&apos;s
+ This will permanently delete the items below from notfair-cmo&apos;s
local store. There is no recovery.
</DialogDescription>
</DialogHeader>
diff --git a/notfair-cmo/src/components/disable-source-crons-dialog.tsx b/notfair-cmo/src/components/disable-source-crons-dialog.tsx
index e8ab8212..46c7d0d2 100644
--- a/notfair-cmo/src/components/disable-source-crons-dialog.tsx
+++ b/notfair-cmo/src/components/disable-source-crons-dialog.tsx
@@ -13,7 +13,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { disableCronsAction } from "@/server/actions/agents";
-import type { CloneSourceCron } from "@/server/openclaw/clone-agent";
+import type { CloneSourceCron } from "@/server/agents/clone";
type Props = {
open: boolean;
diff --git a/notfair-cmo/src/components/global-liveness-poller.test.tsx b/notfair-cmo/src/components/global-liveness-poller.test.tsx
deleted file mode 100644
index 54c4aa98..00000000
--- a/notfair-cmo/src/components/global-liveness-poller.test.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
-import { act, cleanup, render } from "@testing-library/react";
-
-const refresh = vi.fn();
-
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ refresh }),
-}));
-
-import { GlobalLivenessPoller } from "./global-liveness-poller";
-
-// Fake fetch backed by a queue of payloads. The poller hashes the
-// response and only calls router.refresh() when the hash changes — so
-// these tests are about the queue → refresh-count mapping.
-type Payload = { project: string | null; agents: Record<string, number>; approvals: number };
-let payloadQueue: Payload[] = [];
-const fetchMock = vi.fn(async () => {
- const next = payloadQueue.shift() ?? STABLE_PAYLOAD;
- return new Response(JSON.stringify(next), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
-});
-
-const STABLE_PAYLOAD: Payload = {
- project: "acme",
- agents: { "acme-cmo-greg": 1 },
- approvals: 0,
-};
-
-beforeEach(() => {
- refresh.mockReset();
- fetchMock.mockClear();
- payloadQueue = [];
- globalThis.fetch = fetchMock as unknown as typeof fetch;
- vi.useFakeTimers();
-});
-
-afterEach(() => {
- cleanup();
- vi.useRealTimers();
-});
-
-// Flush in-flight microtasks (the async fetch + await chain) inside the
-// fake-timer regime so the signature-tracking effect runs before we
-// assert.
-async function flushAsync() {
- await act(async () => {
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- });
-}
-
-describe("GlobalLivenessPoller", () => {
- it("renders nothing in the DOM", () => {
- const { container } = render(<GlobalLivenessPoller hasInFlight={true} />);
- expect(container.firstChild).toBeNull();
- });
-
- it("does not poll when hasInFlight is false", async () => {
- render(<GlobalLivenessPoller hasInFlight={false} />);
- act(() => {
- vi.advanceTimersByTime(20_000);
- });
- await flushAsync();
- expect(fetchMock).not.toHaveBeenCalled();
- expect(refresh).not.toHaveBeenCalled();
- });
-
- it("polls every 2 s but does NOT call router.refresh when signature is unchanged", async () => {
- payloadQueue = [STABLE_PAYLOAD, STABLE_PAYLOAD, STABLE_PAYLOAD];
- render(<GlobalLivenessPoller hasInFlight={true} />);
- await flushAsync(); // initial seed fetch
- act(() => {
- vi.advanceTimersByTime(2_000);
- });
- await flushAsync();
- act(() => {
- vi.advanceTimersByTime(2_000);
- });
- await flushAsync();
- // 1 seed + 2 ticks = 3 fetches. No refresh because signature is stable.
- expect(fetchMock.mock.calls.length).toBeGreaterThanOrEqual(3);
- expect(refresh).not.toHaveBeenCalled();
- });
-
- it("calls router.refresh exactly when the signature changes", async () => {
- payloadQueue = [
- STABLE_PAYLOAD, // seed
- { ...STABLE_PAYLOAD, agents: { "acme-cmo-greg": 2 } }, // first tick — change!
- { ...STABLE_PAYLOAD, agents: { "acme-cmo-greg": 2 } }, // second tick — same as first
- { ...STABLE_PAYLOAD, agents: { "acme-cmo-greg": 0 } }, // third tick — change!
- ];
- render(<GlobalLivenessPoller hasInFlight={true} />);
- await flushAsync();
- act(() => {
- vi.advanceTimersByTime(2_000);
- });
- await flushAsync();
- expect(refresh).toHaveBeenCalledTimes(1);
- act(() => {
- vi.advanceTimersByTime(2_000);
- });
- await flushAsync();
- expect(refresh).toHaveBeenCalledTimes(1); // unchanged tick — no refresh
- act(() => {
- vi.advanceTimersByTime(2_000);
- });
- await flushAsync();
- expect(refresh).toHaveBeenCalledTimes(2); // change again — refresh
- });
-
- it("tears the interval down when hasInFlight flips to false", async () => {
- payloadQueue = [STABLE_PAYLOAD, { ...STABLE_PAYLOAD, approvals: 1 }];
- const { rerender } = render(<GlobalLivenessPoller hasInFlight={true} />);
- await flushAsync();
- act(() => {
- vi.advanceTimersByTime(2_000);
- });
- await flushAsync();
- expect(refresh).toHaveBeenCalledTimes(1);
- rerender(<GlobalLivenessPoller hasInFlight={false} />);
- fetchMock.mockClear();
- refresh.mockClear();
- act(() => {
- vi.advanceTimersByTime(30_000);
- });
- await flushAsync();
- expect(fetchMock).not.toHaveBeenCalled();
- expect(refresh).not.toHaveBeenCalled();
- });
-
- it("clears the interval on unmount so no stray refreshes fire", async () => {
- payloadQueue = [STABLE_PAYLOAD];
- const { unmount } = render(<GlobalLivenessPoller hasInFlight={true} />);
- await flushAsync();
- unmount();
- fetchMock.mockClear();
- act(() => {
- vi.advanceTimersByTime(60_000);
- });
- await flushAsync();
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it("starts a fresh interval if hasInFlight flips back to true after being false", async () => {
- const { rerender } = render(<GlobalLivenessPoller hasInFlight={false} />);
- act(() => {
- vi.advanceTimersByTime(10_000);
- });
- await flushAsync();
- expect(fetchMock).not.toHaveBeenCalled();
- payloadQueue = [STABLE_PAYLOAD, { ...STABLE_PAYLOAD, approvals: 5 }];
- rerender(<GlobalLivenessPoller hasInFlight={true} />);
- await flushAsync();
- act(() => {
- vi.advanceTimersByTime(2_000);
- });
- await flushAsync();
- expect(refresh).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/notfair-cmo/src/components/global-liveness-poller.tsx b/notfair-cmo/src/components/global-liveness-poller.tsx
deleted file mode 100644
index 61358bf9..00000000
--- a/notfair-cmo/src/components/global-liveness-poller.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-"use client";
-
-import { useEffect, useRef } from "react";
-import { useRouter } from "next/navigation";
-
-/**
- * Lives in the app sidebar (rendered on every route), so the sidebar's
- * per-agent live-task badges + the per-page task list groups stay fresh
- * no matter where the user is sitting — /home, /approvals, /tasks, an
- * agent workspace, etc. — while something is in flight somewhere.
- *
- * Replaces the workspace-scoped AgentLivenessPoller. Same idea, just
- * lifted to the layout level so non-workspace pages don't go stale.
- *
- * Strategy: poll a small JSON endpoint at /api/in-flight-counts, hash
- * the response, and ONLY call router.refresh() when the hash differs
- * from the previous one. Calling router.refresh() unconditionally on
- * every tick re-renders the whole sidebar subtree which made it
- * visibly blink even when nothing changed. With the signature gate,
- * steady-state polling is silent.
- *
- * Cadence: 2 s while `hasInFlight` is true. The first refresh that lands
- * a server-rendered `hasInFlight = false` flips the prop, the effect
- * tears the interval down, and we stop spending requests on idle state.
- */
-export function GlobalLivenessPoller({ hasInFlight }: { hasInFlight: boolean }) {
- const router = useRouter();
- const lastSignatureRef = useRef<string | null>(null);
- useEffect(() => {
- if (!hasInFlight) return;
- let cancelled = false;
-
- async function tick() {
- try {
- const r = await fetch("/api/in-flight-counts", {
- cache: "no-store",
- credentials: "same-origin",
- });
- if (!r.ok) return;
- const body = (await r.json()) as {
- project: string | null;
- agents: Record<string, number>;
- approvals: number;
- };
- // Canonical signature: same shape ⇒ same string. Sort the agent
- // keys so map-iteration order doesn't generate a false-positive.
- 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,
- });
- if (cancelled) return;
- if (lastSignatureRef.current !== null && lastSignatureRef.current !== sig) {
- router.refresh();
- }
- lastSignatureRef.current = sig;
- } catch {
- // Network/JSON hiccup — skip this tick; we'll catch up next.
- }
- }
- // Seed the signature on mount so the first real change triggers
- // a refresh (otherwise the very first tick would always refresh).
- void tick();
- const interval = setInterval(tick, 2_000);
- return () => {
- cancelled = true;
- clearInterval(interval);
- };
- }, [hasInFlight, router]);
- return null;
-}
diff --git a/notfair-cmo/src/components/google-ads-mcp-banner.test.tsx b/notfair-cmo/src/components/google-ads-mcp-banner.test.tsx
index fa9670ca..8cb4c5c7 100644
--- a/notfair-cmo/src/components/google-ads-mcp-banner.test.tsx
+++ b/notfair-cmo/src/components/google-ads-mcp-banner.test.tsx
@@ -19,7 +19,7 @@ vi.mock("sonner", () => ({
}));
import { GoogleAdsMcpBanner } from "./google-ads-mcp-banner";
-import type { McpRuntimeStatus } from "@/server/mcp-state";
+import type { McpRuntimeStatus } from "@/server/mcp/state";
const SLUG = "acme";
diff --git a/notfair-cmo/src/components/google-ads-mcp-banner.tsx b/notfair-cmo/src/components/google-ads-mcp-banner.tsx
index f6e363b2..34e68d18 100644
--- a/notfair-cmo/src/components/google-ads-mcp-banner.tsx
+++ b/notfair-cmo/src/components/google-ads-mcp-banner.tsx
@@ -6,7 +6,7 @@ import { Loader2, Plug, AlertTriangle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { startMcpConnect } from "@/server/actions/mcp";
-import type { McpRuntimeStatus } from "@/server/mcp-state";
+import type { McpRuntimeStatus } from "@/server/mcp/state";
import { projectHref } from "@/lib/project-href";
type Props = {
diff --git a/notfair-cmo/src/components/live-badge.tsx b/notfair-cmo/src/components/live-badge.tsx
new file mode 100644
index 00000000..f55ed955
--- /dev/null
+++ b/notfair-cmo/src/components/live-badge.tsx
@@ -0,0 +1,18 @@
+"use client";
+
+import { Badge } from "@/components/ui/badge";
+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.
+ */
+export function ApprovalsLiveBadge() {
+ const count = useApprovalsBadge();
+ if (count <= 0) return null;
+ return (
+ <Badge variant="secondary" className="ml-auto h-5 px-1.5 text-[10px]">
+ {count}
+ </Badge>
+ );
+}
diff --git a/notfair-cmo/src/components/live-counts-context.test.tsx b/notfair-cmo/src/components/live-counts-context.test.tsx
new file mode 100644
index 00000000..8c355673
--- /dev/null
+++ b/notfair-cmo/src/components/live-counts-context.test.tsx
@@ -0,0 +1,101 @@
+/**
+ * @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,
+};
+
+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
new file mode 100644
index 00000000..f9bf0a18
--- /dev/null
+++ b/notfair-cmo/src/components/live-counts-context.tsx
@@ -0,0 +1,116 @@
+"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 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;
+}
+
+const LiveCountsContext = createContext<LiveCounts>({
+ project: null,
+ agents: {},
+ approvals: 0,
+});
+
+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,
+ });
+ if (sigRef.current === sig) return;
+ sigRef.current = sig;
+ setCounts(body);
+ } 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
index 2ada6db2..9491dbdd 100644
--- a/notfair-cmo/src/components/live-transcript.test.tsx
+++ b/notfair-cmo/src/components/live-transcript.test.tsx
@@ -33,7 +33,7 @@ vi.mock("@/components/markdown", () => ({
}));
import { LiveTranscript } from "./live-transcript";
-import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
+import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
type FetchHandler = (url: string, init?: RequestInit) => Promise<Response>;
diff --git a/notfair-cmo/src/components/live-transcript.tsx b/notfair-cmo/src/components/live-transcript.tsx
index 5993515e..e3490567 100644
--- a/notfair-cmo/src/components/live-transcript.tsx
+++ b/notfair-cmo/src/components/live-transcript.tsx
@@ -41,7 +41,7 @@ import {
parseSlashMessage,
type SlashCommand,
} from "@/lib/slash-commands";
-import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
+import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
import { projectHref } from "@/lib/project-href";
const POLL_INTERVAL_MS = 2_000;
@@ -1279,6 +1279,15 @@ function deriveWorkingView(input: {
turnStartedAt != null
? events.filter((e) => e.ts >= turnStartedAt)
: events;
+ // Turn-ended signal: the harness emits a `final` event when its run
+ // completes; transcript-tail surfaces it as `{ kind: "lifecycle",
+ // phase: "done" }`. Once we've seen it, the agent has stopped
+ // producing tokens — keep the trajectory chips but stop the spinning
+ // "Wrapping up" pill (which otherwise rolls on indefinitely while the
+ // task waits for the agent's now-missing `submit_task_status` call).
+ const turnEnded = turnEvents.some(
+ (e) => e.kind === "lifecycle" && e.phase === "done",
+ );
const lastEvent = turnEvents.length > 0 ? turnEvents[turnEvents.length - 1] : null;
const pendingInFlightTool = pendingTools.find((t) => !t.done) ?? null;
const inFlightCommittedToolCall: Extract<
@@ -1293,6 +1302,21 @@ function deriveWorkingView(input: {
})();
const phases = buildPhases(turnEvents, pendingTools);
+ // Highest precedence: the run has ended cleanly. Don't lie to the user
+ // by showing "Wrapping up" with a spinner for what is in fact a
+ // completed turn that's now parked waiting for the agent to either
+ // call submit_task_status (which it forgot) or for the user to
+ // intervene.
+ if (turnEnded && !pendingInFlightTool && !hasPendingAssistant) {
+ return {
+ headline: "Turn ended",
+ subtitle:
+ "Agent stopped without closing the task — open Approvals or send a follow-up.",
+ phases,
+ mood: "ended",
+ };
+ }
+
if (pendingInFlightTool) {
return {
headline: `Calling ${formatToolName(pendingInFlightTool.name)}`,
diff --git a/notfair-cmo/src/components/mcp-card.test.tsx b/notfair-cmo/src/components/mcp-card.test.tsx
index 342fdc30..d26d70f2 100644
--- a/notfair-cmo/src/components/mcp-card.test.tsx
+++ b/notfair-cmo/src/components/mcp-card.test.tsx
@@ -34,7 +34,7 @@ vi.mock("sonner", () => ({
import { McpCard } from "./mcp-card";
import type { McpSpec } from "@/server/mcp-catalog";
-import type { McpRuntimeStatus } from "@/server/mcp-state";
+import type { McpRuntimeStatus } from "@/server/mcp/state";
const spec: McpSpec = {
key: "notfair-googleads",
diff --git a/notfair-cmo/src/components/mcp-card.tsx b/notfair-cmo/src/components/mcp-card.tsx
index 49602f08..449a7cc8 100644
--- a/notfair-cmo/src/components/mcp-card.tsx
+++ b/notfair-cmo/src/components/mcp-card.tsx
@@ -21,7 +21,7 @@ import {
listMcpToolsAction,
} from "@/server/actions/mcp";
import type { McpSpec } from "@/server/mcp-catalog";
-import type { McpRuntimeStatus } from "@/server/mcp-state";
+import type { McpRuntimeStatus } from "@/server/mcp/state";
import { McpToolsDialog } from "@/components/mcp-tools-dialog";
type Props = {
@@ -226,8 +226,8 @@ function StatusDetail({ status }: { status: McpRuntimeStatus }) {
case "not_configured":
return (
<p className="text-xs text-muted-foreground">
- One click runs the OAuth flow against the issuer and saves the token to
- your local OpenClaw config.
+ One click runs the OAuth flow against the issuer and saves the token
+ locally to this project.
</p>
);
}
diff --git a/notfair-cmo/src/components/onboarding-flow.tsx b/notfair-cmo/src/components/onboarding-flow.tsx
index 9d39cfa1..e82e98e5 100644
--- a/notfair-cmo/src/components/onboarding-flow.tsx
+++ b/notfair-cmo/src/components/onboarding-flow.tsx
@@ -264,6 +264,7 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
top-level files. Skim only, not a code review.
</p>
</div>
+ <HarnessPicker disabled={isPending} />
{errorMessage && (
<p role="alert" className="text-sm text-destructive">
{errorMessage}
@@ -280,6 +281,75 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
);
}
+// ── Harness picker ─────────────────────────────────────────────────
+//
+// Two recommended adapters: Claude Code (default) and Codex. Persisted on
+// the project row so different projects can use different harnesses. The
+// chosen CLI must be on PATH when chats run — adapter testEnvironment is
+// surfaced via the doctor command for diagnostic feedback.
+
+function HarnessPicker({ disabled }: { disabled: boolean }) {
+ const [value, setValue] = useState<"claude-code-local" | "codex-local">(
+ "claude-code-local",
+ );
+ const options: Array<{
+ id: "claude-code-local" | "codex-local";
+ label: string;
+ description: string;
+ }> = [
+ {
+ id: "claude-code-local",
+ label: "Claude Code",
+ description: "Uses your local `claude` CLI. Recommended.",
+ },
+ {
+ id: "codex-local",
+ label: "Codex",
+ description: "Uses your local `codex` CLI.",
+ },
+ ];
+ return (
+ <div className="rounded-md border border-dashed bg-muted/30 p-3 space-y-3">
+ <div className="space-y-1">
+ <Label className="text-xs uppercase tracking-wide text-muted-foreground">
+ AI agent runtime
+ </Label>
+ <p className="text-xs text-muted-foreground">
+ Pick which local CLI runs your agents. You can have different
+ projects on different harnesses.
+ </p>
+ </div>
+ <input type="hidden" name="harness_adapter" value={value} />
+ <div className="grid grid-cols-2 gap-2">
+ {options.map((opt) => (
+ <button
+ key={opt.id}
+ type="button"
+ 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",
+ value === opt.id
+ ? "border-foreground bg-background"
+ : "border-border bg-background/40 hover:bg-background/80",
+ disabled && "opacity-60",
+ )}
+ aria-pressed={value === opt.id}
+ >
+ <div className="flex w-full items-center justify-between">
+ <span className="text-sm font-medium text-foreground">{opt.label}</span>
+ <span className="rounded-full bg-emerald-500/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-emerald-700 dark:text-emerald-300">
+ Recommended
+ </span>
+ </div>
+ <span className="text-xs text-muted-foreground">{opt.description}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
// ── Step 2: Connect ────────────────────────────────────────────────
function ConnectStep({ slug }: { slug: string }) {
diff --git a/notfair-cmo/src/components/paired-openclaw-pill.test.tsx b/notfair-cmo/src/components/paired-openclaw-pill.test.tsx
deleted file mode 100644
index c58170c2..00000000
--- a/notfair-cmo/src/components/paired-openclaw-pill.test.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
-import { cleanup, render, screen } from "@testing-library/react";
-
-const discoverGateway = vi.fn();
-
-vi.mock("@/server/openclaw/gateway-client", () => ({
- discoverGateway: () => discoverGateway(),
-}));
-
-import { PairedOpenclawPill } from "./paired-openclaw-pill";
-
-afterEach(() => cleanup());
-
-beforeEach(() => {
- discoverGateway.mockReset();
-});
-
-describe("PairedOpenclawPill", () => {
- it("renders the pill linking to the dashboard with a token fragment when the gateway is paired", () => {
- discoverGateway.mockReturnValue({
- url: "ws://127.0.0.1:7788",
- token: "secret/token+abc",
- configFile: "/tmp/openclaw.json",
- });
- render(<PairedOpenclawPill />);
- const link = screen.getByRole("link");
- expect(link).toBeInTheDocument();
- expect(link).toHaveAttribute(
- "href",
- `http://127.0.0.1:7788/#token=${encodeURIComponent("secret/token+abc")}`,
- );
- expect(link).toHaveAttribute("target", "_blank");
- expect(link).toHaveAttribute("rel", "noopener noreferrer");
- expect(link).toHaveAttribute("title", "Open OpenClaw dashboard");
- expect(screen.getByText("Paired OpenClaw")).toBeInTheDocument();
- });
-
- it("rewrites a wss:// gateway url to https:// for the dashboard link", () => {
- discoverGateway.mockReturnValue({
- url: "wss://gateway.example:8443",
- token: "t",
- configFile: "/tmp/openclaw.json",
- });
- render(<PairedOpenclawPill />);
- const link = screen.getByRole("link");
- expect(link.getAttribute("href")).toMatch(/^https:\/\/gateway\.example:8443\/#token=t$/);
- });
-
- it("omits the token fragment when the gateway has no token", () => {
- discoverGateway.mockReturnValue({
- url: "ws://127.0.0.1:7788",
- configFile: "/tmp/openclaw.json",
- });
- render(<PairedOpenclawPill />);
- const link = screen.getByRole("link");
- expect(link).toHaveAttribute("href", "http://127.0.0.1:7788/");
- expect(link.getAttribute("href")).not.toContain("#token=");
- });
-
- it("renders nothing when discoverGateway throws (no OpenClaw config)", () => {
- discoverGateway.mockImplementation(() => {
- throw new Error("config not found");
- });
- const { container } = render(<PairedOpenclawPill />);
- expect(container.firstChild).toBeNull();
- expect(screen.queryByRole("link")).not.toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/paired-openclaw-pill.tsx b/notfair-cmo/src/components/paired-openclaw-pill.tsx
deleted file mode 100644
index 01baa7cc..00000000
--- a/notfair-cmo/src/components/paired-openclaw-pill.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { ExternalLink } from "lucide-react";
-import { discoverGateway } from "@/server/openclaw/gateway-client";
-import { cn } from "@/lib/utils";
-
-/**
- * Sidebar pill that opens the OpenClaw gateway dashboard in a new tab with
- * token-based auto-auth. The token is embedded in the URL fragment (`#token=`)
- * — same mechanism `openclaw dashboard` uses — so it isn't sent to the server
- * in the HTTP request line. We render nothing when the gateway config can't
- * be discovered (rather than a broken-looking pill).
- */
-export function PairedOpenclawPill() {
- let dashboardUrl: string | null = null;
- try {
- const gw = discoverGateway();
- // gw.url is ws://host:port — the dashboard lives at the same host:port
- // over http. Token goes in the fragment so it never hits server access
- // logs or HTTP referer headers.
- const httpBase = gw.url.replace(/^ws/, "http");
- dashboardUrl = gw.token
- ? `${httpBase}/#token=${encodeURIComponent(gw.token)}`
- : `${httpBase}/`;
- } catch {
- return null;
- }
-
- return (
- <a
- href={dashboardUrl}
- target="_blank"
- rel="noopener noreferrer"
- className={cn(
- "group inline-flex w-full items-center gap-2 rounded-full",
- "border border-border bg-background px-3 py-1.5",
- "text-xs font-medium text-foreground",
- "transition-colors hover:bg-sidebar-accent",
- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
- // In icon-collapsed sidebar, keep the dot visible and hide the label.
- "group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-2",
- )}
- title="Open OpenClaw dashboard"
- >
- <span
- aria-hidden
- className="size-2 shrink-0 rounded-full bg-emerald-500"
- />
- <span className="flex-1 truncate group-data-[collapsible=icon]:hidden">
- Paired OpenClaw
- </span>
- <ExternalLink
- className="size-3.5 shrink-0 text-muted-foreground group-data-[collapsible=icon]:hidden"
- aria-hidden
- />
- </a>
- );
-}
diff --git a/notfair-cmo/src/components/schedule-cron-dialog.tsx b/notfair-cmo/src/components/schedule-cron-dialog.tsx
index 56048383..cd103fd2 100644
--- a/notfair-cmo/src/components/schedule-cron-dialog.tsx
+++ b/notfair-cmo/src/components/schedule-cron-dialog.tsx
@@ -110,7 +110,7 @@ export function ScheduleCronDialog({ projectSlug, defaultSpecialist, variant = "
<DialogHeader>
<DialogTitle>Schedule recurring work</DialogTitle>
<DialogDescription>
- Creates an OpenClaw cron under this project. The brief is the message the
+ Creates a scheduled job under this project. The brief is the message the
agent will receive on each tick.
</DialogDescription>
</DialogHeader>
@@ -144,7 +144,7 @@ export function ScheduleCronDialog({ projectSlug, defaultSpecialist, variant = "
maxLength={64}
/>
<p className="text-[11px] text-muted-foreground">
- Kebab-case. Becomes part of the cron name shown in OpenClaw.
+ Kebab-case. Becomes the scheduled job's display name.
</p>
</div>
diff --git a/notfair-cmo/src/components/skills-list.tsx b/notfair-cmo/src/components/skills-list.tsx
index 26554e65..3396a56a 100644
--- a/notfair-cmo/src/components/skills-list.tsx
+++ b/notfair-cmo/src/components/skills-list.tsx
@@ -6,7 +6,7 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
-import type { SkillEntry } from "@/server/openclaw/gateway-rpc";
+import type { SkillEntry } from "@/server/agents/skills";
import { setSkillEnabledAction } from "@/server/actions/skills";
type FilterKey = "all" | "enabled" | "disabled";
diff --git a/notfair-cmo/src/components/start-all-tasks-button.tsx b/notfair-cmo/src/components/start-all-tasks-button.tsx
index 13cb635e..7d0835e6 100644
--- a/notfair-cmo/src/components/start-all-tasks-button.tsx
+++ b/notfair-cmo/src/components/start-all-tasks-button.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useTransition } from "react";
+import { startTransition as scheduleTransition, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Loader2, Play } from "lucide-react";
import { toast } from "sonner";
@@ -40,12 +40,18 @@ export function StartAllTasksButton({
toast.success(
`Started ${result.data.started} task${result.data.started === 1 ? "" : "s"}.`,
);
- router.refresh();
+ // 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(() => router.refresh(), 3_000);
+ const intervalId = setInterval(
+ () => scheduleTransition(() => router.refresh()),
+ 3_000,
+ );
const timeoutId = setTimeout(() => {
clearInterval(intervalId);
setPolling(false);
diff --git a/notfair-cmo/src/components/working-indicator.tsx b/notfair-cmo/src/components/working-indicator.tsx
index 1593be88..8f8c8fb8 100644
--- a/notfair-cmo/src/components/working-indicator.tsx
+++ b/notfair-cmo/src/components/working-indicator.tsx
@@ -35,7 +35,7 @@ export type WorkingPhase = {
state: "done" | "active" | "failed";
};
-export type WorkingMood = "waiting" | "tool" | "writing" | "wrapping";
+export type WorkingMood = "waiting" | "tool" | "writing" | "wrapping" | "ended";
export function WorkingIndicator({
agentDisplayName,
@@ -372,4 +372,17 @@ const MOOD_PALETTES: Record<WorkingMood, MoodPalette> = {
accentText: "text-amber-700 dark:text-amber-300",
beam: "hsl(38 92% 55%)",
},
+ ended: {
+ // Muted slate — visually static, no urgency. The aurora bar + dot
+ // heartbeat still animate per shared component, but the cold palette
+ // reads as "done, parked" rather than "actively working".
+ ring: "ring-slate-500/15",
+ dotBg: "bg-slate-500",
+ haloBg: "bg-slate-400/30",
+ chipBg: "bg-slate-500/10",
+ chipText: "text-slate-700 dark:text-slate-300",
+ chipRing: "ring-slate-500/30",
+ accentText: "text-slate-700 dark:text-slate-300",
+ beam: "hsl(215 16% 60%)",
+ },
};
diff --git a/notfair-cmo/src/server/actions/agents.test.ts b/notfair-cmo/src/server/actions/agents.test.ts
deleted file mode 100644
index 8b185523..00000000
--- a/notfair-cmo/src/server/actions/agents.test.ts
+++ /dev/null
@@ -1,705 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const revalidatePathMock = vi.fn();
-vi.mock("next/cache", () => ({
- revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),
-}));
-
-const getActiveProjectMock = vi.fn();
-vi.mock("@/server/active-project", () => ({
- getActiveProject: (...args: unknown[]) => getActiveProjectMock(...args),
-}));
-
-const disableCronMock = vi.fn();
-const listCronsForProjectMock = vi.fn();
-const removeCronMock = vi.fn();
-vi.mock("@/server/openclaw/crons", () => ({
- disableCron: (...args: unknown[]) => disableCronMock(...args),
- listCronsForProject: (...args: unknown[]) => listCronsForProjectMock(...args),
- removeCron: (...args: unknown[]) => removeCronMock(...args),
-}));
-
-const createAgentViaRpcMock = vi.fn();
-const deleteAgentMock = vi.fn();
-const listAllAgentsMock = vi.fn();
-vi.mock("@/server/openclaw/gateway-rpc", () => ({
- createAgentViaRpc: (...args: unknown[]) => createAgentViaRpcMock(...args),
- deleteAgent: (...args: unknown[]) => deleteAgentMock(...args),
- listAllAgents: (...args: unknown[]) => listAllAgentsMock(...args),
-}));
-
-const agentExistsInProjectMock = vi.fn();
-const cloneAgentMock = vi.fn();
-vi.mock("@/server/openclaw/clone-agent", () => ({
- agentExistsInProject: (...args: unknown[]) => agentExistsInProjectMock(...args),
- cloneAgent: (...args: unknown[]) => cloneAgentMock(...args),
-}));
-
-const readAgentMetaMock = vi.fn();
-const writeAgentMetaMock = vi.fn();
-const workspaceDirForMock = vi.fn();
-const listProjectAgentsMock = vi.fn();
-vi.mock("@/server/agent-meta", () => ({
- readAgentMeta: (...args: unknown[]) => readAgentMetaMock(...args),
- writeAgentMeta: (...args: unknown[]) => writeAgentMetaMock(...args),
- workspaceDirFor: (...args: unknown[]) => workspaceDirForMock(...args),
- listProjectAgents: (...args: unknown[]) => listProjectAgentsMock(...args),
-}));
-
-const listSessionsForAgentMock = vi.fn();
-vi.mock("@/server/openclaw/sessions", () => ({
- listSessionsForAgent: (...args: unknown[]) => listSessionsForAgentMock(...args),
-}));
-
-const existsSyncMock = vi.fn();
-const rmMock = vi.fn();
-vi.mock("node:fs", async (importOriginal) => {
- const actual = await importOriginal<typeof import("node:fs")>();
- return {
- ...actual,
- existsSync: (...args: unknown[]) => existsSyncMock(...args),
- };
-});
-vi.mock("node:fs/promises", async (importOriginal) => {
- const actual = await importOriginal<typeof import("node:fs/promises")>();
- return {
- ...actual,
- rm: (...args: unknown[]) => rmMock(...args),
- };
-});
-
-import {
- cascadeDeleteAgent,
- cloneAgentAction,
- createAgentAction,
- deleteAgentCascadeAction,
- disableCronsAction,
- getAgentDeletionSummaryAction,
- listOpenClawAgentsAction,
- listProjectAgentsAction,
- relocateAgent,
- removeCronsAction,
- renameAgentAction,
-} from "./agents";
-
-function project(slug = "acme") {
- return {
- id: "uuid",
- slug,
- display_name: "Acme",
- created_at: "now",
- archived_at: null,
- google_ads_account_id: null,
- };
-}
-
-beforeEach(() => {
- revalidatePathMock.mockReset();
- getActiveProjectMock.mockReset();
- disableCronMock.mockReset();
- listCronsForProjectMock.mockReset();
- removeCronMock.mockReset();
- createAgentViaRpcMock.mockReset();
- deleteAgentMock.mockReset();
- listAllAgentsMock.mockReset();
- agentExistsInProjectMock.mockReset();
- cloneAgentMock.mockReset();
- readAgentMetaMock.mockReset();
- writeAgentMetaMock.mockReset();
- workspaceDirForMock.mockReset();
- listProjectAgentsMock.mockReset();
- listSessionsForAgentMock.mockReset();
- existsSyncMock.mockReset();
- rmMock.mockReset();
-
- workspaceDirForMock.mockImplementation((id: string) => `/ws/${id}`);
-});
-
-describe("listOpenClawAgentsAction", () => {
- it("merges openclaw list with project agent ids and marks membership", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- listProjectAgentsMock.mockResolvedValueOnce([
- { agent_id: "acme-cmo", slug: "cmo-greg", name: "Greg", template_key: "cmo", is_template_default: true },
- ]);
- listAllAgentsMock.mockResolvedValueOnce({
- agents: [
- { id: "acme-cmo", name: "fallback", identity: { name: "CMO" } },
- { id: "other-agent", name: "Other Agent" },
- ],
- });
- const r = await listOpenClawAgentsAction();
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data).toHaveLength(2);
- const cmo = r.data.find((a) => a.agent_id === "acme-cmo")!;
- expect(cmo.in_current_project).toBe(true);
- expect(cmo.display_name).toBe("CMO");
- const other = r.data.find((a) => a.agent_id === "other-agent")!;
- expect(other.in_current_project).toBe(false);
- expect(other.display_name).toBe("Other Agent");
- });
-
- it("falls back to id when no identity name or name present", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- listAllAgentsMock.mockResolvedValueOnce({
- agents: [{ id: "raw-id" }],
- });
- const r = await listOpenClawAgentsAction();
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data[0]!.display_name).toBe("raw-id");
- expect(r.data[0]!.in_current_project).toBe(false);
- });
-
- it("returns error result when listAllAgents throws", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- listAllAgentsMock.mockRejectedValueOnce(new Error("gateway down"));
- const r = await listOpenClawAgentsAction();
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/gateway down/);
- });
-
- it("returns error result with stringified non-Error", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- listAllAgentsMock.mockRejectedValueOnce("boom");
- const r = await listOpenClawAgentsAction();
- expect(r.ok).toBe(false);
- });
-});
-
-describe("listProjectAgentsAction", () => {
- it("returns error when no active project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const r = await listProjectAgentsAction();
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/No active project/);
- });
-
- it("returns project agents on happy path", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- listProjectAgentsMock.mockResolvedValueOnce([
- { agent_id: "acme-cmo", slug: "cmo-greg", name: "Greg", template_key: "cmo", is_template_default: true },
- ]);
- const r = await listProjectAgentsAction();
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data).toHaveLength(1);
- });
-
- it("returns error when listProjectAgents throws", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- listProjectAgentsMock.mockRejectedValueOnce(new Error("disk fail"));
- const r = await listProjectAgentsAction();
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/disk fail/);
- });
-});
-
-describe("createAgentAction", () => {
- it("rejects when no active project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const r = await createAgentAction({ display_name: "Foo" });
- expect(r.ok).toBe(false);
- });
-
- it("rejects when display_name is empty (slugify fails)", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- const r = await createAgentAction({ display_name: "" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/Invalid name/);
- });
-
- it("rejects when an agent with the same slug already exists in the project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- agentExistsInProjectMock.mockReturnValueOnce(true);
- const r = await createAgentAction({ display_name: "Supa" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/already exists/);
- });
-
- it("creates the agent, writes meta, revalidates layout on success", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- agentExistsInProjectMock.mockReturnValueOnce(false);
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
- writeAgentMetaMock.mockResolvedValueOnce(undefined);
- const r = await createAgentAction({ display_name: "Supa Agent" });
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.agent_id).toBe("acme-supa-agent");
- expect(r.data.slug).toBe("supa-agent");
- expect(createAgentViaRpcMock).toHaveBeenCalledWith({
- name: "acme-supa-agent",
- workspace: "/ws/acme-supa-agent",
- });
- expect(writeAgentMetaMock).toHaveBeenCalled();
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("returns error when createAgentViaRpc throws", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- agentExistsInProjectMock.mockReturnValueOnce(false);
- createAgentViaRpcMock.mockRejectedValueOnce(new Error("rpc failed"));
- const r = await createAgentAction({ display_name: "Supa" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/rpc failed/);
- expect(revalidatePathMock).not.toHaveBeenCalled();
- });
-});
-
-describe("cloneAgentAction", () => {
- it("rejects when no active project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const r = await cloneAgentAction({
- source_agent_id: "acme-cmo",
- new_display_name: "Clone",
- });
- expect(r.ok).toBe(false);
- });
-
- it("rejects when both new_display_name and new_slug are empty/whitespace", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- const r = await cloneAgentAction({
- source_agent_id: "acme-cmo",
- new_display_name: " ",
- });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/provide a name/);
- });
-
- it("calls cloneAgent with overridden new_slug and revalidates", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- cloneAgentMock.mockResolvedValueOnce({
- new_agent_id: "acme-shortie",
- new_slug: "shortie",
- files_copied: 1,
- sessions_copied: 0,
- source_crons: [],
- new_cron_ids: [],
- });
- const r = await cloneAgentAction({
- source_agent_id: "acme-cmo",
- new_display_name: "Long Name",
- new_slug: "shortie",
- });
- expect(r.ok).toBe(true);
- expect(cloneAgentMock).toHaveBeenCalledWith({
- source_agent_id: "acme-cmo",
- project_slug: "acme",
- new_slug: "shortie",
- display_name: "Long Name",
- });
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("falls back to new_display_name when new_slug is undefined", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- cloneAgentMock.mockResolvedValueOnce({
- new_agent_id: "acme-clone-name",
- new_slug: "clone-name",
- files_copied: 0,
- sessions_copied: 0,
- source_crons: [],
- new_cron_ids: [],
- });
- const r = await cloneAgentAction({
- source_agent_id: "acme-cmo",
- new_display_name: "Clone Name",
- });
- expect(r.ok).toBe(true);
- expect(cloneAgentMock).toHaveBeenCalledWith({
- source_agent_id: "acme-cmo",
- project_slug: "acme",
- new_slug: "Clone Name",
- display_name: "Clone Name",
- });
- });
-
- it("returns error on cloneAgent failure (no revalidate)", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- cloneAgentMock.mockRejectedValueOnce(new Error("clone exploded"));
- const r = await cloneAgentAction({
- source_agent_id: "acme-cmo",
- new_display_name: "Clone Name",
- });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/clone exploded/);
- expect(revalidatePathMock).not.toHaveBeenCalled();
- });
-});
-
-describe("disableCronsAction", () => {
- it("counts each disable success/failure independently", async () => {
- disableCronMock
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new Error("bad"))
- .mockResolvedValueOnce(undefined);
- const r = await disableCronsAction(["a", "b", "c"]);
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.disabled).toBe(2);
- expect(r.data.failed).toBe(1);
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("handles empty list without throwing", async () => {
- const r = await disableCronsAction([]);
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data).toEqual({ disabled: 0, failed: 0 });
- });
-});
-
-describe("removeCronsAction", () => {
- it("counts each remove success/failure independently", async () => {
- removeCronMock
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new Error("bad"));
- const r = await removeCronsAction(["a", "b"]);
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data).toEqual({ removed: 1, failed: 1 });
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-});
-
-describe("renameAgentAction", () => {
- // Agents are immutable per the identity refactor — the name set at
- // onboarding (or clone time) is permanent. The action exists only so
- // import sites keep typechecking; every call must refuse with a
- // clear, actionable error message.
- it("refuses with an immutability error", async () => {
- const r = await renameAgentAction({
- agent_id: "acme-foo",
- new_display_name: "Bar",
- });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/immutable/i);
- });
-});
-
-describe("relocateAgent", () => {
- it("clones, writes meta with preserved fields, then cascade-deletes source (best-effort)", async () => {
- cloneAgentMock.mockResolvedValueOnce({
- new_agent_id: "newproj-foo",
- new_slug: "foo",
- files_copied: 0,
- sessions_copied: 0,
- source_crons: [],
- new_cron_ids: [],
- });
- writeAgentMetaMock.mockResolvedValue(undefined);
- listCronsForProjectMock.mockResolvedValue({ groups: [] });
- deleteAgentMock.mockResolvedValue(undefined);
- existsSyncMock.mockReturnValue(false);
-
- const r = await relocateAgent({
- old_agent_id: "oldproj-foo",
- source_project_slug: "oldproj",
- new_project_slug: "newproj",
- new_slug: "foo",
- new_display_name: "Foo",
- preserve_template_key: "google_ads",
- preserve_source_agent_id: "src-id",
- preserve_created_at: "2024-01-01T00:00:00Z",
- });
- expect(r).toEqual({ new_agent_id: "newproj-foo", new_slug: "foo" });
- // Template agents don't persist `slug` on the sidecar (it's computed
- // from template_key + name). The relocate writer is expected to omit
- // it when preserve_template_key is set.
- expect(writeAgentMetaMock).toHaveBeenCalledWith(
- expect.objectContaining({
- agent_id: "newproj-foo",
- project_slug: "newproj",
- name: "Foo",
- template_key: "google_ads",
- source_agent_id: "src-id",
- created_at: "2024-01-01T00:00:00Z",
- }),
- );
- });
-
- it("swallows cascadeDeleteAgent failures so the relocate still resolves", async () => {
- cloneAgentMock.mockResolvedValueOnce({
- new_agent_id: "newproj-foo",
- new_slug: "foo",
- files_copied: 0,
- sessions_copied: 0,
- source_crons: [],
- new_cron_ids: [],
- });
- writeAgentMetaMock.mockResolvedValue(undefined);
- // make cascade fail by having deleteAgent throw unrelated error
- listCronsForProjectMock.mockResolvedValue({ groups: [] });
- deleteAgentMock.mockRejectedValue(new Error("opclaw broken"));
- existsSyncMock.mockReturnValue(false);
-
- const r = await relocateAgent({
- old_agent_id: "oldproj-foo",
- source_project_slug: "oldproj",
- new_project_slug: "newproj",
- new_slug: "foo",
- new_display_name: "Foo",
- });
- expect(r.new_agent_id).toBe("newproj-foo");
- });
-
- it("throws when cloneAgent fails (source is left intact)", async () => {
- cloneAgentMock.mockRejectedValueOnce(new Error("clone failed"));
- await expect(
- relocateAgent({
- old_agent_id: "oldproj-foo",
- source_project_slug: "oldproj",
- new_project_slug: "newproj",
- new_slug: "foo",
- new_display_name: "Foo",
- }),
- ).rejects.toThrow(/clone failed/);
- });
-
- it("uses new Date().toISOString() when no preserve_created_at is provided", async () => {
- cloneAgentMock.mockResolvedValueOnce({
- new_agent_id: "newproj-foo",
- new_slug: "foo",
- files_copied: 0,
- sessions_copied: 0,
- source_crons: [],
- new_cron_ids: [],
- });
- writeAgentMetaMock.mockResolvedValue(undefined);
- listCronsForProjectMock.mockResolvedValue({ groups: [] });
- deleteAgentMock.mockResolvedValue(undefined);
- existsSyncMock.mockReturnValue(false);
-
- await relocateAgent({
- old_agent_id: "oldproj-foo",
- source_project_slug: "oldproj",
- new_project_slug: "newproj",
- new_slug: "foo",
- new_display_name: "Foo",
- });
- const writeCall = writeAgentMetaMock.mock.calls[0]![0] as { created_at: string };
- expect(Date.parse(writeCall.created_at)).toBeGreaterThan(0);
- });
-});
-
-describe("getAgentDeletionSummaryAction", () => {
- it("rejects when no active project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const r = await getAgentDeletionSummaryAction("acme-foo");
- expect(r.ok).toBe(false);
- });
-
- it("returns summary with threads + crons + meta info", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- readAgentMetaMock.mockReturnValueOnce({
- agent_id: "acme-foo",
- project_slug: "acme",
- slug: "foo",
- name: "Foo Agent",
- template_key: "google_ads",
- source_agent_id: "src",
- created_at: "now",
- });
- existsSyncMock.mockReturnValue(true);
- listSessionsForAgentMock.mockReturnValueOnce([
- { sessionId: "s1", label: "T1", lastInteractionAt: 12345 },
- { sessionId: "s2", label: "T2", lastInteractionAt: 67890 },
- ]);
- listCronsForProjectMock.mockResolvedValueOnce({
- groups: [
- {
- agent: "acme-foo",
- crons: [
- { id: "c1", name: "acme/foo/job", short_name: "job", agent_id: "acme-foo", disabled: false },
- { id: "c2", name: "n2", short_name: "", agent_id: "acme-other", disabled: false },
- ],
- },
- ],
- });
- const r = await getAgentDeletionSummaryAction("acme-foo");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.exists_in_openclaw).toBe(true);
- expect(r.data.threads).toHaveLength(2);
- expect(r.data.crons).toEqual([
- { id: "c1", name: "job", disabled: false },
- ]);
- expect(r.data.template_key).toBe("google_ads");
- expect(r.data.source_agent_id).toBe("src");
- });
-
- it("returns summary with empty crons when listCronsForProject throws", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- readAgentMetaMock.mockReturnValueOnce(null);
- existsSyncMock.mockReturnValue(false);
- listCronsForProjectMock.mockRejectedValueOnce(new Error("cron down"));
- const r = await getAgentDeletionSummaryAction("acme-foo");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.crons).toEqual([]);
- expect(r.data.threads).toEqual([]);
- expect(r.data.exists_in_openclaw).toBe(false);
- // missing meta: display_name falls back to agent_id
- expect(r.data.display_name).toBe("acme-foo");
- });
-
- it("falls back name to agent_id when openclaw doesn't have the agent dir", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- readAgentMetaMock.mockReturnValueOnce(null);
- existsSyncMock.mockReturnValue(false);
- listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });
- const r = await getAgentDeletionSummaryAction("acme-foo");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- // sessions never called when dir missing
- expect(listSessionsForAgentMock).not.toHaveBeenCalled();
- });
-});
-
-describe("cascadeDeleteAgent", () => {
- it("removes crons from explicit cronIds, deletes agent, cleans meta + openclaw dir", async () => {
- removeCronMock.mockResolvedValueOnce(undefined).mockResolvedValueOnce(undefined);
- deleteAgentMock.mockResolvedValueOnce(undefined);
- existsSyncMock.mockReturnValue(true);
- rmMock.mockResolvedValue(undefined);
-
- const r = await cascadeDeleteAgent({
- agent_id: "acme-foo",
- cronIds: ["c1", "c2"],
- });
- expect(r).toMatchObject({
- agent_id: "acme-foo",
- crons_removed: 2,
- crons_failed: 0,
- openclaw_deleted: true,
- meta_removed: true,
- });
- expect(listCronsForProjectMock).not.toHaveBeenCalled();
- });
-
- it("looks up cronIds via project when not supplied", async () => {
- listCronsForProjectMock.mockResolvedValueOnce({
- groups: [
- {
- agent: "acme-foo",
- crons: [
- { id: "c1", agent_id: "acme-foo" },
- { id: "c2", agent_id: "acme-other" },
- { id: "c3", agent_id: "acme-foo" },
- ],
- },
- ],
- });
- removeCronMock.mockResolvedValue(undefined);
- deleteAgentMock.mockResolvedValueOnce(undefined);
- existsSyncMock.mockReturnValue(false);
-
- const r = await cascadeDeleteAgent({
- agent_id: "acme-foo",
- projectSlug: "acme",
- });
- expect(r.crons_removed).toBe(2);
- expect(removeCronMock).toHaveBeenCalledTimes(2);
- });
-
- it("treats listCronsForProject failure as empty list (no crons removed)", async () => {
- listCronsForProjectMock.mockRejectedValueOnce(new Error("cron down"));
- deleteAgentMock.mockResolvedValueOnce(undefined);
- existsSyncMock.mockReturnValue(false);
- const r = await cascadeDeleteAgent({
- agent_id: "acme-foo",
- projectSlug: "acme",
- });
- expect(r.crons_removed).toBe(0);
- expect(r.crons_failed).toBe(0);
- });
-
- it("counts failed cron removals separately", async () => {
- removeCronMock
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new Error("nope"));
- deleteAgentMock.mockResolvedValueOnce(undefined);
- existsSyncMock.mockReturnValue(false);
- const r = await cascadeDeleteAgent({
- agent_id: "acme-foo",
- cronIds: ["c1", "c2"],
- });
- expect(r.crons_removed).toBe(1);
- expect(r.crons_failed).toBe(1);
- });
-
- it("treats 'unknown agent' from deleteAgent as success", async () => {
- deleteAgentMock.mockRejectedValueOnce(new Error("unknown agent foo"));
- existsSyncMock.mockReturnValue(false);
- const r = await cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] });
- expect(r.openclaw_deleted).toBe(true);
- });
-
- it("treats 'not found' from deleteAgent as success", async () => {
- deleteAgentMock.mockRejectedValueOnce(new Error("agent not found"));
- existsSyncMock.mockReturnValue(false);
- const r = await cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] });
- expect(r.openclaw_deleted).toBe(true);
- });
-
- it("rethrows other deleteAgent errors", async () => {
- deleteAgentMock.mockRejectedValueOnce(new Error("network exploded"));
- await expect(
- cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] }),
- ).rejects.toThrow(/network exploded/);
- });
-
- it("meta_removed is false when workspace dir doesn't exist", async () => {
- deleteAgentMock.mockResolvedValueOnce(undefined);
- existsSyncMock.mockReturnValue(false);
- const r = await cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] });
- expect(r.meta_removed).toBe(false);
- });
-
- it("non-fatal when rm of workspace fails", async () => {
- deleteAgentMock.mockResolvedValueOnce(undefined);
- existsSyncMock.mockReturnValue(true);
- rmMock.mockRejectedValueOnce(new Error("perm denied"));
- const r = await cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] });
- expect(r.openclaw_deleted).toBe(true);
- expect(r.meta_removed).toBe(false);
- });
-});
-
-describe("deleteAgentCascadeAction", () => {
- it("rejects when no active project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const r = await deleteAgentCascadeAction("acme-foo");
- expect(r.ok).toBe(false);
- });
-
- it("returns ok + revalidates layout on successful cascade", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });
- deleteAgentMock.mockResolvedValueOnce(undefined);
- existsSyncMock.mockReturnValue(false);
- const r = await deleteAgentCascadeAction("acme-foo");
- expect(r.ok).toBe(true);
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("wraps cascade errors with 'OpenClaw refused' prefix", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });
- deleteAgentMock.mockRejectedValueOnce(new Error("network down"));
- const r = await deleteAgentCascadeAction("acme-foo");
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/OpenClaw refused/);
- expect(r.error).toMatch(/network down/);
- });
-});
diff --git a/notfair-cmo/src/server/actions/agents.ts b/notfair-cmo/src/server/actions/agents.ts
index a0097968..ef852f90 100644
--- a/notfair-cmo/src/server/actions/agents.ts
+++ b/notfair-cmo/src/server/actions/agents.ts
@@ -1,36 +1,36 @@
"use server";
import { existsSync } from "node:fs";
-import { rm } from "node:fs/promises";
-import { homedir } from "node:os";
-import { join } from "node:path";
import { revalidatePath } from "next/cache";
import { getActiveProject } from "@/server/active-project";
-import { disableCron, listCronsForProject, removeCron } from "@/server/openclaw/crons";
import {
- createAgentViaRpc,
- deleteAgent,
- listAllAgents,
-} from "@/server/openclaw/gateway-rpc";
+ disableCron,
+ listCronsForProject,
+ removeCron,
+} from "@/server/scheduler/display";
import {
agentExistsInProject,
+ cascadeDeleteAgent,
cloneAgent,
type CloneAgentResult,
-} from "@/server/openclaw/clone-agent";
+} from "@/server/agents/clone";
+import {
+ workspaceDirFor,
+ provisionAgent,
+} from "@/server/agents/provisioning";
import {
readAgentMeta,
writeAgentMeta,
- workspaceDirFor,
listProjectAgents,
type AgentMeta,
type ProjectAgentEntry,
} from "@/server/agent-meta";
-import { listSessionsForAgent } from "@/server/openclaw/sessions";
+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";
-const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");
-
export type ActionResult<T = void> =
| { ok: true; data: T }
| { ok: false; error: string };
@@ -41,22 +41,24 @@ export type AgentChoice = {
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 project = await getActiveProject();
- const projectAgentIds = new Set<string>(
- project
- ? (await listProjectAgents(project.slug)).map((a) => a.agent_id)
- : [],
- );
- const list = await listAllAgents();
- const out: AgentChoice[] = list.agents.map((a) => ({
- agent_id: a.id,
- display_name: a.identity?.name?.trim() || a.name?.trim() || a.id,
- in_current_project: projectAgentIds.has(a.id),
- }));
- out.sort((a, b) => a.display_name.localeCompare(b.display_name));
- return { ok: true, data: out };
+ 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) };
}
@@ -72,9 +74,7 @@ export async function listProjectAgentsAction(): Promise<ActionResult<ProjectAge
}
}
-export type CreateAgentInput = {
- display_name: string;
-};
+export type CreateAgentInput = { display_name: string };
export async function createAgentAction(
input: CreateAgentInput,
@@ -92,9 +92,17 @@ export async function createAgentAction(
}
const agentId = `${project.slug}-${slug.slug}`;
- const workspace = workspaceDirFor(agentId);
+ const harness = project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER;
+
try {
- await createAgentViaRpc({ name: agentId, workspace });
+ 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,
@@ -112,7 +120,6 @@ export async function createAgentAction(
export type CloneAgentActionInput = {
source_agent_id: string;
new_display_name: string;
- /** Optional override for the URL slug; defaults to slugified display name. */
new_slug?: string;
};
@@ -157,28 +164,16 @@ export async function disableCronsAction(
return { ok: true, data: { disabled, failed } };
}
-// --- Relocate (used by per-agent rename AND project rename) ---
+// --- Relocate ---
export type RelocateAgentInput = {
- /** Current full agent_id (e.g. `acme-supa`). */
old_agent_id: string;
- /** Source project slug — used for cron-cleanup lookup. */
source_project_slug: string;
- /** Destination project slug — same as source for a rename within a project. */
new_project_slug: string;
- /** Destination agent slug — same as source when only the project changes. */
new_slug: string;
- /** Display name to write into the new agent's meta sidecar. */
new_display_name: string;
- /**
- * Optional template_key to preserve on the new agent's meta sidecar (kept
- * during renames so the sidebar icon stays consistent for template-derived
- * agents).
- */
preserve_template_key?: AgentTemplate["key"];
- /** Optional source_agent_id to preserve on the new meta (clone provenance). */
preserve_source_agent_id?: string;
- /** Optional original created_at to keep the agent's age stable. */
preserve_created_at?: string;
};
@@ -187,16 +182,6 @@ export type RelocateAgentResult = {
new_slug: string;
};
-/**
- * Move an agent from one (project, slug) to another. Underneath: full clone
- * into the destination identifiers, overwrite meta with the preserved fields,
- * then cascade-delete the source. Shared by per-agent rename (same project,
- * new slug) and project rename (new project, same slug per agent).
- *
- * Throws on clone failure (source stays intact). If clone succeeds but the
- * source delete partially fails, the destination is still live and the caller
- * can surface a warning.
- */
export async function relocateAgent(
input: RelocateAgentInput,
): Promise<RelocateAgentResult> {
@@ -205,15 +190,9 @@ export async function relocateAgent(
project_slug: input.new_project_slug,
new_slug: input.new_slug,
display_name: input.new_display_name,
- // We're handing cloneAgent an already-canonical slug from existing meta,
- // not user input — skip the reserved-slug check so template slugs like
- // `cmo` survive a relocate.
slug_is_canonical: true,
});
- // Overwrite meta to drop the clone-provenance fields that cloneAgent set,
- // and preserve the caller-supplied identity (template_key, source, created).
- // Template agents don't persist `slug` (it's computed); clones do.
const isTemplateAgent = !!input.preserve_template_key;
await writeAgentMeta({
agent_id: cloneResult.new_agent_id,
@@ -227,12 +206,7 @@ export async function relocateAgent(
created_at: input.preserve_created_at ?? new Date().toISOString(),
});
- // Delete the source (its crons are looked up under its source project).
- // Best-effort — if it fails the new agent is still usable.
- await cascadeDeleteAgent({
- agent_id: input.old_agent_id,
- projectSlug: input.source_project_slug,
- }).catch(() => {});
+ await cascadeDeleteAgent(input.old_agent_id, input.source_project_slug).catch(() => {});
return {
new_agent_id: cloneResult.new_agent_id,
@@ -243,9 +217,7 @@ export async function relocateAgent(
// --- Rename ---
export type RenameAgentInput = {
- /** Current agent_id (e.g. `e2e-test-brand-supa`). */
agent_id: string;
- /** New display name; slugified to derive the new URL slug. */
new_display_name: string;
};
@@ -253,22 +225,9 @@ export type RenameAgentData = {
agent_id: string;
slug: string;
display_name: string;
- /** True when the slug actually changed (i.e. a full clone+delete ran). */
full_rename: boolean;
};
-/**
- * Per the agent-identity refactor, agents are IMMUTABLE after creation:
- * the name set during onboarding (or clone time) is permanent and the URL
- * slug is computed from it. This action is preserved so internal callers
- * (project-rename cascade via relocateAgent) keep working, but the
- * user-facing rename UI has been removed.
- *
- * For template agents the action refuses — template names are part of the
- * sidebar/role-pill identity the user named at onboarding. For cloned/
- * custom agents the action also refuses; they were already named at clone
- * time.
- */
export async function renameAgentAction(
_input: RenameAgentInput,
): Promise<ActionResult<RenameAgentData>> {
@@ -297,9 +256,9 @@ export async function getAgentDeletionSummaryAction(
if (!project) return { ok: false, error: "No active project." };
const meta: AgentMeta | null = readAgentMeta(agent_id);
- const agentDir = join(OPENCLAW_HOME, "agents", agent_id);
- const existsInOpenclaw = existsSync(agentDir);
- const sessions = existsInOpenclaw ? listSessionsForAgent(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,
@@ -316,7 +275,7 @@ export async function getAgentDeletionSummaryAction(
}
}
} catch {
- // Best-effort; cron service unreachable means we just show an empty list.
+ // best-effort
}
return {
@@ -324,7 +283,8 @@ export async function getAgentDeletionSummaryAction(
data: {
agent_id,
display_name: meta?.name ?? agent_id,
- exists_in_openclaw: existsInOpenclaw,
+ // field kept for UI compatibility — true when the workspace exists
+ exists_in_openclaw: exists,
threads,
crons,
source_agent_id: meta?.source_agent_id,
@@ -341,148 +301,51 @@ export type DeleteAgentData = {
meta_removed: boolean;
};
-/**
- * Cascading agent deletion: removes the agent's crons, calls OpenClaw's
- * `agents.delete` RPC (with deleteFiles:true so workspace + sessions go too),
- * and cleans up the empty parent dirs OpenClaw and our meta sidecar leave
- * behind. Shared by per-agent delete (settings danger zone) and project-wide
- * delete so the cleanup logic stays in one place.
- *
- * Pure helper — does NOT revalidate, redirect, or touch cookies. Callers add
- * their own surrounding concerns (per-agent action revalidates the layout,
- * project delete clears the active-project cookie + db rows).
- *
- * Pass `cronsByAgentId` to skip the cron lookup when the caller already has
- * it (project-wide delete grabs every project cron once up front).
- */
-export type CascadeAgentDeleteOutcome = {
- 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." };
-export async function cascadeDeleteAgent(opts: {
- agent_id: string;
- /**
- * Optional: caller-supplied list of cron IDs to remove for this agent.
- * When omitted, we look them up via the project's cron list.
- */
- projectSlug?: string;
- cronIds?: string[];
-}): Promise<CascadeAgentDeleteOutcome> {
- const { agent_id } = opts;
-
- // 1) Remove agent's crons first — once the agent is gone OpenClaw may reject
- // removeCron for orphans.
let cronsRemoved = 0;
let cronsFailed = 0;
- let cronIds = opts.cronIds;
- if (!cronIds && opts.projectSlug) {
- try {
- const view = await listCronsForProject(opts.projectSlug);
- cronIds = view.groups
- .flatMap((g) => g.crons)
- .filter((c) => c.agent_id === agent_id)
- .map((c) => c.id);
- } catch {
- cronIds = [];
- }
- }
- for (const id of cronIds ?? []) {
- try {
- await removeCron(id);
- cronsRemoved++;
- } catch {
- cronsFailed++;
- }
- }
-
- // 2) Delete the OpenClaw agent.
- let openclawDeleted = false;
- try {
- await deleteAgent(agent_id);
- openclawDeleted = true;
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (msg.includes("unknown agent") || msg.includes("not found")) {
- openclawDeleted = true; // already gone — treat as success
- } else {
- // Rethrow so callers can decide whether to abort.
- throw err;
- }
- }
-
- // 3) Remove our meta sidecar + workspace dir.
- let metaRemoved = false;
try {
- const wsDir = workspaceDirFor(agent_id);
- if (existsSync(wsDir)) {
- await rm(wsDir, { recursive: true, force: true });
- metaRemoved = true;
+ 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 {
- // Non-fatal; agent stays shadow-visible until the sidecar disappears.
+ // best-effort
}
- // 4) OpenClaw's deleteFiles:true trashes the dir contents but leaves the
- // now-empty `~/.openclaw/agents/<id>/` parent behind. Remove it so the
- // slug becomes free to reuse immediately (otherwise next rename/clone
- // rejects with "already exists").
try {
- const openclawAgentDir = join(OPENCLAW_HOME, "agents", agent_id);
- if (existsSync(openclawAgentDir)) {
- await rm(openclawAgentDir, { recursive: true, force: true });
- }
- } catch {
- // Best-effort — trashed contents already represent a successful delete.
- }
-
- return {
- agent_id,
- crons_removed: cronsRemoved,
- crons_failed: cronsFailed,
- openclaw_deleted: openclawDeleted,
- meta_removed: metaRemoved,
- };
-}
-
-export async function deleteAgentCascadeAction(
- agent_id: string,
-): Promise<ActionResult<DeleteAgentData>> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
-
- let outcome: CascadeAgentDeleteOutcome;
- try {
- outcome = await cascadeDeleteAgent({
- agent_id,
- projectSlug: project.slug,
- });
+ await cascadeDeleteAgent(agent_id, project.slug);
} catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- return { ok: false, error: `OpenClaw refused to delete agent: ${msg}` };
+ return {
+ ok: false,
+ error: `Failed to delete agent: ${err instanceof Error ? err.message : String(err)}`,
+ };
}
revalidatePath("/", "layout");
- return { ok: true, data: outcome };
-}
-
-/** Used by the clone-result confirmation if the user opts to delete instead. */
-export async function removeCronsAction(
- cronIds: string[],
-): Promise<ActionResult<{ removed: number; failed: number }>> {
- let removed = 0;
- let failed = 0;
- for (const id of cronIds) {
- try {
- await removeCron(id);
- removed++;
- } catch {
- failed++;
- }
- }
- revalidatePath("/", "layout");
- return { ok: true, data: { removed, failed } };
+ 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/cron-runs.test.ts b/notfair-cmo/src/server/actions/cron-runs.test.ts
deleted file mode 100644
index 955fbe68..00000000
--- a/notfair-cmo/src/server/actions/cron-runs.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const loadCronRunsMock = vi.fn();
-vi.mock("@/server/openclaw/crons", () => ({
- loadCronRuns: (...a: unknown[]) => loadCronRunsMock(...a),
-}));
-
-const tickAtOrBeforeMock = vi.fn();
-vi.mock("@/server/openclaw/cron-schedule", () => ({
- tickAtOrBefore: (...a: unknown[]) => tickAtOrBeforeMock(...a),
-}));
-
-import { getCronRunsAction } from "./cron-runs";
-
-function makeRun(overrides: Record<string, unknown> = {}) {
- return {
- run_at_ms: 1_700_000_000_000,
- finished_at_ms: 1_700_000_001_000,
- status: "ok",
- summary: "ran fine",
- error: undefined,
- duration_ms: 1000,
- session_id: "s-1",
- model: undefined,
- provider: undefined,
- usage: undefined,
- ...overrides,
- };
-}
-
-describe("getCronRunsAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("returns runs with owning_occurrence_at_ms from tickAtOrBefore when a schedule is provided", async () => {
- const runA = makeRun({ run_at_ms: 1000 });
- const runB = makeRun({ run_at_ms: 2000 });
- loadCronRunsMock.mockReturnValue([runA, runB]);
- tickAtOrBeforeMock.mockImplementation((_s: unknown, at: number) => at - 100);
-
- const schedule = { kind: "cron" as const, expr: "0 9 * * *", tz: "UTC" };
- const out = await getCronRunsAction("cron-1", schedule, 50);
-
- expect(out.ok).toBe(true);
- if (!out.ok) return;
- expect(out.runs).toHaveLength(2);
- expect(out.runs[0]!.owning_occurrence_at_ms).toBe(900);
- expect(out.runs[1]!.owning_occurrence_at_ms).toBe(1900);
- expect(loadCronRunsMock).toHaveBeenCalledWith("cron-1", 50);
- expect(tickAtOrBeforeMock).toHaveBeenNthCalledWith(1, schedule, 1000);
- expect(tickAtOrBeforeMock).toHaveBeenNthCalledWith(2, schedule, 2000);
- });
-
- it("sets owning_occurrence_at_ms to undefined when schedule is null", async () => {
- loadCronRunsMock.mockReturnValue([makeRun()]);
- const out = await getCronRunsAction("cron-1", null);
- expect(out.ok).toBe(true);
- if (!out.ok) return;
- expect(out.runs[0]!.owning_occurrence_at_ms).toBeUndefined();
- expect(tickAtOrBeforeMock).not.toHaveBeenCalled();
- });
-
- it("returns empty list when loadCronRuns has no entries", async () => {
- loadCronRunsMock.mockReturnValue([]);
- const out = await getCronRunsAction("cron-1", null);
- expect(out).toEqual({ ok: true, runs: [] });
- });
-
- it("uses default limit of 100 when not specified", async () => {
- loadCronRunsMock.mockReturnValue([]);
- await getCronRunsAction("cron-1", null);
- expect(loadCronRunsMock).toHaveBeenCalledWith("cron-1", 100);
- });
-
- it("supports 'every' schedule shape end-to-end", async () => {
- loadCronRunsMock.mockReturnValue([makeRun({ run_at_ms: 5000 })]);
- tickAtOrBeforeMock.mockReturnValue(4500);
- const schedule = { kind: "every" as const, everyMs: 60_000, anchorMs: 0 };
- const out = await getCronRunsAction("cron-1", schedule);
- expect(out.ok).toBe(true);
- if (!out.ok) return;
- expect(out.runs[0]!.owning_occurrence_at_ms).toBe(4500);
- expect(tickAtOrBeforeMock).toHaveBeenCalledWith(schedule, 5000);
- });
-
- it("returns ok:false with the Error message when loadCronRuns throws", async () => {
- loadCronRunsMock.mockImplementation(() => {
- throw new Error("disk read failed");
- });
- const out = await getCronRunsAction("cron-1", null);
- expect(out).toEqual({ ok: false, error: "disk read failed" });
- });
-
- it("stringifies non-Error throws into the error field", async () => {
- loadCronRunsMock.mockImplementation(() => {
- throw "string-reason";
- });
- const out = await getCronRunsAction("cron-1", null);
- expect(out).toEqual({ ok: false, error: "string-reason" });
- });
-
- it("preserves all CronRun fields from loadCronRuns in the enriched output", async () => {
- const run = makeRun({
- status: "error",
- summary: "boom",
- error: "timeout",
- session_id: "sess-xyz",
- model: "claude-opus-4-7",
- usage: { input_tokens: 100, output_tokens: 50 },
- });
- loadCronRunsMock.mockReturnValue([run]);
- const out = await getCronRunsAction("cron-1", null);
- expect(out.ok).toBe(true);
- if (!out.ok) return;
- expect(out.runs[0]).toMatchObject({
- status: "error",
- summary: "boom",
- error: "timeout",
- session_id: "sess-xyz",
- model: "claude-opus-4-7",
- usage: { input_tokens: 100, output_tokens: 50 },
- });
- });
-});
diff --git a/notfair-cmo/src/server/actions/cron-runs.ts b/notfair-cmo/src/server/actions/cron-runs.ts
index 7c1c4b21..da721d55 100644
--- a/notfair-cmo/src/server/actions/cron-runs.ts
+++ b/notfair-cmo/src/server/actions/cron-runs.ts
@@ -1,7 +1,6 @@
"use server";
-import { loadCronRuns, type CronRun } from "@/server/openclaw/crons";
-import { tickAtOrBefore } from "@/server/openclaw/cron-schedule";
+import { loadCronRuns, tickAtOrBefore, type CronRun, type CronSchedule } from "@/server/scheduler/display";
export type CronRunWithTick = CronRun & {
/**
@@ -13,9 +12,7 @@ export type CronRunWithTick = CronRun & {
owning_occurrence_at_ms?: number;
};
-export type ScheduleInput =
- | { kind: "cron"; expr: string; tz?: string }
- | { kind: "every"; everyMs: number; anchorMs?: number };
+export type ScheduleInput = CronSchedule;
export type GetCronRunsResult =
| { ok: true; runs: CronRunWithTick[] }
diff --git a/notfair-cmo/src/server/actions/crons.test.ts b/notfair-cmo/src/server/actions/crons.test.ts
deleted file mode 100644
index b9990c34..00000000
--- a/notfair-cmo/src/server/actions/crons.test.ts
+++ /dev/null
@@ -1,343 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const revalidatePathMock = vi.fn();
-vi.mock("next/cache", () => ({
- revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),
-}));
-
-const createCronMock = vi.fn();
-const disableCronMock = vi.fn();
-const enableCronMock = vi.fn();
-const removeCronMock = vi.fn();
-const invalidateCronCacheMock = vi.fn();
-vi.mock("@/server/openclaw/crons", () => ({
- createCron: (...a: unknown[]) => createCronMock(...a),
- disableCron: (...a: unknown[]) => disableCronMock(...a),
- enableCron: (...a: unknown[]) => enableCronMock(...a),
- removeCron: (...a: unknown[]) => removeCronMock(...a),
- invalidateCronCache: () => invalidateCronCacheMock(),
-}));
-
-const updateCronMessageMock = vi.fn();
-vi.mock("@/server/openclaw/gateway-rpc", () => ({
- updateCronMessage: (...a: unknown[]) => updateCronMessageMock(...a),
-}));
-
-const logAgentActionMock = vi.fn();
-vi.mock("@/server/db/agent-actions", () => ({
- logAgentAction: (...a: unknown[]) => logAgentActionMock(...a),
-}));
-
-// scheduleCronAction looks up the agent's full id from the project's
-// agent roster — the id encodes the personal name now, so we can't
-// synthesize it from template key alone.
-const listProjectAgentsMock = vi.fn(async (..._a: unknown[]) => [
- {
- agent_id: "demo-cmo-greg",
- slug: "cmo-greg",
- name: "Greg",
- template_key: "cmo" as const,
- is_template_default: true,
- },
- {
- agent_id: "demo-google-ads-ana",
- slug: "google-ads-ana",
- name: "Ana",
- template_key: "google_ads" as const,
- is_template_default: true,
- },
- {
- agent_id: "demo-seo-sam",
- slug: "seo-sam",
- name: "Sam",
- template_key: "seo" as const,
- is_template_default: false,
- },
-]);
-vi.mock("@/server/agent-meta", () => ({
- listProjectAgents: (...a: unknown[]) => listProjectAgentsMock(...a),
-}));
-
-import {
- deleteCronAction,
- pauseCronAction,
- resumeCronAction,
- scheduleCronAction,
- updateCronPromptAction,
-} from "./crons";
-
-describe("scheduleCronAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- createCronMock.mockResolvedValue({ id: "cron-1", name: "demo/google-ads/morning" });
- });
-
- it("creates a cron with kind=cron, logs the action, and revalidates", async () => {
- const out = await scheduleCronAction({
- project_slug: "demo",
- specialist: "google_ads",
- name: "Morning Audit",
- schedule_kind: "cron",
- schedule_value: "0 9 * * *",
- tz: "UTC",
- brief: "Run a daily account health check.",
- });
-
- expect(out).toEqual({ ok: true, cron_id: "cron-1", cron_name: "demo/google-ads/morning" });
- expect(createCronMock).toHaveBeenCalledWith({
- project_slug: "demo",
- agent_slug: "google-ads-ana",
- agent_full_id: "demo-google-ads-ana",
- cron_name: "morning-audit",
- schedule: { kind: "cron", expr: "0 9 * * *", tz: "UTC" },
- message: "Run a daily account health check.",
- });
- expect(logAgentActionMock).toHaveBeenCalledWith({
- project_slug: "demo",
- agent_id: "demo-google-ads-ana",
- action_type: "cron_created",
- summary: "Scheduled 'morning-audit' (cron 0 9 * * *)",
- payload: {
- cron_id: "cron-1",
- cron_name: "demo/google-ads/morning",
- brief: "Run a daily account health check.",
- },
- });
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("creates a cron with kind=every (no tz passthrough)", async () => {
- await scheduleCronAction({
- project_slug: "demo",
- specialist: "seo",
- name: "Hourly Audit",
- schedule_kind: "every",
- schedule_value: "1h",
- brief: "Hourly SEO scan.",
- });
- expect(createCronMock).toHaveBeenCalledWith(
- expect.objectContaining({
- agent_slug: "seo-sam",
- agent_full_id: "demo-seo-sam",
- schedule: { kind: "every", duration: "1h" },
- }),
- );
- });
-
- it("resolves agent_full_id from the project roster (encodes role + personal name)", async () => {
- await scheduleCronAction({
- project_slug: "demo",
- specialist: "google_ads",
- name: "X",
- schedule_kind: "every",
- schedule_value: "1h",
- brief: "x",
- });
- const call = createCronMock.mock.calls[0]?.[0] as Record<string, unknown>;
- expect(call.agent_slug).toBe("google-ads-ana");
- expect(call.agent_full_id).toBe("demo-google-ads-ana");
- });
-
- it("trims brief whitespace before sending and logging", async () => {
- await scheduleCronAction({
- project_slug: "demo",
- specialist: "cmo",
- name: "hello",
- schedule_kind: "every",
- schedule_value: "1h",
- brief: " actual prompt ",
- });
- expect(createCronMock.mock.calls[0]?.[0].message).toBe("actual prompt");
- });
-
- it("trims schedule_value whitespace", async () => {
- await scheduleCronAction({
- project_slug: "demo",
- specialist: "cmo",
- name: "hello",
- schedule_kind: "cron",
- schedule_value: " 0 9 * * * ",
- brief: "b",
- });
- expect(createCronMock.mock.calls[0]?.[0].schedule).toEqual({
- kind: "cron",
- expr: "0 9 * * *",
- tz: undefined,
- });
- });
-
- it("returns ok:false when the name cannot be slugified", async () => {
- const out = await scheduleCronAction({
- project_slug: "demo",
- specialist: "cmo",
- name: " ",
- schedule_kind: "every",
- schedule_value: "1h",
- brief: "b",
- });
- expect(out.ok).toBe(false);
- if (out.ok) return;
- expect(out.error).toMatch(/Invalid name/);
- expect(createCronMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false when brief is empty after trimming", async () => {
- const out = await scheduleCronAction({
- project_slug: "demo",
- specialist: "cmo",
- name: "valid",
- schedule_kind: "every",
- schedule_value: "1h",
- brief: " ",
- });
- expect(out).toEqual({ ok: false, error: "Brief is required." });
- expect(createCronMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false when schedule_value is empty after trimming", async () => {
- const out = await scheduleCronAction({
- project_slug: "demo",
- specialist: "cmo",
- name: "valid",
- schedule_kind: "every",
- schedule_value: " ",
- brief: "brief",
- });
- expect(out).toEqual({ ok: false, error: "Schedule is required." });
- expect(createCronMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false with Error message when createCron throws", async () => {
- createCronMock.mockRejectedValue(new Error("openclaw down"));
- const out = await scheduleCronAction({
- project_slug: "demo",
- specialist: "cmo",
- name: "valid",
- schedule_kind: "every",
- schedule_value: "1h",
- brief: "b",
- });
- expect(out).toEqual({ ok: false, error: "openclaw down" });
- expect(logAgentActionMock).not.toHaveBeenCalled();
- });
-
- it("stringifies non-Error rejections from createCron", async () => {
- createCronMock.mockRejectedValue("rope-burn");
- const out = await scheduleCronAction({
- project_slug: "demo",
- specialist: "cmo",
- name: "valid",
- schedule_kind: "every",
- schedule_value: "1h",
- brief: "b",
- });
- expect(out).toEqual({ ok: false, error: "rope-burn" });
- });
-});
-
-describe("pauseCronAction", () => {
- beforeEach(() => vi.clearAllMocks());
-
- it("disables the cron and revalidates layout", async () => {
- disableCronMock.mockResolvedValue(undefined);
- const out = await pauseCronAction("cron-1");
- expect(out).toEqual({ ok: true });
- expect(disableCronMock).toHaveBeenCalledWith("cron-1");
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("returns ok:false with the Error message when disableCron throws", async () => {
- disableCronMock.mockRejectedValue(new Error("nope"));
- const out = await pauseCronAction("cron-1");
- expect(out).toEqual({ ok: false, error: "nope" });
- expect(revalidatePathMock).not.toHaveBeenCalled();
- });
-
- it("stringifies non-Error rejections", async () => {
- disableCronMock.mockRejectedValue(42);
- const out = await pauseCronAction("cron-1");
- expect(out).toEqual({ ok: false, error: "42" });
- });
-});
-
-describe("resumeCronAction", () => {
- beforeEach(() => vi.clearAllMocks());
-
- it("enables the cron and revalidates layout", async () => {
- enableCronMock.mockResolvedValue(undefined);
- const out = await resumeCronAction("cron-1");
- expect(out).toEqual({ ok: true });
- expect(enableCronMock).toHaveBeenCalledWith("cron-1");
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("returns ok:false with the Error message when enableCron throws", async () => {
- enableCronMock.mockRejectedValue(new Error("auth"));
- const out = await resumeCronAction("cron-1");
- expect(out).toEqual({ ok: false, error: "auth" });
- });
-
- it("stringifies non-Error rejections", async () => {
- enableCronMock.mockRejectedValue("disconnected");
- const out = await resumeCronAction("cron-1");
- expect(out).toEqual({ ok: false, error: "disconnected" });
- });
-});
-
-describe("deleteCronAction", () => {
- beforeEach(() => vi.clearAllMocks());
-
- it("removes the cron and revalidates layout", async () => {
- removeCronMock.mockResolvedValue(undefined);
- const out = await deleteCronAction("cron-1");
- expect(out).toEqual({ ok: true });
- expect(removeCronMock).toHaveBeenCalledWith("cron-1");
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("returns ok:false with the Error message when removeCron throws", async () => {
- removeCronMock.mockRejectedValue(new Error("missing"));
- const out = await deleteCronAction("cron-1");
- expect(out).toEqual({ ok: false, error: "missing" });
- });
-
- it("stringifies non-Error rejections", async () => {
- removeCronMock.mockRejectedValue("io-err");
- const out = await deleteCronAction("cron-1");
- expect(out).toEqual({ ok: false, error: "io-err" });
- });
-});
-
-describe("updateCronPromptAction", () => {
- beforeEach(() => vi.clearAllMocks());
-
- it("rejects empty (whitespace-only) messages without calling the gateway", async () => {
- const out = await updateCronPromptAction("cron-1", " \n\t");
- expect(out).toEqual({ ok: false, error: "Prompt cannot be empty." });
- expect(updateCronMessageMock).not.toHaveBeenCalled();
- expect(invalidateCronCacheMock).not.toHaveBeenCalled();
- });
-
- it("trims the message before sending to the gateway", async () => {
- updateCronMessageMock.mockResolvedValue(undefined);
- const out = await updateCronPromptAction("cron-1", " hello world ");
- expect(out).toEqual({ ok: true });
- expect(updateCronMessageMock).toHaveBeenCalledWith("cron-1", "hello world");
- expect(invalidateCronCacheMock).toHaveBeenCalledTimes(1);
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("returns the Error message when updateCronMessage throws (and skips cache invalidation)", async () => {
- updateCronMessageMock.mockRejectedValue(new Error("rpc error"));
- const out = await updateCronPromptAction("cron-1", "valid");
- expect(out).toEqual({ ok: false, error: "rpc error" });
- expect(invalidateCronCacheMock).not.toHaveBeenCalled();
- expect(revalidatePathMock).not.toHaveBeenCalled();
- });
-
- it("stringifies non-Error rejections", async () => {
- updateCronMessageMock.mockRejectedValue("string-err");
- const out = await updateCronPromptAction("cron-1", "valid");
- expect(out).toEqual({ ok: false, error: "string-err" });
- });
-});
diff --git a/notfair-cmo/src/server/actions/crons.ts b/notfair-cmo/src/server/actions/crons.ts
index 741e36c1..66e2a34d 100644
--- a/notfair-cmo/src/server/actions/crons.ts
+++ b/notfair-cmo/src/server/actions/crons.ts
@@ -7,8 +7,8 @@ import {
enableCron,
invalidateCronCache,
removeCron,
-} from "@/server/openclaw/crons";
-import { updateCronMessage } from "@/server/openclaw/gateway-rpc";
+} 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";
@@ -52,16 +52,25 @@ export async function scheduleCronAction(input: ScheduleCronInput): Promise<Sche
const agent_slug = target.slug;
const agent_full_id = target.agent_id;
+ // The native scheduler only models cron expressions; "every N" inputs come
+ // in as `every 5m` strings which we transcribe to a cron expression with
+ // the equivalent step. For brevity (and since the CMO/specialists rarely
+ // emit non-cron schedules), reject `every` here for now — emitters should
+ // pass a real cron expression.
+ if (input.schedule_kind !== "cron") {
+ return {
+ ok: false,
+ error: "Only cron expressions are supported; use a 5-field cron string.",
+ };
+ }
+
try {
const result = await createCron({
project_slug: input.project_slug,
agent_slug,
agent_full_id,
cron_name: nameSlug.slug,
- schedule:
- input.schedule_kind === "cron"
- ? { kind: "cron", expr: scheduleValueTrimmed, tz: input.tz }
- : { kind: "every", duration: scheduleValueTrimmed },
+ schedule: { kind: "cron", expr: scheduleValueTrimmed, tz: input.tz },
message: briefTrimmed,
});
logAgentAction({
@@ -116,7 +125,9 @@ export async function updateCronPromptAction(
const trimmed = message.trim();
if (!trimmed) return { ok: false, error: "Prompt cannot be empty." };
try {
- await updateCronMessage(id, trimmed);
+ getDb()
+ .prepare("UPDATE scheduled_jobs SET message = ?, updated_at = ? WHERE id = ?")
+ .run(trimmed, new Date().toISOString(), id);
invalidateCronCache();
revalidatePath("/", "layout");
return { ok: true };
diff --git a/notfair-cmo/src/server/actions/mcp.test.ts b/notfair-cmo/src/server/actions/mcp.test.ts
deleted file mode 100644
index fc86fa7c..00000000
--- a/notfair-cmo/src/server/actions/mcp.test.ts
+++ /dev/null
@@ -1,378 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const revalidatePathMock = vi.fn();
-vi.mock("next/cache", () => ({
- revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),
-}));
-
-const headerGetMock = vi.fn();
-vi.mock("next/headers", () => ({
- headers: async () => ({
- get: (...args: unknown[]) => headerGetMock(...args),
- }),
-}));
-
-const getActiveProjectMock = vi.fn();
-vi.mock("@/server/active-project", () => ({
- getActiveProject: (...args: unknown[]) => getActiveProjectMock(...args),
-}));
-
-const setPendingMock = vi.fn();
-vi.mock("@/server/mcp-pending", () => ({
- setPending: (...args: unknown[]) => setPendingMock(...args),
-}));
-
-const runDisconnectMock = vi.fn();
-vi.mock("@/server/mcp-state", () => ({
- disconnectMcp: (...args: unknown[]) => runDisconnectMock(...args),
-}));
-
-// Use the real mcp-catalog so storedMcpKey + mcpSpecByKey work.
-
-import { disconnectMcpAction, startMcpConnect } from "./mcp";
-
-function project(slug = "acme") {
- return {
- id: "uuid",
- slug,
- display_name: "Acme",
- created_at: "now",
- archived_at: null,
- google_ads_account_id: null,
- };
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- // Default header values; individual tests override as needed.
- headerGetMock.mockImplementation((name: string) => {
- if (name === "host") return "localhost:3326";
- return null;
- });
-});
-
-describe("startMcpConnect", () => {
- let fetchMock: ReturnType<typeof vi.fn>;
- beforeEach(() => {
- fetchMock = vi.fn();
- vi.stubGlobal("fetch", fetchMock);
- });
-
- it("rejects unknown mcp_key", async () => {
- const r = await startMcpConnect({ mcp_key: "not-a-real-mcp" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/Unknown MCP key/);
- });
-
- it("rejects when no active project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const r = await startMcpConnect({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/No active project/);
- });
-
- it("surfaces discovery failures", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock.mockResolvedValueOnce({
- ok: false,
- status: 404,
- json: async () => ({}),
- });
- const r = await startMcpConnect({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/Discovery failed/);
- expect(r.error).toMatch(/HTTP 404/);
- });
-
- it("surfaces missing authorization_servers in protected-resource doc", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock.mockResolvedValueOnce({
- ok: true,
- json: async () => ({}),
- });
- const r = await startMcpConnect({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/no authorization_servers/);
- });
-
- it("surfaces incomplete AS metadata", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ authorization_servers: ["https://as.example.com/"] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- authorization_endpoint: "https://as.example.com/authorize",
- // missing token_endpoint + registration_endpoint
- }),
- });
- const r = await startMcpConnect({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/AS metadata missing endpoints/);
- });
-
- it("surfaces DCR failures with status code + text snippet", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ authorization_servers: ["https://as.example.com"] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- authorization_endpoint: "https://as.example.com/authorize",
- token_endpoint: "https://as.example.com/token",
- registration_endpoint: "https://as.example.com/register",
- }),
- })
- .mockResolvedValueOnce({
- ok: false,
- status: 400,
- text: async () => "bad payload",
- });
- const r = await startMcpConnect({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/Registration failed/);
- expect(r.error).toMatch(/DCR 400/);
- });
-
- it("surfaces DCR response missing client_id", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ authorization_servers: ["https://as.example.com"] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- authorization_endpoint: "https://as.example.com/authorize",
- token_endpoint: "https://as.example.com/token",
- registration_endpoint: "https://as.example.com/register",
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({}),
- });
- const r = await startMcpConnect({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/missing client_id/);
- });
-
- it("happy path: stashes pending flow and returns authorize URL with PKCE", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ authorization_servers: ["https://as.example.com/"] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- authorization_endpoint: "https://as.example.com/authorize",
- token_endpoint: "https://as.example.com/token",
- registration_endpoint: "https://as.example.com/register",
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ client_id: "client-xyz", client_secret: "shh" }),
- });
- const r = await startMcpConnect({
- mcp_key: "notfair-googleads",
- return_to: "/chat/foo",
- });
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- const url = new URL(r.authorize_url);
- expect(url.origin).toBe("https://as.example.com");
- expect(url.pathname).toBe("/authorize");
- expect(url.searchParams.get("response_type")).toBe("code");
- expect(url.searchParams.get("client_id")).toBe("client-xyz");
- expect(url.searchParams.get("redirect_uri")).toBe(
- "http://localhost:3326/api/mcp-oauth/callback",
- );
- expect(url.searchParams.get("code_challenge_method")).toBe("S256");
- expect(url.searchParams.get("code_challenge")).toMatch(/^[A-Za-z0-9_-]+$/);
- expect(url.searchParams.get("state")).toMatch(/^[A-Za-z0-9_-]+$/);
- expect(url.searchParams.get("resource")).toBe(
- "https://notfair.co/api/mcp/google_ads",
- );
-
- expect(setPendingMock).toHaveBeenCalledTimes(1);
- const [state, flow] = setPendingMock.mock.calls[0]! as [
- string,
- Record<string, unknown>,
- ];
- expect(state).toBe(url.searchParams.get("state"));
- expect(flow).toMatchObject({
- catalog_key: "notfair-googleads",
- stored_key: "acme-notfair-googleads",
- issuer: "https://as.example.com",
- token_endpoint: "https://as.example.com/token",
- client_id: "client-xyz",
- client_secret: "shh",
- redirect_uri: "http://localhost:3326/api/mcp-oauth/callback",
- project_slug: "acme",
- return_to: "/chat/foo",
- });
- expect(typeof flow.code_verifier).toBe("string");
- expect((flow.code_verifier as string).length).toBeGreaterThan(50);
- });
-
- it("uses x-forwarded-proto + x-forwarded-host when behind a proxy", async () => {
- headerGetMock.mockImplementation((name: string) => {
- if (name === "x-forwarded-proto") return "https";
- if (name === "x-forwarded-host") return "app.example.com";
- if (name === "host") return "internal-host";
- return null;
- });
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ authorization_servers: ["https://as.example.com"] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- authorization_endpoint: "https://as.example.com/authorize",
- token_endpoint: "https://as.example.com/token",
- registration_endpoint: "https://as.example.com/register",
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ client_id: "c" }),
- });
- const r = await startMcpConnect({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.authorize_url).toMatch(/redirect_uri=https%3A%2F%2Fapp\.example\.com/);
- });
-
- it("throws-as-error path: missing host header surfaces as discovery error", async () => {
- headerGetMock.mockImplementation(() => null);
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ authorization_servers: ["https://as.example.com"] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- authorization_endpoint: "https://as.example.com/authorize",
- token_endpoint: "https://as.example.com/token",
- registration_endpoint: "https://as.example.com/register",
- }),
- });
- await expect(
- startMcpConnect({ mcp_key: "notfair-googleads" }),
- ).rejects.toThrow(/Could not derive origin/);
- });
-
- it("rejects open-redirect return_to (absolute URL)", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ authorization_servers: ["https://as.example.com"] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- authorization_endpoint: "https://as.example.com/authorize",
- token_endpoint: "https://as.example.com/token",
- registration_endpoint: "https://as.example.com/register",
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ client_id: "c" }),
- });
- await startMcpConnect({
- mcp_key: "notfair-googleads",
- return_to: "https://evil.example.com/steal",
- });
- const [, flow] = setPendingMock.mock.calls[0]!;
- expect((flow as { return_to: string | undefined }).return_to).toBeUndefined();
- });
-
- it("rejects open-redirect return_to (protocol-relative)", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- fetchMock
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ authorization_servers: ["https://as.example.com"] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- authorization_endpoint: "https://as.example.com/authorize",
- token_endpoint: "https://as.example.com/token",
- registration_endpoint: "https://as.example.com/register",
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ client_id: "c" }),
- });
- await startMcpConnect({
- mcp_key: "notfair-googleads",
- return_to: "//evil.example.com/x",
- });
- const [, flow] = setPendingMock.mock.calls[0]!;
- expect((flow as { return_to: string | undefined }).return_to).toBeUndefined();
- });
-});
-
-describe("disconnectMcpAction", () => {
- it("rejects when no active project", async () => {
- getActiveProjectMock.mockResolvedValueOnce(null);
- const r = await disconnectMcpAction({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/No active project/);
- });
-
- it("calls disconnectMcp with project-scoped key and revalidates layout", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- runDisconnectMock.mockResolvedValueOnce(undefined);
- const r = await disconnectMcpAction({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(true);
- expect(runDisconnectMock).toHaveBeenCalledWith("acme-notfair-googleads");
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("returns error string when disconnect throws an Error", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- runDisconnectMock.mockRejectedValueOnce(new Error("openclaw blew up"));
- const r = await disconnectMcpAction({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/openclaw blew up/);
- expect(revalidatePathMock).not.toHaveBeenCalled();
- });
-
- it("returns error string when disconnect throws a non-Error", async () => {
- getActiveProjectMock.mockResolvedValueOnce(project());
- runDisconnectMock.mockRejectedValueOnce("string thrown");
- const r = await disconnectMcpAction({ mcp_key: "notfair-googleads" });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/string thrown/);
- });
-});
diff --git a/notfair-cmo/src/server/actions/mcp.ts b/notfair-cmo/src/server/actions/mcp.ts
index a9e2b250..105562f7 100644
--- a/notfair-cmo/src/server/actions/mcp.ts
+++ b/notfair-cmo/src/server/actions/mcp.ts
@@ -4,9 +4,9 @@ import { randomBytes, createHash } from "node:crypto";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { getActiveProject } from "@/server/active-project";
-import { mcpSpecByKey, storedMcpKey } from "@/server/mcp-catalog";
+import { mcpSpecByKey } from "@/server/mcp-catalog";
import { setPending } from "@/server/mcp-pending";
-import { disconnectMcp as runDisconnect } from "@/server/mcp-state";
+import { disconnectMcp as runDisconnect } from "@/server/mcp/state";
export type StartMcpConnectResult =
| { ok: true; authorize_url: string }
@@ -35,7 +35,6 @@ export async function startMcpConnect(input: {
if (!project) {
return { ok: false, error: "No active project. Pick one before connecting an MCP." };
}
- const stored_key = storedMcpKey(project.slug, spec.key);
let resolved: ResolvedAuthServer;
try {
@@ -63,7 +62,6 @@ export async function startMcpConnect(input: {
setPending(state, {
catalog_key: spec.key,
- stored_key,
display_name: spec.display_name,
resource_url: spec.resource_url,
issuer: resolved.issuer,
@@ -96,9 +94,8 @@ export async function disconnectMcpAction(input: {
if (!project) {
return { ok: false, error: "No active project to disconnect from." };
}
- const stored_key = storedMcpKey(project.slug, input.mcp_key);
try {
- await runDisconnect(stored_key);
+ await runDisconnect(project.slug, input.mcp_key);
} catch (err) {
return { ok: false, error: humanError(err) };
}
@@ -125,9 +122,8 @@ export async function listMcpToolsAction(input: {
if (!project) {
return { ok: false, error: "No active project." };
}
- const stored_key = storedMcpKey(project.slug, input.mcp_key);
const { getMcpConfig, mcpRpc } = await import("@/server/mcp/rpc");
- const cfg = await getMcpConfig(stored_key);
+ const cfg = getMcpConfig(project.slug, input.mcp_key);
if (!cfg) {
return { ok: false, error: "MCP is not configured for this project." };
}
diff --git a/notfair-cmo/src/server/actions/projects.test.ts b/notfair-cmo/src/server/actions/projects.test.ts
deleted file mode 100644
index 1ac53603..00000000
--- a/notfair-cmo/src/server/actions/projects.test.ts
+++ /dev/null
@@ -1,715 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const revalidatePathMock = vi.fn();
-vi.mock("next/cache", () => ({
- revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),
-}));
-
-const redirectMock = vi.fn((_target: string) => {
- // Mimic Next.js: redirect() throws an internal signal so callers stop.
- throw new Error("NEXT_REDIRECT");
-});
-vi.mock("next/navigation", () => ({
- redirect: (...args: unknown[]) => redirectMock(...(args as [string])),
-}));
-
-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 archiveProjectMock = vi.fn();
-const changeProjectSlugMock = vi.fn();
-const createProjectMock = vi.fn();
-const deleteProjectRowMock = vi.fn();
-const getProjectMock = vi.fn();
-const renameProjectMock = vi.fn();
-vi.mock("@/server/db/projects", () => ({
- archiveProject: (...args: unknown[]) => archiveProjectMock(...args),
- changeProjectSlug: (...args: unknown[]) => changeProjectSlugMock(...args),
- createProject: (...args: unknown[]) => createProjectMock(...args),
- deleteProjectRow: (...args: unknown[]) => deleteProjectRowMock(...args),
- getProject: (...args: unknown[]) => getProjectMock(...args),
- renameProject: (...args: unknown[]) => renameProjectMock(...args),
-}));
-
-const clearActiveProjectMock = vi.fn();
-const setActiveProjectMock = vi.fn();
-vi.mock("@/server/active-project", () => ({
- clearActiveProject: (...args: unknown[]) => clearActiveProjectMock(...args),
- setActiveProject: (...args: unknown[]) => setActiveProjectMock(...args),
-}));
-
-const ensureProjectAgentsMock = vi.fn();
-vi.mock("@/server/agent-templates", () => ({
- ensureProjectAgents: (...args: unknown[]) => ensureProjectAgentsMock(...args),
- // The onboarding scope constant. createProjectAction +
- // createProjectForOnboardingAction read it from agent-templates; the
- // reprovisionAgentsAction also passes it explicitly.
- DEFAULT_ONBOARDING_TEMPLATE_KEYS: ["cmo", "google_ads"],
- // createProjectForOnboardingAction now mints the onboarding task
- // synchronously, so it imports agentNameFor to derive the CMO id.
- agentNameFor: (slug: string, key: string, name: string) =>
- `${slug}-${key.replace(/_/g, "-")}-${name
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")}`,
-}));
-
-// Same flow needs cmo-task-brief + tasks + run-task. Stub them all.
-vi.mock("@/server/onboarding/cmo-task-brief", () => ({
- buildProjectOnboardingBrief: () => ({
- title: "Learn the project and write PROJECT.md",
- brief: "stub brief",
- success_criteria: "stub criteria",
- }),
-}));
-vi.mock("@/server/db/tasks", () => ({
- createTask: vi.fn(() => ({
- id: "onb-uuid",
- display_id: "acme-1",
- project_slug: "acme",
- agent_id: "acme-cmo-greg",
- title: "Learn the project and write PROJECT.md",
- status: "proposed",
- })),
-}));
-vi.mock("@/server/orchestration/run-task", () => ({
- startTaskIfProposed: vi.fn((t: unknown) => t),
-}));
-
-const startProvisioningMock = vi.fn();
-const clearProvisioningMock = vi.fn();
-vi.mock("@/server/onboarding/provisioning-state", () => ({
- startProvisioning: (...args: unknown[]) => startProvisioningMock(...args),
- clearProvisioning: (...args: unknown[]) => clearProvisioningMock(...args),
-}));
-
-const listProjectAgentsMock = vi.fn();
-const readAgentMetaMock = vi.fn();
-vi.mock("@/server/agent-meta", () => ({
- listProjectAgents: (...args: unknown[]) => listProjectAgentsMock(...args),
- readAgentMeta: (...args: unknown[]) => readAgentMetaMock(...args),
-}));
-
-const cascadeDeleteAgentMock = vi.fn();
-const relocateAgentMock = vi.fn();
-vi.mock("@/server/actions/agents", () => ({
- cascadeDeleteAgent: (...args: unknown[]) => cascadeDeleteAgentMock(...args),
- relocateAgent: (...args: unknown[]) => relocateAgentMock(...args),
-}));
-
-const listCronsForProjectMock = vi.fn();
-const disableCronMock = vi.fn();
-vi.mock("@/server/openclaw/crons", () => ({
- listCronsForProject: (...args: unknown[]) => listCronsForProjectMock(...args),
- disableCron: (...args: unknown[]) => disableCronMock(...args),
-}));
-
-const logAgentActionMock = vi.fn();
-vi.mock("@/server/db/agent-actions", () => ({
- logAgentAction: (...args: unknown[]) => logAgentActionMock(...args),
-}));
-
-const getProjectDeletionSummaryMock = vi.fn();
-vi.mock("@/server/openclaw/project-delete", () => ({
- getProjectDeletionSummary: (...args: unknown[]) =>
- getProjectDeletionSummaryMock(...args),
-}));
-
-const disconnectMcpMock = vi.fn();
-vi.mock("@/server/mcp-state", () => ({
- disconnectMcp: (...args: unknown[]) => disconnectMcpMock(...args),
-}));
-
-// mcp-catalog: keep real implementation so storedMcpKey works.
-
-import {
- archiveProjectAction,
- createProjectAction,
- createProjectForOnboardingAction,
- deleteProjectAction,
- getProjectDeletionSummaryAction,
- renameProjectAction,
- renameProjectFullAction,
- reprovisionAgentsAction,
- switchProjectAction,
-} from "./projects";
-
-function project(overrides: Partial<{ slug: string; display_name: string }> = {}) {
- return {
- id: "uuid",
- slug: "acme",
- display_name: "Acme",
- created_at: "now",
- archived_at: null,
- google_ads_account_id: null,
- ...overrides,
- };
-}
-
-function fd(obj: Record<string, string>): FormData {
- const f = new FormData();
- for (const [k, v] of Object.entries(obj)) f.append(k, v);
- return f;
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- ensureProjectAgentsMock.mockResolvedValue({
- created: ["acme-cmo"],
- existed: [],
- failed: [],
- });
-});
-
-describe("createProjectAction", () => {
- it("throws when display_name is empty", async () => {
- await expect(createProjectAction(fd({ display_name: " " }))).rejects.toThrow(
- /Please enter a project name/,
- );
- });
-
- it("throws when createProject returns !ok", async () => {
- createProjectMock.mockReturnValueOnce({ ok: false, reason: "slug reserved" });
- await expect(createProjectAction(fd({ display_name: "api" }))).rejects.toThrow(
- /slug reserved/,
- );
- });
-
- it("redirects to / on success and triggers async provisioning", async () => {
- createProjectMock.mockReturnValueOnce({ ok: true, project: project() });
- await expect(
- createProjectAction(fd({ display_name: "Acme" })),
- ).rejects.toThrow(/NEXT_REDIRECT/);
- expect(redirectMock).toHaveBeenCalledWith("/");
- expect(ensureProjectAgentsMock).toHaveBeenCalledWith("acme", ["cmo", "google_ads"]);
- expect(startProvisioningMock).toHaveBeenCalled();
- expect(setActiveProjectMock).toHaveBeenCalledWith("acme");
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("logs project_created after provisioning resolves", async () => {
- createProjectMock.mockReturnValueOnce({ ok: true, project: project() });
- ensureProjectAgentsMock.mockResolvedValueOnce({
- created: ["acme-cmo", "acme-google-ads"],
- existed: [],
- failed: [],
- });
- await createProjectAction(fd({ display_name: "Acme" })).catch(() => {});
- // Wait for any microtask-queued .then() to drain.
- await new Promise((r) => setTimeout(r, 0));
- expect(logAgentActionMock).toHaveBeenCalledWith(
- expect.objectContaining({
- project_slug: "acme",
- agent_id: "system",
- action_type: "project_created",
- }),
- );
- });
-
- it("provisioning rejection is swallowed (console.error)", async () => {
- createProjectMock.mockReturnValueOnce({ ok: true, project: project() });
- ensureProjectAgentsMock.mockRejectedValueOnce(new Error("rpc down"));
- const spy = vi.spyOn(console, "error").mockImplementation(() => {});
- await createProjectAction(fd({ display_name: "Acme" })).catch(() => {});
- await new Promise((r) => setTimeout(r, 0));
- expect(spy).toHaveBeenCalled();
- spy.mockRestore();
- });
-});
-
-describe("createProjectForOnboardingAction", () => {
- it("returns error result when display_name blank", async () => {
- const r = await createProjectForOnboardingAction(fd({ display_name: "" }));
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/Please enter a project name/);
- });
-
- it("returns error result when createProject fails", async () => {
- createProjectMock.mockReturnValueOnce({ ok: false, reason: "slug taken" });
- const r = await createProjectForOnboardingAction(fd({ display_name: "X" }));
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/slug taken/);
- });
-
- it("returns slug + display_name on success without redirecting", async () => {
- createProjectMock.mockReturnValueOnce({ ok: true, project: project() });
- const r = await createProjectForOnboardingAction(
- fd({ display_name: "Acme" }),
- );
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data).toEqual({ slug: "acme", display_name: "Acme" });
- expect(redirectMock).not.toHaveBeenCalled();
- expect(startProvisioningMock).toHaveBeenCalled();
- });
-});
-
-describe("reprovisionAgentsAction", () => {
- it("returns ok+result on success and revalidates", async () => {
- ensureProjectAgentsMock.mockResolvedValueOnce({
- created: ["a"],
- existed: ["b"],
- failed: [],
- });
- const r = await reprovisionAgentsAction("acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.created).toEqual(["a"]);
- expect(r.existed).toEqual(["b"]);
- expect(revalidatePathMock).toHaveBeenCalled();
- });
-
- it("returns error on rejection", async () => {
- ensureProjectAgentsMock.mockRejectedValueOnce(new Error("boom"));
- const r = await reprovisionAgentsAction("acme");
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/boom/);
- });
-});
-
-describe("switchProjectAction", () => {
- it("sets active project + revalidates", async () => {
- const r = await switchProjectAction("acme");
- expect(r.ok).toBe(true);
- expect(setActiveProjectMock).toHaveBeenCalledWith("acme");
- expect(revalidatePathMock).toHaveBeenCalled();
- });
-});
-
-describe("archiveProjectAction", () => {
- it("returns error when archiveProject returns null", async () => {
- archiveProjectMock.mockReturnValueOnce(null);
- const r = await archiveProjectAction("missing");
- expect(r.ok).toBe(false);
- });
-
- it("halts every enabled cron and counts disabled successes", async () => {
- archiveProjectMock.mockReturnValueOnce(project());
- listCronsForProjectMock.mockResolvedValueOnce({
- groups: [
- {
- agent: "acme-foo",
- crons: [
- { id: "c1", disabled: false },
- { id: "c2", disabled: true },
- { id: "c3", disabled: false },
- ],
- },
- ],
- });
- disableCronMock.mockResolvedValueOnce(undefined).mockResolvedValueOnce(undefined);
- const r = await archiveProjectAction("acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.halted_crons).toBe(2);
- expect(disableCronMock).toHaveBeenCalledTimes(2);
- expect(logAgentActionMock).toHaveBeenCalled();
- });
-
- it("tolerates listCronsForProject failure (no crons halted)", async () => {
- archiveProjectMock.mockReturnValueOnce(project());
- listCronsForProjectMock.mockRejectedValueOnce(new Error("cron down"));
- const spy = vi.spyOn(console, "error").mockImplementation(() => {});
- const r = await archiveProjectAction("acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.halted_crons).toBe(0);
- spy.mockRestore();
- });
-
- it("tolerates individual disable failures and counts the rest", async () => {
- archiveProjectMock.mockReturnValueOnce(project());
- listCronsForProjectMock.mockResolvedValueOnce({
- groups: [
- {
- agent: "acme-foo",
- crons: [
- { id: "c1", disabled: false },
- { id: "c2", disabled: false },
- ],
- },
- ],
- });
- disableCronMock
- .mockRejectedValueOnce(new Error("nope"))
- .mockResolvedValueOnce(undefined);
- const spy = vi.spyOn(console, "error").mockImplementation(() => {});
- const r = await archiveProjectAction("acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.halted_crons).toBe(1);
- spy.mockRestore();
- });
-});
-
-describe("renameProjectAction", () => {
- it("returns error when renameProject returns null", async () => {
- renameProjectMock.mockReturnValueOnce(null);
- const r = await renameProjectAction("acme", "");
- expect(r.ok).toBe(false);
- });
-
- it("returns ok + revalidates on success", async () => {
- renameProjectMock.mockReturnValueOnce(project({ display_name: "Renamed" }));
- const r = await renameProjectAction("acme", "Renamed");
- expect(r.ok).toBe(true);
- expect(revalidatePathMock).toHaveBeenCalled();
- });
-});
-
-describe("renameProjectFullAction", () => {
- it("rejects when project not found", async () => {
- getProjectMock.mockReturnValueOnce(null);
- const r = await renameProjectFullAction({
- current_slug: "missing",
- new_display_name: "X",
- });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/not found/);
- });
-
- it("rejects empty new display_name", async () => {
- getProjectMock.mockReturnValueOnce(project());
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: " ",
- });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/empty/);
- });
-
- it("rejects when slugify fails", async () => {
- getProjectMock.mockReturnValueOnce(project());
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: "@@@",
- });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/Invalid name/);
- });
-
- it("no-op when slug+display name are unchanged", async () => {
- getProjectMock.mockReturnValueOnce(project({ display_name: "Acme" }));
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: "Acme",
- });
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.full_rename).toBe(false);
- expect(renameProjectMock).not.toHaveBeenCalled();
- });
-
- it("display-name-only path when slug stays the same", async () => {
- getProjectMock.mockReturnValueOnce(project({ display_name: "Acme" }));
- // "ACME!" → "acme"
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: "ACME!",
- });
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.full_rename).toBe(false);
- expect(r.data.display_name).toBe("ACME!");
- expect(renameProjectMock).toHaveBeenCalledWith("acme", "ACME!");
- });
-
- it("rejects when destination slug exists", async () => {
- getProjectMock
- .mockReturnValueOnce(project())
- .mockReturnValueOnce(project({ slug: "newslug" }));
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: "Newslug",
- });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/already exists/);
- });
-
- it("full rename relocates each agent and migrates DB rows + repoints cookie", async () => {
- getProjectMock
- .mockReturnValueOnce(project()) // current lookup
- .mockReturnValueOnce(null); // destination uniqueness check
- listProjectAgentsMock.mockResolvedValueOnce([
- {
- agent_id: "acme-cmo",
- slug: "cmo",
- display_name: "CMO",
- template_key: "cmo",
- is_template_default: true,
- },
- ]);
- readAgentMetaMock.mockReturnValueOnce({
- agent_id: "acme-cmo",
- project_slug: "acme",
- slug: "cmo",
- display_name: "CMO",
- created_at: "now",
- source_agent_id: "src",
- });
- relocateAgentMock.mockResolvedValueOnce({
- new_agent_id: "newslug-cmo",
- new_slug: "cmo",
- });
- changeProjectSlugMock.mockReturnValueOnce(undefined);
- cookieGetMock.mockReturnValueOnce({ value: "acme" });
-
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: "Newslug",
- });
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.full_rename).toBe(true);
- expect(r.data.slug).toBe("newslug");
- expect(r.data.agents_relocated).toEqual(["acme-cmo"]);
- expect(r.data.agents_failed).toEqual([]);
- expect(changeProjectSlugMock).toHaveBeenCalledWith("acme", "newslug", "Newslug");
- expect(setActiveProjectMock).toHaveBeenCalledWith("newslug");
- });
-
- it("does NOT repoint cookie when it wasn't pointing at this project", async () => {
- getProjectMock.mockReturnValueOnce(project()).mockReturnValueOnce(null);
- listProjectAgentsMock.mockResolvedValueOnce([]);
- changeProjectSlugMock.mockReturnValueOnce(undefined);
- cookieGetMock.mockReturnValueOnce({ value: "other" });
-
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: "Newslug",
- });
- expect(r.ok).toBe(true);
- expect(setActiveProjectMock).not.toHaveBeenCalled();
- });
-
- it("collects per-agent failures rather than aborting", async () => {
- getProjectMock.mockReturnValueOnce(project()).mockReturnValueOnce(null);
- listProjectAgentsMock.mockResolvedValueOnce([
- {
- agent_id: "acme-cmo",
- slug: "cmo",
- display_name: "CMO",
- is_template_default: true,
- },
- {
- agent_id: "acme-ga",
- slug: "ga",
- display_name: "GA",
- is_template_default: true,
- },
- ]);
- readAgentMetaMock.mockReturnValue(null);
- relocateAgentMock
- .mockResolvedValueOnce({ new_agent_id: "newslug-cmo", new_slug: "cmo" })
- .mockRejectedValueOnce(new Error("relocate failed"));
- changeProjectSlugMock.mockReturnValueOnce(undefined);
- cookieGetMock.mockReturnValueOnce(undefined);
-
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: "Newslug",
- });
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.agents_relocated).toEqual(["acme-cmo"]);
- expect(r.data.agents_failed).toEqual([
- { agent_id: "acme-ga", error: "relocate failed" },
- ]);
- });
-
- it("surfaces changeProjectSlug failure with cleanup-needed messaging", async () => {
- getProjectMock.mockReturnValueOnce(project()).mockReturnValueOnce(null);
- listProjectAgentsMock.mockResolvedValueOnce([]);
- changeProjectSlugMock.mockImplementationOnce(() => {
- throw new Error("FK violation");
- });
- const r = await renameProjectFullAction({
- current_slug: "acme",
- new_display_name: "Newslug",
- });
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/DB migration failed/);
- expect(r.error).toMatch(/FK violation/);
- });
-});
-
-describe("getProjectDeletionSummaryAction", () => {
- it("rejects when project not found", async () => {
- getProjectMock.mockReturnValueOnce(null);
- const r = await getProjectDeletionSummaryAction("missing");
- expect(r.ok).toBe(false);
- });
-
- it("returns the summary on success", async () => {
- getProjectMock.mockReturnValueOnce(project());
- getProjectDeletionSummaryMock.mockResolvedValueOnce({
- project_slug: "acme",
- agents: [],
- mcps: [],
- totals: { agents: 0, threads: 0, crons: 0, mcps: 0 },
- });
- const r = await getProjectDeletionSummaryAction("acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.project_slug).toBe("acme");
- });
-
- it("surfaces summary errors", async () => {
- getProjectMock.mockReturnValueOnce(project());
- getProjectDeletionSummaryMock.mockRejectedValueOnce(new Error("inventory failed"));
- const r = await getProjectDeletionSummaryAction("acme");
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/inventory failed/);
- });
-});
-
-describe("deleteProjectAction", () => {
- it("rejects when confirmation slug mismatches", async () => {
- const r = await deleteProjectAction("acme", "other");
- expect(r.ok).toBe(false);
- if (r.ok) return;
- expect(r.error).toMatch(/Confirmation slug/);
- });
-
- it("rejects when project not found", async () => {
- getProjectMock.mockReturnValueOnce(null);
- const r = await deleteProjectAction("acme", "acme");
- expect(r.ok).toBe(false);
- });
-
- it("cascades agents, mcps, db row, clears cookie when active", async () => {
- getProjectMock.mockReturnValueOnce(project());
- listCronsForProjectMock.mockResolvedValueOnce({
- groups: [
- {
- agent: "acme-cmo",
- crons: [
- { id: "c1", agent_id: "acme-cmo" },
- { id: "c2", agent_id: "acme-cmo" },
- ],
- },
- ],
- });
- listProjectAgentsMock.mockResolvedValueOnce([
- { agent_id: "acme-cmo", slug: "cmo", display_name: "CMO", is_template_default: true },
- ]);
- cascadeDeleteAgentMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- crons_removed: 2,
- crons_failed: 0,
- openclaw_deleted: true,
- meta_removed: true,
- });
- disconnectMcpMock.mockResolvedValueOnce(undefined);
- cookieGetMock.mockReturnValueOnce({ value: "acme" });
-
- const r = await deleteProjectAction("acme", "acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.agents).toEqual(["acme-cmo"]);
- expect(r.data.agentsFailed).toEqual([]);
- expect(r.data.crons).toBe(2);
- expect(r.data.mcps).toBe(1);
- expect(deleteProjectRowMock).toHaveBeenCalledWith("acme");
- expect(clearProvisioningMock).toHaveBeenCalledWith("acme");
- expect(clearActiveProjectMock).toHaveBeenCalled();
- expect(cascadeDeleteAgentMock).toHaveBeenCalledWith({
- agent_id: "acme-cmo",
- cronIds: ["c1", "c2"],
- });
- });
-
- it("does NOT clear active-project cookie when it points elsewhere", async () => {
- getProjectMock.mockReturnValueOnce(project());
- listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });
- listProjectAgentsMock.mockResolvedValueOnce([]);
- disconnectMcpMock.mockResolvedValueOnce(undefined);
- cookieGetMock.mockReturnValueOnce({ value: "other" });
- const r = await deleteProjectAction("acme", "acme");
- expect(r.ok).toBe(true);
- expect(clearActiveProjectMock).not.toHaveBeenCalled();
- });
-
- it("collects failed agents into agentsFailed and continues", async () => {
- getProjectMock.mockReturnValueOnce(project());
- listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });
- listProjectAgentsMock.mockResolvedValueOnce([
- { agent_id: "acme-cmo", slug: "cmo", display_name: "CMO", is_template_default: true },
- { agent_id: "acme-ga", slug: "ga", display_name: "GA", is_template_default: true },
- ]);
- cascadeDeleteAgentMock
- .mockResolvedValueOnce({
- agent_id: "acme-cmo",
- crons_removed: 0,
- crons_failed: 0,
- openclaw_deleted: true,
- meta_removed: true,
- })
- .mockRejectedValueOnce(new Error("delete exploded"));
- disconnectMcpMock.mockResolvedValueOnce(undefined);
- cookieGetMock.mockReturnValueOnce(undefined);
-
- const r = await deleteProjectAction("acme", "acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.agents).toEqual(["acme-cmo"]);
- expect(r.data.agentsFailed).toEqual([
- { agentId: "acme-ga", error: "delete exploded" },
- ]);
- });
-
- it("counts MCP disconnect failures into mcpsFailed", async () => {
- getProjectMock.mockReturnValueOnce(project());
- listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });
- listProjectAgentsMock.mockResolvedValueOnce([]);
- disconnectMcpMock.mockRejectedValueOnce(new Error("can't reach openclaw"));
- cookieGetMock.mockReturnValueOnce(undefined);
- const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
- const r = await deleteProjectAction("acme", "acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.mcps).toBe(0);
- expect(r.data.mcpsFailed).toBe(1);
- spy.mockRestore();
- });
-
- it("continues when listCronsForProject fails (cronsByAgent empty)", async () => {
- getProjectMock.mockReturnValueOnce(project());
- listCronsForProjectMock.mockRejectedValueOnce(new Error("cron service down"));
- listProjectAgentsMock.mockResolvedValueOnce([
- { agent_id: "acme-cmo", slug: "cmo", display_name: "CMO", is_template_default: true },
- ]);
- cascadeDeleteAgentMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- crons_removed: 0,
- crons_failed: 0,
- openclaw_deleted: true,
- meta_removed: true,
- });
- disconnectMcpMock.mockResolvedValueOnce(undefined);
- cookieGetMock.mockReturnValueOnce(undefined);
- const r = await deleteProjectAction("acme", "acme");
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(cascadeDeleteAgentMock).toHaveBeenCalledWith({
- agent_id: "acme-cmo",
- cronIds: [],
- });
- });
-});
diff --git a/notfair-cmo/src/server/actions/projects.ts b/notfair-cmo/src/server/actions/projects.ts
index ce1ab9b2..e92d0fea 100644
--- a/notfair-cmo/src/server/actions/projects.ts
+++ b/notfair-cmo/src/server/actions/projects.ts
@@ -22,15 +22,14 @@ import {
} from "@/server/agent-templates";
import { startProvisioning } from "@/server/onboarding/provisioning-state";
import { listProjectAgents, readAgentMeta } from "@/server/agent-meta";
-import { cascadeDeleteAgent, relocateAgent } from "@/server/actions/agents";
-import { listCronsForProject, disableCron } from "@/server/openclaw/crons";
+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/openclaw/project-delete";
-import { MCP_CATALOG, storedMcpKey } from "@/server/mcp-catalog";
-import { disconnectMcp } from "@/server/mcp-state";
+} from "@/server/agents/cascade-delete";
import { clearProvisioning } from "@/server/onboarding/provisioning-state";
export type ActionResult<T = void> =
@@ -97,6 +96,13 @@ export async function createProjectForOnboardingAction(
const website_url = String(formData.get("website_url") ?? "").trim() || null;
const codebase_path = String(formData.get("codebase_path") ?? "").trim() || null;
+ const harness_raw = String(formData.get("harness_adapter") ?? "").trim();
+ const { isHarnessAdapterId, DEFAULT_HARNESS_ADAPTER } = await import(
+ "@/server/adapters/registry"
+ );
+ const harness_adapter = isHarnessAdapterId(harness_raw)
+ ? harness_raw
+ : DEFAULT_HARNESS_ADAPTER;
// Personal names for the team. Pre-filled with template defaults on the
// client; we still read off the form rather than baking the defaults
@@ -111,7 +117,12 @@ export async function createProjectForOnboardingAction(
...(agent_name_google_ads ? { google_ads: agent_name_google_ads } : {}),
} as Partial<Record<"cmo" | "google_ads" | "seo", string>>;
- const result = createProject({ display_name, website_url, codebase_path });
+ const result = createProject({
+ display_name,
+ website_url,
+ codebase_path,
+ harness_adapter,
+ });
if (!result.ok) return { ok: false, error: result.reason };
// Mint the onboarding task SYNCHRONOUSLY — before provisioning kicks
@@ -446,71 +457,38 @@ export async function deleteProjectAction(
const project = getProject(slug);
if (!project) return { ok: false, error: `Project '${slug}' not found.` };
- const deletedAgents: string[] = [];
+ const projectAgentEntries = await listProjectAgents(slug);
+ const deletedAgents: string[] = projectAgentEntries.map((a) => a.agent_id);
const agentsFailed: Array<{ agentId: string; error: string }> = [];
- // 1) Look up project crons once so we can hand each agent its own slice
- // (avoids N redundant lookups inside the shared helper).
- let cronsByAgent = new Map<string, string[]>();
+ // Count crons + MCP tokens upfront so the result shape stays informative.
+ let cronsDeleted = 0;
try {
- const cronView = await listCronsForProject(slug);
- for (const group of cronView.groups) {
- for (const cron of group.crons) {
- const arr = cronsByAgent.get(cron.agent_id) ?? [];
- arr.push(cron.id);
- cronsByAgent.set(cron.agent_id, arr);
- }
- }
+ const view = await listCronsForProject(slug);
+ cronsDeleted = view.groups.reduce((acc, g) => acc + g.crons.length, 0);
} catch {
- // Cron service unavailable; continue — cascadeDeleteAgent will skip cron
- // cleanup when given an empty list.
- }
-
- // 2) Agents — single source of truth lives in cascadeDeleteAgent. Iterates
- // every agent the project actually has (templates + cloned/custom).
- const projectAgentEntries = await listProjectAgents(slug);
- let cronsDeleted = 0;
- let cronsFailed = 0;
- for (const entry of projectAgentEntries) {
- try {
- const outcome = await cascadeDeleteAgent({
- agent_id: entry.agent_id,
- cronIds: cronsByAgent.get(entry.agent_id) ?? [],
- });
- deletedAgents.push(entry.agent_id);
- cronsDeleted += outcome.crons_removed;
- cronsFailed += outcome.crons_failed;
- } catch (err) {
- agentsFailed.push({
- agentId: entry.agent_id,
- error: err instanceof Error ? err.message : String(err),
- });
- }
+ // best-effort
}
-
- // 3) Revoke per-project MCP connections (bearer tokens live in OpenClaw's
- // mcp config under `<slug>-<catalog-key>`). Per-MCP best-effort so one
- // unreachable MCP doesn't block the rest of the cascade.
- let mcpsRevoked = 0;
- let mcpsFailed = 0;
- for (const spec of MCP_CATALOG) {
- const key = storedMcpKey(slug, spec.key);
- try {
- await disconnectMcp(key);
- mcpsRevoked++;
- } catch (err) {
- // disconnectMcp is already idempotent for "not configured" — anything
- // hitting this path is a real openclaw-cli failure we want to surface.
- const message = err instanceof Error ? err.message : String(err);
- // "not found" / "unknown" responses are swallowed by disconnectMcp;
- // anything else counts as a failure but doesn't abort delete.
- console.warn(`[delete-project] failed to revoke MCP ${key}: ${message}`);
- mcpsFailed++;
- }
+ 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
+ // MCP entries get unregistered too.
+ try {
+ await cascadeDeleteProjectArtifacts(slug);
+ } catch (err) {
+ console.error("[delete-project] cascade failed:", err);
+ agentsFailed.push({
+ agentId: "(project)",
+ error: err instanceof Error ? err.message : String(err),
+ });
}
- // 4) Drop the in-memory provisioning Promise so a re-created project with
- // the same slug starts fresh (and we don't leak the old Promise).
+ // 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>/.
diff --git a/notfair-cmo/src/server/actions/skills.test.ts b/notfair-cmo/src/server/actions/skills.test.ts
deleted file mode 100644
index b686abd9..00000000
--- a/notfair-cmo/src/server/actions/skills.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const revalidatePathMock = vi.fn();
-vi.mock("next/cache", () => ({
- revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),
-}));
-
-const setSkillEnabledMock = vi.fn();
-vi.mock("@/server/openclaw/gateway-rpc", () => ({
- setSkillEnabled: (...a: unknown[]) => setSkillEnabledMock(...a),
-}));
-
-import { setSkillEnabledAction } from "./skills";
-
-describe("setSkillEnabledAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("returns ok:false when skillKey is empty (no gateway call)", async () => {
- const out = await setSkillEnabledAction("", true, "demo-google-ads");
- expect(out).toEqual({ ok: false, error: "skillKey is required" });
- expect(setSkillEnabledMock).not.toHaveBeenCalled();
- expect(revalidatePathMock).not.toHaveBeenCalled();
- });
-
- it("calls setSkillEnabled with the provided key + enabled flag and revalidates layout", async () => {
- setSkillEnabledMock.mockResolvedValue(undefined);
- const out = await setSkillEnabledAction("toprank:google-ads", true, "demo-google-ads");
- expect(out).toEqual({ ok: true });
- expect(setSkillEnabledMock).toHaveBeenCalledWith("toprank:google-ads", true);
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("passes enabled=false through to the gateway when disabling a skill", async () => {
- setSkillEnabledMock.mockResolvedValue(undefined);
- const out = await setSkillEnabledAction("toprank:meta-ads", false, "demo-meta");
- expect(out).toEqual({ ok: true });
- expect(setSkillEnabledMock).toHaveBeenCalledWith("toprank:meta-ads", false);
- });
-
- it("captures gateway Error and surfaces its message (no revalidate)", async () => {
- setSkillEnabledMock.mockRejectedValue(new Error("gateway down"));
- const out = await setSkillEnabledAction("k", true, "a");
- expect(out).toEqual({ ok: false, error: "gateway down" });
- expect(revalidatePathMock).not.toHaveBeenCalled();
- });
-
- it("stringifies non-Error rejections into the error field", async () => {
- setSkillEnabledMock.mockRejectedValue("plain-string-reason");
- const out = await setSkillEnabledAction("k", true, "a");
- expect(out).toEqual({ ok: false, error: "plain-string-reason" });
- });
-
- it("ignores agentSlug (workspace-wide config) but still succeeds", async () => {
- setSkillEnabledMock.mockResolvedValue(undefined);
- const out = await setSkillEnabledAction("k", true, "literally-any-agent");
- expect(out).toEqual({ ok: true });
- expect(setSkillEnabledMock).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/notfair-cmo/src/server/actions/skills.ts b/notfair-cmo/src/server/actions/skills.ts
index 41f06b24..d83f1424 100644
--- a/notfair-cmo/src/server/actions/skills.ts
+++ b/notfair-cmo/src/server/actions/skills.ts
@@ -1,27 +1,24 @@
"use server";
import { revalidatePath } from "next/cache";
-import { setSkillEnabled } from "@/server/openclaw/gateway-rpc";
export type SetSkillEnabledResult = { ok: true } | { ok: false; error: string };
+/**
+ * Skills are inherent to the chosen harness adapter now (Claude Code skills,
+ * Codex prompts, etc.) plus the SKILL.md notfair-cmo writes into each agent
+ * workspace. There's no global enable/disable flag — agents always have
+ * access to the SKILL.md their workspace contains.
+ *
+ * The action is preserved so the existing UI tile in the per-agent Skills
+ * tab keeps compiling; clicks resolve immediately with no side effect.
+ */
export async function setSkillEnabledAction(
skillKey: string,
- enabled: boolean,
- agentSlug: string,
+ _enabled: boolean,
+ _agentSlug: string,
): Promise<SetSkillEnabledResult> {
if (!skillKey) return { ok: false, error: "skillKey is required" };
- try {
- await setSkillEnabled(skillKey, enabled);
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
- // Skills config is workspace-wide, so any agent's skills tab needs to refresh.
- // Cheapest correct invalidation: revalidate the caller's page; user can refresh
- // other tabs themselves on the rare cross-agent reconfig.
- // Path is project-scoped now; invalidating the layout tree is the safest
- // cheap option since we don't have the project slug at this call site.
- void agentSlug;
revalidatePath("/", "layout");
return { ok: true };
}
diff --git a/notfair-cmo/src/server/actions/tasks.ts b/notfair-cmo/src/server/actions/tasks.ts
index be33eeff..4880c31f 100644
--- a/notfair-cmo/src/server/actions/tasks.ts
+++ b/notfair-cmo/src/server/actions/tasks.ts
@@ -105,3 +105,76 @@ export async function cancelTaskAction(
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/adapters/claude-code-local/execute.ts b/notfair-cmo/src/server/adapters/claude-code-local/execute.ts
new file mode 100644
index 00000000..1277a194
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/claude-code-local/execute.ts
@@ -0,0 +1,163 @@
+import { spawn } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import type { HarnessEvent, HarnessExecuteContext } from "../types";
+import { makeClaudeStreamState, parseClaudeLine } from "./parse";
+
+const CLAUDE_BIN = process.env.NOTFAIR_CLAUDE_BIN?.trim() || "claude";
+
+/**
+ * Stream one chat turn through the Claude Code CLI.
+ *
+ * Wire shape:
+ * - We spawn `claude --print --output-format stream-json --input-format text`
+ * with the user message piped in on stdin.
+ * - 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
+ * maps onto an existing Claude session. First turn for a thread is fresh.
+ * - Each stdout line is a JSON event; we forward as HarnessEvents.
+ */
+export async function* executeClaudeCodeLocal(
+ ctx: HarnessExecuteContext,
+): AsyncGenerator<HarnessEvent, void, void> {
+ let identityMd = "";
+ try {
+ identityMd = await readFile(join(ctx.workspaceDir, "IDENTITY.md"), "utf8");
+ } catch {
+ // Missing IDENTITY.md isn't fatal — the workspace dir may still have a
+ // CLAUDE.md Claude Code will auto-load. We pass a brief default below.
+ }
+
+ const args: string[] = [
+ "--print",
+ "--output-format",
+ "stream-json",
+ "--input-format",
+ "text",
+ "--verbose",
+ ];
+ if (identityMd.trim().length > 0) {
+ args.push("--append-system-prompt", identityMd);
+ }
+
+ // Resume a Claude session only when we've actually seen one for this
+ // thread before. notfair-cmo'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)) {
+ args.push("--resume", ctx.harnessSessionId);
+ }
+
+ const child = spawn(CLAUDE_BIN, args, {
+ cwd: ctx.workspaceDir,
+ env: { ...process.env, NOTFAIR_PROJECT_SLUG: ctx.projectSlug, NOTFAIR_AGENT_ID: ctx.agentId },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ const abortHandler = () => {
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ // already dead
+ }
+ };
+ ctx.signal?.addEventListener("abort", abortHandler, { once: true });
+
+ child.stdin.write(ctx.message);
+ child.stdin.end();
+
+ const state = makeClaudeStreamState();
+ let stdoutBuf = "";
+ const events: HarnessEvent[] = [];
+ let exited = false;
+ let exitErr: string | null = null;
+ let resolveWait: (() => void) | null = null;
+ const wake = () => {
+ const r = resolveWait;
+ resolveWait = null;
+ if (r) r();
+ };
+
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdoutBuf += chunk;
+ let idx: number;
+ while ((idx = stdoutBuf.indexOf("\n")) >= 0) {
+ const line = stdoutBuf.slice(0, idx);
+ stdoutBuf = stdoutBuf.slice(idx + 1);
+ const out = parseClaudeLine(line, state);
+ for (const evt of out) events.push(evt);
+ if (out.length > 0) wake();
+ }
+ });
+
+ let stderrBuf = "";
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (chunk: string) => {
+ stderrBuf += chunk;
+ // Stream stderr lines as warnings — Claude Code uses stderr for status
+ // messages too, so we don't treat presence of stderr as an error.
+ });
+
+ child.on("error", (err) => {
+ exited = true;
+ exitErr = err instanceof Error ? err.message : String(err);
+ wake();
+ });
+ child.on("close", (code) => {
+ // Flush any tail bytes (no trailing newline case).
+ if (stdoutBuf.trim().length > 0) {
+ const out = parseClaudeLine(stdoutBuf, state);
+ for (const evt of out) events.push(evt);
+ stdoutBuf = "";
+ }
+ if (code !== 0 && !state.finalized) {
+ const tail = stderrBuf.trim().split("\n").slice(-5).join("\n");
+ events.push({
+ kind: "error",
+ message: `claude exited with code ${code}${tail ? `: ${tail}` : ""}`,
+ });
+ }
+ exited = true;
+ wake();
+ });
+
+ try {
+ while (!exited || events.length > 0) {
+ while (events.length > 0) {
+ const evt = events.shift()!;
+ yield evt;
+ }
+ if (exited) break;
+ await new Promise<void>((resolve) => {
+ resolveWait = resolve;
+ // Safety: never hang forever. Long tool calls can pause the stream;
+ // 5 min is generous for a single turn.
+ setTimeout(() => {
+ if (resolveWait === resolve) {
+ resolveWait = null;
+ resolve();
+ }
+ }, 300_000);
+ });
+ }
+ if (exitErr) {
+ yield { kind: "error", message: exitErr };
+ }
+ } finally {
+ ctx.signal?.removeEventListener("abort", abortHandler);
+ if (!exited) {
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ // ignore
+ }
+ }
+ }
+}
+
+function isUuid(s: string): boolean {
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
+}
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/index.ts b/notfair-cmo/src/server/adapters/claude-code-local/index.ts
new file mode 100644
index 00000000..bf7760ef
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/claude-code-local/index.ts
@@ -0,0 +1,38 @@
+import { homedir } from "node:os";
+import { join } from "node:path";
+import type {
+ HarnessAdapter,
+ HarnessExecuteContext,
+ HarnessEvent,
+ AgentProvisionSpec,
+ McpRegistrationSpec,
+} from "../types";
+import { executeClaudeCodeLocal } from "./execute";
+import { provisionClaudeCodeAgent } from "./provision";
+import { testClaudeCodeLocalEnvironment } from "./test";
+import { registerClaudeCodeMcp, unregisterClaudeCodeMcp } from "./mcp";
+
+function dataDir(): string {
+ return process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
+}
+
+function workspaceDirFor(agentId: string): string {
+ return join(dataDir(), "agents", agentId);
+}
+
+export const claudeCodeLocalAdapter: HarnessAdapter = {
+ id: "claude-code-local",
+ testEnvironment: testClaudeCodeLocalEnvironment,
+ execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void> {
+ return executeClaudeCodeLocal(ctx);
+ },
+ async provisionAgent(spec: AgentProvisionSpec): Promise<void> {
+ await provisionClaudeCodeAgent(spec);
+ },
+ async registerMcp(spec: McpRegistrationSpec): Promise<void> {
+ await registerClaudeCodeMcp(workspaceDirFor(spec.agentId), spec);
+ },
+ async unregisterMcp(serverName: string, agentId: string): Promise<void> {
+ await unregisterClaudeCodeMcp(workspaceDirFor(agentId), serverName);
+ },
+};
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
new file mode 100644
index 00000000..366876df
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/claude-code-local/mcp.test.ts
@@ -0,0 +1,151 @@
+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/mcp.ts b/notfair-cmo/src/server/adapters/claude-code-local/mcp.ts
new file mode 100644
index 00000000..e76e6660
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/claude-code-local/mcp.ts
@@ -0,0 +1,84 @@
+import { readFile, writeFile, mkdir } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+import type { McpRegistrationSpec } from "../types";
+
+/**
+ * Per-agent MCP wiring for Claude Code.
+ *
+ * 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
+ * project-scoped — one agent's notfair-googleads connection must not bleed
+ * into another agent's account.
+ */
+interface ClaudeMcpServerStdio {
+ type?: "stdio";
+ command: string;
+ args?: string[];
+ env?: Record<string, string>;
+}
+
+interface ClaudeMcpServerHttp {
+ type: "http" | "sse";
+ url: string;
+ headers?: Record<string, string>;
+}
+
+type ClaudeMcpServer = ClaudeMcpServerStdio | ClaudeMcpServerHttp;
+
+interface ClaudeMcpFile {
+ mcpServers: Record<string, ClaudeMcpServer>;
+}
+
+function mcpFilePath(workspaceDir: string): string {
+ return join(workspaceDir, ".mcp.json");
+}
+
+async function readMcpFile(workspaceDir: string): Promise<ClaudeMcpFile> {
+ const path = mcpFilePath(workspaceDir);
+ if (!existsSync(path)) return { mcpServers: {} };
+ try {
+ const raw = await readFile(path, "utf8");
+ const parsed = JSON.parse(raw) as Partial<ClaudeMcpFile>;
+ return { mcpServers: parsed.mcpServers ?? {} };
+ } catch {
+ return { mcpServers: {} };
+ }
+}
+
+async function writeMcpFile(workspaceDir: string, file: ClaudeMcpFile): Promise<void> {
+ await mkdir(workspaceDir, { recursive: true });
+ await writeFile(mcpFilePath(workspaceDir), JSON.stringify(file, null, 2), "utf8");
+}
+
+export async function registerClaudeCodeMcp(
+ workspaceDir: string,
+ spec: McpRegistrationSpec,
+): Promise<void> {
+ const file = await readMcpFile(workspaceDir);
+ if (spec.transport.type === "stdio") {
+ file.mcpServers[spec.serverName] = {
+ type: "stdio",
+ command: spec.transport.command,
+ args: spec.transport.args,
+ env: spec.transport.env,
+ };
+ } else {
+ file.mcpServers[spec.serverName] = {
+ type: "http",
+ url: spec.transport.url,
+ headers: spec.transport.headers,
+ };
+ }
+ await writeMcpFile(workspaceDir, file);
+}
+
+export async function unregisterClaudeCodeMcp(
+ workspaceDir: string,
+ serverName: string,
+): Promise<void> {
+ const file = await readMcpFile(workspaceDir);
+ delete file.mcpServers[serverName];
+ await writeMcpFile(workspaceDir, file);
+}
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
new file mode 100644
index 00000000..cc5f3c81
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/claude-code-local/parse.test.ts
@@ -0,0 +1,135 @@
+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/claude-code-local/parse.ts b/notfair-cmo/src/server/adapters/claude-code-local/parse.ts
new file mode 100644
index 00000000..f3167ca3
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/claude-code-local/parse.ts
@@ -0,0 +1,184 @@
+import type { HarnessEvent } from "../types";
+
+/**
+ * Claude Code emits one JSON object per line on stdout when invoked with
+ * `--output-format stream-json`. The shape (per the SDK docs) is a tagged
+ * union: assistant messages contain `content` blocks (text or tool_use),
+ * `result` messages signal turn completion, and `system` messages carry
+ * lifecycle metadata.
+ *
+ * This parser converts each line into zero or more HarnessEvents, tracking
+ * the byte offset of text already emitted so deltas are monotonic even when
+ * Claude re-broadcasts the running buffer.
+ */
+export interface ClaudeStreamState {
+ /** Last text length we forwarded as a delta — anything past this is new. */
+ emittedTextLen: number;
+ /** Concatenated assistant text seen so far this turn. */
+ assistantText: string;
+ /** Whether we've forwarded a `final` event yet. */
+ finalized: boolean;
+ /** Whether we've already emitted the `session` event this turn. */
+ sessionEmitted: boolean;
+}
+
+export function makeClaudeStreamState(): ClaudeStreamState {
+ return {
+ emittedTextLen: 0,
+ assistantText: "",
+ finalized: false,
+ sessionEmitted: false,
+ };
+}
+
+interface ClaudeContentBlock {
+ type?: string;
+ text?: string;
+ id?: string;
+ name?: string;
+ input?: Record<string, unknown>;
+}
+
+interface ClaudeStreamMessage {
+ type?: string;
+ subtype?: string;
+ message?: {
+ content?: ClaudeContentBlock[];
+ role?: string;
+ id?: string;
+ };
+ result?: string;
+ /** Error fields when subtype === "error". */
+ is_error?: boolean;
+ error?: { message?: string };
+ /** Some emitters use top-level `text` instead of nested message.content[].text. */
+ text?: string;
+ delta?: string;
+ /** Session id from the system event so we can correlate. */
+ session_id?: string;
+}
+
+/**
+ * Parse one Claude Code stream-json line. Returns the events that should be
+ * forwarded and mutates `state` to track progress.
+ */
+export function parseClaudeLine(
+ line: string,
+ state: ClaudeStreamState,
+): HarnessEvent[] {
+ const trimmed = line.trim();
+ if (!trimmed) return [];
+ let msg: ClaudeStreamMessage;
+ try {
+ msg = JSON.parse(trimmed) as ClaudeStreamMessage;
+ } catch {
+ return [];
+ }
+
+ const events: HarnessEvent[] = [];
+
+ if (msg.type === "system") {
+ if (typeof msg.subtype === "string") {
+ events.push({ kind: "lifecycle", phase: msg.subtype });
+ }
+ if (!state.sessionEmitted && typeof msg.session_id === "string") {
+ state.sessionEmitted = true;
+ events.push({ kind: "session", harnessSessionId: msg.session_id });
+ }
+ return events;
+ }
+
+ if (msg.type === "assistant" && msg.message?.content) {
+ for (const block of msg.message.content) {
+ if (block.type === "text" && typeof block.text === "string") {
+ state.assistantText += block.text;
+ if (state.assistantText.length > state.emittedTextLen) {
+ const delta = state.assistantText.slice(state.emittedTextLen);
+ state.emittedTextLen = state.assistantText.length;
+ events.push({ kind: "delta", text: delta });
+ }
+ } else if (block.type === "tool_use") {
+ const toolCallId = block.id ?? "";
+ const name = block.name ?? "tool";
+ events.push({
+ kind: "tool",
+ phase: "start",
+ toolCallId,
+ name,
+ label: labelForToolInput(name, block.input),
+ });
+ }
+ }
+ return events;
+ }
+
+ if (msg.type === "user" && msg.message?.content) {
+ // tool_result blocks come back as user messages; we surface them as `tool`
+ // result events so the UI can mark the in-progress step as done.
+ for (const block of msg.message.content) {
+ if (block.type === "tool_result") {
+ const toolCallId = (block as ClaudeContentBlock & { tool_use_id?: string }).tool_use_id ?? "";
+ events.push({
+ kind: "tool",
+ phase: "result",
+ toolCallId,
+ name: "",
+ });
+ }
+ }
+ return events;
+ }
+
+ if (msg.type === "result") {
+ state.finalized = true;
+ if (msg.subtype === "error_max_turns" || msg.subtype === "error_during_execution") {
+ events.push({
+ kind: "error",
+ message: msg.error?.message ?? msg.subtype,
+ });
+ return events;
+ }
+ const finalText = typeof msg.result === "string" ? msg.result : state.assistantText;
+ // Emit any trailing delta we missed (defensive — should be empty).
+ if (finalText.length > state.emittedTextLen) {
+ const delta = finalText.slice(state.emittedTextLen);
+ state.emittedTextLen = finalText.length;
+ events.push({ kind: "delta", text: delta });
+ }
+ events.push({ kind: "final", text: finalText });
+ return events;
+ }
+
+ return events;
+}
+
+function labelForToolInput(name: string, input: unknown): string | undefined {
+ if (!input || typeof input !== "object") return undefined;
+ const obj = input as Record<string, unknown>;
+ const tryKey = (k: string): string | null => {
+ const v = obj[k];
+ return typeof v === "string" && v.trim().length > 0 ? v.trim() : null;
+ };
+ // Bash command first line
+ if (name === "Bash" || name === "bash" || name === "exec") {
+ const cmd = tryKey("command") ?? tryKey("cmd") ?? tryKey("script");
+ if (cmd) {
+ const nl = cmd.indexOf("\n");
+ const line = nl >= 0 ? cmd.slice(0, nl) : cmd;
+ return line.length > 160 ? `${line.slice(0, 159)}…` : line;
+ }
+ }
+ // File paths
+ const path = tryKey("file_path") ?? tryKey("path") ?? tryKey("filename");
+ if (path) return shortenPath(path);
+ // URLs
+ const url = tryKey("url") ?? tryKey("uri");
+ if (url) return url;
+ return undefined;
+}
+
+function shortenPath(p: string): string {
+ const segs = p.split("/");
+ if (segs.length <= 2) return p;
+ return `…/${segs[segs.length - 2]}/${segs[segs.length - 1]}`;
+}
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/provision.ts b/notfair-cmo/src/server/adapters/claude-code-local/provision.ts
new file mode 100644
index 00000000..6f4dfbb7
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/claude-code-local/provision.ts
@@ -0,0 +1,31 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import type { AgentProvisionSpec } from "../types";
+
+/**
+ * Provision a workspace for Claude Code.
+ *
+ * Layout under `<workspaceDir>/`:
+ * IDENTITY.md — system prompt (notfair-cmo'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)
+ * PROJECT.md — project brief if available (sidecar for humans)
+ *
+ * No subprocess calls. Claude Code discovers the workspace lazily on first
+ * invocation; there's no "register agent" step.
+ */
+export async function provisionClaudeCodeAgent(spec: AgentProvisionSpec): Promise<void> {
+ await mkdir(spec.workspaceDir, { recursive: true });
+ await Promise.all([
+ writeFile(join(spec.workspaceDir, "IDENTITY.md"), spec.identityMd, "utf8"),
+ // Mirror to CLAUDE.md so the harness auto-loads it without us passing
+ // --append-system-prompt — useful when users open the workspace directly.
+ writeFile(join(spec.workspaceDir, "CLAUDE.md"), spec.identityMd, "utf8"),
+ spec.skillMd
+ ? writeFile(join(spec.workspaceDir, "SKILL.md"), spec.skillMd, "utf8")
+ : Promise.resolve(),
+ spec.projectMd
+ ? writeFile(join(spec.workspaceDir, "PROJECT.md"), spec.projectMd, "utf8")
+ : Promise.resolve(),
+ ]);
+}
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/test.ts b/notfair-cmo/src/server/adapters/claude-code-local/test.ts
new file mode 100644
index 00000000..b1633e6d
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/claude-code-local/test.ts
@@ -0,0 +1,79 @@
+import { spawn } from "node:child_process";
+import type { HarnessEnvironmentHealth } from "../types";
+
+const CLAUDE_BIN = process.env.NOTFAIR_CLAUDE_BIN?.trim() || "claude";
+
+/**
+ * Probe whether the local Claude Code CLI is installed and authed.
+ *
+ * `claude --version` exits 0 with a version string when the binary is on
+ * PATH. Auth state is best-inferred from `claude config get` returning
+ * a non-empty user section; we deliberately don't run a real prompt because
+ * doctor checks should be cheap and non-billable.
+ */
+export async function testClaudeCodeLocalEnvironment(): Promise<HarnessEnvironmentHealth> {
+ const versionResult = await runCmd(CLAUDE_BIN, ["--version"]);
+ if (versionResult.code !== 0) {
+ return {
+ ok: false,
+ auth: "unknown",
+ message: `\`${CLAUDE_BIN}\` not found on PATH. Install: https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview`,
+ };
+ }
+ const versionLabel = parseVersion(versionResult.stdout);
+
+ // Best-effort auth probe. `claude --print --output-format json --max-turns 0`
+ // is the cheapest path to detect an auth state without invoking the model,
+ // but it's not stable across versions, so we soft-fail to "unknown" if it
+ // doesn't behave as expected. Treat ok=true even with auth="unknown" — the
+ // user will see the real auth error on their first chat turn.
+ return {
+ ok: true,
+ auth: "unknown",
+ versionLabel,
+ };
+}
+
+interface CmdResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+function runCmd(cmd: string, args: string[], timeoutMs = 5_000): Promise<CmdResult> {
+ return new Promise((resolve) => {
+ let stdout = "";
+ let stderr = "";
+ let settled = false;
+ const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ // ignore
+ }
+ resolve({ code: 124, stdout, stderr: stderr || "timeout" });
+ }, timeoutMs);
+ child.stdout.on("data", (c: Buffer) => (stdout += c.toString("utf8")));
+ child.stderr.on("data", (c: Buffer) => (stderr += c.toString("utf8")));
+ child.on("error", () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({ code: 127, stdout, stderr });
+ });
+ child.on("close", (code) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({ code: code ?? 0, stdout, stderr });
+ });
+ });
+}
+
+function parseVersion(stdout: string): string {
+ const m = stdout.match(/(\d+\.\d+\.\d+[\w.\-+]*)/);
+ return m ? `Claude Code ${m[1]}` : "Claude Code";
+}
diff --git a/notfair-cmo/src/server/adapters/codex-local/execute.ts b/notfair-cmo/src/server/adapters/codex-local/execute.ts
new file mode 100644
index 00000000..5566c0e3
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/codex-local/execute.ts
@@ -0,0 +1,178 @@
+import { spawn } from "node:child_process";
+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 { getOrCreateMcpServerSecret } from "@/server/mcp-server/secret";
+import { listProjectMcpTokens } from "@/server/mcp/tokens";
+
+const CODEX_BIN = process.env.NOTFAIR_CODEX_BIN?.trim() || "codex";
+
+/**
+ * Stream one chat turn through the Codex CLI.
+ *
+ * Wire shape:
+ * - We spawn `codex exec --json --skip-git-repo-check -` and pipe the user
+ * message into stdin (the trailing `-` tells codex to read prompt from
+ * stdin).
+ * - Codex does not support a `--system-prompt` flag; instead it auto-loads
+ * AGENTS.md (and friends) from cwd. We write IDENTITY.md to the workspace
+ * AGENTS.md so codex picks it up.
+ * - For thread resumption, codex uses `codex exec resume <thread-id> -`.
+ * - Each stdout line is a JSON event; we forward as HarnessEvents.
+ */
+export async function* executeCodexLocal(
+ ctx: HarnessExecuteContext,
+): AsyncGenerator<HarnessEvent, void, void> {
+ // --dangerously-bypass-approvals-and-sandbox is what makes notfair-cmo
+ // 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
+ // 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
+ // (read its workspace, call our local MCP), so we run unsandboxed.
+ const args: string[] = [
+ "exec",
+ "--json",
+ "--skip-git-repo-check",
+ "--dangerously-bypass-approvals-and-sandbox",
+ ];
+
+ // 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
+ // fail with "thread not found".
+ if (ctx.harnessSessionId && isUuid(ctx.harnessSessionId)) {
+ args.push("resume", ctx.harnessSessionId, "-");
+ } else {
+ args.push("-");
+ }
+
+ // 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-googleads, gsc, etc.: per-project OAuth token from
+ // `mcp_tokens`
+ // Without per-server env vars every MCP would auth with the same
+ // (wrong) bearer and codex would either surface it as Auth Unsupported
+ // or pass the wrong token to the wrong server.
+ const mcpEnv: Record<string, string> = {
+ [CODEX_BEARER_ENV_VAR]: getOrCreateMcpServerSecret(),
+ };
+ for (const token of listProjectMcpTokens(ctx.projectSlug)) {
+ mcpEnv[bearerEnvVarForServer(token.server_name)] = token.access_token_enc;
+ }
+ const child = spawn(CODEX_BIN, args, {
+ cwd: ctx.workspaceDir,
+ env: {
+ ...process.env,
+ NOTFAIR_PROJECT_SLUG: ctx.projectSlug,
+ NOTFAIR_AGENT_ID: ctx.agentId,
+ ...mcpEnv,
+ },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ const abortHandler = () => {
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ // already dead
+ }
+ };
+ ctx.signal?.addEventListener("abort", abortHandler, { once: true });
+
+ child.stdin.write(ctx.message);
+ child.stdin.end();
+
+ const state = makeCodexStreamState();
+ let stdoutBuf = "";
+ const events: HarnessEvent[] = [];
+ let exited = false;
+ let exitErr: string | null = null;
+ let resolveWait: (() => void) | null = null;
+ const wake = () => {
+ const r = resolveWait;
+ resolveWait = null;
+ if (r) r();
+ };
+
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdoutBuf += chunk;
+ let idx: number;
+ while ((idx = stdoutBuf.indexOf("\n")) >= 0) {
+ const line = stdoutBuf.slice(0, idx);
+ stdoutBuf = stdoutBuf.slice(idx + 1);
+ const out = parseCodexLine(line, state);
+ for (const evt of out) events.push(evt);
+ if (out.length > 0) wake();
+ }
+ });
+
+ let stderrBuf = "";
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (chunk: string) => {
+ stderrBuf += chunk;
+ });
+
+ child.on("error", (err) => {
+ exited = true;
+ exitErr = err instanceof Error ? err.message : String(err);
+ wake();
+ });
+ child.on("close", (code) => {
+ if (stdoutBuf.trim().length > 0) {
+ const out = parseCodexLine(stdoutBuf, state);
+ for (const evt of out) events.push(evt);
+ stdoutBuf = "";
+ }
+ if (code !== 0 && !state.finalized) {
+ const tail = stderrBuf.trim().split("\n").slice(-5).join("\n");
+ events.push({
+ kind: "error",
+ message: `codex exited with code ${code}${tail ? `: ${tail}` : ""}`,
+ });
+ }
+ exited = true;
+ wake();
+ });
+
+ try {
+ while (!exited || events.length > 0) {
+ while (events.length > 0) {
+ const evt = events.shift()!;
+ yield evt;
+ }
+ if (exited) break;
+ await new Promise<void>((resolve) => {
+ resolveWait = resolve;
+ setTimeout(() => {
+ if (resolveWait === resolve) {
+ resolveWait = null;
+ resolve();
+ }
+ }, 300_000);
+ });
+ }
+ if (exitErr) {
+ yield { kind: "error", message: exitErr };
+ }
+ } finally {
+ ctx.signal?.removeEventListener("abort", abortHandler);
+ if (!exited) {
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ // ignore
+ }
+ }
+ }
+}
+
+function isUuid(s: string): boolean {
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
+}
diff --git a/notfair-cmo/src/server/adapters/codex-local/index.ts b/notfair-cmo/src/server/adapters/codex-local/index.ts
new file mode 100644
index 00000000..a1573b54
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/codex-local/index.ts
@@ -0,0 +1,28 @@
+import type {
+ HarnessAdapter,
+ HarnessExecuteContext,
+ HarnessEvent,
+ AgentProvisionSpec,
+ McpRegistrationSpec,
+} from "../types";
+import { executeCodexLocal } from "./execute";
+import { provisionCodexAgent } from "./provision";
+import { testCodexLocalEnvironment } from "./test";
+import { registerCodexMcp, unregisterCodexMcp } from "./mcp";
+
+export const codexLocalAdapter: HarnessAdapter = {
+ id: "codex-local",
+ testEnvironment: testCodexLocalEnvironment,
+ execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void> {
+ return executeCodexLocal(ctx);
+ },
+ async provisionAgent(spec: AgentProvisionSpec): Promise<void> {
+ await provisionCodexAgent(spec);
+ },
+ async registerMcp(spec: McpRegistrationSpec): Promise<void> {
+ await registerCodexMcp(spec);
+ },
+ async unregisterMcp(serverName: string, agentId: string): Promise<void> {
+ await unregisterCodexMcp(serverName, agentId);
+ },
+};
diff --git a/notfair-cmo/src/server/adapters/codex-local/mcp.test.ts b/notfair-cmo/src/server/adapters/codex-local/mcp.test.ts
new file mode 100644
index 00000000..332beec1
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/codex-local/mcp.test.ts
@@ -0,0 +1,153 @@
+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,
+ 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_cmo_greg__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_cmo_greg__notfair_orchestration\]/g,
+ );
+ expect(matches?.length).toBe(1);
+ });
+
+ it("namespaces by agent id so two agents don't collide", async () => {
+ await registerCodexMcp(makeHttpSpec({ agentId: "acme-cmo-greg" }));
+ await registerCodexMcp(makeHttpSpec({ agentId: "acme-google-ads-ana" }));
+ const toml = fsState.files.get("/codex/config.toml") ?? "";
+ expect(toml).toContain(
+ `[mcp_servers.notfair_acme_cmo_greg__notfair_orchestration]`,
+ );
+ expect(toml).toContain(
+ `[mcp_servers.notfair_acme_google_ads_ana__notfair_orchestration]`,
+ );
+ });
+});
+
+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 section", async () => {
+ await registerCodexMcp(makeHttpSpec({ agentId: "acme-cmo-greg" }));
+ await registerCodexMcp(makeHttpSpec({ agentId: "acme-google-ads-ana" }));
+ await unregisterCodexMcp("notfair-orchestration", "acme-cmo-greg");
+ const toml = fsState.files.get("/codex/config.toml") ?? "";
+ expect(toml).not.toContain("notfair_acme_cmo_greg__");
+ expect(toml).toContain("notfair_acme_google_ads_ana__");
+ });
+});
diff --git a/notfair-cmo/src/server/adapters/codex-local/mcp.ts b/notfair-cmo/src/server/adapters/codex-local/mcp.ts
new file mode 100644
index 00000000..a82b78d3
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/codex-local/mcp.ts
@@ -0,0 +1,143 @@
+import { readFile, writeFile, mkdir } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import type { McpRegistrationSpec } from "../types";
+
+/**
+ * Per-agent MCP wiring for Codex.
+ *
+ * Codex reads MCP servers from `~/.codex/config.toml`. notfair-cmo wants
+ * project-scoped tokens, but codex's MCP config is global, so we namespace
+ * server names with the agent id: `<serverName>__<agentId>`. The
+ * orchestration MCP that needs to know the agent context can read that.
+ *
+ * We rewrite the [mcp_servers.*] sections under our namespace prefix; we
+ * never touch user-installed servers outside our prefix.
+ */
+function codexConfigDir(): string {
+ return process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");
+}
+
+function codexConfigPath(): string {
+ return join(codexConfigDir(), "config.toml");
+}
+
+const NOTFAIR_NS = "notfair_";
+
+function namespaced(serverName: string, agentId: string): string {
+ return `${NOTFAIR_NS}${agentId.replace(/-/g, "_")}__${serverName.replace(/[^a-zA-Z0-9]/g, "_")}`;
+}
+
+async function readConfig(): Promise<string> {
+ const path = codexConfigPath();
+ if (!existsSync(path)) return "";
+ try {
+ return await readFile(path, "utf8");
+ } catch {
+ return "";
+ }
+}
+
+function stripSection(toml: string, sectionHeader: string): string {
+ // Remove a [mcp_servers."x"] block plus its key/value lines until the next
+ // section header or EOF. Best-effort regex — codex's TOML is well-formed
+ // and we only ever write what we wrote.
+ const re = new RegExp(
+ `\\n*\\[${escapeRe(sectionHeader)}\\][\\s\\S]*?(?=\\n\\[|\\n*$)`,
+ "g",
+ );
+ return toml.replace(re, "");
+}
+
+function escapeRe(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+/**
+ * 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
+ * different bearers. The spawn site (execute.ts) iterates the project's
+ * `mcp_tokens` table + the orchestration secret and injects matching
+ * env vars before invoking codex.
+ *
+ * Why env vars and not literal headers: codex 0.132+ marks raw
+ * `headers = { Authorization = "Bearer ..." }` rows as Auth: Unsupported
+ * and refuses to expose those MCP tools. The `bearer_token_env_var`
+ * 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.agentId)}]`;
+ if (spec.transport.type === "stdio") {
+ const lines = [
+ header,
+ `command = ${JSON.stringify(spec.transport.command)}`,
+ `args = ${JSON.stringify(spec.transport.args)}`,
+ ];
+ if (spec.transport.env) {
+ lines.push(`env = ${tomlInlineTable(spec.transport.env)}`);
+ }
+ return lines.join("\n") + "\n";
+ }
+ const lines = [header, `url = ${JSON.stringify(spec.transport.url)}`];
+ const rawAuth =
+ spec.transport.headers?.Authorization ??
+ spec.transport.headers?.authorization;
+ if (rawAuth) {
+ lines.push(
+ `bearer_token_env_var = ${JSON.stringify(bearerEnvVarForServer(spec.serverName))}`,
+ );
+ }
+ const otherHeaders: Record<string, string> = {};
+ for (const [k, v] of Object.entries(spec.transport.headers ?? {})) {
+ if (k.toLowerCase() !== "authorization") otherHeaders[k] = v;
+ }
+ if (Object.keys(otherHeaders).length > 0) {
+ lines.push(`headers = ${tomlInlineTable(otherHeaders)}`);
+ }
+ return lines.join("\n") + "\n";
+}
+
+function tomlInlineTable(record: Record<string, string>): string {
+ const parts = Object.entries(record).map(
+ ([k, v]) => `${k} = ${JSON.stringify(v)}`,
+ );
+ return `{ ${parts.join(", ")} }`;
+}
+
+export async function registerCodexMcp(spec: McpRegistrationSpec): Promise<void> {
+ await mkdir(codexConfigDir(), { recursive: true });
+ let toml = await readConfig();
+ toml = stripSection(toml, `mcp_servers.${namespaced(spec.serverName, spec.agentId)}`);
+ toml = toml.trimEnd() + "\n\n" + renderServer(spec);
+ await writeFile(codexConfigPath(), toml.trimStart(), "utf8");
+}
+
+export async function unregisterCodexMcp(
+ serverName: string,
+ agentId: string,
+): Promise<void> {
+ let toml = await readConfig();
+ if (!toml) return;
+ toml = stripSection(toml, `mcp_servers.${namespaced(serverName, agentId)}`);
+ await writeFile(codexConfigPath(), toml.trimStart(), "utf8");
+}
diff --git a/notfair-cmo/src/server/adapters/codex-local/parse.test.ts b/notfair-cmo/src/server/adapters/codex-local/parse.test.ts
new file mode 100644
index 00000000..1be71d62
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/codex-local/parse.test.ts
@@ -0,0 +1,85 @@
+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,
+ );
+ expect(out).toEqual([
+ {
+ kind: "tool",
+ phase: "start",
+ toolCallId: "cmd_1",
+ name: "ls -la",
+ label: "ls -la",
+ },
+ ]);
+ });
+
+ 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("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" }]);
+ expect(state.finalized).toBe(true);
+ });
+});
diff --git a/notfair-cmo/src/server/adapters/codex-local/parse.ts b/notfair-cmo/src/server/adapters/codex-local/parse.ts
new file mode 100644
index 00000000..409afe3b
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/codex-local/parse.ts
@@ -0,0 +1,148 @@
+import type { HarnessEvent } from "../types";
+
+/**
+ * Codex CLI emits one JSON event per line on stdout when invoked with
+ * `codex exec --json ...`. Event shape (per the OpenAI codex docs):
+ *
+ * { type: "thread.started", thread_id: "..." }
+ * { type: "item.started", item: { type: "agent_message" | "tool_call", ... } }
+ * { type: "item.completed", item: { type: "agent_message", text: "..." } }
+ * { type: "turn.completed", usage: { ... } }
+ * { type: "turn.failed", error: { message: "..." } }
+ * { type: "error", message: "..." }
+ *
+ * Codex does NOT emit token-by-token deltas — agent_message text arrives
+ * whole on item.completed. We forward it as one delta + a final at
+ * turn.completed so the UI flow matches Claude Code's event sequence.
+ */
+export interface CodexStreamState {
+ emittedTextLen: number;
+ assistantText: string;
+ finalized: boolean;
+ threadId: string | null;
+}
+
+export function makeCodexStreamState(): CodexStreamState {
+ return { emittedTextLen: 0, assistantText: "", finalized: false, threadId: null };
+}
+
+interface CodexEvent {
+ type?: string;
+ thread_id?: string;
+ message?: string;
+ item?: {
+ type?: string;
+ text?: string;
+ name?: string;
+ id?: string;
+ command?: string;
+ arguments?: Record<string, unknown>;
+ };
+ error?: { message?: string };
+}
+
+export function parseCodexLine(
+ line: string,
+ state: CodexStreamState,
+): HarnessEvent[] {
+ const trimmed = line.trim();
+ if (!trimmed) return [];
+ let event: CodexEvent;
+ try {
+ event = JSON.parse(trimmed) as CodexEvent;
+ } catch {
+ return [];
+ }
+
+ const events: HarnessEvent[] = [];
+
+ if (event.type === "thread.started") {
+ state.threadId = event.thread_id ?? state.threadId;
+ events.push({ kind: "lifecycle", phase: "start" });
+ if (state.threadId) {
+ events.push({ kind: "session", harnessSessionId: state.threadId });
+ }
+ return events;
+ }
+
+ if (event.type === "item.started" && event.item) {
+ const item = event.item;
+ if (item.type === "command_execution" || item.type === "tool_call") {
+ const rawName = item.name ?? item.command ?? "tool";
+ // Keep name single-line; multi-line commands belong in the label.
+ const toolName = rawName.split("\n")[0];
+ events.push({
+ kind: "tool",
+ phase: "start",
+ toolCallId: item.id ?? "",
+ name: toolName,
+ label: labelForCodexInput(toolName, item),
+ });
+ }
+ return events;
+ }
+
+ if (event.type === "item.completed" && event.item) {
+ const item = event.item;
+ if (item.type === "agent_message" && typeof item.text === "string") {
+ state.assistantText += item.text;
+ if (state.assistantText.length > state.emittedTextLen) {
+ const delta = state.assistantText.slice(state.emittedTextLen);
+ state.emittedTextLen = state.assistantText.length;
+ events.push({ kind: "delta", text: delta });
+ }
+ } else if (item.type === "command_execution" || item.type === "tool_call") {
+ events.push({
+ kind: "tool",
+ phase: "result",
+ toolCallId: item.id ?? "",
+ name: item.name ?? item.command ?? "tool",
+ });
+ }
+ return events;
+ }
+
+ if (event.type === "turn.completed") {
+ state.finalized = true;
+ events.push({ kind: "final", text: state.assistantText });
+ return events;
+ }
+
+ if (event.type === "turn.failed") {
+ state.finalized = true;
+ events.push({
+ kind: "error",
+ message: event.error?.message ?? "codex turn failed",
+ });
+ return events;
+ }
+
+ if (event.type === "error") {
+ events.push({ kind: "error", message: event.message ?? "codex error" });
+ return events;
+ }
+
+ return events;
+}
+
+function labelForCodexInput(
+ name: string,
+ item: { command?: string; arguments?: Record<string, unknown> },
+): string | undefined {
+ if (item.command && item.command.trim().length > 0) {
+ const firstLine = item.command.split("\n")[0];
+ return firstLine.length > 160 ? `${firstLine.slice(0, 159)}…` : firstLine;
+ }
+ if (!item.arguments) return undefined;
+ const tryKey = (k: string): string | null => {
+ const v = item.arguments?.[k];
+ return typeof v === "string" && v.trim().length > 0 ? v.trim() : null;
+ };
+ return (
+ tryKey("file_path") ??
+ tryKey("path") ??
+ tryKey("url") ??
+ tryKey("query") ??
+ undefined
+ );
+}
diff --git a/notfair-cmo/src/server/adapters/codex-local/provision.ts b/notfair-cmo/src/server/adapters/codex-local/provision.ts
new file mode 100644
index 00000000..09dc197e
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/codex-local/provision.ts
@@ -0,0 +1,26 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+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)
+ * AGENTS.md — same content; codex auto-loads AGENTS.md from cwd
+ * SKILL.md — shared orchestration skill text
+ * PROJECT.md — project brief if available
+ */
+export async function provisionCodexAgent(spec: AgentProvisionSpec): Promise<void> {
+ await mkdir(spec.workspaceDir, { recursive: true });
+ await Promise.all([
+ writeFile(join(spec.workspaceDir, "IDENTITY.md"), spec.identityMd, "utf8"),
+ writeFile(join(spec.workspaceDir, "AGENTS.md"), spec.identityMd, "utf8"),
+ spec.skillMd
+ ? writeFile(join(spec.workspaceDir, "SKILL.md"), spec.skillMd, "utf8")
+ : Promise.resolve(),
+ spec.projectMd
+ ? writeFile(join(spec.workspaceDir, "PROJECT.md"), spec.projectMd, "utf8")
+ : Promise.resolve(),
+ ]);
+}
diff --git a/notfair-cmo/src/server/adapters/codex-local/test.ts b/notfair-cmo/src/server/adapters/codex-local/test.ts
new file mode 100644
index 00000000..ff79709e
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/codex-local/test.ts
@@ -0,0 +1,64 @@
+import { spawn } from "node:child_process";
+import type { HarnessEnvironmentHealth } from "../types";
+
+const CODEX_BIN = process.env.NOTFAIR_CODEX_BIN?.trim() || "codex";
+
+export async function testCodexLocalEnvironment(): Promise<HarnessEnvironmentHealth> {
+ const versionResult = await runCmd(CODEX_BIN, ["--version"]);
+ if (versionResult.code !== 0) {
+ return {
+ ok: false,
+ auth: "unknown",
+ message: `\`${CODEX_BIN}\` not found on PATH. Install: https://github.com/openai/codex`,
+ };
+ }
+ return {
+ ok: true,
+ auth: "unknown",
+ versionLabel: parseVersion(versionResult.stdout),
+ };
+}
+
+interface CmdResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+function runCmd(cmd: string, args: string[], timeoutMs = 5_000): Promise<CmdResult> {
+ return new Promise((resolve) => {
+ let stdout = "";
+ let stderr = "";
+ let settled = false;
+ const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ // ignore
+ }
+ resolve({ code: 124, stdout, stderr: stderr || "timeout" });
+ }, timeoutMs);
+ child.stdout.on("data", (c: Buffer) => (stdout += c.toString("utf8")));
+ child.stderr.on("data", (c: Buffer) => (stderr += c.toString("utf8")));
+ child.on("error", () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({ code: 127, stdout, stderr });
+ });
+ child.on("close", (code) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({ code: code ?? 0, stdout, stderr });
+ });
+ });
+}
+
+function parseVersion(stdout: string): string {
+ const m = stdout.match(/(\d+\.\d+\.\d+[\w.\-+]*)/);
+ return m ? `Codex ${m[1]}` : "Codex";
+}
diff --git a/notfair-cmo/src/server/adapters/display-registry.ts b/notfair-cmo/src/server/adapters/display-registry.ts
new file mode 100644
index 00000000..2c867749
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/display-registry.ts
@@ -0,0 +1,50 @@
+import type { HarnessAdapterId } from "./types";
+
+/**
+ * UI metadata for the harness adapters. Mirrors paperclip's
+ * `adapter-display-registry.ts`. Drives the onboarding picker and any "you're
+ * using X" UI surface.
+ */
+export interface HarnessDisplay {
+ id: HarnessAdapterId;
+ label: string;
+ /** One-line description shown under the label on the picker card. */
+ description: string;
+ /** Show "Recommended" badge + put in the primary row of the picker. */
+ recommended: boolean;
+ /** Where to point a user who doesn't have the CLI installed. */
+ installUrl: string;
+ /** CLI binary name (for doctor checks, install hints). */
+ binary: string;
+}
+
+export const HARNESS_DISPLAY: Record<HarnessAdapterId, HarnessDisplay> = {
+ "claude-code-local": {
+ id: "claude-code-local",
+ label: "Claude Code",
+ description: "Run agents through Anthropic's Claude Code CLI. Uses your existing claude login.",
+ recommended: true,
+ installUrl: "https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview",
+ binary: "claude",
+ },
+ "codex-local": {
+ id: "codex-local",
+ label: "Codex",
+ description: "Run agents through OpenAI's Codex CLI. Uses your existing codex login.",
+ recommended: true,
+ installUrl: "https://github.com/openai/codex",
+ binary: "codex",
+ },
+};
+
+export function listRecommendedHarnesses(): HarnessDisplay[] {
+ return Object.values(HARNESS_DISPLAY).filter((h) => h.recommended);
+}
+
+export function listMoreHarnesses(): HarnessDisplay[] {
+ return Object.values(HARNESS_DISPLAY).filter((h) => !h.recommended);
+}
+
+export function getHarnessDisplay(id: HarnessAdapterId): HarnessDisplay {
+ return HARNESS_DISPLAY[id];
+}
diff --git a/notfair-cmo/src/server/adapters/registry.ts b/notfair-cmo/src/server/adapters/registry.ts
new file mode 100644
index 00000000..0b52cd1b
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/registry.ts
@@ -0,0 +1,37 @@
+import type { HarnessAdapter, HarnessAdapterId } from "./types";
+import { claudeCodeLocalAdapter } from "./claude-code-local";
+import { codexLocalAdapter } from "./codex-local";
+
+const adapters = new Map<HarnessAdapterId, HarnessAdapter>();
+
+function registerBuiltins(): void {
+ adapters.set(claudeCodeLocalAdapter.id, claudeCodeLocalAdapter);
+ adapters.set(codexLocalAdapter.id, codexLocalAdapter);
+}
+registerBuiltins();
+
+export function getAdapter(id: HarnessAdapterId): HarnessAdapter | null {
+ return adapters.get(id) ?? null;
+}
+
+export function requireAdapter(id: HarnessAdapterId): HarnessAdapter {
+ const hit = adapters.get(id);
+ if (!hit) {
+ throw new Error(`Unknown harness adapter: ${id}`);
+ }
+ return hit;
+}
+
+export function listAdapters(): HarnessAdapter[] {
+ return Array.from(adapters.values());
+}
+
+/**
+ * Default adapter used when a project hasn't picked one. Claude Code is the
+ * recommended default per the onboarding UX.
+ */
+export const DEFAULT_HARNESS_ADAPTER: HarnessAdapterId = "claude-code-local";
+
+export function isHarnessAdapterId(value: unknown): value is HarnessAdapterId {
+ return value === "claude-code-local" || value === "codex-local";
+}
diff --git a/notfair-cmo/src/server/adapters/types.ts b/notfair-cmo/src/server/adapters/types.ts
new file mode 100644
index 00000000..2d3b29d0
--- /dev/null
+++ b/notfair-cmo/src/server/adapters/types.ts
@@ -0,0 +1,122 @@
+/**
+ * HarnessAdapter — notfair-cmo's plug-in shape for a local AI coding agent.
+ *
+ * Inspired by paperclip's ServerAdapterModule but pared down: notfair-cmo runs
+ * locally only, so there's no remote execution target, no workspace bridge,
+ * no skill catalog interop. An adapter only needs to:
+ *
+ * 1. Validate its environment (binary installed, auth OK) — testEnvironment
+ * 2. Stream a chat turn for an agent — execute
+ * 3. Provision an agent workspace — provisionAgent
+ * 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.
+ */
+export type HarnessAdapterId = "claude-code-local" | "codex-local";
+
+export interface HarnessEnvironmentHealth {
+ ok: boolean;
+ /** Short label for the status row (e.g. "Claude Code 1.0.42"). */
+ versionLabel?: string;
+ /** Path to the binary that was probed. */
+ binaryPath?: string;
+ /** Auth state: "ok", "missing", "expired", or "unknown" when not applicable. */
+ auth?: "ok" | "missing" | "expired" | "unknown";
+ /** Human-readable failure reason when ok=false. */
+ message?: string;
+}
+
+export interface AgentProvisionSpec {
+ /** Project slug (e.g. "acme"). */
+ projectSlug: string;
+ /** Agent backend id (e.g. "acme-cmo-greg"). */
+ agentId: string;
+ /** Personal display name (e.g. "Greg"). */
+ displayName: string;
+ /** Role / template key (e.g. "cmo", "google_ads"). */
+ 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. */
+ skillMd?: string;
+ /** PROJECT.md context, if a project brief exists yet. */
+ projectMd?: string;
+}
+
+export interface McpRegistrationSpec {
+ /** Logical server name (e.g. "notfair-googleads"). */
+ serverName: string;
+ /** Agent this server should be available to. */
+ agentId: string;
+ /** Project slug — adapters that scope MCP per workspace use this. */
+ projectSlug: string;
+ /** Transport: stdio command, HTTP URL, or local SSE. */
+ transport:
+ | { type: "stdio"; command: string; args: string[]; env?: Record<string, string> }
+ | { type: "http"; url: string; headers?: Record<string, string> };
+}
+
+/**
+ * Execution context for one chat turn.
+ *
+ * The adapter knows nothing about notfair-cmo 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.
+ */
+export interface HarnessExecuteContext {
+ projectSlug: string;
+ agentId: string;
+ workspaceDir: string;
+ /** The user message for this turn. */
+ message: string;
+ /**
+ * Stable thread identifier owned by notfair-cmo (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.
+ */
+ threadId: string;
+ /**
+ * The harness's own session id from a prior turn on this thread, if any.
+ * When set, adapters pass it to their CLI's resume flag (e.g. claude
+ * `--resume`, codex `exec resume`). Null on the first turn of a thread.
+ */
+ harnessSessionId?: string | null;
+ /** Optional cancellation. When aborted the adapter kills its subprocess. */
+ signal?: AbortSignal;
+}
+
+export type HarnessEvent =
+ | { kind: "delta"; text: string }
+ | {
+ kind: "tool";
+ phase: "start" | "update" | "result";
+ toolCallId: string;
+ name: string;
+ label?: string;
+ }
+ | { kind: "lifecycle"; phase: string }
+ | { kind: "final"; text: string }
+ | { kind: "error"; message: string }
+ /**
+ * Adapter has learned the harness's own session id for this thread. The
+ * caller should persist it on the `sessions.harness_session_id` column
+ * so the next turn can pass it to the adapter as `harnessSessionId` for
+ * resume. Emitted at most once per turn.
+ */
+ | { kind: "session"; harnessSessionId: string };
+
+export interface HarnessAdapter {
+ readonly id: HarnessAdapterId;
+
+ testEnvironment(): Promise<HarnessEnvironmentHealth>;
+
+ execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void>;
+
+ provisionAgent(spec: AgentProvisionSpec): Promise<void>;
+
+ registerMcp(spec: McpRegistrationSpec): Promise<void>;
+ unregisterMcp(serverName: string, agentId: string): Promise<void>;
+}
diff --git a/notfair-cmo/src/server/agent-meta.test.ts b/notfair-cmo/src/server/agent-meta.test.ts
index 11a665ac..5d754b44 100644
--- a/notfair-cmo/src/server/agent-meta.test.ts
+++ b/notfair-cmo/src/server/agent-meta.test.ts
@@ -314,13 +314,44 @@ describe("listProjectAgents", () => {
it("skips entries with a matching prefix but no meta sidecar", async () => {
// Create a phantom agent dir without a notfair-meta.json — simulates an
- // OpenClaw workspace dir without the sidecar (e.g., pre-sidecar agents).
+ // 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", () => {
diff --git a/notfair-cmo/src/server/agent-meta.ts b/notfair-cmo/src/server/agent-meta.ts
index ff51b217..0d4aeb3a 100644
--- a/notfair-cmo/src/server/agent-meta.ts
+++ b/notfair-cmo/src/server/agent-meta.ts
@@ -85,7 +85,10 @@ export type ProjectAgentEntry = {
/**
* List agents for a project. Source of truth:
- * - notfair-meta.json sidecars under `<DATA_DIR>/agents/<projectSlug>-*`.
+ * - 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.
@@ -120,7 +123,10 @@ export async function listProjectAgents(project_slug: string): Promise<ProjectAg
}
// 2) Overlay anything we have meta for (template agents written by
- // ensureProjectAgents, plus cloned/custom agents).
+ // 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 {
@@ -129,11 +135,18 @@ export async function listProjectAgents(project_slug: string): Promise<ProjectAg
// 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;
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 cfe1b07c..00000000
--- a/notfair-cmo/src/server/agent-templates.test.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { mkdtempSync, rmSync, readFileSync, existsSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-// ── Mocks ────────────────────────────────────────────────────────────
-// We're testing writeIdentityFile's COMPOSITION behavior end-to-end
-// (file-on-disk shape), so:
-// - openclaw CLI: stubbed (we don't actually shell out)
-// - listProjects: empty (no legacy MCP cleanup needed)
-// - mcp-server/registration: stubbed (provisioning calls into it)
-// - agent-meta.writeAgentMeta: stubbed (also touches disk, not what we test)
-// The real fs writes through.
-
-vi.mock("@/server/openclaw/cli", () => ({
- openclaw: vi.fn(async (args: string[]) => {
- // ensureProjectAgents calls `openclaw agents list` to check existence,
- // and `openclaw agents add` to provision. Stub both as no-ops returning
- // an empty agent list so every template is treated as "new". Track
- // the added ids so the gateway-list mock below can pretend the
- // gateway already knows about them (closes the test-time race).
- if (args[0] === "agents" && args[1] === "list") return "";
- if (args[0] === "agents" && args[1] === "add" && typeof args[2] === "string") {
- seenAgentIds.add(args[2]);
- }
- return undefined;
- }),
- OpenClawError: class extends Error {},
-}));
-
-vi.mock("@/server/db/projects", () => ({
- listProjects: () => [],
-}));
-
-vi.mock("@/server/mcp-server/registration", () => ({
- ensureOrchestrationMcpInstalled: vi.fn(async () => ({
- ok: true,
- status: "already_installed",
- key: "notfair-orchestration",
- url: "http://127.0.0.1:3326/api/mcp/orchestration",
- })),
- cleanupLegacyOrchestrationRows: vi.fn(async () => {}),
-}));
-
-vi.mock("@/server/agent-meta", () => ({
- writeAgentMeta: vi.fn(async () => {}),
-}));
-
-// Provisioning now waits for the gateway's runtime agents list to include
-// the newly-created ids before returning (closes the post-`openclaw agents
-// add` race that stranded onboarding kickoffs). Use a permissive mock that
-// claims every requested id is already present — the wait drops out on its
-// first iteration so provisioning returns synchronously like before.
-const seenAgentIds = new Set<string>();
-vi.mock("@/server/openclaw/gateway-rpc", () => ({
- listAllAgents: vi.fn(async () => ({
- defaultId: "main",
- mainKey: "main",
- agents: [...seenAgentIds].map((id) => ({ id })),
- })),
-}));
-
-import { ensureProjectAgents, agentNameFor } from "./agent-templates";
-import { getOrchestrationSkill } from "./skills/orchestration-skill";
-
-let tmpDataDir: string;
-const ORIGINAL_ENV = process.env.NOTFAIR_CMO_DATA_DIR;
-
-beforeEach(() => {
- tmpDataDir = mkdtempSync(join(tmpdir(), "notfair-cmo-templates-"));
- process.env.NOTFAIR_CMO_DATA_DIR = tmpDataDir;
-});
-
-afterEach(() => {
- if (ORIGINAL_ENV === undefined) delete process.env.NOTFAIR_CMO_DATA_DIR;
- else process.env.NOTFAIR_CMO_DATA_DIR = ORIGINAL_ENV;
- if (tmpDataDir && existsSync(tmpDataDir)) {
- rmSync(tmpDataDir, { recursive: true, force: true });
- }
-});
-
-function read(slug: string, file: "IDENTITY.md" | "SKILL.md"): string {
- return readFileSync(
- join(tmpDataDir, "agents", `${slug}`, file),
- "utf8",
- );
-}
-
-describe("ensureProjectAgents — IDENTITY.md per-agent + SKILL.md shared", () => {
- it("provisions CMO + Google Ads + SEO and writes both files for each", async () => {
- await ensureProjectAgents("demo");
- // Agent ids encode the personal name (default_name per template).
- for (const slug of ["demo-cmo-greg", "demo-google-ads-ana", "demo-seo-sam"]) {
- expect(existsSync(join(tmpDataDir, "agents", slug, "IDENTITY.md"))).toBe(
- true,
- );
- expect(existsSync(join(tmpDataDir, "agents", slug, "SKILL.md"))).toBe(
- true,
- );
- }
- });
-
- // System-prompt-size regression guard: OpenClaw seeds each workspace with
- // ~11 KB of generic boilerplate (camera tools, memory rituals, etc.) that
- // gets injected into every model call but doesn't apply to a marketing
- // CMO. We overwrite the five OpenClaw-default files with sub-300-char
- // stubs so the system prompt stays lean. If someone resurrects the
- // boilerplate, this test catches it.
- it("overwrites OpenClaw default workspace files with minimal stubs", async () => {
- await ensureProjectAgents("demo");
- for (const fname of [
- "AGENTS.md",
- "SOUL.md",
- "TOOLS.md",
- "USER.md",
- "HEARTBEAT.md",
- ]) {
- const path = join(tmpDataDir, "agents", "demo-cmo-greg", fname);
- expect(existsSync(path)).toBe(true);
- const body = readFileSync(path, "utf8");
- // Generous bound; the stubs are ~150–300 chars. Anything beyond 1 KB
- // means the OpenClaw boilerplate snuck back in.
- expect(body.length).toBeLessThan(1024);
- }
- });
-
- it("SKILL.md is byte-identical across all three agents (shared source of truth)", async () => {
- await ensureProjectAgents("demo");
- const cmo = read("demo-cmo-greg", "SKILL.md");
- const ga = read("demo-google-ads-ana", "SKILL.md");
- const seo = read("demo-seo-sam", "SKILL.md");
- expect(cmo).toBe(ga);
- expect(ga).toBe(seo);
- // And matches the exported constant verbatim.
- expect(cmo).toBe(getOrchestrationSkill());
- });
-
- it("each IDENTITY.md pins the correct per-agent runtime identity", async () => {
- await ensureProjectAgents("demo");
- const cmo = read("demo-cmo-greg", "IDENTITY.md");
- const ga = read("demo-google-ads-ana", "IDENTITY.md");
- const seo = read("demo-seo-sam", "IDENTITY.md");
-
- // Every IDENTITY.md must mention this project + its own agent_id.
- expect(cmo).toMatch(/`project_slug`: `demo`/);
- expect(cmo).toMatch(/`agent_id`: `demo-cmo-greg`/);
-
- expect(ga).toMatch(/`project_slug`: `demo`/);
- expect(ga).toMatch(/`agent_id`: `demo-google-ads-ana`/);
-
- expect(seo).toMatch(/`project_slug`: `demo`/);
- expect(seo).toMatch(/`agent_id`: `demo-seo-sam`/);
-
- // Cross-agent leakage check: an agent must NOT see another agent's id.
- expect(cmo).not.toContain("`agent_id`: `demo-google-ads-ana`");
- expect(cmo).not.toContain("`agent_id`: `demo-seo-sam`");
- expect(ga).not.toContain("`agent_id`: `demo-cmo-greg`");
- expect(ga).not.toContain("`agent_id`: `demo-seo-sam`");
- expect(seo).not.toContain("`agent_id`: `demo-cmo-greg`");
- expect(seo).not.toContain("`agent_id`: `demo-google-ads-ana`");
- });
-
- it("each IDENTITY.md appends the full shared skill verbatim after the '---' separator", async () => {
- await ensureProjectAgents("demo");
- const skill = getOrchestrationSkill();
- for (const slug of ["demo-cmo-greg", "demo-google-ads-ana", "demo-seo-sam"]) {
- const body = read(slug, "IDENTITY.md");
- // The separator + skill appear AFTER the role-specific section.
- const sepIdx = body.indexOf("\n---\n");
- expect(sepIdx).toBeGreaterThan(0);
- const tail = body.slice(sepIdx);
- expect(tail).toContain(skill);
- }
- });
-
- it("CMO's role section says 'orchestrator' and specialist sections say 'specialist worker'", async () => {
- await ensureProjectAgents("demo");
- const cmo = read("demo-cmo-greg", "IDENTITY.md");
- const ga = read("demo-google-ads-ana", "IDENTITY.md");
- const seo = read("demo-seo-sam", "IDENTITY.md");
-
- expect(cmo).toContain("## Your role: orchestrator");
- expect(cmo).not.toContain("## Your role: specialist worker");
-
- expect(ga).toContain("## Your role: specialist worker");
- expect(ga).not.toContain("## Your role: orchestrator");
-
- expect(seo).toContain("## Your role: specialist worker");
- expect(seo).not.toContain("## Your role: orchestrator");
- });
-
- it("specialist IDENTITY.md mentions its domain tool (notfair-googleads / GSC)", async () => {
- await ensureProjectAgents("demo");
- const ga = read("demo-google-ads-ana", "IDENTITY.md");
- expect(ga).toContain("notfair-googleads MCP");
- expect(ga).toContain("ads.gaql");
-
- const seo = read("demo-seo-sam", "IDENTITY.md");
- expect(seo).toMatch(/Google Search Console/);
- });
-
- it("CMO IDENTITY.md does NOT contain specialist-only role text and vice versa", async () => {
- await ensureProjectAgents("demo");
- const cmo = read("demo-cmo-greg", "IDENTITY.md");
- const ga = read("demo-google-ads-ana", "IDENTITY.md");
- expect(cmo).not.toContain("## Your role: specialist worker");
- expect(ga).not.toContain("## Your role: orchestrator");
- });
-
- it("re-provisioning the same project rewrites IDENTITY.md (idempotent + picks up skill edits)", async () => {
- await ensureProjectAgents("demo");
- const before = read("demo-cmo-greg", "IDENTITY.md");
- await ensureProjectAgents("demo");
- const after = read("demo-cmo-greg", "IDENTITY.md");
- expect(after).toBe(before);
- });
-
- it("isolates identity across projects (no cross-project bleed)", async () => {
- await ensureProjectAgents("alpha");
- await ensureProjectAgents("beta");
- const alphaCmo = read("alpha-cmo-greg", "IDENTITY.md");
- const betaCmo = read("beta-cmo-greg", "IDENTITY.md");
- expect(alphaCmo).toContain("`project_slug`: `alpha`");
- expect(alphaCmo).toContain("`agent_id`: `alpha-cmo-greg`");
- expect(alphaCmo).not.toMatch(/`project_slug`: `beta`/);
- expect(alphaCmo).not.toMatch(/`agent_id`: `beta-cmo-greg`/);
- expect(betaCmo).toContain("`project_slug`: `beta`");
- expect(betaCmo).toContain("`agent_id`: `beta-cmo-greg`");
- expect(betaCmo).not.toMatch(/`project_slug`: `alpha`/);
- });
-});
-
-describe("agentNameFor (used to derive per-agent identity values)", () => {
- it("encodes <project-slug>-<role>-<slugified-name>", () => {
- expect(agentNameFor("demo", "cmo", "Greg")).toBe("demo-cmo-greg");
- expect(agentNameFor("demo", "google_ads", "Ana")).toBe(
- "demo-google-ads-ana",
- );
- expect(agentNameFor("demo", "seo", "Sam")).toBe("demo-seo-sam");
- });
-
- it("slugifies multi-word names + handles symbols", () => {
- expect(agentNameFor("demo", "google_ads", "Sam Q4!")).toBe(
- "demo-google-ads-sam-q4",
- );
- });
-});
diff --git a/notfair-cmo/src/server/agent-templates.ts b/notfair-cmo/src/server/agent-templates.ts
index 77f6aa52..95816bb0 100644
--- a/notfair-cmo/src/server/agent-templates.ts
+++ b/notfair-cmo/src/server/agent-templates.ts
@@ -1,21 +1,16 @@
-import { mkdir, writeFile } from "node:fs/promises";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { openclaw } from "@/server/openclaw/cli";
-import { listAllAgents } from "@/server/openclaw/gateway-rpc";
+import { stat } from "node:fs/promises";
import {
initProgress,
updateStep,
type ProgressStep,
} from "@/server/onboarding/provisioning-progress";
import { readAgentMeta, writeAgentMeta } from "@/server/agent-meta";
-import {
- cleanupLegacyOrchestrationRows,
- ensureOrchestrationMcpInstalled,
-} from "@/server/mcp-server/registration";
-import { listProjects } from "@/server/db/projects";
+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 { registerOrchestrationForAgent } from "@/server/mcp-server/registration";
/**
* Role-specific behavior for the CMO. Concise — the procedural how-to
@@ -323,356 +318,187 @@ export async function ensureProjectAgents(
// 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. The "gateway" row
- // covers the snapshot-warm-up that happens after the openclaw rows
- // are written.
- const progressSteps: ProgressStep[] = [
- ...templates.map<ProgressStep>((t) => ({
- key: t.key,
- label: `Setting up ${t.display_name}${t.key === "cmo" ? "" : " specialist"}`,
- status: "pending",
- })),
- {
- key: "gateway",
- label: "Connecting agents to gateway",
- status: "pending",
- },
- ];
+ // checklist instead of a single opaque spinner.
+ const progressSteps: ProgressStep[] = templates.map<ProgressStep>((t) => ({
+ key: t.key,
+ label: `Setting up ${t.display_name}${t.key === "cmo" ? "" : " specialist"}`,
+ 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" });
- // Resolve the personal name FIRST. The agent_id encodes it, so this
- // value drives both the OpenClaw backend name and the URL slug.
const personalName = names?.[template.key] ?? template.default_name;
const agentId = agentNameFor(project_slug, template.key, personalName);
- const workspaceAbs = workspaceDirFor(agentId);
const already = await agentExists(agentId);
- if (already) {
- // Idempotently refresh the IDENTITY.md so prompt edits propagate to
- // existing agents without forcing the user to delete + recreate.
- await writeIdentityFile(workspaceAbs, template, project_slug, agentId);
- // Read any existing meta so we PRESERVE the previously-chosen name
- // (immutable per the agent model). Only when no sidecar exists yet
- // do we fall back to the onboarding `names` map / template default.
- const existing = readAgentMeta(agentId);
- const finalName = existing?.name ?? personalName;
- await writeAgentMeta({
- agent_id: agentId,
+
+ try {
+ const identityMd = renderIdentity({
+ template,
project_slug,
- name: finalName,
- template_key: template.key,
- created_at: existing?.created_at ?? new Date().toISOString(),
+ agent_id: agentId,
+ skill,
+ brief,
});
- existed.push(agentId);
- updateStep(project_slug, template.key, { status: "done" });
- continue;
- }
- try {
- // We deliberately do NOT pass --model. OpenClaw applies its
- // agents.defaults.model config (primary + fallbacks chain) when no model
- // is specified. Overriding only the primary string would strip the user's
- // configured fallback list and reintroduce single-point-of-failure
- // behavior on provider cooldowns. The template.model field stays in
- // metadata for documentation; future versions can wire a multi-model
- // override once `openclaw agents add` supports it.
- await openclaw([
- "agents",
- "add",
+ await provisionAgent({
+ projectSlug: project_slug,
agentId,
- "--non-interactive",
- "--workspace",
- workspaceAbs,
- ]);
- await writeIdentityFile(workspaceAbs, template, project_slug, agentId);
- await writeAgentMeta({
- agent_id: agentId,
- project_slug,
- name: personalName,
- template_key: template.key,
- created_at: new Date().toISOString(),
+ displayName: personalName,
+ templateKey: template.key,
+ identityMd,
+ skillMd: skill,
+ projectMd: brief ?? undefined,
+ harnessAdapter,
});
- created.push(agentId);
+ // 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,
+ );
+ }
+ // 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) {
- // Surface but don't crash the loop; partial provisioning recoverable on retry.
const message = err instanceof Error ? err.message : String(err);
- console.error(`Failed to create agent ${agentId}:`, err);
+ console.error(`Failed to provision agent ${agentId}:`, err);
failed.push({ name: agentId, error: message });
- updateStep(project_slug, template.key, {
- status: "failed",
- error: message,
- });
+ updateStep(project_slug, template.key, { status: "failed", error: message });
}
}
- // After provisioning, the openclaw config file has the new agent rows
- // but the gateway daemon's pinned runtime snapshot lags by a beat —
- // sending chat.send during that window hits an INVALID_REQUEST
- // "Agent '<id>' no longer exists in configuration". Wait until the
- // gateway's agents.list reports every newly-created id so the kickoff
- // path immediately after this (createProjectForOnboardingAction's
- // startTaskIfProposed) finds a warm gateway. Best-effort: a timeout
- // here doesn't block provisioning — runTaskKickoffServerSide also has
- // retry-on-this-error as a second line of defense.
- if (created.length > 0) {
- updateStep(project_slug, "gateway", { status: "in_progress" });
- await waitForGatewayToSeeAgents(created);
- updateStep(project_slug, "gateway", { status: "done" });
- } else {
- updateStep(project_slug, "gateway", { status: "done" });
- }
-
- // Register the orchestration MCP server with OpenClaw — once, globally.
- // Tools are project-scoped via a required `project_slug` argument on every
- // call, so a single registration serves every project + every agent in
- // this install. ensureOrchestrationMcpInstalled checks the existing row
- // first and is a no-op when already correct.
- //
- // Also opportunistically prune the legacy per-project rows we wrote
- // before going global. Idempotent — does nothing on fresh installs.
- //
- // Failure is non-fatal: agents fall back to the legacy text-block protocol
- // (still parsed server-side in process-blocks.ts).
- try {
- const r = await ensureOrchestrationMcpInstalled();
- if (!r.ok) {
- console.error(`[provision] orchestration MCP install failed: ${r.error}`);
- }
- const allSlugs = listProjects({ includeArchived: true }).map((p) => p.slug);
- await cleanupLegacyOrchestrationRows(allSlugs);
- } catch (err) {
- console.error("[provision] orchestration MCP install threw:", err);
- }
+ // 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 };
}
/**
- * Poll the gateway's `agents.list` until every newly-provisioned id shows
- * up (or the timeout expires). Closes the post-`openclaw agents add` race
- * where the runtime config snapshot hasn't caught up to the on-disk
- * config file yet, so chat.send hits "Agent '<id>' no longer exists in
- * configuration".
+ * 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).
*/
-async function waitForGatewayToSeeAgents(
- expected: string[],
- opts: { timeoutMs?: number; intervalMs?: number } = {},
-): Promise<void> {
- const timeoutMs = opts.timeoutMs ?? 15_000;
- const intervalMs = opts.intervalMs ?? 500;
- const deadline = Date.now() + timeoutMs;
- const want = new Set(expected);
- while (Date.now() < deadline) {
- try {
- const list = await listAllAgents();
- const seen = new Set(list.agents.map((a) => a.id));
- if ([...want].every((id) => seen.has(id))) return;
- } catch (err) {
- // Transient — gateway may be momentarily unreachable during config
- // rewrites. Fall through to the sleep + retry.
- console.warn(
- `[provision] gateway agents.list probe failed: ${err instanceof Error ? err.message : String(err)}`,
- );
- }
- await new Promise((r) => setTimeout(r, intervalMs));
- }
- console.warn(
- `[provision] gateway didn't surface all new agents within ${timeoutMs}ms; kickoffs will rely on the retry-on-stale-snapshot path`,
- );
-}
-
-function workspaceDirFor(name: string): string {
- const dataDir = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
- return join(dataDir, "agents", name);
-}
-
-async function writeIdentityFile(
- workspaceAbs: string,
- template: AgentTemplate,
- project_slug?: string,
- agent_id?: string,
-): Promise<void> {
- try {
- await mkdir(workspaceAbs, { recursive: true });
-
- // Per-agent identity block — every MCP tool requires the agent to pass
- // its own `project_slug` and `agent_id`, so pin both right at the top
- // of the prompt so the model can fill them into tool calls without
- // guessing. Stable plain text so it survives model version changes.
- const identityBlock = project_slug && agent_id
- ? `\n## Your runtime identity\n\nWhen calling notfair-orchestration MCP tools, pass these exact values:\n\n- \`project_slug\`: \`${project_slug}\`\n- \`agent_id\`: \`${agent_id}\`\n\nDo NOT invent other values. Every orchestration tool call requires both.\n`
- : "";
-
- // Shared, role-agnostic procedural knowledge. Paperclip-style: every
- // agent loads the same skill so MCP tool semantics, state machine,
- // and cron CLI live in one source of truth. Edits to the skill
- // propagate on next provision.
- const skill = getOrchestrationSkill();
-
- // Write SKILL.md to the workspace too — purely cosmetic (OpenClaw
- // reads IDENTITY.md as the agent's prompt source) but useful for
- // humans inspecting an agent's workspace to confirm the skill is
- // in lockstep across all three agents.
- await writeFile(join(workspaceAbs, "SKILL.md"), skill, "utf8");
-
- // Project context: PROJECT.md is the single source of truth for "what
- // is this company / project". Written by the CMO during the first
- // onboarding task via `set_project_brief`. We inline it into IDENTITY.md
- // so every agent in the project (CMO + specialists) shares the same
- // context, and write a sidecar PROJECT.md copy so humans inspecting
- // the workspace see what the agent has. The canonical file lives at
- // ~/.notfair-cmo/projects/<slug>/PROJECT.md.
- let projectContextSection = "";
- if (project_slug) {
- const brief = await readProjectBrief(project_slug);
- if (brief !== null) {
- await writeFile(join(workspaceAbs, "PROJECT.md"), brief, "utf8");
- projectContextSection = `\n## Project context\n\nShared across every agent in this project — derived during onboarding\nand kept in sync via the \`set_project_brief\` MCP tool. Treat this as\nthe authoritative description of who the user is and what they sell.\n\n${brief.trim()}\n`;
- }
- }
-
- // IDENTITY.md = role-specific bits on top, shared skill verbatim
- // below a separator. The separator makes it obvious which half is
- // per-agent and which is shared when a human reads the file.
- const body = `# ${template.display_name}
-
-${template.description}
+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}
-${template.system_prompt}
+${input.template.system_prompt}
---
-${skill}`;
- await writeFile(join(workspaceAbs, "IDENTITY.md"), body, "utf8");
-
- // OpenClaw seeds every agent workspace with generic AGENTS.md / SOUL.md
- // / TOOLS.md / USER.md / HEARTBEAT.md boilerplate (~11 KB total) aimed
- // at general-purpose assistants — workspace memory rituals, camera/SSH
- // tool notes, user-profile templates. None of it applies to a marketing
- // CMO/specialist whose identity already lives in IDENTITY.md, and all
- // of it inflates every model call's system prompt. Overwrite with thin
- // pointer stubs after `openclaw agents add` runs so the runtime still
- // finds the files but the injected bytes drop to ~1 KB.
- await writeMinimalWorkspaceStubs(workspaceAbs);
- } catch (err) {
- console.error(`Could not write IDENTITY.md for ${template.key}:`, err);
- }
-}
-
-const STUB_AGENTS_MD = `# Workspace
-
-This agent's role and operating rules live in IDENTITY.md (loaded
-automatically). The other files in this directory exist only so the
-OpenClaw runtime finds the names it expects — they're intentionally
-empty for prompt-efficiency.
-`;
-
-const STUB_SOUL_MD = `# Personality
-
-Be terse, opinionated, and useful. Skip filler ("Great question!",
-"I'd be happy to help"). Lead with the point — a dollar figure, a
-specific gap, a recommendation. Have a point of view; the user can
-push back if they disagree.
-`;
-
-const STUB_TOOLS_MD = `# Local Notes
-
-Empty by design. Domain tool usage lives in IDENTITY.md; runtime
-infrastructure (cameras, SSH, TTS) does not apply to this agent.
-`;
-
-const STUB_USER_MD = `# About the user
-
-A solo marketer running their own business on the notfair-cmo
-platform. They pay attention to dollar figures and concrete next
-steps. Build context here as you learn it across sessions.
-`;
-
-const STUB_HEARTBEAT_MD = `# Heartbeat
-
-Empty by design — heartbeats are disabled. Cron-driven check-ins
-arrive as normal "(task assignment)" turns instead.
-`;
-
-/**
- * Overwrite the OpenClaw-default workspace files with minimal stubs.
- *
- * Why: `openclaw agents add` seeds each workspace with five generic
- * files aimed at general-purpose assistants (camera/SSH tool notes,
- * memory-discipline lectures, user-profile templates). That's ~11 KB
- * of irrelevant boilerplate injected into every model call. Replacing
- * them with sub-300-char stubs that still satisfy whatever runtime
- * filesystem expectations OpenClaw has cuts the system prompt by
- * roughly that amount.
- *
- * Idempotent: re-running on an existing workspace just rewrites the
- * stubs. We don't delete the files because OpenClaw may probe for them
- * by name during session startup.
- */
-async function writeMinimalWorkspaceStubs(workspaceAbs: string): Promise<void> {
- await Promise.all([
- writeFile(join(workspaceAbs, "AGENTS.md"), STUB_AGENTS_MD, "utf8"),
- writeFile(join(workspaceAbs, "SOUL.md"), STUB_SOUL_MD, "utf8"),
- writeFile(join(workspaceAbs, "TOOLS.md"), STUB_TOOLS_MD, "utf8"),
- writeFile(join(workspaceAbs, "USER.md"), STUB_USER_MD, "utf8"),
- writeFile(join(workspaceAbs, "HEARTBEAT.md"), STUB_HEARTBEAT_MD, "utf8"),
- ]);
+${input.skill}`;
}
/**
- * Re-write IDENTITY.md (and the PROJECT.md sidecar) for every agent in a
- * project, picking up the current canonical PROJECT.md. Called by the
- * `set_project_brief` MCP handler after writing the canonical file so
- * specialists get the updated project context without waiting for the
- * next ensureProjectAgents pass.
- *
- * Best-effort per agent: a write failure on one agent is logged but does
- * not abort the others — the new brief is at least canonical on disk, and
- * the next ensureProjectAgents will catch up.
+ * 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 }> }> {
- // Lazy import to avoid a static cycle: agent-meta -> agent-templates.
const { listProjectAgents } = await import("./agent-meta");
const synced: string[] = [];
const failed: Array<{ name: string; error: string }> = [];
+ const 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) {
- // Custom / cloned agent — we don't know its template, but it still
- // has an IDENTITY.md we shouldn't overwrite blindly. Just refresh
- // the sidecar PROJECT.md so a human inspecting sees the new brief.
- try {
- const workspaceAbs = workspaceDirFor(entry.agent_id);
- const { readProjectBrief } = await import("./onboarding/project-brief");
- const brief = await readProjectBrief(project_slug);
- if (brief !== null) {
- await mkdir(workspaceAbs, { recursive: true });
- await writeFile(join(workspaceAbs, "PROJECT.md"), brief, "utf8");
- synced.push(entry.agent_id);
- }
- } catch (err) {
- failed.push({
- name: entry.agent_id,
- error: err instanceof Error ? err.message : String(err),
- });
- }
+ 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}'`,
- });
+ failed.push({ name: entry.agent_id, error: `Unknown template '${entry.template_key}'` });
continue;
}
try {
- const workspaceAbs = workspaceDirFor(entry.agent_id);
- await writeIdentityFile(workspaceAbs, template, project_slug, entry.agent_id);
+ 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({
@@ -685,12 +511,15 @@ export async function syncProjectBriefToAgents(
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 {
- // `agents list` doesn't currently take a name filter, so list-all and grep.
- // V1 acceptable; revisit if list grows large.
- const out = (await openclaw(["agents", "list"], { json: false })) as string;
- return out.includes(name);
+ const dir = agentWorkspaceDirFor(name);
+ const s = await stat(dir);
+ return s.isDirectory();
} catch {
return false;
}
diff --git a/notfair-cmo/src/server/agents/cascade-delete.ts b/notfair-cmo/src/server/agents/cascade-delete.ts
new file mode 100644
index 00000000..bf02ccb0
--- /dev/null
+++ b/notfair-cmo/src/server/agents/cascade-delete.ts
@@ -0,0 +1,142 @@
+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 { MCP_CATALOG } 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";
+import { getProject } from "@/server/db/projects";
+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;
+ threadCount: number;
+}
+
+export interface ProjectDeletionMcpSummary {
+ catalog_key: string;
+ display_name: string;
+ stored_key: string;
+ configured: boolean;
+}
+
+export interface ProjectDeletionSummary {
+ project_slug: string;
+ agents: ProjectDeletionAgentSummary[];
+ mcps: ProjectDeletionMcpSummary[];
+ totals: {
+ agents: number;
+ threads: number;
+ crons: number;
+ mcps: number;
+ };
+}
+
+/**
+ * Inventory everything tied to a project so the confirmation dialog can show
+ * the user exactly what will be deleted. Reads-only.
+ */
+export async function getProjectDeletionSummary(
+ project_slug: string,
+): Promise<ProjectDeletionSummary> {
+ const entries = await listProjectAgents(project_slug);
+ const agents: ProjectDeletionAgentSummary[] = entries.map((e) => {
+ const dir = workspaceDirFor(e.agent_id);
+ 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,
+ threadCount,
+ };
+ });
+
+ 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.
+ const tokens = listProjectMcpTokens(project_slug);
+ const tokenServers = new Set(tokens.map((t) => t.server_name));
+ const mcps: ProjectDeletionMcpSummary[] = MCP_CATALOG.map((spec) => ({
+ catalog_key: spec.key,
+ display_name: spec.display_name,
+ stored_key: `${project_slug}-${spec.key}`,
+ configured: tokenServers.has(spec.key),
+ }));
+
+ return {
+ project_slug,
+ agents,
+ mcps,
+ 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,
+ },
+ };
+}
+
+/**
+ * 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).
+ */
+export async function cascadeDeleteProjectArtifacts(project_slug: string): Promise<void> {
+ const project = getProject(project_slug);
+ const adapter = project ? requireAdapter(project.harness_adapter) : null;
+ const agents = await listProjectAgents(project_slug);
+
+ // Unregister any MCP servers the adapter wrote into its config (so codex
+ // global config doesn't leak agent-namespaced rows for deleted agents).
+ if (adapter) {
+ for (const agent of agents) {
+ for (const spec of MCP_CATALOG) {
+ try {
+ await adapter.unregisterMcp(spec.key, agent.agent_id);
+ } catch {
+ // best-effort
+ }
+ }
+ }
+ }
+
+ // Drop workspace dirs.
+ for (const agent of agents) {
+ try {
+ await rm(workspaceDirFor(agent.agent_id), { recursive: true, force: true });
+ } catch (err) {
+ console.error(`[delete] failed to rm workspace ${agent.agent_id}:`, err);
+ }
+ }
+
+ // 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 = ?")
+ .run(project_slug);
+
+ // Drop MCP tokens.
+ deleteProjectMcpTokens(project_slug);
+}
diff --git a/notfair-cmo/src/server/agents/clone.ts b/notfair-cmo/src/server/agents/clone.ts
new file mode 100644
index 00000000..eaecd202
--- /dev/null
+++ b/notfair-cmo/src/server/agents/clone.ts
@@ -0,0 +1,148 @@
+import { cp } from "node:fs/promises";
+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 { getDb } from "@/server/db/db";
+import {
+ listAgentScheduledJobs,
+ createScheduledJob,
+} from "@/server/scheduler";
+
+export interface CloneAgentInput {
+ source_agent_id: string;
+ project_slug: string;
+ new_slug: string;
+ display_name?: string;
+ /** Skip the user-input slug validation (relocate/internal callers). */
+ 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[];
+}
+
+/**
+ * Clone an existing agent within a project.
+ *
+ * Workspace dir copy via fs `cp -r`, scheduled jobs duplicated as new rows,
+ * sessions / transcript_events left ON the source (we don't carry chat history
+ * forward — the new agent starts with an empty thread list).
+ */
+export async function cloneAgent(input: CloneAgentInput): Promise<CloneAgentResult> {
+ let newSlug: string;
+ if (input.slug_is_canonical) {
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(input.new_slug)) {
+ throw new Error(`Invalid canonical slug: ${input.new_slug}`);
+ }
+ newSlug = input.new_slug;
+ } else {
+ const slugResult = slugify(input.new_slug);
+ if (!slugResult.ok) {
+ throw new Error(`Invalid agent slug: ${slugResult.reason}`);
+ }
+ newSlug = slugResult.slug;
+ }
+ const newAgentId = `${input.project_slug}-${newSlug}`;
+ if (agentExistsInProject(input.project_slug, newSlug)) {
+ throw new Error(
+ `An agent named "${newSlug}" already exists in this project. Pick a different name.`,
+ );
+ }
+
+ const srcDir = workspaceDirFor(input.source_agent_id);
+ const dstDir = workspaceDirFor(newAgentId);
+ let filesCopied = 0;
+ if (existsSync(srcDir)) {
+ await cp(srcDir, dstDir, { recursive: true });
+ 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(),
+ });
+
+ return {
+ new_agent_id: newAgentId,
+ new_slug: newSlug,
+ files_copied: filesCopied,
+ // sessions deliberately not copied — new agent starts fresh
+ sessions_copied: 0,
+ source_crons: sourceCrons,
+ new_cron_ids: newCronIds,
+ };
+}
+
+export function agentExistsInProject(project_slug: string, slug: string): boolean {
+ const agentId = `${project_slug}-${slug}`;
+ const dir = workspaceDirFor(agentId);
+ if (!existsSync(dir)) return false;
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { readdirSync } = require("node:fs") as typeof import("node:fs");
+ return readdirSync(dir).length > 0;
+ } catch {
+ return true;
+ }
+}
+
+/** Cascade-delete an agent's workspace + sessions + scheduled jobs. */
+export async function cascadeDeleteAgent(agent_id: string, project_slug: string): Promise<void> {
+ const dir = workspaceDirFor(agent_id);
+ const { rm } = await import("node:fs/promises");
+ if (existsSync(dir)) {
+ await rm(dir, { recursive: true, force: true });
+ }
+ getDb()
+ .prepare("DELETE FROM scheduled_jobs WHERE project_slug = ? AND agent_id = ?")
+ .run(project_slug, agent_id);
+ getDb()
+ .prepare("DELETE FROM sessions WHERE project_slug = ? AND agent_id = ?")
+ .run(project_slug, agent_id);
+}
+
+void randomUUID; // imported for future use (sessions cloning if we re-enable)
diff --git a/notfair-cmo/src/server/agents/files.ts b/notfair-cmo/src/server/agents/files.ts
new file mode 100644
index 00000000..356c9f1f
--- /dev/null
+++ b/notfair-cmo/src/server/agents/files.ts
@@ -0,0 +1,72 @@
+import { existsSync } from "node:fs";
+import { readFile, readdir, stat } from "node:fs/promises";
+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
+ * — no harness subprocess or RPC needed.
+ */
+export interface AgentFileEntry {
+ name: string;
+ size: number;
+ updatedAtMs: number;
+ missing: boolean;
+}
+
+export interface AgentFileList {
+ files: AgentFileEntry[];
+ /** Absolute path to the workspace dir — surfaced by the UI as a hint. */
+ workspace: string;
+}
+
+export async function listAgentFiles(agent_id: string): Promise<AgentFileList> {
+ const dir = workspaceDirFor(agent_id);
+ if (!existsSync(dir)) return { files: [], workspace: dir };
+ let entries: string[];
+ try {
+ entries = await readdir(dir);
+ } catch {
+ return { files: [], workspace: dir };
+ }
+ const files: AgentFileEntry[] = [];
+ for (const name of entries.sort()) {
+ try {
+ const s = await stat(join(dir, name));
+ if (!s.isFile()) continue;
+ files.push({
+ name,
+ size: s.size,
+ updatedAtMs: s.mtimeMs,
+ missing: false,
+ });
+ } catch {
+ files.push({ name, size: 0, updatedAtMs: 0, missing: true });
+ }
+ }
+ return { files, workspace: dir };
+}
+
+export interface AgentFileContent {
+ file: {
+ name: string;
+ content: string;
+ size: number;
+ updatedAtMs: number;
+ };
+}
+
+export async function getAgentFile(
+ agent_id: string,
+ name: string,
+): Promise<AgentFileContent> {
+ if (name.includes("..") || name.includes("/")) {
+ throw new Error(`Invalid file name: ${name}`);
+ }
+ const path = join(workspaceDirFor(agent_id), name);
+ const [content, s] = await Promise.all([readFile(path, "utf8"), stat(path)]);
+ return {
+ file: { name, content, size: s.size, updatedAtMs: s.mtimeMs },
+ };
+}
diff --git a/notfair-cmo/src/server/agents/provisioning.ts b/notfair-cmo/src/server/agents/provisioning.ts
new file mode 100644
index 00000000..9c6b5ba5
--- /dev/null
+++ b/notfair-cmo/src/server/agents/provisioning.ts
@@ -0,0 +1,40 @@
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { requireAdapter } from "@/server/adapters/registry";
+import type { HarnessAdapterId, AgentProvisionSpec } from "@/server/adapters/types";
+
+/**
+ * Generic agent provisioning. The adapter writes whatever workspace files
+ * the harness needs (IDENTITY.md, CLAUDE.md, AGENTS.md, etc.) — notfair-cmo
+ * 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");
+ return join(dataDir, "agents", agentId);
+}
+
+export interface ProvisionInput {
+ projectSlug: string;
+ agentId: string;
+ displayName: string;
+ templateKey: string;
+ identityMd: string;
+ skillMd?: string;
+ projectMd?: string;
+ harnessAdapter: HarnessAdapterId;
+}
+
+export async function provisionAgent(input: ProvisionInput): Promise<void> {
+ const adapter = requireAdapter(input.harnessAdapter);
+ const spec: AgentProvisionSpec = {
+ projectSlug: input.projectSlug,
+ agentId: input.agentId,
+ displayName: input.displayName,
+ templateKey: input.templateKey,
+ workspaceDir: workspaceDirFor(input.agentId),
+ identityMd: input.identityMd,
+ skillMd: input.skillMd,
+ projectMd: input.projectMd,
+ };
+ await adapter.provisionAgent(spec);
+}
diff --git a/notfair-cmo/src/server/agents/skills.ts b/notfair-cmo/src/server/agents/skills.ts
new file mode 100644
index 00000000..ce4f8ee6
--- /dev/null
+++ b/notfair-cmo/src/server/agents/skills.ts
@@ -0,0 +1,53 @@
+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/db/migrations.ts b/notfair-cmo/src/server/db/migrations.ts
index 763efd11..941e5505 100644
--- a/notfair-cmo/src/server/db/migrations.ts
+++ b/notfair-cmo/src/server/db/migrations.ts
@@ -383,6 +383,99 @@ CREATE TABLE IF NOT EXISTS questions (
);
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);
`,
},
];
diff --git a/notfair-cmo/src/server/db/projects.test.ts b/notfair-cmo/src/server/db/projects.test.ts
index 62aa869c..cfc4db80 100644
--- a/notfair-cmo/src/server/db/projects.test.ts
+++ b/notfair-cmo/src/server/db/projects.test.ts
@@ -467,6 +467,34 @@ describe("deleteProjectRow", () => {
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 [
@@ -476,6 +504,10 @@ describe("deleteProjectRow", () => {
"oauth_tokens",
"agent_actions",
"sequence_runs",
+ "questions",
+ "mcp_tokens",
+ "scheduled_jobs",
+ "sessions",
]) {
expect(
testDb.prepare(`SELECT 1 FROM ${table} WHERE project_slug = ?`).get("acme"),
@@ -497,6 +529,10 @@ describe("deleteProjectRow", () => {
"oauth_tokens",
"agent_actions",
"sequence_runs",
+ "questions",
+ "mcp_tokens",
+ "scheduled_jobs",
+ "sessions",
]) {
expect(
testDb.prepare(`SELECT 1 FROM ${table} WHERE project_slug = ?`).get("acme"),
diff --git a/notfair-cmo/src/server/db/projects.ts b/notfair-cmo/src/server/db/projects.ts
index 2ba2ffaf..0439c981 100644
--- a/notfair-cmo/src/server/db/projects.ts
+++ b/notfair-cmo/src/server/db/projects.ts
@@ -2,6 +2,8 @@ import { randomUUID } from "node:crypto";
import { getDb } from "./db";
import type { Project } from "@/types";
import { slugify } from "@/lib/slug";
+import { DEFAULT_HARNESS_ADAPTER, isHarnessAdapterId } from "@/server/adapters/registry";
+import type { HarnessAdapterId } from "@/server/adapters/types";
export type CreateProjectInput = {
display_name: string;
@@ -9,6 +11,8 @@ export type CreateProjectInput = {
/** Optional onboarding hints. Free-text — CMO decides how to use them. */
website_url?: string | null;
codebase_path?: string | null;
+ /** Adapter chosen at onboarding. Defaults to claude-code-local. */
+ harness_adapter?: HarnessAdapterId;
};
export type CreateProjectResult =
@@ -40,6 +44,10 @@ export function createProject(input: CreateProjectInput): CreateProjectResult {
const website_url = trimOrNull(input.website_url);
const codebase_path = trimOrNull(input.codebase_path);
+ const harness_adapter: HarnessAdapterId =
+ input.harness_adapter && isHarnessAdapterId(input.harness_adapter)
+ ? input.harness_adapter
+ : DEFAULT_HARNESS_ADAPTER;
const project: Project = {
id: randomUUID(),
@@ -50,10 +58,11 @@ export function createProject(input: CreateProjectInput): CreateProjectResult {
google_ads_account_id: null,
website_url,
codebase_path,
+ harness_adapter,
};
db.prepare(
- "INSERT INTO projects (id, slug, display_name, created_at, archived_at, google_ads_account_id, website_url, codebase_path) VALUES (?, ?, ?, ?, NULL, NULL, ?, ?)",
+ "INSERT INTO projects (id, slug, display_name, created_at, archived_at, google_ads_account_id, website_url, codebase_path, harness_adapter) VALUES (?, ?, ?, ?, NULL, NULL, ?, ?, ?)",
).run(
project.id,
project.slug,
@@ -61,11 +70,21 @@ export function createProject(input: CreateProjectInput): CreateProjectResult {
project.created_at,
project.website_url,
project.codebase_path,
+ project.harness_adapter,
);
return { ok: true, project };
}
+export function setProjectHarnessAdapter(
+ slug: string,
+ adapter: HarnessAdapterId,
+): Project | null {
+ const db = getDb();
+ db.prepare("UPDATE projects SET harness_adapter = ? WHERE slug = ?").run(adapter, slug);
+ return getProject(slug);
+}
+
function trimOrNull(value: string | null | undefined): string | null {
if (value == null) return null;
const trimmed = value.trim();
@@ -134,8 +153,12 @@ export function changeProjectSlug(
"tasks",
"approvals",
"approval_policies",
+ "questions",
"cost_events",
"oauth_tokens",
+ "mcp_tokens",
+ "scheduled_jobs",
+ "sessions",
"agent_actions",
"sequence_runs",
];
@@ -205,13 +228,22 @@ export function unarchiveProject(slug: string): Project | null {
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 is cleaned up by FK ON DELETE CASCADE when we drop
- // the parent approvals rows below.
+ // 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",
];
diff --git a/notfair-cmo/src/server/live-events/emitter.test.ts b/notfair-cmo/src/server/live-events/emitter.test.ts
new file mode 100644
index 00000000..7fb10d02
--- /dev/null
+++ b/notfair-cmo/src/server/live-events/emitter.test.ts
@@ -0,0 +1,59 @@
+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/live-events/emitter.ts b/notfair-cmo/src/server/live-events/emitter.ts
new file mode 100644
index 00000000..40cad9d8
--- /dev/null
+++ b/notfair-cmo/src/server/live-events/emitter.ts
@@ -0,0 +1,53 @@
+import { EventEmitter } from "node:events";
+import type { TranscriptEvent } from "@/server/sessions";
+
+/**
+ * In-process pub/sub for transcript events.
+ *
+ * Mirrors paperclip's live-events EventEmitter pattern: every time the
+ * dispatcher persists a row to `transcript_events`, it also publishes the
+ * event to subscribers keyed by `session_id`. SSE bridges open during a
+ * 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
+ * cluster, swap this for a Redis pub/sub or move events through the DB
+ * with NOTIFY/LISTEN — same subscriber API at the call site.
+ */
+const emitter = new EventEmitter();
+// Generous default — many tabs can attach to the same session on a single
+// machine (user has multiple windows / agents page polls + chat tab open).
+emitter.setMaxListeners(50);
+
+export type SessionEventListener = (event: TranscriptEvent) => void;
+
+/**
+ * Subscribe to all transcript events for one session. Returns an
+ * unsubscribe callback the caller MUST invoke when the consumer goes
+ * away (SSE client disconnect, route shutdown), otherwise we leak
+ * listeners.
+ */
+export function subscribeSessionEvents(
+ session_id: string,
+ listener: SessionEventListener,
+): () => void {
+ emitter.on(session_id, listener);
+ return () => {
+ emitter.off(session_id, listener);
+ };
+}
+
+/**
+ * Publish a transcript event to all live subscribers for a session.
+ *
+ * Called by `appendTranscriptEvent` immediately AFTER the SQLite INSERT
+ * commits — the DB write is the source of truth and the emit is a best-
+ * effort push notification. A late or missed listener can always
+ * recover by re-reading the table from the last-seen `seq`.
+ */
+export function publishSessionEvent(
+ session_id: string,
+ event: TranscriptEvent,
+): void {
+ emitter.emit(session_id, event);
+}
diff --git a/notfair-cmo/src/server/mcp-catalog.test.ts b/notfair-cmo/src/server/mcp-catalog.test.ts
index 7231ecd2..0cbf7157 100644
--- a/notfair-cmo/src/server/mcp-catalog.test.ts
+++ b/notfair-cmo/src/server/mcp-catalog.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { MCP_CATALOG, mcpSpecByKey, storedMcpKey } from "./mcp-catalog";
+import { MCP_CATALOG, mcpSpecByKey } from "./mcp-catalog";
describe("MCP_CATALOG", () => {
it("contains at least one spec", () => {
@@ -57,28 +57,3 @@ describe("mcpSpecByKey", () => {
});
});
-describe("storedMcpKey", () => {
- it("concatenates project slug + catalog key with a hyphen", () => {
- expect(storedMcpKey("acme", "notfair-googleads")).toBe(
- "acme-notfair-googleads",
- );
- });
-
- it("preserves multi-segment project slugs", () => {
- expect(storedMcpKey("acme-q4", "notfair-googleads")).toBe(
- "acme-q4-notfair-googleads",
- );
- });
-
- it("works with arbitrary catalog keys (not just ones in the catalog)", () => {
- expect(storedMcpKey("proj", "arbitrary-thing")).toBe("proj-arbitrary-thing");
- });
-
- it("handles empty project slug (no validation here — that's the caller's job)", () => {
- expect(storedMcpKey("", "notfair-googleads")).toBe("-notfair-googleads");
- });
-
- it("handles empty catalog key", () => {
- expect(storedMcpKey("acme", "")).toBe("acme-");
- });
-});
diff --git a/notfair-cmo/src/server/mcp-catalog.ts b/notfair-cmo/src/server/mcp-catalog.ts
index 50ada0c0..b8197d8b 100644
--- a/notfair-cmo/src/server/mcp-catalog.ts
+++ b/notfair-cmo/src/server/mcp-catalog.ts
@@ -6,15 +6,15 @@
* MCPs (user describes one in chat) still go through the agent — the
* catalog is just the fast path for the ones we ship with.
*
- * MCPs are managed at the project level (the Connections page). All agents
- * inside a given project share the same MCP rows; cross-project boundaries
- * are enforced by OpenClaw's `codex.agents` allowlist (see docs:
- * gateway/configuration-reference#mcp) which `actions/mcp.ts` populates
- * with every agent id in the active project.
+ * MCPs are managed at the project level (the Connections page). Tokens live
+ * in the `mcp_tokens` SQLite table, scoped by (project_slug, server_name).
+ * Per-agent visibility is enforced by the harness adapter's `registerMcp`
+ * hook, which writes the chosen agent's MCP config to point at the right
+ * token row.
*/
export type McpSpec = {
- /** OpenClaw mcp config key (used by `openclaw mcp show/set/unset`). */
+ /** Stable catalog identifier (used by the UI + mcp_tokens.server_name). */
key: string;
display_name: string;
description: string;
@@ -39,15 +39,3 @@ export const MCP_CATALOG: McpSpec[] = [
export function mcpSpecByKey(key: string): McpSpec | undefined {
return MCP_CATALOG.find((m) => m.key === key);
}
-
-/**
- * OpenClaw's mcp config is workspace-global. To keep projects' tokens
- * independent (so connecting an MCP from project A doesn't stomp project
- * B's bearer), we namespace the stored openclaw key with the project
- * slug. Catalog key `notfair-googleads` + project `notfairco` becomes
- * stored key `notfairco-notfair-googleads`. Runtime visibility is still
- * gated by `codex.agents`.
- */
-export function storedMcpKey(project_slug: string, catalog_key: string): string {
- return `${project_slug}-${catalog_key}`;
-}
diff --git a/notfair-cmo/src/server/mcp-pending.ts b/notfair-cmo/src/server/mcp-pending.ts
index 89174c38..4e4aca98 100644
--- a/notfair-cmo/src/server/mcp-pending.ts
+++ b/notfair-cmo/src/server/mcp-pending.ts
@@ -13,13 +13,7 @@
export type PendingMcpFlow = {
/** Catalog identifier (e.g. `notfair-googleads`) — what the UI shows. */
catalog_key: string;
- /**
- * Openclaw mcp config key the callback will `mcp set` against. Project-
- * scoped (e.g. `notfairco-notfair-googleads`) so different projects don't
- * stomp each other's tokens.
- */
- stored_key: string;
- /** OpenClaw-side display name; mirrors the catalog spec. */
+ /** Project-scoped display name; mirrors the catalog spec. */
display_name: string;
resource_url: string;
/** OAuth issuer (the protected resource's authorization server). */
diff --git a/notfair-cmo/src/server/mcp-server/registration.test.ts b/notfair-cmo/src/server/mcp-server/registration.test.ts
deleted file mode 100644
index cec697d5..00000000
--- a/notfair-cmo/src/server/mcp-server/registration.test.ts
+++ /dev/null
@@ -1,175 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-const openclawMock = vi.fn();
-vi.mock("@/server/openclaw/cli", () => {
- class FakeOpenClawError extends Error {
- exitCode: number | null;
- stderr: string;
- constructor(message: string, stderr = "", exitCode = 1) {
- super(message);
- this.name = "OpenClawError";
- this.stderr = stderr;
- this.exitCode = exitCode;
- }
- }
- return {
- openclaw: (...a: unknown[]) => openclawMock(...a),
- OpenClawError: FakeOpenClawError,
- };
-});
-import { OpenClawError } from "@/server/openclaw/cli";
-
-const getSecretMock = vi.fn(() => "deadbeef".repeat(8));
-vi.mock("./secret", () => ({
- getOrCreateMcpServerSecret: () => getSecretMock(),
-}));
-
-import {
- cleanupLegacyOrchestrationRows,
- ensureOrchestrationMcpInstalled,
- getOrchestrationMcpUrl,
- installOrchestrationMcp,
- ORCHESTRATION_MCP_KEY,
-} from "./registration";
-
-const ORIGINAL_ENV = { ...process.env };
-
-beforeEach(() => {
- openclawMock.mockReset();
- getSecretMock.mockClear();
-});
-
-afterEach(() => {
- process.env = { ...ORIGINAL_ENV };
-});
-
-describe("ORCHESTRATION_MCP_KEY", () => {
- it("is a stable global key (no project prefix)", () => {
- expect(ORCHESTRATION_MCP_KEY).toBe("notfair-orchestration");
- });
-});
-
-describe("getOrchestrationMcpUrl", () => {
- it("defaults to http://127.0.0.1:3326/api/mcp/orchestration", () => {
- delete process.env.NOTFAIR_CMO_PORT;
- delete process.env.NOTFAIR_CMO_MCP_URL;
- expect(getOrchestrationMcpUrl()).toBe(
- "http://127.0.0.1:3326/api/mcp/orchestration",
- );
- });
-
- it("respects NOTFAIR_CMO_PORT", () => {
- process.env.NOTFAIR_CMO_PORT = "4001";
- delete process.env.NOTFAIR_CMO_MCP_URL;
- expect(getOrchestrationMcpUrl()).toBe(
- "http://127.0.0.1:4001/api/mcp/orchestration",
- );
- });
-
- it("NOTFAIR_CMO_MCP_URL overrides the host:port construction", () => {
- process.env.NOTFAIR_CMO_MCP_URL = "https://example.invalid/mcp";
- expect(getOrchestrationMcpUrl()).toBe("https://example.invalid/mcp");
- });
-});
-
-describe("ensureOrchestrationMcpInstalled", () => {
- it("installs when the row is missing (mcp show fails)", async () => {
- // First call: openclaw mcp show → throws OpenClawError (row missing).
- // Second call: openclaw mcp set → resolves.
- openclawMock
- .mockRejectedValueOnce(new OpenClawError("not found", "", 1))
- .mockResolvedValueOnce(undefined);
- const r = await ensureOrchestrationMcpInstalled();
- if (!r.ok) throw new Error("expected ok");
- expect(r.status).toBe("installed");
- expect(r.key).toBe("notfair-orchestration");
- expect(openclawMock).toHaveBeenLastCalledWith(
- ["mcp", "set", "notfair-orchestration", expect.any(String)],
- { json: false },
- );
- });
-
- it("no-ops with status 'already_installed' when row matches desired config", async () => {
- const url = "http://127.0.0.1:3326/api/mcp/orchestration";
- delete process.env.NOTFAIR_CMO_PORT;
- delete process.env.NOTFAIR_CMO_MCP_URL;
- openclawMock.mockResolvedValueOnce({
- url,
- transport: "streamable-http",
- headers: { Authorization: `Bearer ${"deadbeef".repeat(8)}` },
- });
- const r = await ensureOrchestrationMcpInstalled();
- if (!r.ok) throw new Error("expected ok");
- expect(r.status).toBe("already_installed");
- // Only the show call happened — no set.
- expect(openclawMock).toHaveBeenCalledTimes(1);
- });
-
- it("re-installs with status 'updated' when stored config drifts (URL changed)", async () => {
- openclawMock
- .mockResolvedValueOnce({
- url: "http://old.invalid/mcp",
- transport: "streamable-http",
- headers: { Authorization: `Bearer ${"deadbeef".repeat(8)}` },
- })
- .mockResolvedValueOnce(undefined);
- const r = await ensureOrchestrationMcpInstalled();
- if (!r.ok) throw new Error("expected ok");
- expect(r.status).toBe("updated");
- expect(openclawMock).toHaveBeenLastCalledWith(
- ["mcp", "set", "notfair-orchestration", expect.any(String)],
- { json: false },
- );
- });
-
- it("returns ok:false with the OpenClaw error on set failure", async () => {
- openclawMock
- .mockRejectedValueOnce(new OpenClawError("not found", "", 1))
- .mockRejectedValueOnce(new OpenClawError("write blew up", "perm denied", 1));
- const r = await ensureOrchestrationMcpInstalled();
- expect(r.ok).toBe(false);
- if (r.ok) throw new Error("unreachable");
- expect(r.error).toMatch(/write blew up/);
- });
-});
-
-describe("installOrchestrationMcp (unconditional)", () => {
- it("always writes the row", async () => {
- openclawMock.mockResolvedValue(undefined);
- const r = await installOrchestrationMcp();
- if (!r.ok) throw new Error("expected ok");
- expect(r.status).toBe("installed");
- expect(openclawMock).toHaveBeenCalledWith(
- ["mcp", "set", "notfair-orchestration", expect.any(String)],
- { json: false },
- );
- });
-});
-
-describe("cleanupLegacyOrchestrationRows", () => {
- it("unsets one row per slug; swallows per-row errors", async () => {
- openclawMock
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new OpenClawError("not found", "", 1))
- .mockResolvedValueOnce(undefined);
- await expect(
- cleanupLegacyOrchestrationRows(["a", "b", "c"]),
- ).resolves.toBeUndefined();
- expect(openclawMock).toHaveBeenCalledTimes(3);
- expect(openclawMock).toHaveBeenNthCalledWith(
- 1,
- ["mcp", "unset", "a-notfair-orchestration"],
- { json: false },
- );
- expect(openclawMock).toHaveBeenNthCalledWith(
- 3,
- ["mcp", "unset", "c-notfair-orchestration"],
- { json: false },
- );
- });
-
- it("no-op on empty slug list", async () => {
- await cleanupLegacyOrchestrationRows([]);
- expect(openclawMock).not.toHaveBeenCalled();
- });
-});
diff --git a/notfair-cmo/src/server/mcp-server/registration.ts b/notfair-cmo/src/server/mcp-server/registration.ts
index 070e5f27..b2f81272 100644
--- a/notfair-cmo/src/server/mcp-server/registration.ts
+++ b/notfair-cmo/src/server/mcp-server/registration.ts
@@ -1,26 +1,18 @@
-import { openclaw, OpenClawError } from "@/server/openclaw/cli";
-
+import { requireAdapter } from "@/server/adapters/registry";
+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";
/**
- * Register notfair-cmo's outbound MCP server with OpenClaw — once, globally.
- *
- * The orchestration tools (`create_task`, `submit_task_status`,
- * `request_approval`, etc.) are project-scoped via a required `project_slug`
- * argument on every tool call, so a SINGLE OpenClaw MCP registration is
- * enough for every project + every agent in this install. Wasteful + brittle
- * to write one MCP row per project (every row points at the same URL with
- * the same secret).
+ * Register notfair-cmo's outbound MCP server (`notfair-orchestration`) with
+ * the project's harness adapter for a specific agent.
*
- * Behavior:
- * - `ensureOrchestrationMcpInstalled()` — idempotent. Calls `openclaw mcp show`
- * first; only writes if the row is missing OR points at a stale URL/secret.
- * Safe to call from every provisioning step.
- * - `installOrchestrationMcp()` — unconditional set (used by a future CLI
- * reinstall command).
- * - `cleanupLegacyOrchestrationRows(slugs)` — one-time migration helper that
- * removes the per-project `<slug>-notfair-orchestration` rows we used to
- * create. Called from provisioning so old installs heal on next provision.
+ * 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.
*
* URL: `NOTFAIR_CMO_MCP_URL` if set, else
* `http://127.0.0.1:${NOTFAIR_CMO_PORT||3326}/api/mcp/orchestration`.
@@ -36,112 +28,139 @@ function defaultMcpUrl(): string {
return `http://127.0.0.1:${port}/api/mcp/orchestration`;
}
-function buildConfig(): { url: string; transport: string; headers: Record<string, string> } {
- return {
- url: defaultMcpUrl(),
- transport: "streamable-http",
- headers: { Authorization: `Bearer ${getOrCreateMcpServerSecret()}` },
- };
-}
-
export type InstallResult =
- | { ok: true; status: "already_installed" | "installed" | "updated"; key: string; url: string }
+ | { ok: true; key: string; url: string }
| { ok: false; key: string; url: string; error: string };
-/**
- * Idempotent install. Reads the current row; writes only when missing or
- * stale (URL changed via NOTFAIR_CMO_MCP_URL, secret rotated, etc.).
- */
-export async function ensureOrchestrationMcpInstalled(): Promise<InstallResult> {
- const desired = buildConfig();
- const key = ORCHESTRATION_MCP_KEY;
- const current = await readMcpRow(key);
- if (current && configMatches(current, desired)) {
- return { ok: true, status: "already_installed", key, url: desired.url };
+export async function registerOrchestrationForAgent(
+ project_slug: string,
+ agent_id: string,
+): Promise<InstallResult> {
+ const url = defaultMcpUrl();
+ const project = getProject(project_slug);
+ if (!project) {
+ return { ok: false, key: ORCHESTRATION_MCP_KEY, url, error: `Unknown project ${project_slug}` };
}
try {
- await openclaw(["mcp", "set", key, JSON.stringify(desired)], { json: false });
+ const adapter = requireAdapter(project.harness_adapter);
+ await adapter.registerMcp({
+ serverName: ORCHESTRATION_MCP_KEY,
+ agentId: agent_id,
+ projectSlug: project_slug,
+ transport: {
+ type: "http",
+ url,
+ headers: { Authorization: `Bearer ${getOrCreateMcpServerSecret()}` },
+ },
+ });
+ return { ok: true, key: ORCHESTRATION_MCP_KEY, url };
+ } catch (err) {
return {
- ok: true,
- status: current ? "updated" : "installed",
- key,
- url: desired.url,
+ ok: false,
+ key: ORCHESTRATION_MCP_KEY,
+ url,
+ error: err instanceof Error ? err.message : String(err),
};
- } catch (err) {
- const message =
- err instanceof OpenClawError
- ? err.message
- : err instanceof Error
- ? err.message
- : String(err);
- return { ok: false, key, url: desired.url, error: message };
}
}
-/** Unconditional install — overwrites whatever's there. */
-export async function installOrchestrationMcp(): Promise<InstallResult> {
- const desired = buildConfig();
- const key = ORCHESTRATION_MCP_KEY;
+/**
+ * Register an external catalog MCP server (Google Ads, GSC, etc.) with the
+ * project's harness adapter for a specific agent. Pulls the OAuth bearer
+ * from the `mcp_tokens` table and the resource URL from the catalog spec.
+ *
+ * Called after a successful OAuth callback so the bearer becomes visible
+ * to running agents without the user manually re-provisioning. Idempotent:
+ * the adapter `registerMcp` overwrites the prior entry on rewrite.
+ */
+export async function registerCatalogMcpForAgent(
+ project_slug: string,
+ catalog_key: string,
+ agent_id: string,
+): Promise<InstallResult> {
+ const spec = mcpSpecByKey(catalog_key);
+ if (!spec) {
+ return {
+ ok: false,
+ key: catalog_key,
+ url: "",
+ error: `Unknown catalog key ${catalog_key}`,
+ };
+ }
+ const project = getProject(project_slug);
+ if (!project) {
+ return {
+ ok: false,
+ key: catalog_key,
+ url: spec.resource_url,
+ error: `Unknown project ${project_slug}`,
+ };
+ }
+ const token = findMcpToken(project_slug, catalog_key);
+ if (!token) {
+ return {
+ ok: false,
+ key: catalog_key,
+ url: spec.resource_url,
+ error: `No token stored for ${catalog_key} in project ${project_slug}`,
+ };
+ }
try {
- await openclaw(["mcp", "set", key, JSON.stringify(desired)], { json: false });
- return { ok: true, status: "installed", key, url: desired.url };
+ const adapter = requireAdapter(project.harness_adapter);
+ await adapter.registerMcp({
+ serverName: catalog_key,
+ agentId: agent_id,
+ projectSlug: project_slug,
+ transport: {
+ type: "http",
+ url: spec.resource_url,
+ headers: { Authorization: `Bearer ${token.access_token_enc}` },
+ },
+ });
+ return { ok: true, key: catalog_key, url: spec.resource_url };
} catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- return { ok: false, key, url: desired.url, error: message };
+ return {
+ ok: false,
+ key: catalog_key,
+ url: spec.resource_url,
+ error: err instanceof Error ? err.message : String(err),
+ };
}
}
/**
- * Remove the legacy per-project `<slug>-notfair-orchestration` rows we wrote
- * before the registration went global. Pass the list of project slugs that
- * may have stale rows. Errors per-slug are swallowed (the row may already be
- * gone). Safe + idempotent — no-op on a fresh install.
+ * Convenience: register an external catalog MCP with EVERY agent in the
+ * project. Called from the OAuth callback so a fresh token reaches all
+ * project agents without re-provisioning. Best-effort per agent — one
+ * failed registration doesn't abort the rest.
*/
-export async function cleanupLegacyOrchestrationRows(
- slugs: string[],
-): Promise<void> {
- for (const slug of slugs) {
- const legacyKey = `${slug}-notfair-orchestration`;
- try {
- await openclaw(["mcp", "unset", legacyKey], { json: false });
- } catch {
- // Row didn't exist or unset failed; ignore.
- }
+export async function registerCatalogMcpForProject(
+ project_slug: string,
+ catalog_key: string,
+): Promise<InstallResult[]> {
+ const agents = await listProjectAgents(project_slug);
+ const results: InstallResult[] = [];
+ for (const agent of agents) {
+ results.push(
+ await registerCatalogMcpForAgent(project_slug, catalog_key, agent.agent_id),
+ );
}
+ return results;
}
-async function readMcpRow(key: string): Promise<{
- url?: string;
- transport?: string;
- headers?: Record<string, string>;
-} | null> {
- try {
- const out = await openclaw(["mcp", "show", key], { json: true });
- if (!out || typeof out !== "object") return null;
- return out as {
- url?: string;
- transport?: string;
- headers?: Record<string, string>;
- };
- } catch (err) {
- if (err instanceof OpenClawError) return null;
- throw err;
- }
-}
-
-function configMatches(
- current: { url?: string; transport?: string; headers?: Record<string, string> },
- desired: { url: string; transport: string; headers: Record<string, string> },
-): boolean {
- if (current.url !== desired.url) return false;
- if (current.transport !== desired.transport) return false;
- const currentAuth =
- current.headers?.Authorization ?? current.headers?.authorization;
- if (currentAuth !== desired.headers.Authorization) return false;
- return true;
+/**
+ * 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
}
-/** Read-only URL accessor for CLI/tooling. */
-export function getOrchestrationMcpUrl(): string {
- return defaultMcpUrl();
+/**
+ * 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/schedule-tool.test.ts b/notfair-cmo/src/server/mcp-server/schedule-tool.test.ts
new file mode 100644
index 00000000..35f321d8
--- /dev/null
+++ b/notfair-cmo/src/server/mcp-server/schedule-tool.test.ts
@@ -0,0 +1,138 @@
+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/tools.ts b/notfair-cmo/src/server/mcp-server/tools.ts
index 297192c2..daf36716 100644
--- a/notfair-cmo/src/server/mcp-server/tools.ts
+++ b/notfair-cmo/src/server/mcp-server/tools.ts
@@ -598,6 +598,103 @@ async function handleSetProjectBriefTool(input: unknown): Promise<ToolResult> {
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[] = [
@@ -741,6 +838,13 @@ export const TOOLS: ToolDefinition[] = [
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,
+ },
];
export function describeTool(tool: ToolDefinition): {
diff --git a/notfair-cmo/src/server/mcp-state.test.ts b/notfair-cmo/src/server/mcp-state.test.ts
deleted file mode 100644
index 6ea1919e..00000000
--- a/notfair-cmo/src/server/mcp-state.test.ts
+++ /dev/null
@@ -1,336 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import { OpenClawError } from "@/server/openclaw/cli";
-
-// ── Mocks ──────────────────────────────────────────────────────────
-
-const openclawMock = vi.fn();
-vi.mock("@/server/openclaw/cli", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@/server/openclaw/cli")>();
- return {
- ...actual,
- openclaw: (...args: unknown[]) => openclawMock(...args),
- };
-});
-
-const readMcpConfigRowMock = vi.fn();
-const bearerFromHeadersMock = vi.fn();
-const mcpRpcMock = vi.fn();
-vi.mock("@/server/mcp/rpc", () => ({
- readMcpConfigRow: (...args: unknown[]) => readMcpConfigRowMock(...args),
- bearerFromHeaders: (...args: unknown[]) => bearerFromHeadersMock(...args),
- mcpRpc: (...args: unknown[]) => mcpRpcMock(...args),
-}));
-
-import { disconnectMcp, getMcpStatus, setMcpBearer } from "./mcp-state";
-
-describe("getMcpStatus", () => {
- beforeEach(() => {
- readMcpConfigRowMock.mockReset();
- bearerFromHeadersMock.mockReset();
- mcpRpcMock.mockReset();
- });
-
- it("returns not_configured when no row", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce(null);
- await expect(getMcpStatus("k")).resolves.toEqual({ state: "not_configured" });
- expect(mcpRpcMock).not.toHaveBeenCalled();
- });
-
- it("returns not_configured when row has no url", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({ transport: "streamable-http" });
- await expect(getMcpStatus("k")).resolves.toEqual({ state: "not_configured" });
- });
-
- it("returns configured_no_token when row has url but no bearer", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({ url: "https://x", headers: {} });
- bearerFromHeadersMock.mockReturnValueOnce(null);
- await expect(getMcpStatus("k")).resolves.toEqual({
- state: "configured_no_token",
- url: "https://x",
- });
- expect(mcpRpcMock).not.toHaveBeenCalled();
- });
-
- it("returns connected with tools_count when probe succeeds with array of tools", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({
- ok: true,
- result: { tools: [{ name: "a" }, { name: "b" }, { name: "c" }] },
- });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({
- state: "connected",
- url: "https://x",
- tools_count: 3,
- });
- if (r.state === "connected") {
- expect(typeof r.last_checked_at).toBe("string");
- expect(new Date(r.last_checked_at).toString()).not.toBe("Invalid Date");
- }
- });
-
- it("returns connected with tools_count=null when result has no tools field", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({ ok: true, result: { something: "else" } });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({ state: "connected", tools_count: null });
- });
-
- it("returns connected with tools_count=null when tools is not an array", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({
- ok: true,
- result: { tools: "not-an-array" },
- });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({ state: "connected", tools_count: null });
- });
-
- it("returns connected with tools_count=null when result is undefined", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({ ok: true, result: undefined });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({ state: "connected", tools_count: null });
- });
-
- it("returns stale_token on 401", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({
- ok: false,
- kind: "http_error",
- status: 401,
- });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({
- state: "stale_token",
- url: "https://x",
- http_status: 401,
- });
- });
-
- it("returns stale_token on 403", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({
- ok: false,
- kind: "http_error",
- status: 403,
- });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({ state: "stale_token", http_status: 403 });
- });
-
- it("returns unreachable HTTP 500 on other http_error", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({
- ok: false,
- kind: "http_error",
- status: 500,
- });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({ state: "unreachable", error: "HTTP 500" });
- });
-
- it("returns unreachable on timeout", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({ ok: false, kind: "timeout" });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({ state: "unreachable", error: "timed out" });
- });
-
- it("returns unreachable on aborted", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({ ok: false, kind: "aborted" });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({ state: "unreachable", error: "aborted" });
- });
-
- it("returns unreachable on rpc_error with code + message", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({
- ok: false,
- kind: "rpc_error",
- code: -32601,
- message: "Method not found",
- });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({
- state: "unreachable",
- error: "rpc error -32601: Method not found",
- });
- });
-
- it("returns unreachable on malformed_response", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({
- ok: false,
- kind: "malformed_response",
- message: "empty body",
- });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({
- state: "unreachable",
- error: "malformed response: empty body",
- });
- });
-
- it("returns unreachable on network_error using the raw message", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({
- ok: false,
- kind: "network_error",
- message: "ECONNREFUSED",
- });
- const r = await getMcpStatus("k");
- expect(r).toMatchObject({ state: "unreachable", error: "ECONNREFUSED" });
- });
-
- it("passes the configured 2s timeout to mcpRpc", async () => {
- readMcpConfigRowMock.mockResolvedValueOnce({
- url: "https://x",
- headers: { Authorization: "Bearer t" },
- });
- bearerFromHeadersMock.mockReturnValueOnce("t");
- mcpRpcMock.mockResolvedValueOnce({ ok: true, result: { tools: [] } });
- await getMcpStatus("k");
- expect(mcpRpcMock).toHaveBeenCalledWith(
- "https://x",
- "t",
- "tools/list",
- {},
- { timeoutMs: 2000 },
- );
- });
-});
-
-describe("disconnectMcp", () => {
- beforeEach(() => {
- openclawMock.mockReset();
- });
-
- it("calls `openclaw mcp unset <key>` with json:false", async () => {
- openclawMock.mockResolvedValueOnce(undefined);
- await disconnectMcp("acme-notfair-googleads");
- expect(openclawMock).toHaveBeenCalledWith(
- ["mcp", "unset", "acme-notfair-googleads"],
- { json: false },
- );
- });
-
- it("swallows OpenClawError when stderr says 'not found' (idempotent)", async () => {
- openclawMock.mockRejectedValueOnce(
- new OpenClawError("exited", "key not found in config", 1),
- );
- await expect(disconnectMcp("missing")).resolves.toBeUndefined();
- });
-
- it("swallows OpenClawError when stderr says 'unknown' (idempotent)", async () => {
- openclawMock.mockRejectedValueOnce(
- new OpenClawError("exited", "unknown mcp key", 1),
- );
- await expect(disconnectMcp("missing")).resolves.toBeUndefined();
- });
-
- it("re-throws OpenClawError with unrelated stderr", async () => {
- openclawMock.mockRejectedValueOnce(
- new OpenClawError("exited", "permission denied", 1),
- );
- await expect(disconnectMcp("k")).rejects.toBeInstanceOf(OpenClawError);
- });
-
- it("re-throws OpenClawError when stderr is empty", async () => {
- openclawMock.mockRejectedValueOnce(new OpenClawError("exited", "", 1));
- await expect(disconnectMcp("k")).rejects.toBeInstanceOf(OpenClawError);
- });
-
- it("re-throws non-OpenClawError errors unchanged", async () => {
- openclawMock.mockRejectedValueOnce(new TypeError("nope"));
- await expect(disconnectMcp("k")).rejects.toBeInstanceOf(TypeError);
- });
-
- it("is case-insensitive on 'not found' matching", async () => {
- openclawMock.mockRejectedValueOnce(
- new OpenClawError("exited", "Key NOT FOUND in openclaw.json", 1),
- );
- await expect(disconnectMcp("k")).resolves.toBeUndefined();
- });
-});
-
-describe("setMcpBearer", () => {
- beforeEach(() => {
- openclawMock.mockReset();
- });
-
- it("calls `openclaw mcp set <key> <json>` with streamable-http transport + bearer", async () => {
- openclawMock.mockResolvedValueOnce(undefined);
- await setMcpBearer("acme-notfair-googleads", "https://x/mcp", "tok-abc");
- expect(openclawMock).toHaveBeenCalledWith(
- [
- "mcp",
- "set",
- "acme-notfair-googleads",
- JSON.stringify({
- url: "https://x/mcp",
- transport: "streamable-http",
- headers: { Authorization: "Bearer tok-abc" },
- }),
- ],
- { json: false },
- );
- });
-
- it("propagates errors from the underlying openclaw call", async () => {
- openclawMock.mockRejectedValueOnce(new Error("disk full"));
- await expect(
- setMcpBearer("k", "https://x", "t"),
- ).rejects.toThrow("disk full");
- });
-});
diff --git a/notfair-cmo/src/server/mcp-state.ts b/notfair-cmo/src/server/mcp-state.ts
deleted file mode 100644
index b1ceed4f..00000000
--- a/notfair-cmo/src/server/mcp-state.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { openclaw, OpenClawError } from "@/server/openclaw/cli";
-import { bearerFromHeaders, mcpRpc, readMcpConfigRow } from "@/server/mcp/rpc";
-
-/**
- * Read the merged state of a configured MCP server from OpenClaw + a fast
- * health probe. We keep this thin: source of truth is openclaw.json (the
- * config the CLI manages); we don't shadow-store tokens locally.
- *
- * `connection_state`:
- * - "not_configured": no row in `openclaw mcp` for this key
- * - "configured_no_token": row exists but lacks an Authorization header
- * - "connected": row + token + probe succeeded
- * - "stale_token": row + token but probe came back 401/403
- * - "unreachable": row + token but probe failed (network/timeout/5xx)
- *
- * HTTP plumbing (config-read, bearer parse, JSON-RPC POST, SSE handling)
- * lives in `@/server/mcp/rpc`. This file owns only the UI status mapping.
- */
-
-export type McpRuntimeStatus =
- | { state: "not_configured" }
- | { state: "configured_no_token"; url: string }
- | {
- state: "connected";
- url: string;
- tools_count: number | null;
- last_checked_at: string;
- }
- | {
- state: "stale_token";
- url: string;
- http_status: number;
- last_checked_at: string;
- }
- | {
- state: "unreachable";
- url: string;
- error: string;
- last_checked_at: string;
- };
-
-export async function getMcpStatus(key: string): Promise<McpRuntimeStatus> {
- const config = await readMcpConfigRow(key);
- if (!config || !config.url) return { state: "not_configured" };
- const url = config.url;
- const token = bearerFromHeaders(config.headers);
- if (!token) return { state: "configured_no_token", url };
- return probe(url, token);
-}
-
-/**
- * Lightweight liveness probe. POSTs JSON-RPC `tools/list` — the cheapest MCP
- * call that exercises auth + transport in one round-trip. 2s timeout: this
- * renders server-side on the MCP tab and we'd rather show "unreachable" than
- * block the page.
- */
-async function probe(url: string, token: string): Promise<McpRuntimeStatus> {
- const last_checked_at = new Date().toISOString();
- const r = await mcpRpc<{ tools?: unknown }>(
- url,
- token,
- "tools/list",
- {},
- { timeoutMs: 2000 },
- );
- if (r.ok) {
- return {
- state: "connected",
- url,
- tools_count: countToolsFromResult(r.result),
- last_checked_at,
- };
- }
- if (r.kind === "http_error" && (r.status === 401 || r.status === 403)) {
- return { state: "stale_token", url, http_status: r.status, last_checked_at };
- }
- if (r.kind === "http_error") {
- return { state: "unreachable", url, error: `HTTP ${r.status}`, last_checked_at };
- }
- if (r.kind === "timeout") {
- return { state: "unreachable", url, error: "timed out", last_checked_at };
- }
- if (r.kind === "aborted") {
- return { state: "unreachable", url, error: "aborted", last_checked_at };
- }
- if (r.kind === "rpc_error") {
- return {
- state: "unreachable",
- url,
- error: `rpc error ${r.code}: ${r.message}`,
- last_checked_at,
- };
- }
- if (r.kind === "malformed_response") {
- return {
- state: "unreachable",
- url,
- error: `malformed response: ${r.message}`,
- last_checked_at,
- };
- }
- // network_error
- return { state: "unreachable", url, error: r.message, last_checked_at };
-}
-
-function countToolsFromResult(result: { tools?: unknown } | undefined): number | null {
- if (!result || typeof result !== "object") return null;
- if (!Array.isArray(result.tools)) return null;
- return result.tools.length;
-}
-
-export async function disconnectMcp(key: string): Promise<void> {
- try {
- await openclaw(["mcp", "unset", key], { json: false });
- } catch (err) {
- // If the row was already gone, treat as success — UI calls this on a
- // "Disconnect" button that should be idempotent.
- if (err instanceof OpenClawError && err.exitCode !== 0) {
- const msg = (err.stderr ?? "").toLowerCase();
- if (msg.includes("not found") || msg.includes("unknown")) return;
- }
- throw err;
- }
-}
-
-export async function setMcpBearer(
- key: string,
- url: string,
- token: string,
-): Promise<void> {
- // Project scoping is via the openclaw key namespace alone (project slug
- // prefix). We deliberately do not write `codex.agents`: it only worked
- // for the Codex app-server runtime and was silently ignored on other
- // backends (DeepSeek, Claude, etc.), so its semantics were inconsistent.
- // Per-project tokens + project-prefixed keys give us a uniform "soft
- // isolation" model that's the same across every runtime.
- const config = {
- url,
- transport: "streamable-http",
- headers: { Authorization: `Bearer ${token}` },
- };
- await openclaw(["mcp", "set", key, JSON.stringify(config)], { json: false });
-}
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 84668902..00000000
--- a/notfair-cmo/src/server/mcp/rpc.test.ts
+++ /dev/null
@@ -1,281 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { OpenClawError } from "@/server/openclaw/cli";
-
-const openclawMock = vi.fn();
-vi.mock("@/server/openclaw/cli", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@/server/openclaw/cli")>();
- return {
- ...actual,
- openclaw: (...args: unknown[]) => openclawMock(...args),
- };
-});
-
-import {
- bearerFromHeaders,
- getMcpConfig,
- mcpRpc,
- readMcpConfigRow,
-} from "./rpc";
-
-describe("bearerFromHeaders", () => {
- it("extracts bearer from Authorization header", () => {
- expect(bearerFromHeaders({ Authorization: "Bearer abc123" })).toBe("abc123");
- });
-
- it("accepts lowercase 'authorization' key", () => {
- expect(bearerFromHeaders({ authorization: "Bearer xyz" })).toBe("xyz");
- });
-
- it("accepts case-mixed 'bearer' scheme", () => {
- expect(bearerFromHeaders({ Authorization: "bearer abc" })).toBe("abc");
- expect(bearerFromHeaders({ Authorization: "BEARER abc" })).toBe("abc");
- });
-
- it("returns null on undefined headers", () => {
- expect(bearerFromHeaders(undefined)).toBeNull();
- });
-
- it("returns null on empty headers", () => {
- expect(bearerFromHeaders({})).toBeNull();
- });
-
- it("returns null when scheme is not Bearer", () => {
- expect(bearerFromHeaders({ Authorization: "Basic abc" })).toBeNull();
- });
-
- it("trims trailing whitespace from token", () => {
- expect(bearerFromHeaders({ Authorization: "Bearer abc " })).toBe("abc");
- });
-});
-
-describe("readMcpConfigRow", () => {
- beforeEach(() => {
- openclawMock.mockReset();
- });
-
- it("returns the row when openclaw succeeds", async () => {
- const row = {
- url: "https://example.com/mcp",
- transport: "streamable-http",
- headers: { Authorization: "Bearer t" },
- };
- openclawMock.mockResolvedValueOnce(row);
- await expect(readMcpConfigRow("test-key")).resolves.toEqual(row);
- expect(openclawMock).toHaveBeenCalledWith(["mcp", "show", "test-key"], {
- json: true,
- });
- });
-
- it("returns null when openclaw returns non-object", async () => {
- openclawMock.mockResolvedValueOnce(null);
- await expect(readMcpConfigRow("test-key")).resolves.toBeNull();
- });
-
- it("returns null when openclaw throws OpenClawError", async () => {
- openclawMock.mockRejectedValueOnce(new OpenClawError("unknown key", "", 1));
- await expect(readMcpConfigRow("missing-key")).resolves.toBeNull();
- });
-
- it("re-throws non-OpenClawError errors", async () => {
- openclawMock.mockRejectedValueOnce(new TypeError("totally different"));
- await expect(readMcpConfigRow("test-key")).rejects.toThrow(TypeError);
- });
-});
-
-describe("getMcpConfig", () => {
- beforeEach(() => {
- openclawMock.mockReset();
- });
-
- it("returns {url, token} when row has both", async () => {
- openclawMock.mockResolvedValueOnce({
- url: "https://example.com",
- headers: { Authorization: "Bearer t" },
- });
- await expect(getMcpConfig("k")).resolves.toEqual({
- url: "https://example.com",
- token: "t",
- });
- });
-
- it("returns null when row missing", async () => {
- openclawMock.mockResolvedValueOnce(null);
- await expect(getMcpConfig("k")).resolves.toBeNull();
- });
-
- it("returns null when row has url but no bearer", async () => {
- openclawMock.mockResolvedValueOnce({ url: "https://example.com" });
- await expect(getMcpConfig("k")).resolves.toBeNull();
- });
-
- it("returns null when row has bearer but no url", async () => {
- openclawMock.mockResolvedValueOnce({
- headers: { Authorization: "Bearer t" },
- });
- await expect(getMcpConfig("k")).resolves.toBeNull();
- });
-});
-
-describe("mcpRpc", () => {
- const fetchMock = vi.fn();
- const originalFetch = globalThis.fetch;
-
- beforeEach(() => {
- fetchMock.mockReset();
- globalThis.fetch = fetchMock as unknown as typeof fetch;
- });
-
- afterEach(() => {
- globalThis.fetch = originalFetch;
- });
-
- function jsonResponse(status: number, body: unknown): Response {
- return new Response(JSON.stringify(body), {
- status,
- headers: { "Content-Type": "application/json" },
- });
- }
-
- function sseResponse(status: number, frames: string[]): Response {
- const body = frames.map((f) => `data: ${f}`).join("\n\n") + "\n\n";
- return new Response(body, {
- status,
- headers: { "Content-Type": "text/event-stream" },
- });
- }
-
- it("returns {ok, result} on a successful JSON envelope", async () => {
- fetchMock.mockResolvedValueOnce(
- jsonResponse(200, { jsonrpc: "2.0", id: 1, result: { tools: [] } }),
- );
- const r = await mcpRpc("http://x", "tok", "tools/list");
- expect(r).toEqual({ ok: true, result: { tools: [] } });
- });
-
- it("sends bearer auth header and JSON-RPC envelope in body", async () => {
- fetchMock.mockResolvedValueOnce(
- jsonResponse(200, { jsonrpc: "2.0", id: 1, result: { ok: true } }),
- );
- await mcpRpc("http://x", "tok", "tools/call", { name: "X" });
- const [, init] = fetchMock.mock.calls[0]!;
- expect(init.method).toBe("POST");
- expect((init.headers as Record<string, string>).Authorization).toBe(
- "Bearer tok",
- );
- expect(JSON.parse(init.body as string)).toMatchObject({
- jsonrpc: "2.0",
- method: "tools/call",
- params: { name: "X" },
- });
- });
-
- it("returns {ok, result} on SSE-framed response with final data: frame", async () => {
- fetchMock.mockResolvedValueOnce(
- sseResponse(200, [
- JSON.stringify({ jsonrpc: "2.0", id: 1, result: { partial: true } }),
- JSON.stringify({ jsonrpc: "2.0", id: 1, result: { final: true } }),
- ]),
- );
- const r = await mcpRpc("http://x", "tok", "tools/list");
- expect(r).toEqual({ ok: true, result: { final: true } });
- });
-
- it("returns rpc_error on JSON-RPC error envelope", async () => {
- fetchMock.mockResolvedValueOnce(
- jsonResponse(200, {
- jsonrpc: "2.0",
- id: 1,
- error: { code: -32601, message: "Method not found" },
- }),
- );
- const r = await mcpRpc("http://x", "tok", "nope");
- expect(r).toEqual({
- ok: false,
- kind: "rpc_error",
- code: -32601,
- message: "Method not found",
- });
- });
-
- it("returns http_error with 401 status", async () => {
- fetchMock.mockResolvedValueOnce(new Response("", { status: 401 }));
- const r = await mcpRpc("http://x", "tok", "tools/list");
- expect(r).toEqual({ ok: false, kind: "http_error", status: 401 });
- });
-
- it("returns http_error with 500 status", async () => {
- fetchMock.mockResolvedValueOnce(new Response("server fire", { status: 500 }));
- const r = await mcpRpc("http://x", "tok", "tools/list");
- expect(r).toEqual({ ok: false, kind: "http_error", status: 500 });
- });
-
- it("returns network_error when fetch throws (not abort)", async () => {
- fetchMock.mockRejectedValueOnce(new TypeError("fetch failed"));
- const r = await mcpRpc("http://x", "tok", "tools/list");
- expect(r).toMatchObject({ ok: false, kind: "network_error" });
- if (!r.ok && r.kind === "network_error") {
- expect(r.message).toBe("fetch failed");
- }
- });
-
- it("returns timeout when our internal timer fires", async () => {
- fetchMock.mockImplementationOnce(
- (_url, init) =>
- new Promise((_resolve, reject) => {
- const sig = (init as RequestInit).signal as AbortSignal;
- sig.addEventListener("abort", () => {
- const e = new Error("aborted");
- e.name = "AbortError";
- reject(e);
- });
- }),
- );
- const r = await mcpRpc("http://x", "tok", "tools/list", {}, { timeoutMs: 10 });
- expect(r).toEqual({ ok: false, kind: "timeout" });
- });
-
- it("returns aborted when caller's signal fires before timeout", async () => {
- const caller = new AbortController();
- fetchMock.mockImplementationOnce(
- (_url, init) =>
- new Promise((_resolve, reject) => {
- const sig = (init as RequestInit).signal as AbortSignal;
- sig.addEventListener("abort", () => {
- const e = new Error("aborted");
- e.name = "AbortError";
- reject(e);
- });
- }),
- );
- const p = mcpRpc(
- "http://x",
- "tok",
- "tools/list",
- {},
- { timeoutMs: 60_000, signal: caller.signal },
- );
- caller.abort();
- await expect(p).resolves.toEqual({ ok: false, kind: "aborted" });
- });
-
- it("returns malformed_response on empty body", async () => {
- fetchMock.mockResolvedValueOnce(new Response("", { status: 200 }));
- const r = await mcpRpc("http://x", "tok", "tools/list");
- expect(r).toMatchObject({ ok: false, kind: "malformed_response" });
- });
-
- it("returns malformed_response on invalid JSON body", async () => {
- fetchMock.mockResolvedValueOnce(new Response("not json", { status: 200 }));
- const r = await mcpRpc("http://x", "tok", "tools/list");
- expect(r).toMatchObject({ ok: false, kind: "malformed_response" });
- });
-
- it("returns malformed_response when envelope has neither result nor error", async () => {
- fetchMock.mockResolvedValueOnce(
- jsonResponse(200, { jsonrpc: "2.0", id: 1 }),
- );
- const r = await mcpRpc("http://x", "tok", "tools/list");
- expect(r).toMatchObject({ ok: false, kind: "malformed_response" });
- });
-});
diff --git a/notfair-cmo/src/server/mcp/rpc.ts b/notfair-cmo/src/server/mcp/rpc.ts
index 25d97702..b4116026 100644
--- a/notfair-cmo/src/server/mcp/rpc.ts
+++ b/notfair-cmo/src/server/mcp/rpc.ts
@@ -1,25 +1,28 @@
-import { openclaw, OpenClawError } from "@/server/openclaw/cli";
+import { findMcpToken } from "@/server/mcp/tokens";
+import { mcpSpecByKey } from "@/server/mcp-catalog";
/**
* Shared MCP HTTP plumbing. Two callers use this today:
- * - `mcp-state.ts:probe()` (liveness check via tools/list)
+ * - `mcp/state.ts:probe()` (liveness check via tools/list)
* - `onboarding/audit.ts` (real audit via tools/call runScript)
*
- * Single source of truth for: subprocess-config read, bearer extraction,
- * JSON-RPC envelope construction, SSE-vs-JSON response parsing, error shapes.
+ * Single source of truth for: token lookup (from notfair-cmo SQLite), bearer
+ * extraction, JSON-RPC envelope construction, SSE-vs-JSON response parsing,
+ * error shapes.
*
- * Security: never log the McpConfig.token. The bearer is held in memory only
- * for the duration of one RPC call. `openclaw mcp show` subprocess output
- * must never be logged either (full stdout contains the token in headers).
+ * Security: never log the bearer. Token is held in memory only for the
+ * duration of one RPC call.
*/
-export type McpConfigRow = {
+export interface McpConfigRow {
url?: string;
- transport?: string;
headers?: Record<string, string>;
-};
+}
-export type McpConfig = { url: string; token: string };
+export interface McpConfig {
+ url: string;
+ token: string;
+}
export type RpcResult<T> =
| { ok: true; result: T }
@@ -31,24 +34,24 @@ export type RpcResult<T> =
| { ok: false; kind: "malformed_response"; message: string };
/**
- * Read the raw MCP config row from OpenClaw. Returns null when the key is
- * unknown (OpenClaw exits non-zero). Callers that need to distinguish
- * "no row" from "row but no bearer" (e.g., the UI status surface) should
- * use this + bearerFromHeaders directly. Callers that just need usable
- * credentials should use getMcpConfig.
+ * 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.
*/
-export async function readMcpConfigRow(key: string): Promise<McpConfigRow | null> {
- try {
- const out = await openclaw(["mcp", "show", key], { json: true });
- if (!out || typeof out !== "object") return null;
- return out as McpConfigRow;
- } catch (err) {
- if (err instanceof OpenClawError) return null;
- throw err;
- }
+export function readMcpConfigRow(
+ project_slug: string,
+ catalog_key: string,
+): McpConfigRow | null {
+ const spec = mcpSpecByKey(catalog_key);
+ if (!spec) return null;
+ const token = findMcpToken(project_slug, catalog_key);
+ if (!token) return { url: spec.resource_url };
+ return {
+ url: spec.resource_url,
+ headers: { Authorization: `Bearer ${token.access_token_enc}` },
+ };
}
-/** Parse the bearer out of an `Authorization: Bearer <token>` header. */
export function bearerFromHeaders(
headers: Record<string, string> | undefined,
): string | null {
@@ -59,41 +62,19 @@ export function bearerFromHeaders(
return m ? m[1].trim() : null;
}
-/**
- * Convenience wrapper for callers that just need URL + bearer. Returns null
- * when the key isn't configured OR has no bearer — the two failure modes
- * collapse to the same "can't talk to this MCP" answer.
- */
-export async function getMcpConfig(key: string): Promise<McpConfig | null> {
- const row = await readMcpConfigRow(key);
+export function getMcpConfig(project_slug: string, catalog_key: string): McpConfig | null {
+ const row = readMcpConfigRow(project_slug, catalog_key);
if (!row || !row.url) return null;
const token = bearerFromHeaders(row.headers);
if (!token) return null;
return { url: row.url, token };
}
-export type McpRpcOpts = {
- /** Hard timeout in ms. Defaults to 10s. */
+export interface McpRpcOpts {
timeoutMs?: number;
- /** Caller's abort signal — composed with our internal timeout. */
signal?: AbortSignal;
-};
+}
-/**
- * Send one JSON-RPC call to an MCP server over streamable-http transport.
- *
- * Every failure has a named kind so callers can branch:
- * - http_error — non-2xx HTTP (401/403 = stale token; 5xx = server)
- * - timeout — our internal timer fired
- * - aborted — caller's signal fired
- * - network_error — fetch threw before getting a response
- * - rpc_error — server returned a JSON-RPC error envelope
- * - malformed_response — body wasn't parseable JSON-RPC
- *
- * Body is buffered (text() then parsed). MCP can reply with either plain
- * JSON or SSE-framed (`data: ...\n\n`); for a single RPC we want the final
- * envelope, so we extract the last `data:` frame when SSE is detected.
- */
export async function mcpRpc<T = unknown>(
url: string,
token: string,
@@ -182,12 +163,7 @@ function parseRpcBody<T>(body: string): RpcResult<T> {
};
}
if (parsed.error) {
- return {
- ok: false,
- kind: "rpc_error",
- code: parsed.error.code,
- message: parsed.error.message,
- };
+ return { ok: false, kind: "rpc_error", code: parsed.error.code, message: parsed.error.message };
}
if (parsed.result === undefined) {
return {
@@ -199,11 +175,6 @@ function parseRpcBody<T>(body: string): RpcResult<T> {
return { ok: true, result: parsed.result };
}
-/**
- * MCP streamable-http can return plain JSON OR SSE (`data: ...\n\n`).
- * For a single RPC we want the last full `data:` frame; for plain JSON we
- * return the body as-is. Returns null when the body has no usable envelope.
- */
function pickRpcEnvelope(body: string): string | null {
const trimmed = body.trim();
if (!trimmed) return null;
diff --git a/notfair-cmo/src/server/mcp/state.ts b/notfair-cmo/src/server/mcp/state.ts
new file mode 100644
index 00000000..228e1e10
--- /dev/null
+++ b/notfair-cmo/src/server/mcp/state.ts
@@ -0,0 +1,119 @@
+import { findMcpToken, upsertMcpToken, deleteMcpToken } from "./tokens";
+import { mcpSpecByKey } from "@/server/mcp-catalog";
+import { mcpRpc } from "./rpc";
+
+/**
+ * Status surface for the Connections page + dashboard banners.
+ *
+ * - "not_configured": no row in mcp_tokens
+ * - "configured_no_token": (legacy compat — pre-OAuth half-config rows)
+ * - "connected": token present and probe succeeded
+ * - "stale_token": probe came back 401/403
+ * - "unreachable": probe failed (network/timeout/5xx)
+ */
+export type McpRuntimeStatus =
+ | { state: "not_configured" }
+ | { state: "configured_no_token"; url: string }
+ | {
+ state: "connected";
+ url: string;
+ tools_count: number | null;
+ last_checked_at: string;
+ }
+ | {
+ state: "stale_token";
+ url: string;
+ http_status: number;
+ last_checked_at: string;
+ }
+ | {
+ state: "unreachable";
+ url: string;
+ error: string;
+ last_checked_at: string;
+ };
+
+export async function getMcpStatus(
+ project_slug: string,
+ catalog_key: string,
+): Promise<McpRuntimeStatus> {
+ const spec = mcpSpecByKey(catalog_key);
+ if (!spec) return { state: "not_configured" };
+ const token = findMcpToken(project_slug, catalog_key);
+ if (!token) return { state: "not_configured" };
+ return probe(spec.resource_url, token.access_token_enc);
+}
+
+async function probe(url: string, token: string): Promise<McpRuntimeStatus> {
+ const last_checked_at = new Date().toISOString();
+ const r = await mcpRpc<{ tools?: unknown }>(
+ url,
+ token,
+ "tools/list",
+ {},
+ { timeoutMs: 2000 },
+ );
+ if (r.ok) {
+ return {
+ state: "connected",
+ url,
+ tools_count: countToolsFromResult(r.result),
+ last_checked_at,
+ };
+ }
+ if (r.kind === "http_error" && (r.status === 401 || r.status === 403)) {
+ return { state: "stale_token", url, http_status: r.status, last_checked_at };
+ }
+ if (r.kind === "http_error") {
+ return { state: "unreachable", url, error: `HTTP ${r.status}`, last_checked_at };
+ }
+ if (r.kind === "timeout") {
+ return { state: "unreachable", url, error: "timed out", last_checked_at };
+ }
+ if (r.kind === "aborted") {
+ return { state: "unreachable", url, error: "aborted", last_checked_at };
+ }
+ if (r.kind === "rpc_error") {
+ return {
+ state: "unreachable",
+ url,
+ error: `rpc error ${r.code}: ${r.message}`,
+ last_checked_at,
+ };
+ }
+ if (r.kind === "malformed_response") {
+ return {
+ state: "unreachable",
+ url,
+ error: `malformed response: ${r.message}`,
+ last_checked_at,
+ };
+ }
+ return { state: "unreachable", url, error: r.message, last_checked_at };
+}
+
+function countToolsFromResult(result: { tools?: unknown } | undefined): number | null {
+ if (!result || typeof result !== "object") return null;
+ if (!Array.isArray(result.tools)) return null;
+ return result.tools.length;
+}
+
+export async function disconnectMcp(project_slug: string, catalog_key: string): Promise<void> {
+ const token = findMcpToken(project_slug, catalog_key);
+ if (token) deleteMcpToken(token.id);
+}
+
+export async function setMcpBearer(
+ project_slug: string,
+ catalog_key: string,
+ token: string,
+ options: { scope?: string; expires_at?: string } = {},
+): Promise<void> {
+ upsertMcpToken({
+ project_slug,
+ server_name: catalog_key,
+ access_token: token,
+ scope: options.scope,
+ expires_at: options.expires_at,
+ });
+}
diff --git a/notfair-cmo/src/server/mcp/tokens.ts b/notfair-cmo/src/server/mcp/tokens.ts
new file mode 100644
index 00000000..23382f34
--- /dev/null
+++ b/notfair-cmo/src/server/mcp/tokens.ts
@@ -0,0 +1,130 @@
+import { randomUUID } from "node:crypto";
+import { getDb } from "@/server/db/db";
+
+/**
+ * MCP token storage for notfair-cmo.
+ *
+ * Replaces OpenClaw's config-file storage (`openclaw mcp set/unset`). Tokens
+ * are project-scoped — one project's notfair-googleads connection never bleeds
+ * into another's.
+ *
+ * `access_token_enc` / `refresh_token_enc` columns are encrypted-at-rest
+ * placeholders today (we store the raw JSON envelope from the OAuth callback)
+ * but the schema is ready for a keytar-backed encryption pass.
+ */
+export interface McpToken {
+ id: string;
+ project_slug: string;
+ server_name: string;
+ account_label: string;
+ access_token_enc: string;
+ refresh_token_enc: string | null;
+ expires_at: string | null;
+ scope: string | null;
+ metadata_json: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface UpsertMcpTokenInput {
+ project_slug: string;
+ server_name: string;
+ account_label?: string;
+ access_token: string;
+ refresh_token?: string;
+ expires_at?: string;
+ scope?: string;
+ metadata?: Record<string, unknown>;
+}
+
+export function upsertMcpToken(input: UpsertMcpTokenInput): McpToken {
+ const db = getDb();
+ const account_label = input.account_label ?? "";
+ const now = new Date().toISOString();
+ const existing = db
+ .prepare(
+ "SELECT * FROM mcp_tokens WHERE project_slug = ? AND server_name = ? AND account_label = ?",
+ )
+ .get(input.project_slug, input.server_name, account_label) as McpToken | undefined;
+
+ if (existing) {
+ db.prepare(
+ "UPDATE mcp_tokens SET access_token_enc = ?, refresh_token_enc = ?, expires_at = ?, scope = ?, metadata_json = ?, updated_at = ? WHERE id = ?",
+ ).run(
+ input.access_token,
+ input.refresh_token ?? null,
+ input.expires_at ?? null,
+ input.scope ?? null,
+ input.metadata ? JSON.stringify(input.metadata) : null,
+ now,
+ existing.id,
+ );
+ return getMcpToken(existing.id)!;
+ }
+
+ const token: McpToken = {
+ id: randomUUID(),
+ project_slug: input.project_slug,
+ server_name: input.server_name,
+ account_label,
+ access_token_enc: input.access_token,
+ refresh_token_enc: input.refresh_token ?? null,
+ expires_at: input.expires_at ?? null,
+ scope: input.scope ?? null,
+ metadata_json: input.metadata ? JSON.stringify(input.metadata) : null,
+ created_at: now,
+ updated_at: now,
+ };
+ db.prepare(
+ "INSERT INTO mcp_tokens (id, project_slug, server_name, account_label, access_token_enc, refresh_token_enc, expires_at, scope, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ ).run(
+ token.id,
+ token.project_slug,
+ token.server_name,
+ token.account_label,
+ token.access_token_enc,
+ token.refresh_token_enc,
+ token.expires_at,
+ token.scope,
+ token.metadata_json,
+ token.created_at,
+ token.updated_at,
+ );
+ return token;
+}
+
+export function getMcpToken(id: string): McpToken | null {
+ return (
+ (getDb()
+ .prepare("SELECT * FROM mcp_tokens WHERE id = ?")
+ .get(id) as McpToken | undefined) ?? null
+ );
+}
+
+export function findMcpToken(
+ project_slug: string,
+ server_name: string,
+ account_label = "",
+): McpToken | null {
+ return (
+ (getDb()
+ .prepare(
+ "SELECT * FROM mcp_tokens WHERE project_slug = ? AND server_name = ? AND account_label = ?",
+ )
+ .get(project_slug, server_name, account_label) as McpToken | undefined) ?? null
+ );
+}
+
+export function listProjectMcpTokens(project_slug: string): McpToken[] {
+ return getDb()
+ .prepare("SELECT * FROM mcp_tokens WHERE project_slug = ? ORDER BY server_name, account_label")
+ .all(project_slug) as McpToken[];
+}
+
+export function deleteMcpToken(id: string): void {
+ getDb().prepare("DELETE FROM mcp_tokens WHERE id = ?").run(id);
+}
+
+export function deleteProjectMcpTokens(project_slug: string): void {
+ getDb().prepare("DELETE FROM mcp_tokens WHERE project_slug = ?").run(project_slug);
+}
diff --git a/notfair-cmo/src/server/onboarding/accounts.test.ts b/notfair-cmo/src/server/onboarding/accounts.test.ts
index fb65b70d..0e7c9469 100644
--- a/notfair-cmo/src/server/onboarding/accounts.test.ts
+++ b/notfair-cmo/src/server/onboarding/accounts.test.ts
@@ -114,7 +114,7 @@ function toolCallResult(payload: unknown): {
describe("listGoogleAdsAccounts", () => {
beforeEach(() => {
vi.clearAllMocks();
- getMcpConfigMock.mockResolvedValue({
+ getMcpConfigMock.mockReturnValue({
url: "https://notfair.co/api/mcp/google_ads",
token: "tok",
});
@@ -143,7 +143,7 @@ describe("listGoogleAdsAccounts", () => {
});
it("returns mcp_not_configured when getMcpConfig returns null", async () => {
- getMcpConfigMock.mockResolvedValueOnce(null);
+ getMcpConfigMock.mockReturnValueOnce(null);
const r = await listGoogleAdsAccounts("acme");
expect(r).toMatchObject({ ok: false, kind: "mcp_not_configured" });
expect(mcpRpcMock).not.toHaveBeenCalled();
@@ -181,7 +181,7 @@ describe("listGoogleAdsAccounts", () => {
describe("setOnboardingAccountAction", () => {
beforeEach(() => {
vi.clearAllMocks();
- getMcpConfigMock.mockResolvedValue({
+ getMcpConfigMock.mockReturnValue({
url: "https://notfair.co/api/mcp/google_ads",
token: "tok",
});
diff --git a/notfair-cmo/src/server/onboarding/accounts.ts b/notfair-cmo/src/server/onboarding/accounts.ts
index b5951e84..d2fa3158 100644
--- a/notfair-cmo/src/server/onboarding/accounts.ts
+++ b/notfair-cmo/src/server/onboarding/accounts.ts
@@ -3,7 +3,6 @@
import { revalidatePath } from "next/cache";
import { getMcpConfig, mcpRpc } from "@/server/mcp/rpc";
-import { storedMcpKey } from "@/server/mcp-catalog";
import { getProject, setProjectGoogleAdsAccount } from "@/server/db/projects";
import type { Project } from "@/types";
@@ -46,7 +45,7 @@ const LIST_TIMEOUT_MS = 8_000;
export async function listGoogleAdsAccounts(
project_slug: string,
): Promise<ListAccountsResult> {
- const cfg = await getMcpConfig(storedMcpKey(project_slug, MCP_CATALOG_KEY));
+ const cfg = getMcpConfig(project_slug, MCP_CATALOG_KEY);
if (!cfg) {
return {
ok: false,
diff --git a/notfair-cmo/src/server/openclaw/agent-turn.test.ts b/notfair-cmo/src/server/openclaw/agent-turn.test.ts
deleted file mode 100644
index e0a216b9..00000000
--- a/notfair-cmo/src/server/openclaw/agent-turn.test.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { EventEmitter } from "node:events";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-const spawnMock = vi.fn();
-vi.mock("node:child_process", () => ({
- spawn: (cmd: string, args: string[], opts?: unknown) => spawnMock(cmd, args, opts),
-}));
-
-import { streamAgentTurn } from "./agent-turn";
-
-type FakeChild = EventEmitter & {
- stdout: EventEmitter;
- stderr: EventEmitter;
- kill: ReturnType<typeof vi.fn>;
-};
-
-function makeChild(): FakeChild {
- const proc = new EventEmitter() as FakeChild;
- proc.stdout = new EventEmitter();
- proc.stderr = new EventEmitter();
- proc.kill = vi.fn(() => true);
- return proc;
-}
-
-async function collect(gen: AsyncGenerator<string, void, void>): Promise<string[]> {
- const out: string[] = [];
- for await (const chunk of gen) out.push(chunk);
- return out;
-}
-
-describe("streamAgentTurn", () => {
- beforeEach(() => {
- spawnMock.mockReset();
- });
-
- afterEach(() => {
- spawnMock.mockReset();
- });
-
- it("spawns openclaw with --agent and --message args", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stdout.emit("end");
- child.emit("close", 0);
- });
- await collect(streamAgentTurn({ agent: "demo-cmo", message: "hi" }));
- expect(spawnMock).toHaveBeenCalledTimes(1);
- const [cmd, args] = spawnMock.mock.calls[0]!;
- expect(cmd).toBe("openclaw");
- expect(args).toEqual(["agent", "--agent", "demo-cmo", "--message", "hi"]);
- });
-
- it("includes --session-id when provided", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stdout.emit("end");
- child.emit("close", 0);
- });
- await collect(streamAgentTurn({ agent: "a", message: "m", sessionId: "sess-1" }));
- const args = spawnMock.mock.calls[0]![1] as string[];
- expect(args).toContain("--session-id");
- expect(args[args.indexOf("--session-id") + 1]).toBe("sess-1");
- });
-
- it("includes --thinking flag when provided", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stdout.emit("end");
- child.emit("close", 0);
- });
- await collect(streamAgentTurn({ agent: "a", message: "m", thinking: "high" }));
- const args = spawnMock.mock.calls[0]![1] as string[];
- expect(args).toContain("--thinking");
- expect(args[args.indexOf("--thinking") + 1]).toBe("high");
- });
-
- it("yields stdout chunks as they arrive", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stdout.emit("data", Buffer.from("hello "));
- child.stdout.emit("data", Buffer.from("world"));
- child.stdout.emit("end");
- child.emit("close", 0);
- });
- const chunks = await collect(streamAgentTurn({ agent: "a", message: "m" }));
- expect(chunks.join("")).toBe("hello world");
- });
-
- it("throws when openclaw exits non-zero, including stderr in error message", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stderr.emit("data", Buffer.from("auth failed: token expired"));
- child.stdout.emit("end");
- child.emit("close", 7);
- });
- await expect(
- collect(streamAgentTurn({ agent: "a", message: "m" })),
- ).rejects.toThrow(/exited with code 7/);
- });
-
- it("includes stderr snippet in the thrown error", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stderr.emit("data", Buffer.from("boom!"));
- child.stdout.emit("end");
- child.emit("close", 1);
- });
- let caught: unknown;
- try {
- await collect(streamAgentTurn({ agent: "a", message: "m" }));
- } catch (err) {
- caught = err;
- }
- expect((caught as Error).message).toMatch(/boom!/);
- });
-
- it("truncates very long stderr to 500 chars in the error message", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- const longErr = "x".repeat(2000);
- setImmediate(() => {
- child.stderr.emit("data", Buffer.from(longErr));
- child.stdout.emit("end");
- child.emit("close", 1);
- });
- let caught: unknown;
- try {
- await collect(streamAgentTurn({ agent: "a", message: "m" }));
- } catch (err) {
- caught = err;
- }
- const msg = (caught as Error).message;
- expect(msg.length).toBeLessThan(longErr.length);
- expect(msg).toMatch(/x{200,500}/);
- });
-
- it("propagates process 'error' events", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- // Don't emit close — emit error to trigger rejectErr path.
- child.emit("error", new Error("ENOENT openclaw"));
- // After throwing, also emit close so any internal waiters resolve.
- child.stdout.emit("end");
- child.emit("close", null);
- });
- await expect(
- collect(streamAgentTurn({ agent: "a", message: "m" })),
- ).rejects.toThrow(/ENOENT openclaw/);
- });
-
- it("clears the kill timer on success (timeout never fires)", async () => {
- vi.useFakeTimers();
- try {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- // Schedule end on the next macrotask under fake timers.
- setImmediate(() => {
- child.stdout.emit("end");
- child.emit("close", 0);
- });
- const p = collect(streamAgentTurn({ agent: "a", message: "m", timeoutMs: 1000 }));
- // Advance to drain queued setImmediates.
- await vi.advanceTimersByTimeAsync(0);
- await p;
- // Advance well past the timeout — kill should NOT have been called.
- vi.advanceTimersByTime(60_000);
- expect(child.kill).not.toHaveBeenCalled();
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("uses default 300s timeout when none provided", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stdout.emit("end");
- child.emit("close", 0);
- });
- await collect(streamAgentTurn({ agent: "a", message: "m" }));
- // No assertion error means default timeout was set without crashing.
- expect(child.kill).not.toHaveBeenCalled();
- });
-
- it("yields nothing when the process emits no stdout but exits cleanly", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stdout.emit("end");
- child.emit("close", 0);
- });
- const chunks = await collect(streamAgentTurn({ agent: "a", message: "m" }));
- expect(chunks).toEqual([]);
- });
-
- it("passes the right stdio config to spawn", async () => {
- const child = makeChild();
- spawnMock.mockImplementationOnce(() => child);
- setImmediate(() => {
- child.stdout.emit("end");
- child.emit("close", 0);
- });
- await collect(streamAgentTurn({ agent: "a", message: "m" }));
- const opts = spawnMock.mock.calls[0]![2] as { stdio: [string, string, string] };
- expect(opts.stdio).toEqual(["ignore", "pipe", "pipe"]);
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/agent-turn.ts b/notfair-cmo/src/server/openclaw/agent-turn.ts
deleted file mode 100644
index 5431590e..00000000
--- a/notfair-cmo/src/server/openclaw/agent-turn.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { spawn } from "node:child_process";
-
-export type AgentTurnInput = {
- agent: string;
- message: string;
- sessionId?: string;
- timeoutMs?: number;
- thinking?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
-};
-
-/**
- * Stream the output of `openclaw agent --agent <name> --message <text>`.
- * We yield text chunks as they arrive on stdout. The OpenClaw CLI emits
- * a mix of progress and final-answer text; consumers can filter.
- */
-export async function* streamAgentTurn(input: AgentTurnInput): AsyncGenerator<string, void, void> {
- const args = [
- "agent",
- "--agent",
- input.agent,
- "--message",
- input.message,
- ];
- if (input.sessionId) {
- args.push("--session-id", input.sessionId);
- }
- if (input.thinking) {
- args.push("--thinking", input.thinking);
- }
-
- const proc = spawn("openclaw", args, { stdio: ["ignore", "pipe", "pipe"] });
- const timeout = setTimeout(() => proc.kill("SIGTERM"), input.timeoutMs ?? 300_000);
-
- try {
- const stdoutQueue: string[] = [];
- let stdoutEnded = false;
- let rejectErr: Error | null = null;
-
- const onChunk = (chunk: Buffer) => {
- stdoutQueue.push(chunk.toString("utf8"));
- };
-
- const stdoutEnd = new Promise<void>((resolve, reject) => {
- proc.stdout.on("data", onChunk);
- proc.stdout.on("end", () => {
- stdoutEnded = true;
- resolve();
- });
- proc.on("error", (err) => {
- rejectErr = err;
- reject(err);
- });
- });
-
- // Drain stderr to avoid backpressure; surface on close if exit was nonzero.
- let stderr = "";
- proc.stderr.on("data", (chunk) => {
- stderr += chunk.toString("utf8");
- });
-
- const exitPromise = new Promise<number | null>((resolve) => {
- proc.on("close", (code) => resolve(code));
- });
-
- while (!stdoutEnded || stdoutQueue.length > 0) {
- if (stdoutQueue.length > 0) {
- yield stdoutQueue.shift()!;
- } else {
- await Promise.race([
- new Promise<void>((res) => proc.stdout.once("data", () => res())),
- stdoutEnd,
- ]);
- }
- if (rejectErr) throw rejectErr;
- }
-
- const code = await exitPromise;
- if (code !== 0) {
- throw new Error(
- `openclaw agent exited with code ${code}. stderr: ${stderr.trim().slice(0, 500)}`,
- );
- }
- } finally {
- clearTimeout(timeout);
- }
-}
diff --git a/notfair-cmo/src/server/openclaw/cli.test.ts b/notfair-cmo/src/server/openclaw/cli.test.ts
deleted file mode 100644
index 5e75b7b8..00000000
--- a/notfair-cmo/src/server/openclaw/cli.test.ts
+++ /dev/null
@@ -1,431 +0,0 @@
-import { EventEmitter } from "node:events";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-// Mock node:child_process so we don't actually spawn binaries in tests.
-// Each test sets up its own queue of fake spawn results.
-const spawnMock = vi.fn();
-vi.mock("node:child_process", () => ({
- spawn: (cmd: string, args: string[]) => spawnMock(cmd, args),
-}));
-
-import {
- OpenClawError,
- getHealth,
- isOpenClawAvailable,
- listAgents,
- listCrons,
- openclaw,
-} from "./cli";
-
-type SpawnResult = {
- stdout?: string;
- stderr?: string;
- exitCode: number | null;
-};
-
-type FakeChild = EventEmitter & {
- stdout: EventEmitter;
- stderr: EventEmitter;
- kill: (sig?: string) => boolean;
-};
-
-/**
- * Plain EventEmitters for stdout/stderr + the process itself — that's all
- * the cli.ts implementation listens to (`.on("data")` + `.on("close")`).
- * Schedule emits with setImmediate so the cli's listeners are guaranteed
- * to be attached before any event fires.
- */
-function fakeChild({ stdout = "", stderr = "", exitCode }: SpawnResult): FakeChild {
- const proc = new EventEmitter() as FakeChild;
- proc.stdout = new EventEmitter();
- proc.stderr = new EventEmitter();
- proc.kill = () => true;
- setImmediate(() => {
- if (stdout) proc.stdout.emit("data", Buffer.from(stdout));
- if (stderr) proc.stderr.emit("data", Buffer.from(stderr));
- proc.emit("close", exitCode);
- });
- return proc;
-}
-
-describe("openclaw cli", () => {
- beforeEach(() => {
- spawnMock.mockReset();
- });
-
- afterEach(() => {
- spawnMock.mockReset();
- });
-
- describe("happy path", () => {
- it("returns parsed JSON on a successful run", async () => {
- spawnMock.mockImplementationOnce(() =>
- fakeChild({ stdout: '{"ok":true,"name":"demo"}', exitCode: 0 }),
- );
- const out = await openclaw(["mcp", "list"]);
- expect(out).toEqual({ ok: true, name: "demo" });
- });
-
- it("returns raw stdout when json:false", async () => {
- spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "plain text\n", exitCode: 0 }));
- const out = await openclaw(["health"], { json: false });
- expect(out).toBe("plain text\n");
- });
-
- it("appends --json by default when not already present", async () => {
- spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "{}", exitCode: 0 }));
- await openclaw(["agents", "list"]);
- expect(spawnMock).toHaveBeenCalledWith(
- "openclaw",
- ["agents", "list", "--json"],
- );
- });
-
- it("does NOT append --json when json:false", async () => {
- spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "", exitCode: 0 }));
- await openclaw(["mcp", "unset", "demo-foo"], { json: false });
- expect(spawnMock).toHaveBeenCalledWith(
- "openclaw",
- ["mcp", "unset", "demo-foo"],
- );
- });
- });
-
- describe("error reporting", () => {
- it("rejects with OpenClawError that includes stderr in the message", async () => {
- spawnMock.mockImplementationOnce(() =>
- fakeChild({
- stderr:
- "[openclaw] Could not start the CLI. [openclaw] Reason: bad config",
- exitCode: 1,
- }),
- );
- let caught: unknown;
- try {
- await openclaw(["mcp", "set", "bad"]);
- } catch (err) {
- caught = err;
- }
- expect(caught).toBeInstanceOf(OpenClawError);
- const err = caught as OpenClawError;
- expect(err.exitCode).toBe(1);
- expect(err.stderr).toMatch(/Reason: bad config/);
- // The user-visible message must include the stderr snippet so the
- // OAuth callback can render it without separate plumbing.
- expect(err.message).toMatch(/exited with code 1/);
- expect(err.message).toMatch(/Reason: bad config/);
- });
-
- it("rejects with OpenClawError when stdout is not valid JSON", async () => {
- spawnMock.mockImplementationOnce(() =>
- fakeChild({ stdout: "<not json>", exitCode: 0 }),
- );
- let caught: unknown;
- try {
- await openclaw(["mcp", "list"]);
- } catch (err) {
- caught = err;
- }
- expect(caught).toBeInstanceOf(OpenClawError);
- expect((caught as OpenClawError).message).toMatch(/not valid JSON/);
- });
-
- it("truncates very long stderr to 240 chars in the message", async () => {
- const longStderr = "x".repeat(500);
- spawnMock.mockImplementationOnce(() =>
- fakeChild({ stderr: longStderr, exitCode: 1 }),
- );
- let caught: unknown;
- try {
- await openclaw(["foo"]);
- } catch (err) {
- caught = err;
- }
- const msg = (caught as OpenClawError).message;
- // Message has the base "exited with code N: " plus up to 240 stderr chars.
- // Full stderr ("x" × 500) is still stored on the error object for logs.
- expect((caught as OpenClawError).stderr).toBe(longStderr);
- expect(msg.length).toBeLessThan(longStderr.length);
- expect(msg).toMatch(/x{200,240}/);
- });
- });
-
- describe('retry on "config changed since last load"', () => {
- it("retries up to 3 times and succeeds when a later attempt wins", async () => {
- // First two attempts hit the cross-process race; third one writes
- // cleanly. The mock returns a fresh child per call, simulating
- // sequential CLI invocations.
- spawnMock
- .mockImplementationOnce(() =>
- fakeChild({
- stderr: "[openclaw] Reason: config changed since last load",
- exitCode: 1,
- }),
- )
- .mockImplementationOnce(() =>
- fakeChild({
- stderr: "[openclaw] Reason: config changed since last load",
- exitCode: 1,
- }),
- )
- .mockImplementationOnce(() => fakeChild({ stdout: '{"ok":true}', exitCode: 0 }));
-
- const out = await openclaw(["mcp", "set", "demo-foo", "{}"]);
- expect(out).toEqual({ ok: true });
- expect(spawnMock).toHaveBeenCalledTimes(3);
- });
-
- it("retries on EAGAIN / EBUSY (other transient writes against openclaw.json)", async () => {
- spawnMock
- .mockImplementationOnce(() =>
- fakeChild({ stderr: "open EAGAIN at /Users/x/.openclaw/openclaw.json", exitCode: 1 }),
- )
- .mockImplementationOnce(() => fakeChild({ stdout: '{"ok":true}', exitCode: 0 }));
-
- const out = await openclaw(["mcp", "set", "demo-foo", "{}"]);
- expect(out).toEqual({ ok: true });
- expect(spawnMock).toHaveBeenCalledTimes(2);
- });
-
- it("does NOT retry when stderr doesn't match the transient pattern", async () => {
- spawnMock.mockImplementationOnce(() =>
- fakeChild({ stderr: "permission denied", exitCode: 1 }),
- );
- await expect(openclaw(["foo"])).rejects.toThrow(/permission denied/);
- expect(spawnMock).toHaveBeenCalledTimes(1);
- });
-
- it("gives up after maxAttempts when the race never resolves", async () => {
- const transient = {
- stderr: "[openclaw] Reason: config changed since last load",
- exitCode: 1,
- } as const;
- spawnMock
- .mockImplementationOnce(() => fakeChild(transient))
- .mockImplementationOnce(() => fakeChild(transient))
- .mockImplementationOnce(() => fakeChild(transient));
-
- await expect(openclaw(["mcp", "set", "demo-foo", "{}"])).rejects.toThrow(
- /config changed since last load/,
- );
- expect(spawnMock).toHaveBeenCalledTimes(3);
- });
- });
-
- describe("in-process serialization", () => {
- it("serializes concurrent calls — second waits for first to finish", async () => {
- // The mutex should hold p2's spawn until p1 has emitted its close.
- // We give p1 a deferred close (controlled by `releaseFirst`) so
- // we can probe the queue mid-flight; p2 uses the normal fakeChild
- // that auto-closes once released.
- const callOrder: number[] = [];
- let releaseFirst!: () => void;
-
- spawnMock
- .mockImplementationOnce(() => {
- callOrder.push(1);
- const proc = new EventEmitter() as FakeChild;
- proc.stdout = new EventEmitter();
- proc.stderr = new EventEmitter();
- proc.kill = () => true;
- releaseFirst = () => {
- proc.stdout.emit("data", Buffer.from('{"id":1}'));
- proc.emit("close", 0);
- };
- return proc;
- })
- .mockImplementationOnce(() => {
- callOrder.push(2);
- return fakeChild({ stdout: '{"id":2}', exitCode: 0 });
- });
-
- const p1 = openclaw(["a"]);
- const p2 = openclaw(["b"]);
-
- // Let microtasks + setImmediates drain — first spawn should have
- // happened, second should be still queued behind p1.
- await new Promise((r) => setImmediate(r));
- await new Promise((r) => setImmediate(r));
- expect(callOrder).toEqual([1]);
-
- releaseFirst();
- await expect(p1).resolves.toEqual({ id: 1 });
- await expect(p2).resolves.toEqual({ id: 2 });
- expect(callOrder).toEqual([1, 2]);
- });
-
- it("a failing call doesn't poison the queue — next call still runs", async () => {
- spawnMock
- .mockImplementationOnce(() => fakeChild({ stderr: "permanent failure", exitCode: 1 }))
- .mockImplementationOnce(() => fakeChild({ stdout: '{"ok":true}', exitCode: 0 }));
-
- const failing = openclaw(["a"]);
- const succeeding = openclaw(["b"]);
-
- await expect(failing).rejects.toThrow();
- // Without the `.catch` on the queue tail, this would never resolve.
- await expect(succeeding).resolves.toEqual({ ok: true });
- });
- });
-
- describe("spawn-level errors", () => {
- it("maps ENOENT (openclaw not installed) into a friendly message", async () => {
- spawnMock.mockImplementationOnce(() => {
- const proc = new EventEmitter() as FakeChild;
- proc.stdout = new EventEmitter();
- proc.stderr = new EventEmitter();
- proc.kill = () => true;
- // No close — the 'error' handler is the terminal event for this case.
- setImmediate(() => {
- const err = new Error("spawn openclaw ENOENT") as NodeJS.ErrnoException;
- err.code = "ENOENT";
- proc.emit("error", err);
- });
- return proc;
- });
-
- let caught: unknown;
- try {
- await openclaw(["agents", "list"]);
- } catch (err) {
- caught = err;
- }
- expect(caught).toBeInstanceOf(OpenClawError);
- const e = caught as OpenClawError;
- expect(e.message).toMatch(/openclaw not found on PATH/i);
- expect(e.exitCode).toBeNull();
- });
-
- it("maps a generic spawn error into an OpenClawError", async () => {
- spawnMock.mockImplementationOnce(() => {
- const proc = new EventEmitter() as FakeChild;
- proc.stdout = new EventEmitter();
- proc.stderr = new EventEmitter();
- proc.kill = () => true;
- setImmediate(() => {
- proc.stderr.emit("data", Buffer.from("buffered stderr"));
- proc.emit("error", new Error("something exploded"));
- });
- return proc;
- });
-
- let caught: unknown;
- try {
- await openclaw(["foo"]);
- } catch (err) {
- caught = err;
- }
- expect(caught).toBeInstanceOf(OpenClawError);
- const e = caught as OpenClawError;
- expect(e.message).toMatch(/something exploded/);
- expect(e.stderr).toMatch(/buffered stderr/);
- expect(e.exitCode).toBeNull();
- });
- });
-
- describe("convenience wrappers", () => {
- it("listAgents spawns `agents list --json` and returns parsed JSON", async () => {
- spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "[]", exitCode: 0 }));
- const r = await listAgents();
- expect(r).toEqual([]);
- expect(spawnMock).toHaveBeenCalledWith("openclaw", ["agents", "list", "--json"]);
- });
-
- it("listCrons spawns `cron list --json` and returns parsed JSON", async () => {
- spawnMock.mockImplementationOnce(() => fakeChild({ stdout: '[{"id":"x"}]', exitCode: 0 }));
- const r = await listCrons();
- expect(r).toEqual([{ id: "x" }]);
- expect(spawnMock).toHaveBeenCalledWith("openclaw", ["cron", "list", "--json"]);
- });
-
- it("getHealth spawns `health` without --json and returns raw stdout", async () => {
- spawnMock.mockImplementationOnce(() =>
- fakeChild({ stdout: "ok\n", exitCode: 0 }),
- );
- const r = await getHealth();
- expect(r).toBe("ok\n");
- expect(spawnMock).toHaveBeenCalledWith("openclaw", ["health"]);
- });
-
- it("isOpenClawAvailable returns true when --version exits 0", async () => {
- spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "v1.0.0\n", exitCode: 0 }));
- const ok = await isOpenClawAvailable();
- expect(ok).toBe(true);
- expect(spawnMock).toHaveBeenCalledWith("openclaw", ["--version"]);
- });
-
- it("isOpenClawAvailable returns false when the spawn fails", async () => {
- spawnMock.mockImplementationOnce(() => {
- const proc = new EventEmitter() as FakeChild;
- proc.stdout = new EventEmitter();
- proc.stderr = new EventEmitter();
- proc.kill = () => true;
- setImmediate(() => {
- const err = new Error("spawn openclaw ENOENT") as NodeJS.ErrnoException;
- err.code = "ENOENT";
- proc.emit("error", err);
- });
- return proc;
- });
- const ok = await isOpenClawAvailable();
- expect(ok).toBe(false);
- });
- });
-
- describe("timeout", () => {
- it("kills the subprocess and rejects when the process never closes", async () => {
- vi.useFakeTimers();
- try {
- let killed = false;
- spawnMock.mockImplementationOnce(() => {
- const proc = new EventEmitter() as FakeChild;
- proc.stdout = new EventEmitter();
- proc.stderr = new EventEmitter();
- proc.kill = () => {
- killed = true;
- return true;
- };
- // Never emit 'close' — let the internal timer fire.
- return proc;
- });
-
- const p = openclaw(["slow"], { timeout: 50 });
- // Attach a no-op catch so vitest doesn't warn about unhandled rejection.
- const observed = p.catch((err) => err);
- // Run the queue + spawn microtasks before advancing the fake clock.
- await vi.advanceTimersByTimeAsync(0);
- await vi.advanceTimersByTimeAsync(50);
- const err = (await observed) as OpenClawError;
- expect(err).toBeInstanceOf(OpenClawError);
- expect(err.message).toMatch(/timed out after 50ms/);
- expect(killed).toBe(true);
- } finally {
- vi.useRealTimers();
- }
- });
- });
-
- describe("JSON parsing edge cases", () => {
- it("resolves to null when stdout is empty + json:true (default)", async () => {
- spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "", exitCode: 0 }));
- const r = await openclaw(["empty"]);
- expect(r).toBeNull();
- });
-
- it("resolves to null when stdout is whitespace-only", async () => {
- spawnMock.mockImplementationOnce(() => fakeChild({ stdout: " \n ", exitCode: 0 }));
- const r = await openclaw(["whitespace"]);
- expect(r).toBeNull();
- });
-
- it("does not append --json when caller already included it explicitly", async () => {
- spawnMock.mockImplementationOnce(() =>
- fakeChild({ stdout: "{}", exitCode: 0 }),
- );
- await openclaw(["foo", "--json"]);
- // --json must appear exactly once.
- const args = spawnMock.mock.calls[0]![1] as string[];
- expect(args.filter((a) => a === "--json").length).toBe(1);
- });
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/cli.ts b/notfair-cmo/src/server/openclaw/cli.ts
deleted file mode 100644
index f7613327..00000000
--- a/notfair-cmo/src/server/openclaw/cli.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import { spawn } from "node:child_process";
-
-export class OpenClawError extends Error {
- readonly stderr: string;
- readonly exitCode: number | null;
- constructor(message: string, stderr: string, exitCode: number | null) {
- // Surface a short snippet of stderr in the message itself — the
- // OAuth callback path only renders `error.message`, and silently
- // throwing away "what openclaw actually said" turns every CLI
- // failure into a black box. Cap at 240 chars so URL-encoded
- // redirect query strings stay reasonable.
- const snippet = stderr.trim().replace(/\s+/g, " ").slice(0, 240);
- const fullMessage = snippet ? `${message}: ${snippet}` : message;
- super(fullMessage);
- this.name = "OpenClawError";
- this.stderr = stderr;
- this.exitCode = exitCode;
- }
-}
-
-export type OpenClawOptions = {
- /** Timeout in ms. Defaults to 30s. */
- timeout?: number;
- /** When true, expect JSON on stdout and parse. Defaults to true. */
- json?: boolean;
-};
-
-/**
- * `openclaw mcp set`, `openclaw agents set` etc. all write to
- * ~/.openclaw/openclaw.json. The CLI does not lock — two concurrent
- * invocations can clobber each other's writes (provisioning fires
- * during onboarding while the OAuth callback later runs `mcp set`;
- * if they overlap, one exits non-zero with a corrupt-config message).
- *
- * Serialize every call from this process to remove the race. Calls
- * stay in-order, the queue depth is naturally bounded (we only have
- * a handful of openclaw invocations per user action), and read-only
- * commands aren't expensive enough to justify a read/write split.
- */
-let openclawQueue: Promise<unknown> = Promise.resolve();
-
-/**
- * Run an OpenClaw CLI command and return parsed stdout.
- * Always passes `--json` when `json: true` (default) — caller does not.
- */
-export async function openclaw(
- args: string[],
- options: OpenClawOptions = {},
-): Promise<unknown> {
- const run = () => runOpenclawWithRetry(args, options);
- const next = openclawQueue.then(run, run);
- // Keep the chain alive even when a call rejects — without `.catch`
- // a single failure would propagate forever to subsequent callers.
- openclawQueue = next.catch(() => undefined);
- return next;
-}
-
-/**
- * The OpenClaw CLI does optimistic concurrency on ~/.openclaw/openclaw.json:
- * it loads at startup, and on write checks whether the file changed
- * underneath it. When the gateway daemon (a separate process) writes
- * between our load and our write, we get exit code 1 with stderr:
- *
- * [openclaw] Could not start the CLI.
- * [openclaw] Reason: config changed since last load
- *
- * This is a transient cross-process race that our in-process mutex
- * can't prevent. Retry a couple of times — each attempt re-reads the
- * config, so a winning retry is essentially "no overlap this time".
- */
-async function runOpenclawWithRetry(
- args: string[],
- options: OpenClawOptions,
-): Promise<unknown> {
- const maxAttempts = 3;
- let lastErr: unknown;
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
- try {
- return await runOpenclaw(args, options);
- } catch (err) {
- lastErr = err;
- if (!(err instanceof OpenClawError)) throw err;
- const transient =
- err.exitCode === 1 &&
- /config changed since last load|EAGAIN|EBUSY/i.test(err.stderr);
- if (!transient || attempt === maxAttempts) throw err;
- // Small backoff with jitter so two competing callers don't lock-
- // step into the same retry slot forever.
- const delayMs = 150 * attempt + Math.floor(Math.random() * 100);
- await new Promise((r) => setTimeout(r, delayMs));
- }
- }
- throw lastErr;
-}
-
-function runOpenclaw(args: string[], options: OpenClawOptions): Promise<unknown> {
- const timeout = options.timeout ?? 30_000;
- const wantJson = options.json ?? true;
- const finalArgs = wantJson && !args.includes("--json") ? [...args, "--json"] : args;
-
- return new Promise((resolve, reject) => {
- const proc = spawn("openclaw", finalArgs, {
- stdio: ["ignore", "pipe", "pipe"],
- });
-
- let stdout = "";
- let stderr = "";
-
- const timer = setTimeout(() => {
- proc.kill("SIGTERM");
- reject(new OpenClawError(`openclaw ${args[0] ?? ""} timed out after ${timeout}ms`, stderr, null));
- }, timeout);
-
- proc.stdout.on("data", (chunk) => {
- stdout += chunk.toString();
- });
- proc.stderr.on("data", (chunk) => {
- stderr += chunk.toString();
- });
-
- proc.on("error", (err) => {
- clearTimeout(timer);
- if ((err as NodeJS.ErrnoException).code === "ENOENT") {
- reject(
- new OpenClawError(
- "openclaw not found on PATH. Install: https://docs.openclaw.ai/install",
- "",
- null,
- ),
- );
- return;
- }
- reject(new OpenClawError(err.message, stderr, null));
- });
-
- proc.on("close", (code) => {
- clearTimeout(timer);
- if (code !== 0) {
- reject(
- new OpenClawError(
- `openclaw ${args.join(" ")} exited with code ${code}`,
- stderr,
- code,
- ),
- );
- return;
- }
- if (!wantJson) {
- resolve(stdout);
- return;
- }
- try {
- resolve(stdout.trim() ? JSON.parse(stdout) : null);
- } catch (parseErr) {
- reject(
- new OpenClawError(
- `openclaw output was not valid JSON: ${(parseErr as Error).message}`,
- stderr,
- code,
- ),
- );
- }
- });
- });
-}
-
-/** Type-narrowed wrappers for common operations. */
-
-export async function listAgents(): Promise<unknown> {
- return openclaw(["agents", "list"]);
-}
-
-export async function listCrons(): Promise<unknown> {
- return openclaw(["cron", "list"]);
-}
-
-export async function getHealth(): Promise<string> {
- return openclaw(["health"], { json: false }) as Promise<string>;
-}
-
-export async function isOpenClawAvailable(): Promise<boolean> {
- try {
- await openclaw(["--version"], { json: false, timeout: 5_000 });
- return true;
- } catch {
- return false;
- }
-}
diff --git a/notfair-cmo/src/server/openclaw/clone-agent.test.ts b/notfair-cmo/src/server/openclaw/clone-agent.test.ts
deleted file mode 100644
index 826c49df..00000000
--- a/notfair-cmo/src/server/openclaw/clone-agent.test.ts
+++ /dev/null
@@ -1,493 +0,0 @@
-import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
-import { join } from "node:path";
-import {
- afterAll,
- beforeEach,
- describe,
- expect,
- it,
- vi,
-} from "vitest";
-
-const { tmpHome, tmpData, ORIGINAL_HOME, ORIGINAL_DATA } = vi.hoisted(() => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { tmpdir } = require("node:os") as typeof import("node:os");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { join: joinPath } = require("node:path") as typeof import("node:path");
- const origHome = process.env.OPENCLAW_HOME;
- const origData = process.env.NOTFAIR_CMO_DATA_DIR;
- const home = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-clone-home-"));
- const data = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-clone-data-"));
- process.env.OPENCLAW_HOME = home;
- process.env.NOTFAIR_CMO_DATA_DIR = data;
- return {
- tmpHome: home,
- tmpData: data,
- ORIGINAL_HOME: origHome,
- ORIGINAL_DATA: origData,
- };
-});
-
-// Mock openclaw CLI subprocess.
-const openclawMock = vi.fn();
-vi.mock("./cli", () => ({
- openclaw: (...args: unknown[]) => openclawMock(...args),
-}));
-
-// Mock gateway-rpc methods used by clone-agent.
-const createAgentViaRpcMock = vi.fn();
-const listAgentFilesMock = vi.fn();
-const getAgentFileMock = vi.fn();
-const setAgentFileMock = vi.fn();
-vi.mock("./gateway-rpc", () => ({
- createAgentViaRpc: (...args: unknown[]) => createAgentViaRpcMock(...args),
- listAgentFiles: (...args: unknown[]) => listAgentFilesMock(...args),
- getAgentFile: (...args: unknown[]) => getAgentFileMock(...args),
- setAgentFile: (...args: unknown[]) => setAgentFileMock(...args),
-}));
-
-import { agentExistsInProject, cloneAgent } from "./clone-agent";
-
-function writeSourceSessionsDir(
- sourceAgent: string,
- sessionsJson: Record<string, unknown>,
- extras: Record<string, string> = {},
-): void {
- const dir = join(tmpHome, "agents", sourceAgent, "sessions");
- mkdirSync(dir, { recursive: true });
- writeFileSync(join(dir, "sessions.json"), JSON.stringify(sessionsJson), "utf8");
- for (const [name, content] of Object.entries(extras)) {
- writeFileSync(join(dir, name), content, "utf8");
- }
-}
-
-beforeEach(() => {
- openclawMock.mockReset();
- createAgentViaRpcMock.mockReset();
- listAgentFilesMock.mockReset();
- getAgentFileMock.mockReset();
- setAgentFileMock.mockReset();
-});
-
-afterAll(() => {
- if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;
- else delete process.env.OPENCLAW_HOME;
- if (ORIGINAL_DATA) process.env.NOTFAIR_CMO_DATA_DIR = ORIGINAL_DATA;
- else delete process.env.NOTFAIR_CMO_DATA_DIR;
-});
-
-describe("agentExistsInProject", () => {
- it("returns false when neither dir exists", () => {
- expect(agentExistsInProject("none", "missing")).toBe(false);
- });
-
- it("returns true when notfair data dir has content", () => {
- const dir = join(tmpData, "agents", "p1-foo");
- mkdirSync(dir, { recursive: true });
- writeFileSync(join(dir, "meta"), "x", "utf8");
- expect(agentExistsInProject("p1", "foo")).toBe(true);
- });
-
- it("returns true when openclaw agent dir has content", () => {
- const dir = join(tmpHome, "agents", "p2-bar");
- mkdirSync(dir, { recursive: true });
- writeFileSync(join(dir, "marker"), "x", "utf8");
- expect(agentExistsInProject("p2", "bar")).toBe(true);
- });
-
- it("returns false when the dir exists but is empty (deleted remnant)", () => {
- const dir = join(tmpHome, "agents", "p3-empty");
- mkdirSync(dir, { recursive: true });
- expect(agentExistsInProject("p3", "empty")).toBe(false);
- });
-});
-
-describe("cloneAgent", () => {
- it("rejects an invalid user slug", async () => {
- await expect(
- cloneAgent({
- source_agent_id: "demo-cmo",
- project_slug: "demo",
- new_slug: "###",
- }),
- ).rejects.toThrow(/Invalid agent slug/);
- });
-
- it("rejects an invalid canonical slug when slug_is_canonical=true", async () => {
- await expect(
- cloneAgent({
- source_agent_id: "demo-cmo",
- project_slug: "demo",
- new_slug: "BAD SLUG",
- slug_is_canonical: true,
- }),
- ).rejects.toThrow(/Invalid canonical slug/);
- });
-
- it("allows reserved slugs when slug_is_canonical=true (relocate path)", async () => {
- // `cmo` is reserved in slugify but allowed as a canonical slug.
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
- listAgentFilesMock.mockRejectedValueOnce(new Error("list down")); // exercise outer catch
- // No jobs.json so loadAllCrons returns [].
- const result = await cloneAgent({
- source_agent_id: "demo-cmo",
- project_slug: "fresh-proj-1",
- new_slug: "cmo",
- slug_is_canonical: true,
- });
- expect(result.new_slug).toBe("cmo");
- expect(result.new_agent_id).toBe("fresh-proj-1-cmo");
- expect(result.files_copied).toBe(0);
- expect(result.sessions_copied).toBe(0);
- expect(result.source_crons).toEqual([]);
- });
-
- it("throws when an agent at the target slug already exists in the project", async () => {
- // Pre-create the notfair sidecar dir to trigger agentExistsInProject.
- const dir = join(tmpData, "agents", "collide-cmo");
- mkdirSync(dir, { recursive: true });
- writeFileSync(join(dir, "x"), "1", "utf8");
-
- await expect(
- cloneAgent({
- source_agent_id: "demo-cmo",
- project_slug: "collide",
- new_slug: "cmo",
- slug_is_canonical: true,
- }),
- ).rejects.toThrow(/already exists in this project/);
- });
-
- it("copies workspace files via the gateway, skipping missing/erroring files", async () => {
- listAgentFilesMock.mockResolvedValueOnce({
- agentId: "src-cmo",
- workspace: "/ws",
- files: [
- { name: "REM.md", path: "/ws/REM.md", missing: false },
- { name: "GONE.md", path: "/ws/GONE.md", missing: true },
- { name: "BAD.md", path: "/ws/BAD.md", missing: false },
- { name: "OK.md", path: "/ws/OK.md", missing: false },
- ],
- });
- getAgentFileMock.mockImplementation(async (_id: string, name: string) => {
- if (name === "BAD.md") throw new Error("permission denied");
- return { agentId: "src-cmo", workspace: "/ws", file: { name, content: `body of ${name}` } };
- });
- setAgentFileMock.mockResolvedValue(undefined);
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
-
- // Silence the SUT's console.error on the BAD.md skip.
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- try {
- const result = await cloneAgent({
- source_agent_id: "src-cmo",
- project_slug: "proj1",
- new_slug: "custom-clone",
- });
- // 2 files copied (REM.md, OK.md). GONE.md was missing, BAD.md errored.
- expect(result.files_copied).toBe(2);
- expect(setAgentFileMock).toHaveBeenCalledWith(
- "proj1-custom-clone",
- "REM.md",
- "body of REM.md",
- );
- expect(setAgentFileMock).toHaveBeenCalledWith(
- "proj1-custom-clone",
- "OK.md",
- "body of OK.md",
- );
- } finally {
- errSpy.mockRestore();
- }
- });
-
- it("copies sessions dir and rewrites sessions.json keys with the new agent prefix", async () => {
- const src = "srcproj-cmo";
- writeSourceSessionsDir(
- src,
- {
- "agent:srcproj-cmo:thread-1": { sessionId: "s1", updatedAt: 1 },
- "agent:srcproj-cmo:thread-2": { sessionId: "s2", updatedAt: 2 },
- // A key without our prefix is left untouched.
- "alien-key": { sessionId: "alien", updatedAt: 3 },
- },
- { "thread-1.jsonl": "log-line\n" },
- );
-
- listAgentFilesMock.mockResolvedValueOnce({ agentId: src, workspace: "/ws", files: [] });
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
-
- const result = await cloneAgent({
- source_agent_id: src,
- project_slug: "dst",
- new_slug: "clone",
- });
- const dstSessionsDir = join(tmpHome, "agents", "dst-clone", "sessions");
- expect(existsSync(dstSessionsDir)).toBe(true);
- expect(existsSync(join(dstSessionsDir, "thread-1.jsonl"))).toBe(true);
- const rewritten = JSON.parse(
- readFileSync(join(dstSessionsDir, "sessions.json"), "utf8"),
- );
- expect(rewritten["agent:dst-clone:thread-1"]).toEqual({
- sessionId: "s1",
- updatedAt: 1,
- });
- expect(rewritten["agent:dst-clone:thread-2"]).toEqual({
- sessionId: "s2",
- updatedAt: 2,
- });
- // Alien keys are preserved as-is.
- expect(rewritten["alien-key"]).toEqual({ sessionId: "alien", updatedAt: 3 });
- expect(result.sessions_copied).toBe(3);
- });
-
- it("tolerates broken sessions.json by logging and reporting 0 sessions copied", async () => {
- const src = "broken-src";
- const dir = join(tmpHome, "agents", src, "sessions");
- mkdirSync(dir, { recursive: true });
- writeFileSync(join(dir, "sessions.json"), "{ not json", "utf8");
-
- listAgentFilesMock.mockResolvedValueOnce({ agentId: src, workspace: "/ws", files: [] });
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
-
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- try {
- const result = await cloneAgent({
- source_agent_id: src,
- project_slug: "broken-dst",
- new_slug: "clone",
- });
- // sessions.json existed but couldn't be parsed — 0 sessions copied, no throw.
- expect(result.sessions_copied).toBe(0);
- } finally {
- errSpy.mockRestore();
- }
- });
-
- it("recreates source crons under the new agent + project naming convention", async () => {
- // Write jobs.json with two crons assigned to the source agent + one
- // unrelated to a different agent (should be ignored).
- const cronDir = join(tmpHome, "cron");
- mkdirSync(cronDir, { recursive: true });
- writeFileSync(
- join(cronDir, "jobs.json"),
- JSON.stringify([
- {
- id: "c1",
- name: "src/agent/morning-job",
- agentId: "cron-src-cmo",
- description: "morning",
- schedule: { kind: "cron", expr: "0 9 * * *", tz: "UTC" },
- payload: { kind: "agentTurn", message: "do work" },
- },
- {
- id: "c2",
- name: "every-five",
- agentId: "cron-src-cmo",
- schedule: { kind: "every", everyMs: 5 * 60_000 },
- payload: { message: "tick" },
- enabled: false,
- },
- {
- id: "skip",
- name: "x",
- agentId: "other-agent",
- schedule: { kind: "cron", expr: "* * * * *" },
- },
- ]),
- "utf8",
- );
-
- listAgentFilesMock.mockResolvedValueOnce({ agentId: "cron-src-cmo", workspace: "/ws", files: [] });
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
- // openclaw cron add — should be called twice, return ids.
- openclawMock
- .mockResolvedValueOnce({ id: "new-1" })
- .mockResolvedValueOnce({ id: "new-2" });
-
- const result = await cloneAgent({
- source_agent_id: "cron-src-cmo",
- project_slug: "destproj",
- new_slug: "destslug",
- });
-
- expect(result.new_cron_ids).toEqual(["new-1", "new-2"]);
- expect(result.source_crons.length).toBe(2);
- expect(result.source_crons.map((c) => c.id).sort()).toEqual(["c1", "c2"]);
- // c2 was enabled:false → disabled:true.
- const c2 = result.source_crons.find((c) => c.id === "c2")!;
- expect(c2.disabled).toBe(true);
-
- // First cron: cron expr + tz, --description + --message, --no-deliver.
- const firstArgs = openclawMock.mock.calls[0]![0] as string[];
- expect(firstArgs.slice(0, 2)).toEqual(["cron", "add"]);
- expect(firstArgs).toContain("--name");
- // Name = `<project>/<new-slug>/<last-segment-as-cron-slug>`. Source name
- // was "src/agent/morning-job" so last segment is "morning-job".
- const nameIdx = firstArgs.indexOf("--name");
- expect(firstArgs[nameIdx + 1]).toBe("destproj/destslug/morning-job");
- expect(firstArgs).toContain("--cron");
- expect(firstArgs).toContain("--tz");
- expect(firstArgs).toContain("--description");
- expect(firstArgs).toContain("--message");
- expect(firstArgs).toContain("--no-deliver");
- expect(firstArgs[firstArgs.indexOf("--message") + 1]).toBe("do work");
- // Agent target should be the NEW full id.
- expect(firstArgs[firstArgs.indexOf("--agent") + 1]).toBe("destproj-destslug");
-
- // Second cron: 'every' schedule + no description.
- const secondArgs = openclawMock.mock.calls[1]![0] as string[];
- expect(secondArgs).toContain("--every");
- expect(secondArgs[secondArgs.indexOf("--every") + 1]).toBe("5m");
- expect(secondArgs).not.toContain("--cron");
- expect(secondArgs).not.toContain("--description");
- });
-
- it("falls back to disabled hourly schedule when source has an unknown kind", async () => {
- const cronDir = join(tmpHome, "cron");
- mkdirSync(cronDir, { recursive: true });
- writeFileSync(
- join(cronDir, "jobs.json"),
- JSON.stringify([
- {
- id: "weird",
- name: "src/agent/weird",
- agentId: "weird-src-cmo",
- schedule: { kind: "moon-cycle" },
- },
- ]),
- "utf8",
- );
-
- listAgentFilesMock.mockResolvedValueOnce({ agentId: "weird-src-cmo", workspace: "/ws", files: [] });
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
- openclawMock.mockResolvedValueOnce({ id: "new-weird" });
-
- await cloneAgent({
- source_agent_id: "weird-src-cmo",
- project_slug: "weirdproj",
- new_slug: "weirdslug",
- });
- const args = openclawMock.mock.calls[0]![0] as string[];
- expect(args).toContain("--every");
- expect(args[args.indexOf("--every") + 1]).toBe("1h");
- });
-
- it("handles jobs.json wrapped in {jobs: [...]}", async () => {
- const cronDir = join(tmpHome, "cron");
- mkdirSync(cronDir, { recursive: true });
- writeFileSync(
- join(cronDir, "jobs.json"),
- JSON.stringify({
- jobs: [
- {
- id: "j1",
- name: "src/agent/job",
- agentId: "wrap-src-cmo",
- schedule: { kind: "cron", expr: "0 9 * * *" },
- },
- ],
- }),
- "utf8",
- );
-
- listAgentFilesMock.mockResolvedValueOnce({ agentId: "wrap-src-cmo", workspace: "/ws", files: [] });
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
- openclawMock.mockResolvedValueOnce({ id: "ok" });
-
- const r = await cloneAgent({
- source_agent_id: "wrap-src-cmo",
- project_slug: "wproj",
- new_slug: "wslug",
- });
- expect(r.new_cron_ids).toEqual(["ok"]);
- });
-
- it("continues when openclaw cron add fails on one cron", async () => {
- const cronDir = join(tmpHome, "cron");
- mkdirSync(cronDir, { recursive: true });
- writeFileSync(
- join(cronDir, "jobs.json"),
- JSON.stringify([
- {
- id: "p1",
- name: "src/agent/a",
- agentId: "partial-src-cmo",
- schedule: { kind: "cron", expr: "0 9 * * *" },
- },
- {
- id: "p2",
- name: "src/agent/b",
- agentId: "partial-src-cmo",
- schedule: { kind: "cron", expr: "0 9 * * *" },
- },
- ]),
- "utf8",
- );
- listAgentFilesMock.mockResolvedValueOnce({ agentId: "partial-src-cmo", workspace: "/ws", files: [] });
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
- openclawMock
- .mockRejectedValueOnce(new Error("transient"))
- .mockResolvedValueOnce({ id: "ok-2" });
-
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- try {
- const r = await cloneAgent({
- source_agent_id: "partial-src-cmo",
- project_slug: "pproj",
- new_slug: "pslug",
- });
- // source_crons still records BOTH; new_cron_ids only the one that succeeded.
- expect(r.source_crons.length).toBe(2);
- expect(r.new_cron_ids).toEqual(["ok-2"]);
- } finally {
- errSpy.mockRestore();
- }
- });
-
- it("writes the notfair-meta sidecar after a successful clone", async () => {
- listAgentFilesMock.mockResolvedValueOnce({ agentId: "meta-src", workspace: "/ws", files: [] });
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
-
- await cloneAgent({
- source_agent_id: "meta-src",
- project_slug: "metaproj",
- new_slug: "metaclone",
- display_name: "Custom Display",
- });
-
- const metaPath = join(
- tmpData,
- "agents",
- "metaproj-metaclone",
- "notfair-meta.json",
- );
- expect(existsSync(metaPath)).toBe(true);
- const meta = JSON.parse(readFileSync(metaPath, "utf8"));
- expect(meta.agent_id).toBe("metaproj-metaclone");
- expect(meta.project_slug).toBe("metaproj");
- expect(meta.slug).toBe("metaclone");
- expect(meta.name).toBe("Custom Display");
- expect(meta.source_agent_id).toBe("meta-src");
- expect(typeof meta.created_at).toBe("string");
- });
-
- it("defaults name to the source agent id when display_name is not provided", async () => {
- listAgentFilesMock.mockResolvedValueOnce({ agentId: "no-display-src", workspace: "/ws", files: [] });
- createAgentViaRpcMock.mockResolvedValueOnce(undefined);
- await cloneAgent({
- source_agent_id: "no-display-src",
- project_slug: "ndproj",
- new_slug: "ndclone",
- });
- const meta = JSON.parse(
- readFileSync(
- join(tmpData, "agents", "ndproj-ndclone", "notfair-meta.json"),
- "utf8",
- ),
- );
- expect(meta.name).toBe("no-display-src");
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/clone-agent.ts b/notfair-cmo/src/server/openclaw/clone-agent.ts
deleted file mode 100644
index f615cc82..00000000
--- a/notfair-cmo/src/server/openclaw/clone-agent.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
-import { existsSync, readFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { slugify } from "@/lib/slug";
-import { workspaceDirFor, writeAgentMeta } from "@/server/agent-meta";
-
-const NOTFAIR_DATA_DIR =
- process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
-import { openclaw } from "@/server/openclaw/cli";
-import {
- createAgentViaRpc,
- getAgentFile,
- listAgentFiles,
-} from "@/server/openclaw/gateway-rpc";
-
-const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");
-const NAME_SEPARATOR = "/";
-
-export type CloneAgentInput = {
- source_agent_id: string;
- project_slug: string;
- /** URL-safe slug for the new agent (post-project prefix). Required. */
- new_slug: string;
- /** Display name shown in sidebar etc. Defaults to source agent id if unset. */
- display_name?: string;
- /**
- * When true, treat `new_slug` as already-canonical: skip the user-input
- * reserved-slug check (so internal callers can reuse template slugs like
- * `cmo` during a relocate without slugify rejecting them).
- */
- slug_is_canonical?: boolean;
-};
-
-export type CloneSourceCron = {
- id: string;
- /** The cron's original name, kept so the UI can show the user what they're disabling. */
- name: string;
- disabled: boolean;
-};
-
-export type CloneAgentResult = {
- new_agent_id: string;
- new_slug: string;
- files_copied: number;
- sessions_copied: number;
- source_crons: CloneSourceCron[];
- new_cron_ids: string[];
-};
-
-/**
- * Clone an existing OpenClaw agent into the active project.
- *
- * Steps (in order; each is idempotent enough to retry after a partial failure):
- * 1. Validate inputs + compute target ids.
- * 2. Create the destination agent via `agents.create` RPC.
- * 3. Copy workspace files (read via agents.files.get, write via agents.files.set).
- * 4. Filesystem-copy ~/.openclaw/agents/<src>/sessions → ~/.openclaw/agents/<dst>/sessions
- * and rewrite sessions.json keys to point at the new agent name.
- * 5. List source crons, recreate each targeting the new agent with our
- * `<project> / <slug> / <cron>` naming convention.
- * 6. Write our notfair-meta sidecar so the sidebar finds it.
- */
-export async function cloneAgent(input: CloneAgentInput): Promise<CloneAgentResult> {
- let newSlug: string;
- if (input.slug_is_canonical) {
- // Internal caller (e.g. relocateAgent) has a slug that already passed
- // user-facing validation at creation time. Re-running slugify would
- // reject reserved slugs like `cmo` that are valid template slugs.
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(input.new_slug)) {
- throw new Error(`Invalid canonical slug: ${input.new_slug}`);
- }
- newSlug = input.new_slug;
- } else {
- const slugResult = slugify(input.new_slug);
- if (!slugResult.ok) {
- throw new Error(`Invalid agent slug: ${slugResult.reason}`);
- }
- newSlug = slugResult.slug;
- }
- const newAgentId = `${input.project_slug}-${newSlug}`;
- if (agentExistsInProject(input.project_slug, newSlug)) {
- throw new Error(
- `An agent named "${newSlug}" already exists in this project. Pick a different name.`,
- );
- }
- const dstWorkspace = workspaceDirFor(newAgentId);
- const displayName = (input.display_name ?? input.source_agent_id).trim() || input.source_agent_id;
-
- // 2) Create the destination agent.
- await createAgentViaRpc({ name: newAgentId, workspace: dstWorkspace });
-
- // 3) Copy workspace files.
- let filesCopied = 0;
- try {
- const list = await listAgentFiles(input.source_agent_id);
- for (const f of list.files) {
- if (f.missing) continue;
- try {
- const got = await getAgentFile(input.source_agent_id, f.name);
- // Use the gateway's setter so OpenClaw's safety/symlink checks run.
- await callAgentsFilesSet(newAgentId, f.name, got.file.content);
- filesCopied++;
- } catch (err) {
- console.error(`clone: skipping file ${f.name}:`, err);
- }
- }
- } catch (err) {
- console.error("clone: could not list source workspace files:", err);
- }
-
- // 4) Copy sessions (filesystem) + rewrite sessions.json keys.
- const srcSessionsDir = join(OPENCLAW_HOME, "agents", input.source_agent_id, "sessions");
- const dstSessionsDir = join(OPENCLAW_HOME, "agents", newAgentId, "sessions");
- let sessionsCopied = 0;
- if (existsSync(srcSessionsDir)) {
- await mkdir(dstSessionsDir, { recursive: true });
- // Copy everything (jsonl, .trajectory*, sessions.json, .bak files). `force:true`
- // overwrites anything OpenClaw auto-created at agents.create time.
- await cp(srcSessionsDir, dstSessionsDir, { recursive: true, force: true });
-
- // Rewrite sessions.json so key prefix matches the new agent. Without this,
- // OpenClaw won't recognize the imported entries as belonging to the dest.
- const dstSessionsJson = join(dstSessionsDir, "sessions.json");
- if (existsSync(dstSessionsJson)) {
- try {
- const raw = await readFile(dstSessionsJson, "utf8");
- const parsed = JSON.parse(raw) as Record<string, unknown>;
- const oldPrefix = `agent:${input.source_agent_id}:`;
- const newPrefix = `agent:${newAgentId}:`;
- const rewritten: Record<string, unknown> = {};
- for (const [k, v] of Object.entries(parsed)) {
- const newKey = k.startsWith(oldPrefix) ? newPrefix + k.slice(oldPrefix.length) : k;
- rewritten[newKey] = v;
- sessionsCopied++;
- }
- await writeFile(dstSessionsJson, JSON.stringify(rewritten, null, 2), "utf8");
- } catch (err) {
- console.error("clone: could not rewrite sessions.json:", err);
- }
- }
- }
-
- // 5) Crons.
- const sourceCrons: CloneSourceCron[] = [];
- const newCronIds: string[] = [];
- try {
- const allCrons = await loadAllCrons();
- const mine = allCrons.filter((c) => c.agentId === input.source_agent_id);
- for (const c of mine) {
- sourceCrons.push({ id: c.id, name: c.name, disabled: c.enabled === false || !!c.disabled });
- try {
- const newId = await createClonedCron(c, input.project_slug, newSlug, newAgentId);
- newCronIds.push(newId);
- } catch (err) {
- console.error(`clone: could not recreate cron '${c.name}':`, err);
- }
- }
- } catch (err) {
- console.error("clone: could not list crons:", err);
- }
-
- // 6) Meta sidecar so the sidebar shows the new agent. Cloned agents
- // aren't backed by a template — they keep the user-chosen `slug`
- // on the sidecar (the rest of the system computes template agents'
- // slugs from template_key + name instead).
- await writeAgentMeta({
- agent_id: newAgentId,
- project_slug: input.project_slug,
- slug: newSlug,
- name: displayName,
- source_agent_id: input.source_agent_id,
- created_at: new Date().toISOString(),
- });
-
- return {
- new_agent_id: newAgentId,
- new_slug: newSlug,
- files_copied: filesCopied,
- sessions_copied: sessionsCopied,
- source_crons: sourceCrons,
- new_cron_ids: newCronIds,
- };
-}
-
-// --- helpers ---
-
-/**
- * True if a project already has an agent at this slug. Considers both our
- * notfair meta sidecar and OpenClaw's agent dir, but only counts directories
- * that contain something — OpenClaw's `agents.delete` leaves an empty parent
- * dir behind after moving the contents to trash, and we don't want that
- * remnant to block reusing the slug.
- */
-export function agentExistsInProject(project_slug: string, slug: string): boolean {
- const agentId = `${project_slug}-${slug}`;
- return (
- hasNonEmptyDir(join(NOTFAIR_DATA_DIR, "agents", agentId)) ||
- hasNonEmptyDir(join(OPENCLAW_HOME, "agents", agentId))
- );
-}
-
-function hasNonEmptyDir(path: string): boolean {
- if (!existsSync(path)) return false;
- try {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { readdirSync } = require("node:fs") as typeof import("node:fs");
- return readdirSync(path).length > 0;
- } catch {
- return true; // be conservative if we can't read it
- }
-}
-
-async function callAgentsFilesSet(agentId: string, name: string, content: string): Promise<void> {
- // setAgentFile in gateway-rpc.ts already wraps this; import lazily to keep
- // the top of this file readable.
- const { setAgentFile } = await import("./gateway-rpc");
- await setAgentFile(agentId, name, content);
-}
-
-type RawCron = {
- id: string;
- agentId?: string;
- name: string;
- enabled?: boolean;
- disabled?: boolean;
- description?: string;
- schedule?:
- | { kind: "cron"; expr: string; tz?: string }
- | { kind: "every"; everyMs: number; anchorMs?: number }
- | { kind: string; [k: string]: unknown };
- payload?: { kind?: string; message?: string; timeoutSeconds?: number };
-};
-
-async function loadAllCrons(): Promise<RawCron[]> {
- // Read jobs.json directly — same data the CLI prints, but avoids spawning
- // a subprocess (which can be 5–15s on cold paths).
- const jobsPath = join(OPENCLAW_HOME, "cron", "jobs.json");
- if (!existsSync(jobsPath)) return [];
- try {
- const raw = readFileSync(jobsPath, "utf8");
- const parsed = JSON.parse(raw) as unknown;
- if (Array.isArray(parsed)) return parsed as RawCron[];
- if (parsed && typeof parsed === "object") {
- const cands = parsed as { jobs?: unknown; crons?: unknown };
- if (Array.isArray(cands.jobs)) return cands.jobs as RawCron[];
- if (Array.isArray(cands.crons)) return cands.crons as RawCron[];
- }
- } catch {
- // Fall through to empty list.
- }
- return [];
-}
-
-async function createClonedCron(
- source: RawCron,
- projectSlug: string,
- newAgentSlug: string,
- newAgentId: string,
-): Promise<string> {
- // Convention: `<project>/<agent-slug>/<cron-slug>` (no surrounding spaces).
- // When cloning, the source's name may already follow `<proj>/<agent>/<cron>`
- // (e.g. a clone of a clone). Only take the trailing segment so we don't
- // end up with redundant project/agent prefixes baked into the cron slug.
- const lastSegment = source.name.split(/\s*\/\s*/).pop()?.trim() ?? source.name;
- const slugAttempt = slugify(lastSegment);
- const cronSlug = slugAttempt.ok && slugAttempt.slug ? slugAttempt.slug : "cloned-job";
- const fullName = `${projectSlug}${NAME_SEPARATOR}${newAgentSlug}${NAME_SEPARATOR}${cronSlug}`;
-
- const args = [
- "cron",
- "add",
- "--name",
- fullName,
- "--agent",
- newAgentId,
- "--no-deliver",
- ];
- if (source.description) {
- args.push("--description", source.description);
- }
- const message = source.payload?.message ?? "";
- if (message) {
- args.push("--message", message);
- }
- const schedule = source.schedule;
- if (schedule?.kind === "cron" && typeof (schedule as { expr?: string }).expr === "string") {
- args.push("--cron", (schedule as { expr: string }).expr);
- const tz = (schedule as { tz?: string }).tz;
- if (tz) args.push("--tz", tz);
- } else if (schedule?.kind === "every" && typeof (schedule as { everyMs?: number }).everyMs === "number") {
- args.push("--every", msToDuration((schedule as { everyMs: number }).everyMs));
- } else {
- // Unknown schedule shape — fall back to disabled hourly so we don't lose
- // the job. User will see it in the crons tab and can fix.
- args.push("--every", "1h");
- }
-
- const result = (await openclaw(args)) as { id?: string };
- if (!result?.id) throw new Error(`openclaw cron add returned no id for '${fullName}'`);
- return String(result.id);
-}
-
-function msToDuration(ms: number): string {
- if (ms < 60_000) return `${Math.max(1, Math.round(ms / 1000))}s`;
- if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m`;
- if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h`;
- return `${Math.round(ms / 86_400_000)}d`;
-}
diff --git a/notfair-cmo/src/server/openclaw/cron-schedule.test.ts b/notfair-cmo/src/server/openclaw/cron-schedule.test.ts
deleted file mode 100644
index 0169a775..00000000
--- a/notfair-cmo/src/server/openclaw/cron-schedule.test.ts
+++ /dev/null
@@ -1,399 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const loadCronRunsMock = vi.fn();
-vi.mock("./crons", () => ({
- loadCronRuns: (...args: unknown[]) => loadCronRunsMock(...args),
-}));
-
-import {
- annotateOccurrencesWithRunStatus,
- expandSchedule,
- groupOccurrencesByDay,
- tickAtOrBefore,
- type CronOccurrence,
-} from "./cron-schedule";
-
-const META = {
- name: "demo/agent/cron",
- short_name: "cron",
- agent_id: "demo-agent",
- agent_slug: "agent",
- schedule_text: "every 1m",
-};
-
-describe("expandSchedule", () => {
- it("returns [] when schedule is undefined", () => {
- expect(expandSchedule("c1", undefined, { from: 0, until: 1000 }, META)).toEqual([]);
- });
-
- it("returns [] when schedule.kind is unknown", () => {
- expect(
- expandSchedule(
- "c1",
- { kind: "weird", foo: "bar" } as never,
- { from: 0, until: 1000 },
- META,
- ),
- ).toEqual([]);
- });
-
- it("expands cron expression to multiple occurrences within window", () => {
- const from = new Date("2026-01-01T00:00:00Z").getTime();
- const until = from + 5 * 60 * 1000;
- const occs = expandSchedule(
- "c1",
- { kind: "cron", expr: "* * * * *", tz: "UTC" },
- { from, until },
- META,
- );
- expect(occs.length).toBeGreaterThan(0);
- expect(occs[0]?.cron_id).toBe("c1");
- expect(occs[0]?.cron_name).toBe(META.name);
- expect(occs[0]?.agent_slug).toBe(META.agent_slug);
- });
-
- it("respects maxPerCron cap on cron schedules", () => {
- const from = new Date("2026-01-01T00:00:00Z").getTime();
- const until = from + 1000 * 60 * 60;
- const occs = expandSchedule(
- "c1",
- { kind: "cron", expr: "* * * * *", tz: "UTC" },
- { from, until },
- META,
- 3,
- );
- expect(occs.length).toBe(3);
- });
-
- it("returns [] on invalid cron expression", () => {
- const occs = expandSchedule(
- "c1",
- { kind: "cron", expr: "not a cron" },
- { from: 0, until: 100000 },
- META,
- );
- expect(occs).toEqual([]);
- });
-
- it("returns [] when cron.expr is not a string", () => {
- const occs = expandSchedule(
- "c1",
- { kind: "cron", expr: 42 as unknown as string },
- { from: 0, until: 100000 },
- META,
- );
- expect(occs).toEqual([]);
- });
-
- it("expands 'every' schedule starting from `from` when no anchor", () => {
- const occs = expandSchedule(
- "c1",
- { kind: "every", everyMs: 1000 },
- { from: 0, until: 3000 },
- META,
- );
- expect(occs.map((o) => o.at)).toEqual([0, 1000, 2000, 3000]);
- });
-
- it("expands 'every' schedule advancing past `from` from earlier anchor", () => {
- const occs = expandSchedule(
- "c1",
- { kind: "every", everyMs: 1000, anchorMs: -500 },
- { from: 0, until: 2500 },
- META,
- );
- expect(occs.map((o) => o.at)).toEqual([500, 1500, 2500]);
- });
-
- it("expands 'every' schedule with anchor at exactly `from`", () => {
- const occs = expandSchedule(
- "c1",
- { kind: "every", everyMs: 1000, anchorMs: 0 },
- { from: 0, until: 2000 },
- META,
- );
- expect(occs.map((o) => o.at)).toEqual([0, 1000, 2000]);
- });
-
- it("uses future anchor as the first occurrence", () => {
- const occs = expandSchedule(
- "c1",
- { kind: "every", everyMs: 1000, anchorMs: 5000 },
- { from: 0, until: 7000 },
- META,
- );
- expect(occs.map((o) => o.at)).toEqual([5000, 6000, 7000]);
- });
-
- it("returns [] when everyMs <= 0", () => {
- expect(
- expandSchedule(
- "c1",
- { kind: "every", everyMs: 0 },
- { from: 0, until: 1000 },
- META,
- ),
- ).toEqual([]);
- expect(
- expandSchedule(
- "c1",
- { kind: "every", everyMs: -5 },
- { from: 0, until: 1000 },
- META,
- ),
- ).toEqual([]);
- });
-
- it("returns [] when every.everyMs is not a number", () => {
- expect(
- expandSchedule(
- "c1",
- { kind: "every", everyMs: "10" as unknown as number },
- { from: 0, until: 1000 },
- META,
- ),
- ).toEqual([]);
- });
-
- it("caps 'every' expansion at maxPerCron", () => {
- const occs = expandSchedule(
- "c1",
- { kind: "every", everyMs: 1 },
- { from: 0, until: 1_000_000 },
- META,
- 5,
- );
- expect(occs.length).toBe(5);
- });
-});
-
-describe("tickAtOrBefore", () => {
- it("returns undefined for undefined schedule", () => {
- expect(tickAtOrBefore(undefined, 1000)).toBeUndefined();
- });
-
- it("returns undefined for unknown kind", () => {
- expect(tickAtOrBefore({ kind: "weird" } as never, 1000)).toBeUndefined();
- });
-
- it("returns nearest tick at-or-before `at` for cron expr", () => {
- const at = new Date("2026-01-01T00:10:30Z").getTime();
- // Use a 1h lookback so we don't blow the 10k iteration cap inside.
- const tick = tickAtOrBefore(
- { kind: "cron", expr: "* * * * *", tz: "UTC" },
- at,
- 60 * 60 * 1000,
- );
- expect(tick).toBeDefined();
- expect(tick!).toBeLessThanOrEqual(at);
- expect(at - tick!).toBeLessThan(60_000);
- });
-
- it("returns undefined on invalid cron expr", () => {
- expect(tickAtOrBefore({ kind: "cron", expr: "garbage" }, 1000)).toBeUndefined();
- });
-
- it("returns undefined when cron.expr is not a string", () => {
- expect(
- tickAtOrBefore({ kind: "cron", expr: 5 as unknown as string }, 1000),
- ).toBeUndefined();
- });
-
- it("returns undefined when no tick exists in lookback window for cron", () => {
- const at = new Date("2026-01-01T00:00:00Z").getTime();
- // Lookback is 1ms; cron fires every minute so no tick in that window unless on boundary.
- const tick = tickAtOrBefore(
- { kind: "cron", expr: "*/30 * * * *", tz: "UTC" },
- at + 1,
- 1,
- );
- // Could be undefined or exactly `at`; either is acceptable per spec.
- if (tick !== undefined) {
- expect(tick).toBeLessThanOrEqual(at + 1);
- }
- });
-
- it("returns floor(k) tick for every schedule with anchor", () => {
- expect(tickAtOrBefore({ kind: "every", everyMs: 1000, anchorMs: 0 }, 3500)).toBe(3000);
- });
-
- it("returns the anchor when at == anchor", () => {
- expect(tickAtOrBefore({ kind: "every", everyMs: 1000, anchorMs: 1000 }, 1000)).toBe(1000);
- });
-
- it("returns undefined when anchor is in the future of `at`", () => {
- expect(tickAtOrBefore({ kind: "every", everyMs: 1000, anchorMs: 5000 }, 3000)).toBeUndefined();
- });
-
- it("returns undefined when every.everyMs <= 0", () => {
- expect(tickAtOrBefore({ kind: "every", everyMs: 0 }, 1000)).toBeUndefined();
- expect(tickAtOrBefore({ kind: "every", everyMs: -5 }, 1000)).toBeUndefined();
- });
-
- it("returns undefined when every.everyMs is not a number", () => {
- expect(
- tickAtOrBefore({ kind: "every", everyMs: "10" as unknown as number }, 1000),
- ).toBeUndefined();
- });
-
- it("defaults anchor to `at` when no anchorMs provided", () => {
- expect(tickAtOrBefore({ kind: "every", everyMs: 1000 }, 1234)).toBe(1234);
- });
-});
-
-describe("annotateOccurrencesWithRunStatus", () => {
- beforeEach(() => {
- loadCronRunsMock.mockReset();
- });
-
- it("annotates occurrences whose tick matches a run's owning tick", () => {
- const schedule = { kind: "every", everyMs: 1000, anchorMs: 0 } as const;
- const occs: CronOccurrence[] = [
- {
- at: 1000,
- cron_id: "c1",
- cron_name: "n",
- short_name: "n",
- agent_id: "a",
- agent_slug: "a",
- schedule_text: "every 1s",
- },
- {
- at: 2000,
- cron_id: "c1",
- cron_name: "n",
- short_name: "n",
- agent_id: "a",
- agent_slug: "a",
- schedule_text: "every 1s",
- },
- ];
- loadCronRunsMock.mockReturnValueOnce([
- { run_at_ms: 1050, status: "ok" },
- { run_at_ms: 2100, status: "error" },
- ]);
- const out = annotateOccurrencesWithRunStatus(
- occs,
- new Map([["c1", schedule]]),
- );
- expect(out[0]!.run_status).toBe("ok");
- expect(out[1]!.run_status).toBe("error");
- expect(loadCronRunsMock).toHaveBeenCalledWith("c1", 200);
- });
-
- it("skips crons missing from the schedules map", () => {
- const occs: CronOccurrence[] = [
- {
- at: 1000,
- cron_id: "no-sched",
- cron_name: "n",
- short_name: "n",
- agent_id: "a",
- agent_slug: "a",
- schedule_text: "?",
- },
- ];
- const out = annotateOccurrencesWithRunStatus(occs, new Map());
- expect(out[0]!.run_status).toBeUndefined();
- expect(loadCronRunsMock).not.toHaveBeenCalled();
- });
-
- it("does not overwrite first-seen status when a later run has same owning tick", () => {
- const schedule = { kind: "every", everyMs: 1000, anchorMs: 0 } as const;
- const occs: CronOccurrence[] = [
- {
- at: 1000,
- cron_id: "c1",
- cron_name: "n",
- short_name: "n",
- agent_id: "a",
- agent_slug: "a",
- schedule_text: "?",
- },
- ];
- loadCronRunsMock.mockReturnValueOnce([
- { run_at_ms: 1010, status: "ok" },
- { run_at_ms: 1500, status: "error" },
- ]);
- const out = annotateOccurrencesWithRunStatus(occs, new Map([["c1", schedule]]));
- expect(out[0]!.run_status).toBe("ok");
- });
-
- it("groups by cron id and only fetches each cron's runs once", () => {
- const schedule = { kind: "every", everyMs: 1000, anchorMs: 0 } as const;
- const occs: CronOccurrence[] = [
- { at: 1000, cron_id: "c1", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- { at: 2000, cron_id: "c1", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- { at: 3000, cron_id: "c2", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- ];
- loadCronRunsMock.mockReturnValue([]);
- annotateOccurrencesWithRunStatus(
- occs,
- new Map([
- ["c1", schedule],
- ["c2", schedule],
- ]),
- );
- expect(loadCronRunsMock).toHaveBeenCalledTimes(2);
- });
-
- it("returns runs with no matching occurrence as unaffected", () => {
- const schedule = { kind: "every", everyMs: 1000, anchorMs: 0 } as const;
- const occs: CronOccurrence[] = [
- { at: 1000, cron_id: "c1", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- ];
- loadCronRunsMock.mockReturnValueOnce([
- { run_at_ms: 5050, status: "ok" }, // owning tick is 5000, not 1000
- ]);
- const out = annotateOccurrencesWithRunStatus(occs, new Map([["c1", schedule]]));
- expect(out[0]!.run_status).toBeUndefined();
- });
-});
-
-describe("groupOccurrencesByDay", () => {
- it("buckets occurrences into the correct day index", () => {
- const dayMs = 24 * 60 * 60 * 1000;
- const start = 0;
- const occs: CronOccurrence[] = [
- { at: 0, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- { at: dayMs + 1, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- { at: 2 * dayMs + 100, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- ];
- const days = groupOccurrencesByDay(occs, start, 3);
- expect(days.length).toBe(3);
- expect(days[0]!.length).toBe(1);
- expect(days[1]!.length).toBe(1);
- expect(days[2]!.length).toBe(1);
- });
-
- it("drops occurrences before the first day or beyond the last", () => {
- const dayMs = 24 * 60 * 60 * 1000;
- const start = dayMs;
- const occs: CronOccurrence[] = [
- { at: 0, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- { at: dayMs, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- { at: 10 * dayMs, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- ];
- const days = groupOccurrencesByDay(occs, start, 2);
- expect(days[0]!.length).toBe(1);
- expect(days[1]!.length).toBe(0);
- });
-
- it("sorts each day's occurrences ascending by `at`", () => {
- const dayMs = 24 * 60 * 60 * 1000;
- const occs: CronOccurrence[] = [
- { at: 300, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- { at: 100, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- { at: 200, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },
- ];
- const days = groupOccurrencesByDay(occs, 0, 1);
- expect(days[0]!.map((o) => o.at)).toEqual([100, 200, 300]);
- expect(dayMs).toBeGreaterThan(0);
- });
-
- it("returns numDays empty buckets when occurrences list is empty", () => {
- const days = groupOccurrencesByDay([], 0, 5);
- expect(days.length).toBe(5);
- expect(days.every((d) => d.length === 0)).toBe(true);
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/cron-schedule.ts b/notfair-cmo/src/server/openclaw/cron-schedule.ts
deleted file mode 100644
index efe6df7a..00000000
--- a/notfair-cmo/src/server/openclaw/cron-schedule.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import { CronExpressionParser } from "cron-parser";
-import type { DisplayCron } from "./crons";
-import { loadCronRuns } from "./crons";
-
-export type CronOccurrence = {
- /** ms epoch */
- at: number;
- cron_id: string;
- cron_name: string;
- short_name: string;
- agent_id: string;
- agent_slug: string;
- schedule_text: string;
- /** Raw status string from OpenClaw when a matching run is found. */
- run_status?: string;
-};
-
-type ScheduleInput =
- | { kind: "cron"; expr: string; tz?: string }
- | { kind: "every"; everyMs: number; anchorMs?: number }
- | { kind: string; [k: string]: unknown };
-
-/**
- * Compute upcoming occurrences for one cron up to `until` (ms epoch).
- * Returns at most `maxPerCron` entries — high-frequency crons are capped so
- * we don't render thousands of chips for an every-second job.
- */
-export function expandSchedule(
- cron_id: string,
- schedule: ScheduleInput | undefined,
- range: { from: number; until: number },
- meta: Pick<DisplayCron, "name" | "short_name" | "agent_id"> & { agent_slug: string; schedule_text: string },
- maxPerCron = 60,
-): CronOccurrence[] {
- if (!schedule) return [];
- const { from, until } = range;
- const out: CronOccurrence[] = [];
-
- const make = (at: number): CronOccurrence => ({
- at,
- 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,
- });
-
- if (schedule.kind === "cron" && typeof (schedule as { expr?: unknown }).expr === "string") {
- const s = schedule as { expr: string; tz?: string };
- try {
- const it = CronExpressionParser.parse(s.expr, {
- currentDate: new Date(from),
- endDate: new Date(until),
- tz: s.tz,
- });
- while (out.length < maxPerCron) {
- try {
- const next = it.next();
- out.push(make(next.toDate().getTime()));
- } catch {
- break;
- }
- }
- } catch {
- return [];
- }
- return out;
- }
-
- if (schedule.kind === "every" && typeof (schedule as { everyMs?: unknown }).everyMs === "number") {
- const s = schedule as { everyMs: number; anchorMs?: number };
- if (s.everyMs <= 0) return [];
- const anchor = typeof s.anchorMs === "number" ? s.anchorMs : from;
- // First occurrence at or after `from`.
- let next = anchor;
- if (anchor < from) {
- const k = Math.ceil((from - anchor) / s.everyMs);
- next = anchor + k * s.everyMs;
- }
- while (next <= until && out.length < maxPerCron) {
- out.push(make(next));
- next += s.everyMs;
- }
- return out;
- }
-
- return [];
-}
-
-/**
- * Find the most recent scheduled tick at or before `at` for a given schedule.
- * Used to attribute a cron run (whose `runAtMs` is when the scheduler actually
- * fired, often 5-10 minutes after the nominal tick) back to the calendar
- * occurrence it belongs to.
- *
- * Returns the tick's ms epoch, or `undefined` if no tick before `at` is in the
- * lookback window (defaults to 14 days, enough to catch the previous tick of
- * any reasonable daily/weekly schedule).
- */
-export function tickAtOrBefore(
- schedule: ScheduleInput | undefined,
- at: number,
- lookbackMs = 14 * 24 * 60 * 60 * 1000,
-): number | undefined {
- if (!schedule) return undefined;
- const from = at - lookbackMs;
-
- if (schedule.kind === "cron" && typeof (schedule as { expr?: unknown }).expr === "string") {
- const s = schedule as { expr: string; tz?: string };
- try {
- const it = CronExpressionParser.parse(s.expr, {
- currentDate: new Date(from),
- endDate: new Date(at + 1),
- tz: s.tz,
- });
- 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;
- }
- }
-
- if (schedule.kind === "every" && typeof (schedule as { everyMs?: unknown }).everyMs === "number") {
- const s = schedule as { everyMs: number; anchorMs?: number };
- if (s.everyMs <= 0) return undefined;
- const anchor = typeof s.anchorMs === "number" ? s.anchorMs : at;
- if (anchor > at) return undefined;
- const k = Math.floor((at - anchor) / s.everyMs);
- return anchor + k * s.everyMs;
- }
-
- return undefined;
-}
-
-/**
- * Annotate occurrences with their owning run's status (when one exists in the
- * cron run log). Mutates and returns the list for caller convenience.
- *
- * Reads `~/.openclaw/cron/runs/<cronId>.jsonl` per unique cron in the input.
- * Each run's owning nominal tick is computed via `tickAtOrBefore` so late-fired
- * runs still match their intended occurrence.
- */
-export function annotateOccurrencesWithRunStatus(
- occurrences: CronOccurrence[],
- schedulesByCronId: Map<string, ScheduleInput | undefined>,
-): CronOccurrence[] {
- // Group occurrences by cron so we hit the run log at most once per cron.
- 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);
- // Index runs by owning tick for O(1) lookup.
- 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;
-}
-
-/**
- * Expand a list of crons into a flat occurrence list grouped by day-of-week.
- * Days are in user local time (matches what the user sees in the calendar).
- */
-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/openclaw/crons.test.ts b/notfair-cmo/src/server/openclaw/crons.test.ts
deleted file mode 100644
index 8f1b5a47..00000000
--- a/notfair-cmo/src/server/openclaw/crons.test.ts
+++ /dev/null
@@ -1,596 +0,0 @@
-import { writeFileSync, mkdirSync } from "node:fs";
-import { join } from "node:path";
-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-const { tmpHome, ORIGINAL_HOME } = vi.hoisted(() => {
- // Hoisted so it runs before any imports — must be set BEFORE crons.ts
- // module-evaluates and captures OPENCLAW_HOME.
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { tmpdir } = require("node:os") as typeof import("node:os");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { join: joinPath } = require("node:path") as typeof import("node:path");
- const original = process.env.OPENCLAW_HOME;
- const tmp = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-crons-"));
- process.env.OPENCLAW_HOME = tmp;
- return { tmpHome: tmp, ORIGINAL_HOME: original };
-});
-
-const openclawMock = vi.fn();
-vi.mock("./cli", () => ({
- openclaw: (...args: unknown[]) => openclawMock(...args),
-}));
-
-import {
- createCron,
- disableCron,
- enableCron,
- invalidateCronCache,
- listCronsForProject,
- loadCronRuns,
- removeCron,
-} from "./crons";
-
-describe("crons module", () => {
- beforeEach(() => {
- openclawMock.mockReset();
- invalidateCronCache();
- });
-
- afterEach(() => {
- invalidateCronCache();
- });
-
- describe("listCronsForProject", () => {
- it("matches crons by 'project<sep>...' name with no surrounding spaces", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "demo/google-ads/morning", agentId: "demo-google-ads" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.project_slug).toBe("demo");
- expect(view.groups.length).toBe(1);
- expect(view.groups[0]!.agent).toBe("google-ads");
- expect(view.groups[0]!.crons[0]!.id).toBe("1");
- });
-
- it("matches crons by 'project <sep>...' name with surrounding spaces", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "demo / seo / weekly", agentId: "demo-seo" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups[0]!.agent).toBe("seo");
- });
-
- it("matches crons by agentId starting with '<project>-' even with unrelated name", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "anonymous-cron", agentId: "demo-cmo" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups.length).toBe(1);
- expect(view.groups[0]!.agent).toBe("cmo");
- });
-
- it("skips crons that don't match the project", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "other/seo/x", agentId: "other-seo" },
- { id: "2", name: "demo/google-ads/x", agentId: "demo-google-ads" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups.length).toBe(1);
- expect(view.groups[0]!.crons.length).toBe(1);
- expect(view.groups[0]!.crons[0]!.id).toBe("2");
- });
-
- it("normalizes a jobs:[] wrapper from openclaw", async () => {
- openclawMock.mockResolvedValueOnce({
- jobs: [{ id: "1", name: "demo/cmo/x", agentId: "demo-cmo" }],
- });
- const view = await listCronsForProject("demo");
- expect(view.groups.length).toBe(1);
- });
-
- it("normalizes a crons:[] wrapper from openclaw", async () => {
- openclawMock.mockResolvedValueOnce({
- crons: [{ id: "1", name: "demo/cmo/x", agentId: "demo-cmo" }],
- });
- const view = await listCronsForProject("demo");
- expect(view.groups.length).toBe(1);
- });
-
- it("returns empty groups when openclaw returns garbage", async () => {
- openclawMock.mockResolvedValueOnce("not an array");
- const view = await listCronsForProject("demo");
- expect(view.groups).toEqual([]);
- });
-
- it("derives agent slug from cron name when agentId is missing", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "demo/google-ads/morning" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups.length).toBe(1);
- expect(view.groups[0]!.agent).toBe("google-ads");
- });
-
- it("groups multiple crons by agent and sorts groups alphabetically", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "demo/seo/a", agentId: "demo-seo" },
- { id: "2", name: "demo/google-ads/a", agentId: "demo-google-ads" },
- { id: "3", name: "demo/google-ads/b", agentId: "demo-google-ads" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups.map((g) => g.agent)).toEqual(["google-ads", "seo"]);
- expect(view.groups[0]!.crons.length).toBe(2);
- });
-
- it("formats cron expression schedule with tz suffix", async () => {
- openclawMock.mockResolvedValueOnce([
- {
- id: "1",
- name: "demo/cmo/x",
- agentId: "demo-cmo",
- schedule: { kind: "cron", expr: "0 9 * * *", tz: "America/Los_Angeles" },
- },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups[0]!.crons[0]!.schedule_text).toBe(
- "0 9 * * * · America/Los_Angeles",
- );
- });
-
- it("formats cron expression schedule without tz", async () => {
- openclawMock.mockResolvedValueOnce([
- {
- id: "1",
- name: "demo/cmo/x",
- agentId: "demo-cmo",
- schedule: { kind: "cron", expr: "0 9 * * *" },
- },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups[0]!.crons[0]!.schedule_text).toBe("0 9 * * *");
- });
-
- it("formats every schedule in seconds/minutes/hours/days", async () => {
- const cases: Array<[number, string]> = [
- [30_000, "every 30s"],
- [5 * 60_000, "every 5m"],
- [3 * 60 * 60_000, "every 3h"],
- [2 * 24 * 60 * 60_000, "every 2d"],
- ];
- for (const [everyMs, expected] of cases) {
- openclawMock.mockReset();
- invalidateCronCache();
- openclawMock.mockResolvedValueOnce([
- {
- id: "1",
- name: "demo/cmo/x",
- agentId: "demo-cmo",
- schedule: { kind: "every", everyMs },
- },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups[0]!.crons[0]!.schedule_text).toBe(expected);
- }
- });
-
- it("dash-formats schedule for missing/unknown shapes", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "demo/cmo/a", agentId: "demo-cmo" },
- {
- id: "2",
- name: "demo/cmo/b",
- agentId: "demo-cmo",
- schedule: { kind: "weird" },
- },
- ]);
- const view = await listCronsForProject("demo");
- const crons = view.groups[0]!.crons;
- const byId = Object.fromEntries(crons.map((c) => [c.id, c]));
- expect(byId["1"]!.schedule_text).toBe("—");
- expect(byId["2"]!.schedule_text).toBe(JSON.stringify({ kind: "weird" }));
- });
-
- it("status_text falls back to 'idle' when no state on enabled cron", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "demo/cmo/x", agentId: "demo-cmo" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups[0]!.crons[0]!.status_text).toBe("idle");
- expect(view.groups[0]!.crons[0]!.disabled).toBe(false);
- });
-
- it("status_text uses lastStatus then falls back to lastRunStatus", async () => {
- openclawMock.mockResolvedValueOnce([
- {
- id: "1",
- name: "demo/cmo/a",
- agentId: "demo-cmo",
- state: { lastStatus: "ok" },
- },
- {
- id: "2",
- name: "demo/cmo/b",
- agentId: "demo-cmo",
- state: { lastRunStatus: "error" },
- },
- ]);
- const view = await listCronsForProject("demo");
- const byId = Object.fromEntries(view.groups[0]!.crons.map((c) => [c.id, c]));
- expect(byId["1"]!.status_text).toBe("ok");
- expect(byId["2"]!.status_text).toBe("error");
- });
-
- it("marks disabled crons (either disabled:true OR enabled:false)", async () => {
- openclawMock.mockResolvedValueOnce([
- {
- id: "1",
- name: "demo/cmo/a",
- agentId: "demo-cmo",
- disabled: true,
- state: { lastStatus: "ok" },
- },
- {
- id: "2",
- name: "demo/cmo/b",
- agentId: "demo-cmo",
- enabled: false,
- },
- ]);
- const view = await listCronsForProject("demo");
- const byId = Object.fromEntries(view.groups[0]!.crons.map((c) => [c.id, c]));
- expect(byId["1"]!.disabled).toBe(true);
- expect(byId["1"]!.status_text).toBe("disabled");
- expect(byId["2"]!.disabled).toBe(true);
- });
-
- it("derives short_name from last segment of name", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "demo/google-ads/morning-budget", agentId: "demo-google-ads" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups[0]!.crons[0]!.short_name).toBe("morning-budget");
- });
-
- it("propagates message + description + last_error fields", async () => {
- openclawMock.mockResolvedValueOnce([
- {
- id: "1",
- name: "demo/cmo/x",
- agentId: "demo-cmo",
- description: "a job",
- payload: { kind: "agentTurn", message: "hi" },
- state: { lastError: "blew up" },
- },
- ]);
- const view = await listCronsForProject("demo");
- const d = view.groups[0]!.crons[0]!;
- expect(d.description).toBe("a job");
- expect(d.message).toBe("hi");
- expect(d.last_error).toBe("blew up");
- });
-
- it("falls back to lastErrorReason when lastError missing", async () => {
- openclawMock.mockResolvedValueOnce([
- {
- id: "1",
- name: "demo/cmo/x",
- agentId: "demo-cmo",
- state: { lastErrorReason: "no creds" },
- },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups[0]!.crons[0]!.last_error).toBe("no creds");
- });
-
- it("formats next/last run as relative seconds/minutes/hours/days", async () => {
- const now = Date.now();
- openclawMock.mockResolvedValueOnce([
- {
- id: "1",
- name: "demo/cmo/x",
- agentId: "demo-cmo",
- state: {
- nextRunAtMs: now + 30_000,
- lastRunAtMs: now - 5 * 60_000,
- },
- },
- {
- id: "2",
- name: "demo/cmo/y",
- agentId: "demo-cmo",
- state: {
- nextRunAtMs: now + 2 * 60 * 60_000,
- lastRunAtMs: now - 3 * 24 * 60 * 60_000,
- },
- },
- ]);
- const view = await listCronsForProject("demo");
- const byId = Object.fromEntries(view.groups[0]!.crons.map((c) => [c.id, c]));
- expect(byId["1"]!.next_run_text).toMatch(/^in 30s$/);
- expect(byId["1"]!.last_run_text).toMatch(/5m ago/);
- expect(byId["2"]!.next_run_text).toMatch(/in 2h/);
- expect(byId["2"]!.last_run_text).toMatch(/3d ago/);
- });
-
- it("renders '—' for missing run timestamps", async () => {
- openclawMock.mockResolvedValueOnce([
- { id: "1", name: "demo/cmo/x", agentId: "demo-cmo" },
- ]);
- const view = await listCronsForProject("demo");
- expect(view.groups[0]!.crons[0]!.next_run_text).toBe("—");
- expect(view.groups[0]!.crons[0]!.last_run_text).toBe("—");
- });
- });
-
- describe("subprocess cache", () => {
- it("caches openclaw output within the TTL window", async () => {
- openclawMock.mockResolvedValue([{ id: "1", name: "demo/cmo/x", agentId: "demo-cmo" }]);
- // Two back-to-back calls; cache key is project_slug-agnostic.
- await listCronsForProject("demo");
- await listCronsForProject("other-project");
- expect(openclawMock).toHaveBeenCalledTimes(1);
- });
-
- it("invalidateCronCache forces a refetch", async () => {
- openclawMock.mockResolvedValue([]);
- await listCronsForProject("demo");
- invalidateCronCache();
- await listCronsForProject("demo");
- expect(openclawMock).toHaveBeenCalledTimes(2);
- });
-
- it("invalidates the cache when openclaw rejects", async () => {
- openclawMock.mockRejectedValueOnce(new Error("transient"));
- await expect(listCronsForProject("demo")).rejects.toThrow("transient");
- openclawMock.mockResolvedValueOnce([]);
- await expect(listCronsForProject("demo")).resolves.toBeTruthy();
- expect(openclawMock).toHaveBeenCalledTimes(2);
- });
- });
-
- describe("mutators invalidate cache + call openclaw", () => {
- beforeEach(() => {
- openclawMock.mockResolvedValue(undefined);
- });
-
- it("disableCron calls 'cron disable <id>' without json", async () => {
- await disableCron("c1");
- expect(openclawMock).toHaveBeenCalledWith(["cron", "disable", "c1"], { json: false });
- });
-
- it("enableCron calls 'cron enable <id>' without json", async () => {
- await enableCron("c1");
- expect(openclawMock).toHaveBeenCalledWith(["cron", "enable", "c1"], { json: false });
- });
-
- it("removeCron calls 'cron rm <id>' without json", async () => {
- await removeCron("c1");
- expect(openclawMock).toHaveBeenCalledWith(["cron", "rm", "c1"], { json: false });
- });
-
- it("mutators invalidate the cron list cache", async () => {
- openclawMock.mockReset();
- openclawMock.mockResolvedValueOnce([]); // first listCronsForProject
- await listCronsForProject("demo");
- openclawMock.mockResolvedValueOnce(undefined); // disable
- await disableCron("c1");
- openclawMock.mockResolvedValueOnce([]); // refetch after invalidate
- await listCronsForProject("demo");
- // 3 calls total = list + disable + list-after-disable
- expect(openclawMock).toHaveBeenCalledTimes(3);
- });
- });
-
- describe("createCron", () => {
- it("builds full name and passes cron schedule + tz", async () => {
- openclawMock.mockResolvedValueOnce({ id: "cron-id-1", name: "demo/cmo/morning" });
- const r = await createCron({
- project_slug: "demo",
- agent_slug: "cmo",
- agent_full_id: "demo-cmo",
- cron_name: "morning",
- schedule: { kind: "cron", expr: "0 9 * * *", tz: "UTC" },
- message: "hello",
- });
- expect(r).toEqual({ id: "cron-id-1", name: "demo/cmo/morning" });
- expect(openclawMock).toHaveBeenCalledWith([
- "cron",
- "add",
- "--name",
- "demo/cmo/morning",
- "--agent",
- "demo-cmo",
- "--message",
- "hello",
- "--no-deliver",
- "--cron",
- "0 9 * * *",
- "--tz",
- "UTC",
- ]);
- });
-
- it("omits --tz when not provided", async () => {
- openclawMock.mockResolvedValueOnce({});
- await createCron({
- project_slug: "demo",
- agent_slug: "cmo",
- agent_full_id: "demo-cmo",
- cron_name: "morning",
- schedule: { kind: "cron", expr: "0 9 * * *" },
- message: "hello",
- });
- const args = openclawMock.mock.calls[0]![0] as string[];
- expect(args).not.toContain("--tz");
- });
-
- it("uses --every for duration-based schedules", async () => {
- openclawMock.mockResolvedValueOnce({ id: "abc" });
- await createCron({
- project_slug: "demo",
- agent_slug: "cmo",
- agent_full_id: "demo-cmo",
- cron_name: "ping",
- schedule: { kind: "every", duration: "5m" },
- message: "tick",
- });
- const args = openclawMock.mock.calls[0]![0] as string[];
- expect(args).toContain("--every");
- expect(args).toContain("5m");
- expect(args).not.toContain("--cron");
- });
-
- it("includes --description when provided", async () => {
- openclawMock.mockResolvedValueOnce({});
- await createCron({
- project_slug: "demo",
- agent_slug: "cmo",
- agent_full_id: "demo-cmo",
- cron_name: "x",
- schedule: { kind: "cron", expr: "* * * * *" },
- message: "m",
- description: "this is the desc",
- });
- const args = openclawMock.mock.calls[0]![0] as string[];
- const idx = args.indexOf("--description");
- expect(idx).toBeGreaterThan(-1);
- expect(args[idx + 1]).toBe("this is the desc");
- });
-
- it("coerces missing id/name to empty string / fullName", async () => {
- openclawMock.mockResolvedValueOnce(null);
- const r = await createCron({
- project_slug: "demo",
- agent_slug: "cmo",
- agent_full_id: "demo-cmo",
- cron_name: "ping",
- schedule: { kind: "every", duration: "5m" },
- message: "m",
- });
- expect(r.id).toBe("");
- expect(r.name).toBe("demo/cmo/ping");
- });
- });
-
- describe("loadCronRuns", () => {
- function runsPath(cronId: string): string {
- const dir = join(tmpHome, "cron", "runs");
- mkdirSync(dir, { recursive: true });
- return join(dir, `${cronId}.jsonl`);
- }
-
- it("returns [] when the run log file doesn't exist", () => {
- expect(loadCronRuns("nonexistent-cron", 10)).toEqual([]);
- });
-
- it("parses finished entries newest-first", () => {
- const p = runsPath("cron-a");
- const lines = [
- JSON.stringify({ action: "started", runAtMs: 1000 }),
- JSON.stringify({
- action: "finished",
- runAtMs: 1000,
- ts: 1100,
- status: "ok",
- summary: "did it",
- durationMs: 100,
- }),
- JSON.stringify({
- action: "finished",
- runAtMs: 2000,
- ts: 2200,
- status: "error",
- summary: "",
- error: "kaboom",
- sessionId: "sess-1",
- model: "m",
- provider: "p",
- usage: { input_tokens: 5 },
- }),
- ];
- writeFileSync(p, lines.join("\n") + "\n", "utf8");
- const runs = loadCronRuns("cron-a", 10);
- expect(runs.length).toBe(2);
- // Newest first.
- expect(runs[0]!.status).toBe("error");
- expect(runs[0]!.run_at_ms).toBe(2000);
- expect(runs[0]!.finished_at_ms).toBe(2200);
- expect(runs[0]!.error).toBe("kaboom");
- expect(runs[0]!.session_id).toBe("sess-1");
- expect(runs[0]!.model).toBe("m");
- expect(runs[0]!.provider).toBe("p");
- expect(runs[0]!.usage).toEqual({ input_tokens: 5 });
- expect(runs[1]!.status).toBe("ok");
- expect(runs[1]!.duration_ms).toBe(100);
- });
-
- it("respects limit cap", () => {
- const p = runsPath("cron-b");
- const lines = Array.from({ length: 5 }, (_, i) =>
- JSON.stringify({ action: "finished", runAtMs: 1000 + i, ts: 1000 + i, status: "ok" }),
- );
- writeFileSync(p, lines.join("\n") + "\n", "utf8");
- const runs = loadCronRuns("cron-b", 2);
- expect(runs.length).toBe(2);
- // Newest two are runAtMs 1004 then 1003.
- expect(runs.map((r) => r.run_at_ms)).toEqual([1004, 1003]);
- });
-
- it("skips non-finished entries", () => {
- const p = runsPath("cron-c");
- writeFileSync(
- p,
- [
- JSON.stringify({ action: "started", runAtMs: 1000 }),
- JSON.stringify({ action: "skipped", runAtMs: 1500 }),
- JSON.stringify({ action: "finished", runAtMs: 2000, ts: 2100, status: "ok" }),
- ].join("\n") + "\n",
- "utf8",
- );
- const runs = loadCronRuns("cron-c", 10);
- expect(runs.length).toBe(1);
- expect(runs[0]!.run_at_ms).toBe(2000);
- });
-
- it("skips entries missing runAtMs or with invalid JSON", () => {
- const p = runsPath("cron-d");
- writeFileSync(
- p,
- [
- "not json at all",
- JSON.stringify({ action: "finished" }), // no runAtMs
- JSON.stringify({ action: "finished", runAtMs: 0 }),
- JSON.stringify({ action: "finished", runAtMs: 5000, status: "ok" }),
- "",
- ].join("\n"),
- "utf8",
- );
- const runs = loadCronRuns("cron-d", 10);
- expect(runs.length).toBe(1);
- expect(runs[0]!.run_at_ms).toBe(5000);
- });
-
- it("provides sensible defaults for missing fields", () => {
- const p = runsPath("cron-e");
- writeFileSync(
- p,
- JSON.stringify({ action: "finished", runAtMs: 1000 }) + "\n",
- "utf8",
- );
- const runs = loadCronRuns("cron-e", 10);
- expect(runs[0]!.finished_at_ms).toBe(1000); // ts missing -> falls back to runAtMs
- expect(runs[0]!.status).toBe("unknown");
- expect(runs[0]!.summary).toBe("");
- expect(runs[0]!.error).toBeUndefined();
- expect(runs[0]!.usage).toBeUndefined();
- });
- });
-});
-
-// Restore env for downstream tests sharing the process.
-afterAll(() => {
- if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;
- else delete process.env.OPENCLAW_HOME;
-});
diff --git a/notfair-cmo/src/server/openclaw/crons.ts b/notfair-cmo/src/server/openclaw/crons.ts
deleted file mode 100644
index b6a60280..00000000
--- a/notfair-cmo/src/server/openclaw/crons.ts
+++ /dev/null
@@ -1,377 +0,0 @@
-import { existsSync, readFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { cache } from "react";
-import { openclaw } from "./cli";
-
-const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");
-
-/**
- * Module-level in-memory cache for the `openclaw cron list` subprocess.
- * Single-user local app, so a tiny TTL across requests is safe and avoids
- * 1-2s subprocess spawns blocking every page render. Per-request dedup is
- * additionally handled by React's `cache()` wrapper below.
- */
-// Cron list rarely changes second-to-second; cache aggressively so the upstream
-// `openclaw cron list` subprocess (which can take 5-15s on some machines) does
-// not block every page render.
-const CACHE_TTL_MS = 30_000;
-let cachedCronsAt = 0;
-let cachedCronsPromise: Promise<unknown> | null = null;
-
-async function rawListAllCrons(): Promise<unknown> {
- const now = Date.now();
- if (cachedCronsPromise && now - cachedCronsAt < CACHE_TTL_MS) {
- return cachedCronsPromise;
- }
- cachedCronsAt = now;
- // `--all` because the CLI defaults to enabled-only and we want disabled
- // crons in the calendar too (so the Disabled filter has something to show).
- cachedCronsPromise = openclaw(["cron", "list", "--all"]).catch((err) => {
- // Invalidate on failure so the next caller retries instead of getting a cached reject.
- cachedCronsAt = 0;
- cachedCronsPromise = null;
- throw err;
- });
- return cachedCronsPromise;
-}
-
-export function invalidateCronCache(): void {
- cachedCronsAt = 0;
- cachedCronsPromise = null;
-}
-
-type CronSchedule =
- | { kind: "cron"; expr: string; tz?: string }
- | { kind: "every"; everyMs: number; anchorMs?: number }
- | { kind: string; [k: string]: unknown };
-
-type CronState = {
- nextRunAtMs?: number;
- lastRunAtMs?: number;
- lastStatus?: string;
- lastRunStatus?: string;
- lastError?: string;
- lastErrorReason?: string;
- runs?: number;
-};
-
-export type OpenClawCron = {
- id: string;
- name: string;
- description?: string;
- agentId?: string;
- schedule?: CronSchedule;
- state?: CronState;
- disabled?: boolean;
- enabled?: boolean;
- payload?: { kind?: string; message?: string; timeoutSeconds?: number };
- // Catch any other fields without losing them.
- [k: string]: unknown;
-};
-
-export type DisplayCron = {
- id: string;
- name: string;
- short_name: string;
- agent_id: string;
- /** Short, project-stripped agent slug (e.g. "google-ads") for color lookup. */
- agent_slug: string;
- schedule_raw: CronSchedule | undefined;
- schedule_text: string;
- next_run_text: string;
- last_run_text: string;
- status_text: string;
- disabled: boolean;
- /** The prompt/message the cron sends to the agent on each tick. */
- message?: string;
- description?: string;
- /** Last execution time (ms epoch); used to align "ran" vs "scheduled" per occurrence. */
- last_run_at_ms?: number;
- /** Raw status string from OpenClaw (e.g. "ok", "error", "skipped"). */
- last_status?: string;
- last_error?: string;
- next_run_at_ms?: number;
-};
-
-export type CronGroup = {
- agent: string;
- crons: DisplayCron[];
-};
-
-export type ProjectCronView = {
- project_slug: string;
- groups: CronGroup[];
-};
-
-const NAME_SEPARATOR = "/";
-
-/**
- * Fetch all crons from OpenClaw and group by project prefix + agent.
- * Project prefix convention: cron name is `<project-slug> / <agent-slug> / <cron-slug>`.
- * We also match crons whose `agentId` starts with `<project-slug>-` for crons
- * created outside this naming convention (e.g., directly via openclaw cli).
- */
-export const listCronsForProject = cache(async (project_slug: string): Promise<ProjectCronView> => {
- const raw = await rawListAllCrons();
- const allCrons = normalize(raw);
-
- const matching = allCrons.filter((c) => {
- const name = (c.name ?? "").trim();
- if (
- name.startsWith(`${project_slug} ${NAME_SEPARATOR}`) ||
- name.startsWith(`${project_slug}${NAME_SEPARATOR}`)
- ) {
- return true;
- }
- if (c.agentId && c.agentId.startsWith(`${project_slug}-`)) {
- return true;
- }
- return false;
- });
-
- const byAgent = new Map<string, DisplayCron[]>();
- for (const cron of matching) {
- const agentId = cron.agentId ?? deriveAgentFromName(cron.name, project_slug) ?? "unknown";
- const shortAgent = shortenAgentId(agentId, project_slug);
- const display = toDisplay(cron, shortAgent, project_slug);
- const list = byAgent.get(shortAgent) ?? [];
- list.push(display);
- byAgent.set(shortAgent, list);
- }
-
- const groups: CronGroup[] = Array.from(byAgent.entries())
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([agent, crons]) => ({ agent, crons }));
-
- return { project_slug, groups };
-});
-
-function toDisplay(cron: OpenClawCron, shortAgent: string, _project_slug: string): DisplayCron {
- const agent_id = cron.agentId ?? "unknown";
- const disabled = !!cron.disabled || cron.enabled === false;
- const rawStatus = cron.state?.lastStatus ?? cron.state?.lastRunStatus;
- const status_text = disabled ? "disabled" : rawStatus ?? "idle";
- return {
- id: cron.id,
- name: cron.name,
- short_name: deriveCronShortName(cron.name),
- agent_id,
- agent_slug: shortAgent,
- schedule_raw: cron.schedule,
- schedule_text: formatSchedule(cron.schedule),
- next_run_text: formatRelativeMs(cron.state?.nextRunAtMs),
- last_run_text: formatRelativeMs(cron.state?.lastRunAtMs),
- status_text,
- disabled,
- message: cron.payload?.message,
- description: cron.description,
- last_run_at_ms: cron.state?.lastRunAtMs,
- last_status: rawStatus,
- last_error: cron.state?.lastError ?? cron.state?.lastErrorReason,
- next_run_at_ms: cron.state?.nextRunAtMs,
- };
-}
-
-function formatSchedule(schedule: CronSchedule | undefined): string {
- if (!schedule) return "—";
- if (schedule.kind === "cron" && "expr" in schedule) {
- return schedule.tz
- ? `${schedule.expr} · ${schedule.tz}`
- : (schedule.expr as string);
- }
- if (schedule.kind === "every" && "everyMs" in schedule) {
- return `every ${formatDurationMs(schedule.everyMs as number)}`;
- }
- return JSON.stringify(schedule);
-}
-
-function formatDurationMs(ms: number): string {
- const seconds = Math.round(ms / 1000);
- if (seconds < 60) return `${seconds}s`;
- const minutes = Math.round(seconds / 60);
- if (minutes < 60) return `${minutes}m`;
- const hours = Math.round(minutes / 60);
- if (hours < 24) return `${hours}h`;
- const days = Math.round(hours / 24);
- return `${days}d`;
-}
-
-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 normalize(raw: unknown): OpenClawCron[] {
- if (Array.isArray(raw)) return raw as OpenClawCron[];
- if (raw && typeof raw === "object") {
- const candidate = raw as Record<string, unknown>;
- if (Array.isArray(candidate.jobs)) return candidate.jobs as OpenClawCron[];
- if (Array.isArray(candidate.crons)) return candidate.crons as OpenClawCron[];
- }
- return [];
-}
-
-function deriveAgentFromName(name: string | undefined, project_slug: string): string | null {
- if (!name) return null;
- const parts = name.split(NAME_SEPARATOR).map((s) => s.trim());
- if (parts.length >= 2 && parts[0] === project_slug) return parts[1];
- return null;
-}
-
-function deriveCronShortName(name: string): string {
- const parts = name.split(NAME_SEPARATOR).map((s) => s.trim());
- return parts[parts.length - 1] ?? name;
-}
-
-function shortenAgentId(agentId: string, project_slug: string): string {
- const prefix = `${project_slug}-`;
- return agentId.startsWith(prefix) ? agentId.slice(prefix.length) : agentId;
-}
-
-export async function disableCron(id: string): Promise<void> {
- await openclaw(["cron", "disable", id], { json: false });
- invalidateCronCache();
-}
-
-export async function enableCron(id: string): Promise<void> {
- await openclaw(["cron", "enable", id], { json: false });
- invalidateCronCache();
-}
-
-export async function removeCron(id: string): Promise<void> {
- await openclaw(["cron", "rm", id], { json: false });
- invalidateCronCache();
-}
-
-export type CreateCronInput = {
- project_slug: string;
- agent_slug: string;
- agent_full_id: string;
- cron_name: string;
- schedule:
- | { kind: "cron"; expr: string; tz?: string }
- | { kind: "every"; duration: string };
- message: string;
- description?: string;
-};
-
-export type CreateCronResult = {
- id: string;
- name: string;
-};
-
-/**
- * Create a cron in OpenClaw using our naming convention.
- * Called by the `schedule_recurring_work` MCP tool from specialist agents.
- */
-// --- Per-run history ---
-
-export type CronRun = {
- /** When the run was scheduled to fire (matches calendar occurrence.at within ~seconds). */
- run_at_ms: number;
- /** When the run finished (ts in the JSONL). */
- finished_at_ms: number;
- /** Raw OpenClaw status: "ok" | "error" | "skipped" | etc. */
- status: string;
- /** Agent's final reply / report. Empty when missing (e.g. crashed runs). */
- summary: string;
- /** Failure detail string, when status="error". */
- error?: string;
- duration_ms?: number;
- session_id?: string;
- model?: string;
- provider?: string;
- usage?: { input_tokens?: number; output_tokens?: number; total_tokens?: number };
-};
-
-/**
- * Read the per-job cron run log. Returns the most recent runs (newest first).
- * The file is JSONL with one entry per finished run, persisted by OpenClaw's
- * cron service under `~/.openclaw/cron/runs/<jobId>.jsonl`.
- */
-export function loadCronRuns(cron_id: string, limit = 100): CronRun[] {
- const path = join(OPENCLAW_HOME, "cron", "runs", `${cron_id}.jsonl`);
- if (!existsSync(path)) return [];
- let raw: string;
- try {
- raw = readFileSync(path, "utf8");
- } catch {
- return [];
- }
- const lines = raw.split("\n").filter((l) => l.trim().length > 0);
- // Iterate newest-last → flip + cap.
- const out: CronRun[] = [];
- for (let i = lines.length - 1; i >= 0 && out.length < limit; i--) {
- let entry: Record<string, unknown>;
- try {
- entry = JSON.parse(lines[i]!) as Record<string, unknown>;
- } catch {
- continue;
- }
- if (entry.action !== "finished") continue;
- const run_at_ms = typeof entry.runAtMs === "number" ? entry.runAtMs : 0;
- if (!run_at_ms) continue;
- out.push({
- run_at_ms,
- finished_at_ms: typeof entry.ts === "number" ? entry.ts : run_at_ms,
- status: typeof entry.status === "string" ? entry.status : "unknown",
- summary: typeof entry.summary === "string" ? entry.summary : "",
- error: typeof entry.error === "string" ? entry.error : undefined,
- duration_ms: typeof entry.durationMs === "number" ? entry.durationMs : undefined,
- session_id: typeof entry.sessionId === "string" ? entry.sessionId : undefined,
- model: typeof entry.model === "string" ? entry.model : undefined,
- provider: typeof entry.provider === "string" ? entry.provider : undefined,
- usage:
- entry.usage && typeof entry.usage === "object"
- ? (entry.usage as CronRun["usage"])
- : undefined,
- });
- }
- return out;
-}
-
-export async function createCron(input: CreateCronInput): Promise<CreateCronResult> {
- const fullName = `${input.project_slug}${NAME_SEPARATOR}${input.agent_slug}${NAME_SEPARATOR}${input.cron_name}`;
- const args = [
- "cron",
- "add",
- "--name",
- fullName,
- "--agent",
- input.agent_full_id,
- "--message",
- input.message,
- "--no-deliver",
- ];
- if (input.description) {
- args.push("--description", input.description);
- }
- if (input.schedule.kind === "cron") {
- args.push("--cron", input.schedule.expr);
- if (input.schedule.tz) args.push("--tz", input.schedule.tz);
- } else {
- args.push("--every", input.schedule.duration);
- }
- const result = (await openclaw(args)) as { id?: string; name?: string };
- invalidateCronCache();
- return {
- id: String(result?.id ?? ""),
- name: String(result?.name ?? fullName),
- };
-}
diff --git a/notfair-cmo/src/server/openclaw/gateway-client.test.ts b/notfair-cmo/src/server/openclaw/gateway-client.test.ts
deleted file mode 100644
index 68d9d10e..00000000
--- a/notfair-cmo/src/server/openclaw/gateway-client.test.ts
+++ /dev/null
@@ -1,893 +0,0 @@
-import {
- mkdtempSync,
- rmSync,
- writeFileSync,
-} from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import {
- afterAll,
- afterEach,
- beforeAll,
- beforeEach,
- describe,
- expect,
- it,
- vi,
-} from "vitest";
-
-// ---------------------------------------------------------------------------
-// Fake WebSocket implementation (hoisted so vi.mock can reference it)
-// ---------------------------------------------------------------------------
-//
-// gateway-client only exercises a small slice of `ws`'s surface:
-// - constructor(url, opts)
-// - .once("open" | "error", fn)
-// - .removeListener("error", fn)
-// - .on("message" | "close" | "error", fn)
-// - .send(string)
-// - .close()
-// - .readyState (compared against the static `OPEN` constant)
-//
-// We back the fake with EventEmitter so .on / .once / .removeListener all
-// behave correctly without re-implementing them.
-
-const { FakeWS } = vi.hoisted(() => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { EventEmitter: EE } = require("node:events") as typeof import("node:events");
-
- class FakeWSImpl extends EE {
- static readonly OPEN = 1;
- static readonly CLOSED = 3;
-
- readyState: number = 0;
- readonly url: string;
- readonly opts: Record<string, unknown>;
- readonly sent: string[] = [];
- closed = false;
-
- constructor(url: string, opts: Record<string, unknown> = {}) {
- super();
- this.url = url;
- this.opts = opts;
- FakeWSImpl.instances.push(this);
- }
-
- send(data: string): void {
- this.sent.push(data);
- }
-
- close(): void {
- this.closed = true;
- this.readyState = FakeWSImpl.CLOSED;
- setImmediate(() => this.emit("close"));
- }
-
- fireOpen(): void {
- this.readyState = FakeWSImpl.OPEN;
- this.emit("open");
- }
- fireMessage(frame: unknown): void {
- this.emit("message", JSON.stringify(frame));
- }
- fireError(err: Error): void {
- this.emit("error", err);
- }
- fireClose(): void {
- this.readyState = FakeWSImpl.CLOSED;
- this.emit("close");
- }
-
- static instances: FakeWSImpl[] = [];
- static reset(): void {
- FakeWSImpl.instances = [];
- }
- static latest(): FakeWSImpl {
- return FakeWSImpl.instances[FakeWSImpl.instances.length - 1]!;
- }
- }
-
- return { FakeWS: FakeWSImpl };
-});
-
-type FakeWST = InstanceType<typeof FakeWS>;
-
-vi.mock("ws", () => ({
- default: FakeWS,
- WebSocket: FakeWS,
-}));
-
-// ---------------------------------------------------------------------------
-// Set up a fake OPENCLAW_HOME with a discovery file so discoverGateway()
-// returns a known URL + token.
-// ---------------------------------------------------------------------------
-
-const { tmpHome, ORIGINAL_HOME, ORIGINAL_STATE } = ((): {
- tmpHome: string;
- ORIGINAL_HOME: string | undefined;
- ORIGINAL_STATE: string | undefined;
-} => {
- const origHome = process.env.OPENCLAW_HOME;
- const origState = process.env.OPENCLAW_STATE_DIR;
- const tmp = mkdtempSync(join(tmpdir(), "notfair-cmo-gateway-"));
- process.env.OPENCLAW_HOME = tmp;
- delete process.env.OPENCLAW_STATE_DIR;
- return { tmpHome: tmp, ORIGINAL_HOME: origHome, ORIGINAL_STATE: origState };
-})();
-
-function writeConfig(parsed: unknown): void {
- writeFileSync(join(tmpHome, "openclaw.json"), JSON.stringify(parsed), "utf8");
-}
-
-// Default config used by most tests.
-beforeAll(() => {
- writeConfig({
- gateway: {
- port: 7799,
- bind: "loopback",
- auth: { token: "tok-abc" },
- },
- });
-});
-
-afterAll(() => {
- try {
- rmSync(tmpHome, { recursive: true, force: true });
- } catch {}
- if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;
- else delete process.env.OPENCLAW_HOME;
- if (ORIGINAL_STATE) process.env.OPENCLAW_STATE_DIR = ORIGINAL_STATE;
-});
-
-// Late import so the env + mocks are in place.
-import {
- discoverGateway,
- GatewayClient,
- streamChatViaGateway,
-} from "./gateway-client";
-
-beforeEach(() => {
- // Don't reset between every test — the streamChatViaGateway singleton
- // retains a ws reference across tests. Individual GatewayClient tests
- // construct a fresh client + ws each time, so a stale instances list
- // is fine for them too (they call FakeWS.latest() after constructing).
-});
-
-// ---------------------------------------------------------------------------
-// discoverGateway
-// ---------------------------------------------------------------------------
-
-describe("discoverGateway", () => {
- it("reads port + token from openclaw.json (loopback default)", () => {
- const cfg = discoverGateway();
- expect(cfg.url).toBe("ws://127.0.0.1:7799");
- expect(cfg.token).toBe("tok-abc");
- expect(cfg.password).toBeUndefined();
- expect(cfg.configFile).toBe(join(tmpHome, "openclaw.json"));
- });
-
- it("prefers gateway.remote.url when present", () => {
- writeConfig({
- gateway: {
- port: 1,
- remote: { url: "wss://my-tailnet:9999 " },
- auth: { token: "remote-tok" },
- },
- });
- const cfg = discoverGateway();
- expect(cfg.url).toBe("wss://my-tailnet:9999");
- // Restore default config for downstream tests.
- writeConfig({
- gateway: { port: 7799, bind: "loopback", auth: { token: "tok-abc" } },
- });
- });
-
- it("uses 127.0.0.1 even on bind='lan' when remote.url is not set", () => {
- writeConfig({
- gateway: { port: 1234, bind: "lan", auth: { password: "pw" } },
- });
- const cfg = discoverGateway();
- expect(cfg.url).toBe("ws://127.0.0.1:1234");
- expect(cfg.token).toBeUndefined();
- expect(cfg.password).toBe("pw");
- writeConfig({
- gateway: { port: 7799, bind: "loopback", auth: { token: "tok-abc" } },
- });
- });
-
- it("throws when the config file does not exist", () => {
- const prev = process.env.OPENCLAW_HOME;
- const missing = mkdtempSync(join(tmpdir(), "notfair-cmo-missing-"));
- rmSync(missing, { recursive: true, force: true });
- process.env.OPENCLAW_HOME = missing;
- try {
- expect(() => discoverGateway()).toThrow(/OpenClaw config not found/);
- } finally {
- process.env.OPENCLAW_HOME = prev;
- }
- });
-
- it("throws when the config file is not JSON", () => {
- const bad = mkdtempSync(join(tmpdir(), "notfair-cmo-bad-"));
- process.env.OPENCLAW_HOME = bad;
- writeFileSync(join(bad, "openclaw.json"), "{ not valid", "utf8");
- try {
- expect(() => discoverGateway()).toThrow(/Could not parse/);
- } finally {
- process.env.OPENCLAW_HOME = tmpHome;
- rmSync(bad, { recursive: true, force: true });
- }
- });
-
- it("throws when gateway.port is missing/invalid and no remote.url", () => {
- writeConfig({ gateway: { bind: "loopback" } });
- try {
- expect(() => discoverGateway()).toThrow(/Could not read gateway\.port/);
- } finally {
- writeConfig({
- gateway: { port: 7799, bind: "loopback", auth: { token: "tok-abc" } },
- });
- }
- });
-
- it("respects OPENCLAW_STATE_DIR over OPENCLAW_HOME", () => {
- const state = mkdtempSync(join(tmpdir(), "notfair-cmo-state-"));
- writeFileSync(
- join(state, "openclaw.json"),
- JSON.stringify({
- gateway: { port: 5555, bind: "loopback", auth: {} },
- }),
- "utf8",
- );
- process.env.OPENCLAW_STATE_DIR = state;
- try {
- const cfg = discoverGateway();
- expect(cfg.url).toBe("ws://127.0.0.1:5555");
- expect(cfg.configFile).toBe(join(state, "openclaw.json"));
- } finally {
- delete process.env.OPENCLAW_STATE_DIR;
- rmSync(state, { recursive: true, force: true });
- }
- });
-});
-
-// ---------------------------------------------------------------------------
-// GatewayClient: open / connect handshake
-// ---------------------------------------------------------------------------
-
-describe("GatewayClient.open", () => {
- /**
- * Helper: drive a GatewayClient through the open handshake.
- * Returns the connected client + the underlying FakeWS so the test can
- * push more frames after.
- */
- async function openAndAck(): Promise<{ client: GatewayClient; ws: FakeWST }> {
- const client = new GatewayClient();
- const openP = client.open();
- // After microtasks, the constructor + ws creation should have happened.
- await tick();
- const ws = FakeWS.latest();
- ws.fireOpen();
- // Now the client sends the `connect` req frame. Pull it + ack.
- await tick();
- const reqRaw = ws.sent[0];
- expect(reqRaw).toBeDefined();
- const req = JSON.parse(reqRaw!) as { id: string; method: string };
- expect(req.method).toBe("connect");
- ws.fireMessage({ type: "res", id: req.id, ok: true, payload: { protocol: 4 } });
- await openP;
- return { client, ws };
- }
-
- it("constructs a WebSocket with the discovered URL", async () => {
- const { client, ws } = await openAndAck();
- expect(ws.url).toBe("ws://127.0.0.1:7799");
- // perMessageDeflate disabled + 5s handshake timeout (loopback is fast).
- expect(ws.opts.perMessageDeflate).toBe(false);
- expect(ws.opts.handshakeTimeout).toBe(5_000);
- expect(client.isOpen()).toBe(true);
- client.close();
- });
-
- it("uses opts.url / opts.token over discovery values", async () => {
- const client = new GatewayClient({
- url: "ws://override:1234",
- token: "ovr-tok",
- scopes: ["operator.read"],
- });
- const p = client.open();
- await tick();
- const ws = FakeWS.latest();
- expect(ws.url).toBe("ws://override:1234");
- ws.fireOpen();
- await tick();
- const req = JSON.parse(ws.sent[0]!) as {
- params: { auth?: { token?: string }; scopes?: string[] };
- };
- expect(req.params.auth?.token).toBe("ovr-tok");
- expect(req.params.scopes).toEqual(["operator.read"]);
- ws.fireMessage({
- type: "res",
- id: (JSON.parse(ws.sent[0]!) as { id: string }).id,
- ok: true,
- });
- await p;
- client.close();
- });
-
- it("open() is idempotent — second call resolves without a new socket", async () => {
- const { client, ws } = await openAndAck();
- const before = FakeWS.instances.length;
- await client.open();
- expect(FakeWS.instances.length).toBe(before);
- client.close();
- });
-
- it("concurrent open() calls share the same in-flight promise", async () => {
- const baseline = FakeWS.instances.length;
- const client = new GatewayClient();
- const a = client.open();
- const b = client.open();
- await tick();
- // Only one new socket should have been constructed.
- expect(FakeWS.instances.length - baseline).toBe(1);
- const ws = FakeWS.latest();
- ws.fireOpen();
- await tick();
- const id = (JSON.parse(ws.sent[0]!) as { id: string }).id;
- ws.fireMessage({ type: "res", id, ok: true });
- await Promise.all([a, b]);
- expect(client.isOpen()).toBe(true);
- client.close();
- });
-
- it("rejects when the socket errors before opening", async () => {
- const client = new GatewayClient();
- const p = client.open();
- await tick();
- const ws = FakeWS.latest();
- ws.fireError(new Error("conn refused"));
- await expect(p).rejects.toThrow(/conn refused/);
- expect(client.isOpen()).toBe(false);
- });
-});
-
-// ---------------------------------------------------------------------------
-// GatewayClient.request — pending / response routing
-// ---------------------------------------------------------------------------
-
-describe("GatewayClient.request", () => {
- async function openAndAck(): Promise<{ client: GatewayClient; ws: FakeWST }> {
- const client = new GatewayClient();
- const openP = client.open();
- await tick();
- const ws = FakeWS.latest();
- ws.fireOpen();
- await tick();
- const id = (JSON.parse(ws.sent[0]!) as { id: string }).id;
- ws.fireMessage({ type: "res", id, ok: true });
- await openP;
- return { client, ws };
- }
-
- it("resolves with payload when server returns ok:true", async () => {
- const { client, ws } = await openAndAck();
- const p = client.request("foo.bar", { x: 1 });
- await tick();
- const req = JSON.parse(ws.sent[ws.sent.length - 1]!) as {
- id: string;
- method: string;
- params: unknown;
- };
- expect(req.method).toBe("foo.bar");
- expect(req.params).toEqual({ x: 1 });
- ws.fireMessage({ type: "res", id: req.id, ok: true, payload: { hello: "world" } });
- await expect(p).resolves.toEqual({ hello: "world" });
- client.close();
- });
-
- it("rejects with formatted error message when ok:false", async () => {
- const { client, ws } = await openAndAck();
- const p = client.request("foo.bar");
- await tick();
- const id = (JSON.parse(ws.sent[ws.sent.length - 1]!) as { id: string }).id;
- ws.fireMessage({
- type: "res",
- id,
- ok: false,
- error: { code: "FORBIDDEN", message: "no", details: { why: "scope" } },
- });
- await expect(p).rejects.toThrow(/gateway error \(FORBIDDEN\): no/);
- await expect(p.catch((e) => (e as Error).message)).resolves.toMatch(
- /details=.*scope/,
- );
- client.close();
- });
-
- it("rejects with default UNKNOWN code when error envelope is missing fields", async () => {
- const { client, ws } = await openAndAck();
- const p = client.request("foo.bar");
- await tick();
- const id = (JSON.parse(ws.sent[ws.sent.length - 1]!) as { id: string }).id;
- ws.fireMessage({ type: "res", id, ok: false });
- await expect(p).rejects.toThrow(/gateway error \(UNKNOWN\): request failed/);
- client.close();
- });
-
- it("rejects request when socket is closed", async () => {
- const client = new GatewayClient();
- await expect(client.request("foo")).rejects.toThrow(/gateway not connected/);
- });
-
- it("rejects all pending requests on close event", async () => {
- const { client, ws } = await openAndAck();
- const a = client.request("a");
- const b = client.request("b");
- await tick();
- ws.fireClose();
- await Promise.all([
- expect(a).rejects.toThrow(/gateway connection closed/),
- expect(b).rejects.toThrow(/gateway connection closed/),
- ]);
- client.close();
- });
-
- it("ignores response frames for unknown ids (no crash)", async () => {
- const { client, ws } = await openAndAck();
- // Unmatched id — should silently noop.
- ws.fireMessage({ type: "res", id: "no-such-id", ok: true });
- // Subsequent legit request still works.
- const p = client.request("foo");
- await tick();
- const id = (JSON.parse(ws.sent[ws.sent.length - 1]!) as { id: string }).id;
- ws.fireMessage({ type: "res", id, ok: true, payload: 42 });
- await expect(p).resolves.toBe(42);
- client.close();
- });
-
- it("ignores frames that aren't valid JSON", async () => {
- const { client, ws } = await openAndAck();
- ws.emit("message", "{not json"); // direct emit bypasses fireMessage's stringify
- const p = client.request("foo");
- await tick();
- const id = (JSON.parse(ws.sent[ws.sent.length - 1]!) as { id: string }).id;
- ws.fireMessage({ type: "res", id, ok: true });
- await expect(p).resolves.toBeUndefined();
- client.close();
- });
-});
-
-// ---------------------------------------------------------------------------
-// Event listener dispatch
-// ---------------------------------------------------------------------------
-
-describe("GatewayClient.addEventListener", () => {
- async function openAndAck(): Promise<{ client: GatewayClient; ws: FakeWST }> {
- const client = new GatewayClient();
- const p = client.open();
- await tick();
- const ws = FakeWS.latest();
- ws.fireOpen();
- await tick();
- const id = (JSON.parse(ws.sent[0]!) as { id: string }).id;
- ws.fireMessage({ type: "res", id, ok: true });
- await p;
- return { client, ws };
- }
-
- it("dispatches event-typed frames to subscribers", async () => {
- const { client, ws } = await openAndAck();
- const received: unknown[] = [];
- const off = client.addEventListener((evt) => received.push(evt));
- ws.fireMessage({
- type: "event",
- event: "chat",
- payload: { hi: 1 },
- });
- expect(received).toHaveLength(1);
- off();
- ws.fireMessage({ type: "event", event: "chat", payload: { hi: 2 } });
- expect(received).toHaveLength(1);
- client.close();
- });
-
- it("swallows listener throws so other listeners still see the frame", async () => {
- const { client, ws } = await openAndAck();
- const a = vi.fn().mockImplementation(() => {
- throw new Error("listener exploded");
- });
- const b = vi.fn();
- client.addEventListener(a);
- client.addEventListener(b);
- // Silence the console.error call from the SUT's catch block.
- const spy = vi.spyOn(console, "error").mockImplementation(() => {});
- try {
- ws.fireMessage({ type: "event", event: "chat", payload: {} });
- } finally {
- spy.mockRestore();
- }
- expect(a).toHaveBeenCalled();
- expect(b).toHaveBeenCalled();
- client.close();
- });
-
- it("filters out connect.challenge events (device-auth, not for loopback)", async () => {
- const { client, ws } = await openAndAck();
- const seen: unknown[] = [];
- client.addEventListener((e) => seen.push(e.event));
- ws.fireMessage({ type: "event", event: "connect.challenge", payload: {} });
- ws.fireMessage({ type: "event", event: "chat", payload: {} });
- expect(seen).toEqual(["chat"]);
- client.close();
- });
-});
-
-// ---------------------------------------------------------------------------
-// close() cleanup
-// ---------------------------------------------------------------------------
-
-describe("GatewayClient.close", () => {
- it("clears listeners + pending + nulls out ws", async () => {
- const client = new GatewayClient();
- const p = client.open();
- await tick();
- const ws = FakeWS.latest();
- ws.fireOpen();
- await tick();
- const id = (JSON.parse(ws.sent[0]!) as { id: string }).id;
- ws.fireMessage({ type: "res", id, ok: true });
- await p;
-
- expect(client.isOpen()).toBe(true);
- client.close();
- expect(client.isOpen()).toBe(false);
- // After close, request rejects.
- await expect(client.request("x")).rejects.toThrow(/not connected/);
- });
-
- it("close() is safe to call before open()", () => {
- const client = new GatewayClient();
- expect(() => client.close()).not.toThrow();
- expect(client.isOpen()).toBe(false);
- });
-});
-
-// ---------------------------------------------------------------------------
-// streamChatViaGateway (high-level helper)
-// ---------------------------------------------------------------------------
-
-describe("streamChatViaGateway", () => {
- // The streaming helper uses a process-singleton client. Tests must NOT
- // assume a clean slate between runs — but since each test issues its own
- // chat.send and aborts shortly after, the shared client just gets reused.
- //
- // To exercise the singleton end-to-end without timing flakes, each test
- // here aborts immediately after a few frames so the generator terminates.
-
- /**
- * Returns an iteration wrapper that handles the gotcha of starting an
- * async generator: gen.next() must be called to begin execution, but
- * its returned value is the first yielded event. We capture it and
- * surface it via `events()` so tests see ALL events.
- */
- async function bootstrapStream(input: {
- sessionKey: string;
- message: string;
- signal?: AbortSignal;
- }): Promise<{
- ws: FakeWST;
- /** Drains the generator and returns all yielded events. */
- drain: () => Promise<unknown[]>;
- sendReqId: string;
- }> {
- const baselineCount = FakeWS.instances.length;
- const gen = streamChatViaGateway(input) as AsyncGenerator<unknown, void, void>;
- // Start the generator (this also triggers the chat.send req). We hold the
- // promise so the first yielded event isn't dropped.
- const firstResultPromise = gen.next();
- // Allow the singleton bootstrap to run if needed.
- await tick();
- let ws: FakeWST;
- if (FakeWS.instances.length > baselineCount) {
- ws = FakeWS.latest();
- ws.fireOpen();
- await tick();
- const connectId = (JSON.parse(ws.sent[0]!) as { id: string }).id;
- ws.fireMessage({ type: "res", id: connectId, ok: true });
- await tick();
- } else {
- ws = FakeWS.latest();
- }
- const lastSent = ws.sent[ws.sent.length - 1]!;
- const sendReqId = (JSON.parse(lastSent) as { id: string }).id;
-
- const drain = async (): Promise<unknown[]> => {
- const out: unknown[] = [];
- const first = await firstResultPromise;
- if (!first.done) out.push(first.value);
- // Now iterate the rest.
- for (;;) {
- const r = await gen.next();
- if (r.done) break;
- out.push(r.value);
- }
- return out;
- };
- return { ws, drain, sendReqId };
- }
-
- it("yields delta + final events when chat state goes final", async () => {
- const ac = new AbortController();
- const { ws, drain, sendReqId } = await bootstrapStream({
- sessionKey: "session-A",
- message: "hi",
- signal: ac.signal,
- });
- ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });
- ws.fireMessage({
- type: "event",
- event: "chat",
- payload: {
- sessionKey: "session-A",
- state: "delta",
- message: { content: [{ type: "text", text: "hello" }] },
- },
- });
- ws.fireMessage({
- type: "event",
- event: "chat",
- payload: {
- sessionKey: "session-A",
- state: "final",
- message: { content: [{ type: "text", text: "hello world" }] },
- },
- });
-
- const out = await drain();
- const kinds = out.map((e) => (e as { kind: string }).kind);
- expect(kinds).toContain("delta");
- expect(kinds).toContain("final");
- const finalEv = out.find((e) => (e as { kind: string }).kind === "final") as {
- text: string;
- };
- expect(finalEv.text).toBe("hello world");
- });
-
- it("ignores events for a different sessionKey", async () => {
- const { ws, drain, sendReqId } = await bootstrapStream({
- sessionKey: "session-B",
- message: "hi",
- });
- ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });
- ws.fireMessage({
- type: "event",
- event: "chat",
- payload: {
- sessionKey: "other-session",
- state: "delta",
- message: { content: [{ type: "text", text: "should be ignored" }] },
- },
- });
- // Final for our session with content (so we don't hit the chat.history
- // fallback that retries for ~640ms).
- ws.fireMessage({
- type: "event",
- event: "chat",
- payload: {
- sessionKey: "session-B",
- state: "final",
- message: { content: [{ type: "text", text: "ours" }] },
- },
- });
-
- const out = await drain();
- const finalEv = out.find((e) => (e as { kind: string }).kind === "final") as {
- text: string;
- };
- expect(finalEv).toBeDefined();
- expect(finalEv.text).toBe("ours");
- // None of the deltas should contain "should be ignored".
- const deltas = out
- .filter((e) => (e as { kind: string }).kind === "delta")
- .map((e) => (e as { text: string }).text)
- .join("");
- expect(deltas).not.toContain("should be ignored");
- });
-
- it("emits tool events with phase + name + label", async () => {
- const { ws, drain, sendReqId } = await bootstrapStream({
- sessionKey: "session-C",
- message: "hi",
- });
- ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });
-
- ws.fireMessage({
- type: "event",
- event: "agent",
- payload: {
- sessionKey: "session-C",
- stream: "tool",
- data: {
- phase: "start",
- name: "exec",
- toolCallId: "tc-1",
- args: { command: "pnpm test" },
- },
- },
- });
- ws.fireMessage({
- type: "event",
- event: "agent",
- payload: {
- sessionKey: "session-C",
- stream: "tool",
- data: { phase: "result", name: "exec", toolCallId: "tc-1" },
- },
- });
- ws.fireMessage({
- type: "event",
- event: "chat",
- payload: {
- sessionKey: "session-C",
- state: "final",
- message: { content: [{ type: "text", text: "done" }] },
- },
- });
-
- const out = await drain();
- const toolEvs = out.filter((e) => (e as { kind: string }).kind === "tool") as Array<{
- phase: string;
- label?: string;
- }>;
- expect(toolEvs.length).toBe(2);
- expect(toolEvs[0]!.phase).toBe("start");
- expect(toolEvs[0]!.label).toBe("pnpm test");
- expect(toolEvs[1]!.phase).toBe("result");
- });
-
- it("emits lifecycle events from data.phase and payload.state", async () => {
- const { ws, drain, sendReqId } = await bootstrapStream({
- sessionKey: "session-D",
- message: "hi",
- });
- ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });
-
- ws.fireMessage({
- type: "event",
- event: "agent",
- payload: {
- sessionKey: "session-D",
- stream: "lifecycle",
- data: { phase: "start" },
- },
- });
- ws.fireMessage({
- type: "event",
- event: "agent",
- payload: {
- sessionKey: "session-D",
- stream: "lifecycle",
- state: "end",
- },
- });
- ws.fireMessage({
- type: "event",
- event: "chat",
- payload: {
- sessionKey: "session-D",
- state: "final",
- message: { content: [{ type: "text", text: "done" }] },
- },
- });
-
- const out = await drain();
- const lifecycle = (out.filter((e) => (e as { kind: string }).kind === "lifecycle") as Array<{
- phase: string;
- }>).map((e) => e.phase);
- expect(lifecycle).toEqual(["start", "end"]);
- });
-
- it("coalesces assistant deltas + replace into a monotonic stream", async () => {
- const { ws, drain, sendReqId } = await bootstrapStream({
- sessionKey: "session-E",
- message: "hi",
- });
- ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });
-
- ws.fireMessage({
- type: "event",
- event: "agent",
- payload: {
- sessionKey: "session-E",
- stream: "assistant",
- data: { delta: "Hel" },
- },
- });
- ws.fireMessage({
- type: "event",
- event: "agent",
- payload: {
- sessionKey: "session-E",
- stream: "assistant",
- data: { delta: "lo" },
- },
- });
- ws.fireMessage({
- type: "event",
- event: "agent",
- payload: {
- sessionKey: "session-E",
- stream: "assistant",
- data: { replace: true, text: "Hello world" },
- },
- });
- ws.fireMessage({
- type: "event",
- event: "chat",
- payload: {
- sessionKey: "session-E",
- state: "final",
- message: { content: [{ type: "text", text: "Hello world" }] },
- },
- });
-
- const out = await drain();
- const text = (out.filter((e) => (e as { kind: string }).kind === "delta") as Array<{
- text: string;
- }>)
- .map((e) => e.text)
- .join("");
- expect(text).toBe("Hello world");
- });
-
- it("aborts via signal: fires chat.abort and terminates", async () => {
- const ac = new AbortController();
- const { ws, drain } = await bootstrapStream({
- sessionKey: "session-F",
- message: "hi",
- signal: ac.signal,
- });
- const sentBefore = ws.sent.length;
- ac.abort();
- const out = await drain();
- expect(out).toBeDefined();
- // The abort path sends a chat.abort request (we don't bother to ack it).
- expect(ws.sent.length).toBeGreaterThan(sentBefore);
- const lastSent = JSON.parse(ws.sent[ws.sent.length - 1]!) as { method: string };
- expect(lastSent.method).toBe("chat.abort");
- });
-
- it("emits error event when chat.send is rejected by the gateway", async () => {
- const { ws, drain, sendReqId } = await bootstrapStream({
- sessionKey: "session-G",
- message: "hi",
- });
- ws.fireMessage({
- type: "res",
- id: sendReqId,
- ok: false,
- error: { code: "RATE_LIMITED", message: "slow down" },
- });
-
- const out = await drain();
- const errEv = out.find((e) => (e as { kind: string }).kind === "error") as {
- message: string;
- };
- expect(errEv).toBeDefined();
- expect(errEv.message).toMatch(/RATE_LIMITED/);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-/** Advance microtasks + immediate timers. */
-function tick(): Promise<void> {
- return new Promise((r) => setImmediate(r));
-}
-
-afterEach(() => {
- // Nothing to clean up beyond resetting fake WS — singleton from
- // streamChatViaGateway is intentionally retained.
-});
diff --git a/notfair-cmo/src/server/openclaw/gateway-client.ts b/notfair-cmo/src/server/openclaw/gateway-client.ts
deleted file mode 100644
index ae948207..00000000
--- a/notfair-cmo/src/server/openclaw/gateway-client.ts
+++ /dev/null
@@ -1,728 +0,0 @@
-import { existsSync, readFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { randomUUID } from "node:crypto";
-import WebSocket from "ws";
-
-/**
- * Minimal OpenClaw Gateway WebSocket client for streaming chat.
- *
- * Wire protocol (lifted from openclaw/openclaw `ui/src/ui/gateway.ts`):
- * - Open WS to ws://<host>:<port>
- * - Server may emit `event: connect.challenge` with a nonce; we ignore for
- * token-only auth on loopback.
- * - Client sends `{ type: "req", id, method: "connect", params: {...} }`
- * with auth.token; server replies `{ type: "res", ok: true, payload: helloOk }`.
- * - All requests use `{ type: "req", id, method, params }` and receive
- * `{ type: "res", id, ok, payload?, error? }`.
- * - Streaming chat tokens arrive as `{ type: "event", event: "chat", payload }`
- * events; payload includes { runId, sessionKey, state, deltaText, message }.
- *
- * URL + token discovery: read OpenClaw's own config file. We never hard-code
- * port or host — the user's `~/.openclaw/openclaw.json` (or
- * `OPENCLAW_STATE_DIR`/profile path) is the source of truth.
- */
-
-// --- Discovery ---
-
-export type GatewayConfig = {
- url: string; // ws://host:port
- token?: string;
- password?: string;
- configFile: string;
-};
-
-function resolveConfigFile(): string {
- const dir =
- process.env.OPENCLAW_STATE_DIR?.trim() ||
- process.env.OPENCLAW_HOME?.trim() ||
- join(homedir(), ".openclaw");
- return join(dir, "openclaw.json");
-}
-
-export function discoverGateway(): GatewayConfig {
- const configFile = resolveConfigFile();
- if (!existsSync(configFile)) {
- throw new Error(
- `OpenClaw config not found at ${configFile}. Is OpenClaw installed and configured?`,
- );
- }
- let parsed: Record<string, unknown>;
- try {
- parsed = JSON.parse(readFileSync(configFile, "utf8")) as Record<string, unknown>;
- } catch (err) {
- throw new Error(
- `Could not parse ${configFile}: ${err instanceof Error ? err.message : String(err)}`,
- );
- }
-
- const gateway = (parsed.gateway ?? {}) as Record<string, unknown>;
-
- // Prefer remote URL if user configured one; otherwise build from port + bind.
- const remote = (gateway.remote ?? {}) as Record<string, unknown>;
- const remoteUrl = typeof remote.url === "string" ? remote.url.trim() : "";
- let url = remoteUrl;
-
- if (!url) {
- const port = Number(gateway.port);
- if (!Number.isFinite(port) || port <= 0) {
- throw new Error(`Could not read gateway.port from ${configFile}`);
- }
- const bind = typeof gateway.bind === "string" ? gateway.bind : "loopback";
- // For loopback/auto, connect to 127.0.0.1. For lan/tailnet, the user
- // typically also sets gateway.remote.url; if not, loopback is the safest
- // local default.
- const host = bind === "lan" || bind === "tailnet" ? "127.0.0.1" : "127.0.0.1";
- url = `ws://${host}:${port}`;
- }
-
- const auth = (gateway.auth ?? {}) as Record<string, unknown>;
- const token = typeof auth.token === "string" && auth.token.length > 0 ? auth.token : undefined;
- const password =
- typeof auth.password === "string" && auth.password.length > 0 ? auth.password : undefined;
-
- return { url, token, password, configFile };
-}
-
-// --- Frame types ---
-
-type ReqFrame = { type: "req"; id: string; method: string; params?: unknown };
-type ResFrame = {
- type: "res";
- id: string;
- ok: boolean;
- payload?: unknown;
- error?: { code: string; message: string; details?: unknown };
-};
-type EventFrame = { type: "event"; event: string; payload?: unknown; seq?: number };
-type AnyFrame = ResFrame | EventFrame | { type: string; [k: string]: unknown };
-
-// Wide protocol range so the gateway picks whatever it supports. Older
-// installs speak protocol 3; newer ones speak 4+. The server returns the
-// chosen version in hello-ok.
-const CLIENT_MIN_PROTOCOL = 2 as const;
-const CLIENT_MAX_PROTOCOL = 10 as const;
-
-export type GatewayConnectOptions = {
- /** override discovery. */
- url?: string;
- token?: string;
- password?: string;
- /** scopes to request; default operator.read + write (enough for chat.send). */
- scopes?: string[];
-};
-
-export class GatewayClient {
- private ws: WebSocket | null = null;
- private pending = new Map<
- string,
- { resolve: (v: unknown) => void; reject: (err: Error) => void }
- >();
- private eventListeners = new Set<(evt: EventFrame) => void>();
- private connected = false;
- private connectPromise: Promise<void> | null = null;
- private readonly cfg: GatewayConfig;
- private readonly scopes: string[];
-
- constructor(opts: GatewayConnectOptions = {}) {
- const discovered = discoverGateway();
- this.cfg = {
- url: opts.url ?? discovered.url,
- token: opts.token ?? discovered.token,
- password: opts.password ?? discovered.password,
- configFile: discovered.configFile,
- };
- // Local single-user app; default to admin so config mutations (skills.update,
- // crons CRUD) work without per-call scope juggling.
- this.scopes = opts.scopes ?? [
- "operator.read",
- "operator.write",
- "operator.admin",
- ];
- }
-
- /** Open + connect, idempotent. */
- async open(): Promise<void> {
- if (this.connected) return;
- if (this.connectPromise) return this.connectPromise;
- this.connectPromise = this.openInternal().finally(() => {
- this.connectPromise = null;
- });
- return this.connectPromise;
- }
-
- private async openInternal(): Promise<void> {
- const ws = new WebSocket(this.cfg.url, {
- perMessageDeflate: false,
- handshakeTimeout: 5_000,
- });
- this.ws = ws;
-
- await new Promise<void>((resolve, reject) => {
- const onErr = (err: Error) => reject(err);
- ws.once("error", onErr);
- ws.once("open", () => {
- ws.removeListener("error", onErr);
- resolve();
- });
- });
-
- ws.on("message", (raw) => this.handleMessage(String(raw)));
- ws.on("close", () => {
- this.connected = false;
- for (const p of this.pending.values()) {
- p.reject(new Error("gateway connection closed"));
- }
- this.pending.clear();
- });
- ws.on("error", () => {
- // Errors after open propagate via close.
- });
-
- // Send connect frame and wait for hello-ok payload.
- await this.request("connect", {
- minProtocol: CLIENT_MIN_PROTOCOL,
- maxProtocol: CLIENT_MAX_PROTOCOL,
- client: {
- id: "gateway-client",
- version: "0.1.0",
- platform: process.platform,
- mode: "backend",
- instanceId: process.pid.toString(),
- },
- role: "operator",
- scopes: this.scopes,
- // "tool-events" opts us into the tool-event broadcast stream. Without
- // this, the gateway gates those frames per `server-methods/chat.ts`
- // (`registerToolEventRecipient` only fires when the cap is present), so
- // the whole `stream:"tool"` channel goes dark — even though everything
- // else (assistant deltas, lifecycle, chat) still arrives.
- caps: ["tool-events"],
- ...(this.cfg.token || this.cfg.password
- ? { auth: { token: this.cfg.token, password: this.cfg.password } }
- : {}),
- userAgent: `notfair-cmo/0.1.0 node/${process.versions.node}`,
- locale: "en-US",
- });
- this.connected = true;
- }
-
- close(): void {
- this.connected = false;
- try {
- this.ws?.close();
- } catch {}
- this.ws = null;
- this.pending.clear();
- this.eventListeners.clear();
- }
-
- isOpen(): boolean {
- return this.connected && !!this.ws && this.ws.readyState === WebSocket.OPEN;
- }
-
- request<T = unknown>(method: string, params?: unknown): Promise<T> {
- const ws = this.ws;
- if (!ws || ws.readyState !== WebSocket.OPEN) {
- return Promise.reject(new Error("gateway not connected"));
- }
- const id = randomUUID();
- const frame: ReqFrame = { type: "req", id, method, params };
- return new Promise<T>((resolve, reject) => {
- this.pending.set(id, {
- resolve: (v) => resolve(v as T),
- reject,
- });
- ws.send(JSON.stringify(frame));
- });
- }
-
- addEventListener(listener: (evt: EventFrame) => void): () => void {
- this.eventListeners.add(listener);
- return () => this.eventListeners.delete(listener);
- }
-
- private handleMessage(raw: string): void {
- let parsed: AnyFrame;
- try {
- parsed = JSON.parse(raw) as AnyFrame;
- } catch {
- return;
- }
- if (parsed.type === "res") {
- const res = parsed as ResFrame;
- const p = this.pending.get(res.id);
- if (!p) return;
- this.pending.delete(res.id);
- if (res.ok) p.resolve(res.payload);
- else {
- const detailsStr = res.error?.details
- ? ` details=${JSON.stringify(res.error.details).slice(0, 300)}`
- : "";
- p.reject(
- new Error(
- `gateway error (${res.error?.code ?? "UNKNOWN"}): ${res.error?.message ?? "request failed"}${detailsStr}`,
- ),
- );
- }
- return;
- }
- if (parsed.type === "event") {
- const evt = parsed as EventFrame;
- // connect.challenge is for device auth; we don't use it on loopback +
- // shared-token. Safe to ignore.
- if (evt.event === "connect.challenge") return;
- for (const listener of this.eventListeners) {
- try {
- listener(evt);
- } catch (err) {
- console.error("[gateway-client] event listener error:", err);
- }
- }
- }
- }
-}
-
-// --- High-level streaming chat helper ---
-
-export type StreamChatInput = {
- sessionKey: string;
- sessionId?: string;
- message: string;
- /** Cancellation signal. When aborted, we issue chat.abort and stop. */
- signal?: AbortSignal;
- /** Optional profiler — caller passes a ChatPerf to receive timing marks. */
- perf?: ChatPerf;
-};
-
-export type ChatPerf = {
- mark(name: string): void;
-};
-
-export type ChatStreamEvent =
- | { kind: "delta"; text: string }
- | {
- kind: "tool";
- /**
- * OpenClaw emits start → (update*) → result for each tool invocation.
- * We surface all three so the UI can show in-progress + final state.
- */
- phase: "start" | "update" | "result";
- /** Stable id per tool invocation; lets the UI update the right row. */
- toolCallId: string;
- /** Raw tool name (e.g. "exec", "read", "edit", or "mcp:foo.bar"). */
- name: string;
- /**
- * Human-readable one-liner the UI shows next to the tool name
- * (e.g. command for exec, path for read/write). Pre-computed on the
- * server so the client doesn't need to know every tool's args shape.
- */
- label?: string;
- }
- | {
- kind: "lifecycle";
- /** "start" | "end" | "error" — useful for UI heartbeat / "agent is working". */
- phase: string;
- }
- | { kind: "final"; text: string }
- | { kind: "error"; message: string };
-
-/**
- * Process-wide singleton gateway client.
- *
- * Why: opening a fresh WebSocket per chat turn was costing ~10-30 ms for the
- * TCP+WS handshake plus a `connect`/hello round-trip (see `[chat-perf]`
- * traces). Reusing one connection across turns eliminates that overhead.
- *
- * Resilience: if the underlying socket closes (OpenClaw restarted), `isOpen()`
- * returns false and we lazily reconnect on the next call.
- */
-let sharedClient: GatewayClient | null = null;
-let sharedClientPromise: Promise<GatewayClient> | null = null;
-
-/**
- * Returns the shared singleton gateway client, lazily creating it on first
- * call. The promise cache makes concurrent callers await the SAME in-flight
- * connect — without it, two callers arriving before the first open()
- * completes would each create a fresh GatewayClient, opening two WebSockets
- * and racing each other's connect handshake against the OpenClaw gateway
- * (which rejects any frame before a connect with "invalid handshake: first
- * request must be connect"). React StrictMode double-mounting client
- * effects in Next dev was the easiest reproducer.
- */
-async function getSharedClient(): Promise<GatewayClient> {
- if (sharedClient && sharedClient.isOpen()) return sharedClient;
- if (sharedClientPromise) return sharedClientPromise;
- sharedClientPromise = (async () => {
- const candidate = new GatewayClient();
- try {
- await candidate.open();
- sharedClient = candidate;
- return candidate;
- } finally {
- sharedClientPromise = null;
- }
- })();
- return sharedClientPromise;
-}
-
-/**
- * Stream a chat turn from OpenClaw. Yields incremental delta text events as
- * the agent produces tokens, then a final event with the full text once done.
- *
- * Three text channels are coalesced into a single monotonically-growing
- * transcript and surfaced as delta events:
- * 1. `event: "agent"`, `stream: "assistant"` — true token-by-token streaming
- * from providers that support it. Carries `data.delta` (incremental) or
- * `data.text` (full text-so-far when `replace: true`).
- * 2. `event: "chat"`, `state: "delta"` — provider-buffered streaming with
- * the merged text in `message.content[0].text`.
- * 3. `chat.history` fallback — for deltaless providers (codex/gpt-5.5) the
- * assistant text only appears in the persisted transcript. After the
- * terminal `chat` event we poll `chat.history` until an assistant message
- * timestamped at-or-after `turnStartedAt` shows up.
- */
-export async function* streamChatViaGateway(
- input: StreamChatInput,
-): AsyncGenerator<ChatStreamEvent, void, void> {
- const perf = input.perf;
- perf?.mark("gw_open_start");
- let client: GatewayClient;
- try {
- client = await getSharedClient();
- } catch (err) {
- // First-time failure means the cached null instance is fine — the next
- // call will retry. Surface error to the caller.
- sharedClient = null;
- throw err;
- }
- perf?.mark("gw_open_end");
-
- const runId = randomUUID();
- const turnStartedAt = Date.now();
- const events: ChatStreamEvent[] = [];
- let done = false;
- let lastEmittedLen = 0;
- let resolveWait: (() => void) | null = null;
- let firstEventSeen = false;
- let firstDeltaEmitted = false;
- // Per-channel "first event" marks so the perf trace shows which OpenClaw
- // stream type unblocked the user. Helps attribute latency to the model
- // (first tool start / text) vs. plumbing (first lifecycle event).
- let firstLifecycleSeen = false;
- let firstToolStartSeen = false;
-
- const wake = () => {
- if (resolveWait) {
- const r = resolveWait;
- resolveWait = null;
- r();
- }
- };
-
- // Helper: emit a delta consisting of the suffix beyond what we've already
- // shown the client. Coalesces text coming from agent-stream events (live
- // tokens), chat-state delta events (provider-buffered), and the final
- // chat.history fallback into a single monotonically-growing transcript.
- const emitMergedText = (merged: string) => {
- if (merged.length <= lastEmittedLen) return;
- const delta = merged.slice(lastEmittedLen);
- lastEmittedLen = merged.length;
- if (!firstDeltaEmitted) {
- firstDeltaEmitted = true;
- perf?.mark("gw_first_delta");
- }
- events.push({ kind: "delta", text: delta });
- wake();
- };
-
- // Agent text deltas: OpenClaw streams live assistant tokens via
- // `event: "agent"` with `stream: "assistant"`, payload.data.delta = the new
- // characters. Older bursts (e.g., the first chunk on a deltaless provider)
- // arrive as data.text containing the full text-so-far instead. Handle both.
- let agentAssistantBuffer = "";
-
- const unsubscribe = client.addEventListener((evt) => {
- const payload = evt.payload as
- | {
- runId?: string;
- sessionKey?: string;
- stream?: string;
- state?: string;
- deltaText?: string;
- replace?: boolean;
- data?: {
- delta?: string;
- text?: string;
- replace?: boolean;
- phase?: string;
- name?: string;
- toolCallId?: string;
- args?: unknown;
- };
- message?: { content?: Array<{ type?: string; text?: string }> };
- }
- | undefined;
- if (!payload) return;
- // Filter by sessionKey, not runId: OpenClaw's tool/lifecycle/assistant
- // events carry the *engine* runId, which is distinct from the
- // idempotencyKey we pass in chat.send. Per the OpenClaw web UI
- // (`ui/src/ui/app-tool-stream.ts`), session is the only reliable key.
- // Runs are serialized per session, so only one turn is in flight here.
- if (payload.sessionKey && payload.sessionKey !== input.sessionKey) return;
-
- if (!firstEventSeen) {
- firstEventSeen = true;
- perf?.mark("gw_first_event");
- }
-
- if (evt.event === "agent" && payload.stream === "tool") {
- const d = payload.data ?? {};
- const toolCallId = typeof d.toolCallId === "string" ? d.toolCallId : "";
- if (!toolCallId) return;
- const phase = d.phase === "start" || d.phase === "update" || d.phase === "result"
- ? d.phase
- : null;
- if (!phase) return;
- const name = typeof d.name === "string" ? d.name : "tool";
- const label = phase === "start" ? labelForTool(name, d.args) : undefined;
- if (phase === "start" && !firstToolStartSeen) {
- firstToolStartSeen = true;
- perf?.mark("gw_first_tool_start");
- }
- events.push({ kind: "tool", phase, toolCallId, name, label });
- wake();
- return;
- }
-
- if (evt.event === "agent" && payload.stream === "lifecycle") {
- const d = payload.data ?? {};
- const phase = typeof d.phase === "string" ? d.phase : payload.state;
- if (phase) {
- if (!firstLifecycleSeen) {
- firstLifecycleSeen = true;
- perf?.mark("gw_first_lifecycle");
- }
- events.push({ kind: "lifecycle", phase });
- wake();
- }
- return;
- }
-
- if (evt.event === "agent" && payload.stream === "assistant") {
- const d = payload.data ?? {};
- if (d.replace === true && typeof d.text === "string") {
- agentAssistantBuffer = d.text;
- } else if (typeof d.delta === "string") {
- agentAssistantBuffer = agentAssistantBuffer + d.delta;
- } else if (typeof d.text === "string" && d.text.length > agentAssistantBuffer.length) {
- agentAssistantBuffer = d.text;
- }
- emitMergedText(agentAssistantBuffer);
- return;
- }
-
- if (evt.event !== "chat") return;
-
- const merged = extractText(payload.message?.content);
- emitMergedText(merged);
-
- if (payload.state === "final" || payload.state === "complete") {
- perf?.mark("gw_final");
- // If nothing was streamed (deltaless provider AND empty final.message),
- // fall back to chat.history to pull the persisted assistant reply so
- // the user actually sees the text.
- if (lastEmittedLen === 0) {
- fetchHistoryFallback(client, input.sessionKey, turnStartedAt)
- .then((text) => {
- if (text && text.length > 0) emitMergedText(text);
- })
- .catch(() => {})
- .finally(() => {
- events.push({ kind: "final", text: merged });
- done = true;
- wake();
- });
- } else {
- events.push({ kind: "final", text: merged });
- done = true;
- wake();
- }
- }
- });
-
- // Wire abort: best-effort chat.abort + bail out.
- const onAbort = () => {
- void client.request("chat.abort", { sessionKey: input.sessionKey, runId }).catch(() => {});
- done = true;
- wake();
- };
- if (input.signal) {
- if (input.signal.aborted) onAbort();
- else input.signal.addEventListener("abort", onAbort, { once: true });
- }
-
- try {
- // Fire the request. The promise resolves quickly with the runId-or-ack
- // payload; streaming text arrives as events.
- perf?.mark("gw_chat_send_start");
- void client
- .request("chat.send", {
- sessionKey: input.sessionKey,
- ...(input.sessionId ? { sessionId: input.sessionId } : {}),
- message: input.message,
- deliver: false,
- idempotencyKey: runId,
- })
- .then(() => {
- perf?.mark("gw_chat_send_ack");
- })
- .catch((err: Error) => {
- events.push({ kind: "error", message: err.message });
- done = true;
- wake();
- });
-
- while (!done || events.length > 0) {
- while (events.length > 0) {
- yield events.shift()!;
- }
- if (done) break;
- await new Promise<void>((resolve) => {
- resolveWait = resolve;
- // Safety: time-bounded wait so we never hang forever if events stop.
- setTimeout(() => {
- if (resolveWait === resolve) {
- resolveWait = null;
- resolve();
- }
- }, 30_000);
- });
- }
- } finally {
- unsubscribe();
- if (input.signal) input.signal.removeEventListener("abort", onAbort);
- // Do NOT close the shared client — subsequent turns reuse it.
- }
-}
-
-/**
- * Compress a tool invocation's args into a single human-readable label.
- * Matches the spirit of OpenClaw's menu-bar status text (`exec: pnpm test`,
- * `read: apps/foo.ts`) so the chat UI feels familiar to anyone who's seen
- * the desktop app. Falls back to the bare tool name when nothing useful
- * can be extracted.
- */
-function labelForTool(name: string, args: unknown): string | undefined {
- if (!args || typeof args !== "object") return undefined;
- const a = args as Record<string, unknown>;
- // exec / shell: show the first line of the command
- const cmd = pickString(a, ["command", "cmd", "script"]);
- if (cmd) return firstLine(cmd);
- // file ops: show the path
- const path = pickString(a, ["path", "file_path", "filename", "file"]);
- if (path) return shortenPath(path);
- // web fetches: show the URL
- const url = pickString(a, ["url", "uri"]);
- if (url) return url;
- // MCP / generic: show a method or query if present
- const method = pickString(a, ["method", "tool", "operation"]);
- if (method) return method;
- const query = pickString(a, ["query", "q", "prompt"]);
- if (query) return truncate(query, 120);
- // Last resort: stringify the args (capped) so the user sees *something*.
- try {
- const json = JSON.stringify(a);
- return truncate(json, 120);
- } catch {
- return undefined;
- }
-}
-
-function pickString(obj: Record<string, unknown>, keys: string[]): string | null {
- for (const k of keys) {
- const v = obj[k];
- if (typeof v === "string" && v.trim().length > 0) return v.trim();
- }
- return null;
-}
-
-function firstLine(s: string): string {
- const nl = s.indexOf("\n");
- const line = nl >= 0 ? s.slice(0, nl) : s;
- return truncate(line, 160);
-}
-
-function shortenPath(p: string): string {
- // Keep filename + one parent dir to stay informative without taking up
- // a whole row — matches the menu-bar app's heuristic.
- const segs = p.split("/");
- if (segs.length <= 2) return p;
- return `…/${segs[segs.length - 2]}/${segs[segs.length - 1]}`;
-}
-
-function truncate(s: string, n: number): string {
- return s.length > n ? `${s.slice(0, n - 1)}…` : s;
-}
-
-function extractText(content: Array<{ type?: string; text?: string }> | undefined): string {
- if (!Array.isArray(content)) return "";
- return content
- .filter((c) => c?.type === "text" && typeof c.text === "string")
- .map((c) => c.text as string)
- .join("");
-}
-
-/**
- * On terminal `chat` events with empty content (codex and other deltaless
- * providers), the assistant reply lives only in the persisted transcript.
- * The OpenClaw web UI handles this by calling `chat.history` after the final
- * event, and so do we — but transcript persistence happens asynchronously,
- * milliseconds after the final event fires, so a naive call returns the
- * previous turn's reply. Retry briefly until we see an assistant message
- * whose timestamp is at or after `notBefore` (the moment we sent the turn).
- *
- * Returns "" if no fresh assistant message appears within the retry budget.
- */
-async function fetchHistoryFallback(
- client: GatewayClient,
- sessionKey: string,
- notBefore: number,
-): Promise<string> {
- type HistoryMessage = {
- role?: string;
- content?: Array<{ type?: string; text?: string }>;
- text?: string;
- timestamp?: number;
- };
- type HistoryResponse = { messages?: HistoryMessage[] };
-
- const findLatestAssistant = (msgs: HistoryMessage[]) => {
- for (let i = msgs.length - 1; i >= 0; i--) {
- const m = msgs[i];
- if (m?.role !== "assistant") continue;
- const text = extractText(m.content) || (typeof m.text === "string" ? m.text : "");
- if (!text.trim()) continue;
- return { text, timestamp: typeof m.timestamp === "number" ? m.timestamp : 0 };
- }
- return null;
- };
-
- const MAX_ATTEMPTS = 8;
- const DELAY_MS = 80;
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
- try {
- const res = (await client.request("chat.history", {
- sessionKey,
- limit: 8,
- })) as HistoryResponse | undefined;
- const msgs = Array.isArray(res?.messages) ? res!.messages : [];
- const hit = findLatestAssistant(msgs);
- if (hit && hit.timestamp >= notBefore) return hit.text;
- } catch {
- // swallow and retry
- }
- await new Promise((r) => setTimeout(r, DELAY_MS));
- }
- return "";
-}
diff --git a/notfair-cmo/src/server/openclaw/gateway-rpc.test.ts b/notfair-cmo/src/server/openclaw/gateway-rpc.test.ts
deleted file mode 100644
index 711f6946..00000000
--- a/notfair-cmo/src/server/openclaw/gateway-rpc.test.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-type MockedClient = {
- open: ReturnType<typeof vi.fn>;
- request: ReturnType<typeof vi.fn>;
- close: ReturnType<typeof vi.fn>;
-};
-
-const clientInstances: MockedClient[] = [];
-
-let nextRequestImpl: ((method: string, params?: unknown) => unknown) | null = null;
-
-vi.mock("./gateway-client", () => {
- class FakeGatewayClient {
- open: ReturnType<typeof vi.fn>;
- request: ReturnType<typeof vi.fn>;
- close: ReturnType<typeof vi.fn>;
- constructor() {
- const impl = nextRequestImpl ?? (async () => undefined);
- nextRequestImpl = null;
- this.open = vi.fn().mockResolvedValue(undefined);
- this.request = vi.fn().mockImplementation(impl);
- this.close = vi.fn();
- clientInstances.push(this);
- }
- }
- return { GatewayClient: FakeGatewayClient };
-});
-
-import {
- createAgentViaRpc,
- deleteAgent,
- getAgentFile,
- getSkillStatus,
- listAgentFiles,
- listAllAgents,
- setAgentFile,
- setSkillEnabled,
- updateCronMessage,
-} from "./gateway-rpc";
-
-function latest(): MockedClient {
- return clientInstances[clientInstances.length - 1]!;
-}
-
-function nextRequestReturns(value: unknown): void {
- nextRequestImpl = async () => value;
-}
-
-function nextRequestThrows(err: Error): void {
- nextRequestImpl = async () => {
- throw err;
- };
-}
-
-describe("gateway-rpc", () => {
- beforeEach(() => {
- clientInstances.length = 0;
- nextRequestImpl = null;
- });
-
- it("listAgentFiles opens, requests agents.files.list, returns payload, then closes", async () => {
- const expected = {
- agentId: "demo-agent",
- workspace: "/ws",
- files: [{ name: "REM.md", path: "/ws/REM.md", missing: false, size: 10 }],
- };
- nextRequestReturns(expected);
-
- await expect(listAgentFiles("demo-agent")).resolves.toEqual(expected);
- const c = latest();
- expect(c.open).toHaveBeenCalledTimes(1);
- expect(c.request).toHaveBeenCalledWith("agents.files.list", { agentId: "demo-agent" });
- expect(c.close).toHaveBeenCalledTimes(1);
- });
-
- it("closes the client even when the request throws", async () => {
- nextRequestThrows(new Error("boom"));
- await expect(listAgentFiles("a")).rejects.toThrow("boom");
- expect(latest().close).toHaveBeenCalled();
- });
-
- it("getAgentFile requests agents.files.get with agentId + name", async () => {
- const out = {
- agentId: "a",
- workspace: "/w",
- file: { name: "TODO.md", path: "/w/TODO.md", missing: false, content: "hi" },
- };
- nextRequestReturns(out);
- await expect(getAgentFile("a", "TODO.md")).resolves.toEqual(out);
- expect(latest().request).toHaveBeenCalledWith("agents.files.get", {
- agentId: "a",
- name: "TODO.md",
- });
- });
-
- it("setAgentFile requests agents.files.set and resolves void", async () => {
- await setAgentFile("a", "n", "content");
- expect(latest().request).toHaveBeenCalledWith("agents.files.set", {
- agentId: "a",
- name: "n",
- content: "content",
- });
- });
-
- it("getSkillStatus requests skills.status with agentId", async () => {
- const out = {
- workspaceDir: "/w",
- managedSkillsDir: "/w/skills",
- agentId: "a",
- skills: [],
- };
- nextRequestReturns(out);
- await expect(getSkillStatus("a")).resolves.toEqual(out);
- expect(latest().request).toHaveBeenCalledWith("skills.status", { agentId: "a" });
- });
-
- it("setSkillEnabled requests skills.update with skillKey + enabled flag", async () => {
- await setSkillEnabled("my-skill", true);
- expect(latest().request).toHaveBeenCalledWith("skills.update", {
- skillKey: "my-skill",
- enabled: true,
- });
- await setSkillEnabled("my-skill", false);
- expect(latest().request).toHaveBeenCalledWith("skills.update", {
- skillKey: "my-skill",
- enabled: false,
- });
- });
-
- it("deleteAgent requests agents.delete with deleteFiles:true", async () => {
- await deleteAgent("a");
- expect(latest().request).toHaveBeenCalledWith("agents.delete", {
- agentId: "a",
- deleteFiles: true,
- });
- });
-
- it("listAllAgents requests agents.list with empty params", async () => {
- const out = { defaultId: "a", mainKey: "main", agents: [] };
- nextRequestReturns(out);
- await expect(listAllAgents()).resolves.toEqual(out);
- expect(latest().request).toHaveBeenCalledWith("agents.list", {});
- });
-
- it("createAgentViaRpc forwards the full input as params", async () => {
- const input = { name: "demo-cmo", workspace: "/ws", model: "claude-opus-4", emoji: "🎯" };
- await createAgentViaRpc(input);
- expect(latest().request).toHaveBeenCalledWith("agents.create", input);
- });
-
- it("updateCronMessage wraps the new message in a payload patch", async () => {
- await updateCronMessage("cron-id", "fresh prompt");
- expect(latest().request).toHaveBeenCalledWith("cron.update", {
- id: "cron-id",
- patch: { payload: { kind: "agentTurn", message: "fresh prompt" } },
- });
- });
-
- it("each call opens a fresh GatewayClient instance and closes it", async () => {
- await setAgentFile("a", "f", "");
- await setAgentFile("a", "g", "");
- expect(clientInstances.length).toBe(2);
- for (const c of clientInstances) {
- expect(c.open).toHaveBeenCalledTimes(1);
- expect(c.close).toHaveBeenCalledTimes(1);
- }
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/gateway-rpc.ts b/notfair-cmo/src/server/openclaw/gateway-rpc.ts
deleted file mode 100644
index 6d6c0f11..00000000
--- a/notfair-cmo/src/server/openclaw/gateway-rpc.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { GatewayClient } from "./gateway-client";
-
-/**
- * Thin wrappers around the OpenClaw gateway RPC methods we use from server
- * components. Each call opens a fresh GatewayClient, does one request, and
- * closes it. Per-request overhead is a single WS handshake to loopback (sub
- * 50ms on local), which is fine for SSR page loads where the alternative is
- * a multi-second `openclaw …` subprocess spawn.
- *
- * If we need higher-throughput access later, swap to a long-lived shared
- * client at process scope.
- */
-
-async function withClient<T>(fn: (c: GatewayClient) => Promise<T>): Promise<T> {
- const client = new GatewayClient();
- await client.open();
- try {
- return await fn(client);
- } finally {
- client.close();
- }
-}
-
-// --- agents.files ---
-
-export type AgentFileEntry = {
- name: string;
- path: string;
- missing: boolean;
- size?: number;
- updatedAtMs?: number;
-};
-
-export type AgentFilesList = {
- agentId: string;
- workspace: string;
- files: AgentFileEntry[];
-};
-
-export async function listAgentFiles(agentId: string): Promise<AgentFilesList> {
- return withClient((c) => c.request<AgentFilesList>("agents.files.list", { agentId }));
-}
-
-export type AgentFileGet = {
- agentId: string;
- workspace: string;
- file: AgentFileEntry & { content: string };
-};
-
-export async function getAgentFile(agentId: string, name: string): Promise<AgentFileGet> {
- return withClient((c) => c.request<AgentFileGet>("agents.files.get", { agentId, name }));
-}
-
-export async function setAgentFile(
- agentId: string,
- name: string,
- content: string,
-): Promise<void> {
- await withClient((c) => c.request("agents.files.set", { agentId, name, content }));
-}
-
-// --- skills.status ---
-
-export type SkillEntry = {
- name: string;
- description: string;
- source: string;
- bundled: boolean;
- filePath: string;
- baseDir: string;
- skillKey: string;
- emoji?: string;
- always: boolean;
- disabled: boolean;
- eligible: boolean;
- blockedByAllowlist: boolean;
- blockedByAgentFilter: boolean;
- userInvocable: boolean;
- commandVisible: boolean;
- // Other fields exist (requirements, install) — leave as unknown until we
- // surface them in the UI.
-};
-
-export type SkillStatusReport = {
- workspaceDir: string;
- managedSkillsDir: string;
- agentId?: string;
- agentSkillFilter?: string[];
- skills: SkillEntry[];
-};
-
-export async function getSkillStatus(agentId: string): Promise<SkillStatusReport> {
- return withClient((c) =>
- c.request<SkillStatusReport>("skills.status", { agentId }),
- );
-}
-
-/**
- * Toggle a skill on/off in the workspace config. Requires operator.admin scope.
- * Affects all agents in the workspace (skills.config is workspace-wide).
- */
-export async function setSkillEnabled(
- skillKey: string,
- enabled: boolean,
-): Promise<void> {
- await withClient((c) =>
- c.request("skills.update", { skillKey, enabled }),
- );
-}
-
-// --- agents.delete ---
-
-/**
- * Delete an agent from OpenClaw. With deleteFiles:true (default), removes the
- * workspace dir + sessions store so all thread history goes with it.
- * Requires operator.admin scope.
- */
-export async function deleteAgent(agentId: string): Promise<void> {
- await withClient((c) =>
- c.request("agents.delete", { agentId, deleteFiles: true }),
- );
-}
-
-// --- agents.list / agents.create ---
-
-export type GatewayAgentRow = {
- id: string;
- name?: string;
- identity?: {
- name?: string;
- emoji?: string;
- avatar?: string;
- };
- model?: string;
-};
-
-export type AgentsListResult = {
- defaultId: string;
- mainKey: string;
- agents: GatewayAgentRow[];
-};
-
-export async function listAllAgents(): Promise<AgentsListResult> {
- return withClient((c) => c.request<AgentsListResult>("agents.list", {}));
-}
-
-export type AgentCreateInput = {
- /** Full agentId, e.g. `<project>-<slug>`. */
- name: string;
- /** Absolute workspace directory. */
- workspace: string;
- model?: string;
- emoji?: string;
-};
-
-export async function createAgentViaRpc(input: AgentCreateInput): Promise<void> {
- await withClient((c) => c.request("agents.create", input));
-}
-
-// --- cron.update ---
-
-/**
- * Replace a cron's agent-turn prompt. Other fields (schedule, agent target,
- * delivery) are left as-is. Requires operator.admin scope.
- */
-export async function updateCronMessage(cron_id: string, message: string): Promise<void> {
- await withClient((c) =>
- c.request("cron.update", {
- id: cron_id,
- patch: {
- payload: { kind: "agentTurn", message },
- },
- }),
- );
-}
-
diff --git a/notfair-cmo/src/server/openclaw/project-delete.test.ts b/notfair-cmo/src/server/openclaw/project-delete.test.ts
deleted file mode 100644
index 9050d19d..00000000
--- a/notfair-cmo/src/server/openclaw/project-delete.test.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-import { mkdirSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
-import {
- afterAll,
- beforeEach,
- describe,
- expect,
- it,
- vi,
-} from "vitest";
-
-const { tmpHome, ORIGINAL_HOME } = vi.hoisted(() => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { tmpdir } = require("node:os") as typeof import("node:os");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { join: joinPath } = require("node:path") as typeof import("node:path");
- const original = process.env.OPENCLAW_HOME;
- const tmp = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-project-delete-"));
- process.env.OPENCLAW_HOME = tmp;
- return { tmpHome: tmp, ORIGINAL_HOME: original };
-});
-
-// Mock all dependencies the SUT pulls in.
-const listProjectAgentsMock = vi.fn();
-vi.mock("@/server/agent-meta", () => ({
- listProjectAgents: (...args: unknown[]) => listProjectAgentsMock(...args),
-}));
-
-const listSessionsMock = vi.fn();
-vi.mock("@/server/openclaw/sessions", () => ({
- listSessionsForAgent: (...args: unknown[]) => listSessionsMock(...args),
-}));
-
-const listCronsMock = vi.fn();
-vi.mock("@/server/openclaw/crons", () => ({
- listCronsForProject: (...args: unknown[]) => listCronsMock(...args),
-}));
-
-const readMcpConfigRowMock = vi.fn();
-vi.mock("@/server/mcp/rpc", () => ({
- readMcpConfigRow: (...args: unknown[]) => readMcpConfigRowMock(...args),
-}));
-
-// mcp-catalog provides MCP_CATALOG + storedMcpKey. We use the real impl
-// because it's just data + a pure helper.
-
-import { getProjectDeletionSummary } from "./project-delete";
-import { MCP_CATALOG } from "@/server/mcp-catalog";
-
-function ensureAgentDir(agentId: string): void {
- // The SUT does `existsSync(<OPENCLAW_HOME>/agents/<agentId>)` to decide
- // if `exists` is true and if it should list sessions.
- mkdirSync(join(tmpHome, "agents", agentId), { recursive: true });
- writeFileSync(join(tmpHome, "agents", agentId, "marker"), "x", "utf8");
-}
-
-beforeEach(() => {
- listProjectAgentsMock.mockReset();
- listSessionsMock.mockReset();
- listCronsMock.mockReset();
- readMcpConfigRowMock.mockReset();
-});
-
-afterAll(() => {
- if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;
- else delete process.env.OPENCLAW_HOME;
-});
-
-describe("getProjectDeletionSummary", () => {
- it("returns empty totals when no agents / crons / mcps are configured", async () => {
- listProjectAgentsMock.mockResolvedValueOnce([]);
- listCronsMock.mockResolvedValueOnce({ groups: [] });
- readMcpConfigRowMock.mockResolvedValue(null);
-
- const summary = await getProjectDeletionSummary("empty-project");
- expect(summary.project_slug).toBe("empty-project");
- expect(summary.agents).toEqual([]);
- expect(summary.totals).toEqual({
- agents: 0,
- threads: 0,
- crons: 0,
- mcps: 0,
- });
- // mcps array is one entry per catalog spec, all marked unconfigured.
- expect(summary.mcps.length).toBe(MCP_CATALOG.length);
- expect(summary.mcps.every((m) => !m.configured)).toBe(true);
- });
-
- it("counts threads from listSessionsForAgent for agents that exist on disk", async () => {
- ensureAgentDir("demo-cmo");
- ensureAgentDir("demo-google-ads");
-
- listProjectAgentsMock.mockResolvedValueOnce([
- {
- agent_id: "demo-cmo",
- slug: "cmo-greg",
- name: "Greg",
- template_key: "cmo",
- is_template_default: true,
- },
- {
- agent_id: "demo-google-ads",
- slug: "google-ads-ana",
- name: "Ana",
- template_key: "google_ads",
- is_template_default: true,
- },
- // Agent listed in meta but not on disk — exists:false, threads:0.
- {
- agent_id: "demo-ghost",
- slug: "ghost",
- name: "Ghost",
- is_template_default: false,
- },
- ]);
- // Two threads in CMO, none in google-ads.
- listSessionsMock.mockImplementation((id: string) => {
- if (id === "demo-cmo")
- return [
- { sessionId: "s1", label: "main", sessionKey: "x", lastInteractionAt: 0, pending: false },
- { sessionId: "s2", label: "alt", sessionKey: "y", lastInteractionAt: 0, pending: false },
- ];
- return [];
- });
- listCronsMock.mockResolvedValueOnce({
- groups: [
- { agent: "cmo", crons: [{ id: "c1" }, { id: "c2" }] },
- { agent: "google-ads", crons: [{ id: "c3" }] },
- ],
- });
- readMcpConfigRowMock.mockResolvedValue(null);
-
- const summary = await getProjectDeletionSummary("demo");
- expect(summary.totals.agents).toBe(2); // only the two that exist on disk
- expect(summary.totals.threads).toBe(2);
- expect(summary.totals.crons).toBe(3);
-
- const byId = Object.fromEntries(summary.agents.map((a) => [a.agentId, a]));
- expect(byId["demo-cmo"]!.exists).toBe(true);
- expect(byId["demo-cmo"]!.threadCount).toBe(2);
- expect(byId["demo-google-ads"]!.threadCount).toBe(0);
- expect(byId["demo-ghost"]!.exists).toBe(false);
- expect(byId["demo-ghost"]!.threadCount).toBe(0);
- // listSessionsMock should not have been called for the ghost agent.
- expect(listSessionsMock).not.toHaveBeenCalledWith("demo-ghost");
- });
-
- it("counts MCPs as configured when readMcpConfigRow returns a truthy row", async () => {
- listProjectAgentsMock.mockResolvedValueOnce([]);
- listCronsMock.mockResolvedValueOnce({ groups: [] });
- // Configure the first catalog entry; leave the rest unconfigured.
- const firstKey = MCP_CATALOG[0]!.key;
- readMcpConfigRowMock.mockImplementation(async (stored_key: string) => {
- if (stored_key === `demo-${firstKey}`) {
- return { url: "https://x", headers: { Authorization: "Bearer y" } };
- }
- return null;
- });
-
- const summary = await getProjectDeletionSummary("demo");
- expect(summary.totals.mcps).toBe(1);
- const m = summary.mcps.find((x) => x.catalog_key === firstKey);
- expect(m?.configured).toBe(true);
- expect(m?.stored_key).toBe(`demo-${firstKey}`);
- });
-
- it("treats listCronsForProject errors as 0 crons (best-effort)", async () => {
- listProjectAgentsMock.mockResolvedValueOnce([]);
- listCronsMock.mockRejectedValueOnce(new Error("openclaw down"));
- readMcpConfigRowMock.mockResolvedValue(null);
-
- const summary = await getProjectDeletionSummary("demo");
- expect(summary.totals.crons).toBe(0);
- });
-
- it("treats readMcpConfigRow errors as unconfigured (best-effort)", async () => {
- listProjectAgentsMock.mockResolvedValueOnce([]);
- listCronsMock.mockResolvedValueOnce({ groups: [] });
- readMcpConfigRowMock.mockRejectedValue(new Error("subprocess fail"));
-
- const summary = await getProjectDeletionSummary("demo");
- expect(summary.totals.mcps).toBe(0);
- expect(summary.mcps.every((m) => !m.configured)).toBe(true);
- });
-
- it("propagates template + display fields onto the agent summary", async () => {
- ensureAgentDir("demo-cmo");
- listProjectAgentsMock.mockResolvedValueOnce([
- {
- agent_id: "demo-cmo",
- slug: "cmo-greg",
- name: "Chief Marketing Officer",
- template_key: "cmo",
- is_template_default: true,
- },
- ]);
- listSessionsMock.mockReturnValue([]);
- listCronsMock.mockResolvedValueOnce({ groups: [] });
- readMcpConfigRowMock.mockResolvedValue(null);
-
- const summary = await getProjectDeletionSummary("demo");
- expect(summary.agents[0]!.template).toBe("cmo");
- expect(summary.agents[0]!.display_name).toBe("Chief Marketing Officer");
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/project-delete.ts b/notfair-cmo/src/server/openclaw/project-delete.ts
deleted file mode 100644
index 7a810d25..00000000
--- a/notfair-cmo/src/server/openclaw/project-delete.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { existsSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import type { AgentTemplate } from "@/server/agent-templates";
-import { listProjectAgents } from "@/server/agent-meta";
-import { MCP_CATALOG, storedMcpKey } from "@/server/mcp-catalog";
-import { readMcpConfigRow } from "@/server/mcp/rpc";
-import { listSessionsForAgent } from "@/server/openclaw/sessions";
-import { listCronsForProject } from "@/server/openclaw/crons";
-
-const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");
-
-export type ProjectDeletionAgentSummary = {
- /** Template key when this agent came from a bootstrap template, else undefined. */
- template?: AgentTemplate["key"];
- display_name: string;
- agentId: string;
- exists: boolean;
- threadCount: number;
-};
-
-export type ProjectDeletionMcpSummary = {
- catalog_key: string;
- display_name: string;
- stored_key: string;
- /** True when an MCP config row exists for this project + catalog entry. */
- configured: boolean;
-};
-
-export type ProjectDeletionSummary = {
- project_slug: string;
- agents: ProjectDeletionAgentSummary[];
- mcps: ProjectDeletionMcpSummary[];
- totals: {
- agents: number;
- threads: number;
- crons: number;
- mcps: number;
- };
-};
-
-/**
- * Inventory everything tied to a project so the confirmation dialog can show
- * the user exactly what will be deleted. Reads-only; no mutations.
- *
- * Source of truth: `listProjectAgents()` — covers bootstrap templates AND any
- * cloned/custom agents created via the `+` button. Iterating TEMPLATES alone
- * would silently skip user-created agents and leak them after project delete.
- */
-export async function getProjectDeletionSummary(
- project_slug: string,
-): Promise<ProjectDeletionSummary> {
- const entries = await listProjectAgents(project_slug);
- const agents: ProjectDeletionAgentSummary[] = entries.map((e) => {
- const agentDir = join(OPENCLAW_HOME, "agents", e.agent_id);
- const exists = existsSync(agentDir);
- const threadCount = exists ? listSessionsForAgent(e.agent_id).length : 0;
- return {
- template: e.template_key,
- display_name: e.name,
- agentId: e.agent_id,
- exists,
- threadCount,
- };
- });
-
- let cronCount = 0;
- try {
- const cronView = await listCronsForProject(project_slug);
- cronCount = cronView.groups.reduce((acc, g) => acc + g.crons.length, 0);
- } catch {
- // OpenClaw cron service unreachable — show 0 and let the user decide.
- }
-
- // MCP connections live in OpenClaw's mcp config under per-project keys
- // (`<slug>-<catalog-key>`). Deleting the project means revoking these
- // bearer tokens — surface a count in the confirmation so the user knows
- // what's about to disconnect.
- const mcps: ProjectDeletionMcpSummary[] = await Promise.all(
- MCP_CATALOG.map(async (spec) => {
- const stored_key = storedMcpKey(project_slug, spec.key);
- let configured = false;
- try {
- const row = await readMcpConfigRow(stored_key);
- configured = Boolean(row);
- } catch {
- // OpenClaw mcp command unavailable — treat as unconfigured for
- // summary purposes; the actual delete is also best-effort.
- }
- return {
- catalog_key: spec.key,
- display_name: spec.display_name,
- stored_key,
- configured,
- };
- }),
- );
-
- return {
- project_slug,
- agents,
- mcps,
- 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,
- },
- };
-}
diff --git a/notfair-cmo/src/server/openclaw/sessions.test.ts b/notfair-cmo/src/server/openclaw/sessions.test.ts
deleted file mode 100644
index 7c442baa..00000000
--- a/notfair-cmo/src/server/openclaw/sessions.test.ts
+++ /dev/null
@@ -1,263 +0,0 @@
-import { mkdirSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- it,
- vi,
-} from "vitest";
-
-const { tmpHome, ORIGINAL_HOME } = vi.hoisted(() => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { tmpdir } = require("node:os") as typeof import("node:os");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { join: joinPath } = require("node:path") as typeof import("node:path");
- const original = process.env.OPENCLAW_HOME;
- const tmp = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-sessions-"));
- process.env.OPENCLAW_HOME = tmp;
- return { tmpHome: tmp, ORIGINAL_HOME: original };
-});
-
-// Mock next/headers cookies API. Each test sets the cookie state via the
-// `cookieStore` helper below.
-type CookieMap = Map<string, string>;
-const cookieStore: CookieMap = new Map();
-let setCalls: Array<{ name: string; value: string; opts: unknown }> = [];
-
-vi.mock("next/headers", () => ({
- cookies: async () => ({
- get: (name: string) => {
- const v = cookieStore.get(name);
- return v === undefined ? undefined : { value: v };
- },
- set: (name: string, value: string, opts: unknown) => {
- cookieStore.set(name, value);
- setCalls.push({ name, value, opts });
- },
- }),
-}));
-
-import {
- buildPendingSessionKey,
- findSessionBySessionId,
- getSessionsView,
- listSessionsForAgent,
- newSessionId,
- setActiveSession,
-} from "./sessions";
-
-function sessionsPath(agentFullId: string): string {
- return join(tmpHome, "agents", agentFullId, "sessions", "sessions.json");
-}
-
-function writeSessions(
- agentFullId: string,
- parsed: Record<string, unknown>,
-): void {
- const path = sessionsPath(agentFullId);
- mkdirSync(join(tmpHome, "agents", agentFullId, "sessions"), {
- recursive: true,
- });
- writeFileSync(path, JSON.stringify(parsed), "utf8");
-}
-
-beforeEach(() => {
- cookieStore.clear();
- setCalls = [];
-});
-
-afterAll(() => {
- if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;
- else delete process.env.OPENCLAW_HOME;
-});
-
-describe("listSessionsForAgent", () => {
- it("returns [] when the sessions.json file doesn't exist", () => {
- expect(listSessionsForAgent("nobody-cmo")).toEqual([]);
- });
-
- it("returns [] when the file is not valid JSON", () => {
- const agent = "broken-cmo";
- const p = sessionsPath(agent);
- mkdirSync(join(tmpHome, "agents", agent, "sessions"), { recursive: true });
- writeFileSync(p, "{ not json", "utf8");
- expect(listSessionsForAgent(agent)).toEqual([]);
- });
-
- it("parses sessions with the agent: prefix and strips it from label", () => {
- const agent = "demo-cmo";
- writeSessions(agent, {
- "agent:demo-cmo:main": { sessionId: "s1", updatedAt: 100 },
- "agent:demo-cmo:0xabc": { sessionId: "s2", lastInteractionAt: 200 },
- });
- const out = listSessionsForAgent(agent);
- expect(out.map((s) => s.label).sort()).toEqual(["0xabc", "main"]);
- // Newest-first: s2's lastInteractionAt is 200, larger than s1's 100.
- expect(out[0]!.sessionId).toBe("s2");
- expect(out[0]!.lastInteractionAt).toBe(200);
- expect(out[0]!.pending).toBe(false);
- expect(out[1]!.lastInteractionAt).toBe(100);
- });
-
- it("keeps the raw key as label when the prefix doesn't match", () => {
- const agent = "demo-cmo";
- writeSessions(agent, {
- "unusual-key-without-prefix": { sessionId: "s3", updatedAt: 1 },
- });
- const out = listSessionsForAgent(agent);
- expect(out[0]!.label).toBe("unusual-key-without-prefix");
- });
-
- it("skips entries with no sessionId", () => {
- const agent = "demo-cmo";
- writeSessions(agent, {
- "agent:demo-cmo:bad": { updatedAt: 1 },
- "agent:demo-cmo:good": { sessionId: "s-good", updatedAt: 5 },
- });
- const out = listSessionsForAgent(agent);
- expect(out.length).toBe(1);
- expect(out[0]!.sessionId).toBe("s-good");
- });
-
- it("falls back to updatedAt when lastInteractionAt missing, then to 0", () => {
- const agent = "demo-cmo";
- writeSessions(agent, {
- "agent:demo-cmo:a": { sessionId: "a", updatedAt: 50 },
- "agent:demo-cmo:b": { sessionId: "b" },
- });
- const out = listSessionsForAgent(agent);
- const byId = Object.fromEntries(out.map((s) => [s.sessionId, s]));
- expect(byId["a"]!.lastInteractionAt).toBe(50);
- expect(byId["b"]!.lastInteractionAt).toBe(0);
- });
-});
-
-describe("buildPendingSessionKey", () => {
- it("joins agent + sessionId with the `agent:` prefix", () => {
- expect(buildPendingSessionKey("demo-cmo", "uuid-1")).toBe(
- "agent:demo-cmo:uuid-1",
- );
- });
-});
-
-describe("findSessionBySessionId", () => {
- const agent = "demo-cmo";
- beforeEach(() => {
- writeSessions(agent, {
- "agent:demo-cmo:thread-label": {
- sessionId: "internal-uuid-1",
- updatedAt: 1,
- },
- "agent:demo-cmo:another": {
- sessionId: "internal-uuid-2",
- updatedAt: 2,
- },
- });
- });
-
- it("matches by label first", () => {
- const r = findSessionBySessionId(agent, "thread-label");
- expect(r?.sessionId).toBe("internal-uuid-1");
- });
-
- it("falls back to matching by internal sessionId", () => {
- const r = findSessionBySessionId(agent, "internal-uuid-2");
- expect(r?.sessionId).toBe("internal-uuid-2");
- expect(r?.label).toBe("another");
- });
-
- it("returns null when nothing matches", () => {
- expect(findSessionBySessionId(agent, "no-such-thread")).toBeNull();
- });
-});
-
-describe("newSessionId", () => {
- it("returns a UUID-shaped string", () => {
- const id = newSessionId();
- expect(id).toMatch(
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
- );
- // Reasonably unique.
- expect(newSessionId()).not.toBe(id);
- });
-});
-
-describe("getSessionsView", () => {
- // The template `cmo` resolves to `<project>-cmo`.
- it("uses the existing top session when no cookie is set", async () => {
- writeSessions("alpha-cmo", {
- "agent:alpha-cmo:m1": { sessionId: "s1", updatedAt: 100 },
- "agent:alpha-cmo:m2": { sessionId: "s2", updatedAt: 200 },
- });
- const view = await getSessionsView("alpha", "cmo", "alpha-cmo");
- expect(view.active.sessionId).toBe("s2");
- expect(view.all.length).toBe(2);
- expect(view.active.pending).toBe(false);
- });
-
- it("synthesizes a fresh pending session when no sessions exist + no cookie", async () => {
- const view = await getSessionsView("beta", "cmo", "beta-cmo");
- expect(view.active.pending).toBe(true);
- expect(view.active.label).toBe("main");
- expect(view.active.sessionKey).toBe(
- `agent:beta-cmo:${view.active.sessionId}`,
- );
- // The synthetic active is prepended to `all`.
- expect(view.all.length).toBe(1);
- expect(view.all[0]).toBe(view.active);
- });
-
- it("uses the cookie's sessionId when it matches an existing session", async () => {
- writeSessions("gamma-cmo", {
- "agent:gamma-cmo:t-old": { sessionId: "old", updatedAt: 1 },
- "agent:gamma-cmo:t-new": { sessionId: "cookie-id", updatedAt: 2 },
- });
- cookieStore.set("notfair_active_session_gamma_cmo", "cookie-id");
- const view = await getSessionsView("gamma", "cmo", "gamma-cmo");
- expect(view.active.sessionId).toBe("cookie-id");
- expect(view.active.pending).toBe(false);
- // All sessions returned in newest-first order.
- expect(view.all.map((s) => s.sessionId)).toEqual(["cookie-id", "old"]);
- });
-
- it("treats unknown cookie sessionId as a pending session and prepends it", async () => {
- writeSessions("delta-cmo", {
- "agent:delta-cmo:t-real": { sessionId: "real-id", updatedAt: 1 },
- });
- cookieStore.set("notfair_active_session_delta_cmo", "imaginary-id");
- const view = await getSessionsView("delta", "cmo", "delta-cmo");
- expect(view.active.sessionId).toBe("imaginary-id");
- expect(view.active.pending).toBe(true);
- // Label is the first 8 chars of the cookie id.
- expect(view.active.label).toBe("imaginar");
- // The pending entry shows up at the front of `all`, with existing kept.
- expect(view.all[0]!.sessionId).toBe("imaginary-id");
- expect(view.all.find((s) => s.sessionId === "real-id")).toBeDefined();
- });
-});
-
-describe("setActiveSession", () => {
- it("writes the cookie with the expected name + opts", async () => {
- await setActiveSession("epsilon", "cmo", "fresh-uuid");
- expect(cookieStore.get("notfair_active_session_epsilon_cmo")).toBe(
- "fresh-uuid",
- );
- expect(setCalls.length).toBe(1);
- const opts = setCalls[0]!.opts as {
- httpOnly: boolean;
- sameSite: string;
- path: string;
- maxAge: number;
- };
- expect(opts.httpOnly).toBe(true);
- expect(opts.sameSite).toBe("lax");
- expect(opts.path).toBe("/");
- // 1 year (365d) approx.
- expect(opts.maxAge).toBe(60 * 60 * 24 * 365);
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/sessions.ts b/notfair-cmo/src/server/openclaw/sessions.ts
deleted file mode 100644
index eabd82a4..00000000
--- a/notfair-cmo/src/server/openclaw/sessions.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import { existsSync, readFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { randomUUID } from "node:crypto";
-import { cookies } from "next/headers";
-import type { AgentTemplateKey } from "@/server/agent-templates";
-
-/**
- * Sessions are owned by OpenClaw. We never persist threads, history, or
- * session metadata ourselves. We only:
- * 1. Read OpenClaw's session store (`~/.openclaw/agents/<agent>/sessions/sessions.json`)
- * to list a user's existing sessions for the chat thread dropdown.
- * 2. Generate fresh UUIDs to start new sessions (OpenClaw creates the session
- * entry on the first agent turn).
- * 3. Remember the active session per (project, agent_template) in a cookie.
- *
- * No DB table, no migrations, no ownership of session lifecycle.
- */
-
-const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");
-
-export type OpenClawSession = {
- /** OpenClaw-assigned session id (UUID). What we pass to --session-id. */
- sessionId: string;
- /** Optional short label parsed from the full session-key, if present. */
- label: string;
- /**
- * Full sessionKey OpenClaw uses internally (`agent:<agent>:<label>`). The
- * label half is the canonical identifier for an existing thread — OpenClaw
- * may register `<main>` for its bootstrap thread instead of the sessionId.
- * For brand-new threads we create, the label IS the sessionId UUID.
- */
- sessionKey: string;
- /** Last interaction (ms epoch). 0 if unknown / freshly minted. */
- lastInteractionAt: number;
- /** True if this session exists only in our cookie (user clicked New, hasn't sent a message yet). */
- pending: boolean;
-};
-
-type RawSessionEntry = {
- sessionId?: string;
- updatedAt?: number;
- lastInteractionAt?: number;
-};
-
-function sessionsFilePath(agentFullId: string): string {
- return join(OPENCLAW_HOME, "agents", agentFullId, "sessions", "sessions.json");
-}
-
-export function listSessionsForAgent(agentFullId: string): OpenClawSession[] {
- const path = sessionsFilePath(agentFullId);
- if (!existsSync(path)) return [];
- let parsed: Record<string, RawSessionEntry>;
- try {
- parsed = JSON.parse(readFileSync(path, "utf8")) as Record<string, RawSessionEntry>;
- } catch {
- return [];
- }
- const prefix = `agent:${agentFullId}:`;
- const out: OpenClawSession[] = [];
- for (const [key, entry] of Object.entries(parsed)) {
- if (!entry.sessionId) continue;
- const label = key.startsWith(prefix) ? key.slice(prefix.length) : key;
- out.push({
- sessionId: entry.sessionId,
- label,
- sessionKey: key,
- lastInteractionAt: entry.lastInteractionAt ?? entry.updatedAt ?? 0,
- pending: false,
- });
- }
- out.sort((a, b) => b.lastInteractionAt - a.lastInteractionAt);
- return out;
-}
-
-/**
- * Build the canonical sessionKey for a brand-new thread we're about to send
- * the first message to. Label = the same UUID we're using as sessionId, so
- * the thread becomes self-identifying in OpenClaw's store.
- */
-export function buildPendingSessionKey(agentFullId: string, sessionId: string): string {
- return `agent:${agentFullId}:${sessionId}`;
-}
-
-/**
- * Look up an existing session by the URL thread id we mint for new chats.
- *
- * That id ends up as the **label** part of OpenClaw's sessionKey
- * (`agent:<agent>:<label>`), not as OpenClaw's internal `sessionId` — which is
- * a different UUID the gateway assigns when it first writes the transcript
- * file. So we match on label first, falling back to sessionId for the older
- * case where the two happened to coincide.
- *
- * Returns null when the thread id is unknown to OpenClaw — caller should
- * treat it as a pending new thread.
- */
-export function findSessionBySessionId(
- agentFullId: string,
- threadId: string,
-): OpenClawSession | null {
- const all = listSessionsForAgent(agentFullId);
- return (
- all.find((s) => s.label === threadId) ??
- all.find((s) => s.sessionId === threadId) ??
- null
- );
-}
-
-/** Generate a brand-new session id. OpenClaw creates the entry on first turn. */
-export function newSessionId(): string {
- return randomUUID();
-}
-
-// --- Active session per (project, agent-template) is just a cookie. ---
-
-function cookieName(project_slug: string, agent_template_key: string): string {
- return `notfair_active_session_${project_slug}_${agent_template_key}`;
-}
-
-/**
- * Return the active session for an agent along with the full list of
- * sessions in dropdown order. If the cookie points at a UUID not yet in
- * OpenClaw's store (pending first-message), it appears at the top as a
- * synthetic entry tagged pending.
- *
- * `agent_full_id` is the canonical OpenClaw agent id (already includes
- * the role + personal name suffix); `agent_template_key` is used only
- * for the cookie name so different roles keep separate active sessions
- * per project.
- */
-export async function getSessionsView(
- project_slug: string,
- agent_template_key: AgentTemplateKey,
- agent_full_id: string,
-): Promise<{ active: OpenClawSession; all: OpenClawSession[] }> {
- const agentFullId = agent_full_id;
- const existing = listSessionsForAgent(agentFullId);
-
- const c = await cookies();
- const cookieSessionId = c.get(cookieName(project_slug, agent_template_key))?.value;
-
- let active: OpenClawSession | undefined;
- if (cookieSessionId) {
- active = existing.find((s) => s.sessionId === cookieSessionId);
- if (!active) {
- active = {
- sessionId: cookieSessionId,
- label: cookieSessionId.slice(0, 8),
- sessionKey: buildPendingSessionKey(agentFullId, cookieSessionId),
- lastInteractionAt: 0,
- pending: true,
- };
- }
- }
-
- if (!active) {
- if (existing.length > 0) {
- active = existing[0]!;
- } else {
- // No history yet — synthesize a default session id. Cookie will be set
- // when the user sends their first message.
- const newId = newSessionId();
- active = {
- sessionId: newId,
- label: "main",
- sessionKey: buildPendingSessionKey(agentFullId, newId),
- lastInteractionAt: 0,
- pending: true,
- };
- }
- }
-
- const all = active.pending && !existing.find((s) => s.sessionId === active!.sessionId)
- ? [active, ...existing]
- : existing;
-
- return { active, all };
-}
-
-export async function setActiveSession(
- project_slug: string,
- agent_template_key: AgentTemplateKey,
- sessionId: string,
-): Promise<void> {
- const c = await cookies();
- c.set(cookieName(project_slug, agent_template_key), sessionId, {
- httpOnly: true,
- sameSite: "lax",
- path: "/",
- maxAge: 60 * 60 * 24 * 365,
- });
-}
diff --git a/notfair-cmo/src/server/openclaw/shadow-transcript.test.ts b/notfair-cmo/src/server/openclaw/shadow-transcript.test.ts
deleted file mode 100644
index c5b035db..00000000
--- a/notfair-cmo/src/server/openclaw/shadow-transcript.test.ts
+++ /dev/null
@@ -1,396 +0,0 @@
-import { mkdtempSync, readFileSync } from "node:fs";
-import { rm } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { afterAll, beforeEach, describe, expect, it } from "vitest";
-
-import type { ChatStreamEvent } from "@/server/openclaw/gateway-client";
-import { rawEntryToEvents } from "@/server/openclaw/transcript-tail";
-
-// Pin the data dir BEFORE importing shadow-transcript so the path
-// helper resolves inside the tmpdir. The module reads
-// process.env.NOTFAIR_CMO_DATA_DIR lazily on each call, so it picks up
-// the value set here.
-const tmpRoot = mkdtempSync(join(tmpdir(), "notfair-cmo-shadow-"));
-process.env.NOTFAIR_CMO_DATA_DIR = tmpRoot;
-
-import {
- openShadowWriter,
- readShadowFromOffset,
- shadowStreamEvent,
- shadowTranscriptExists,
- shadowTranscriptPath,
-} from "./shadow-transcript";
-
-const AGENT = "demo-cmo-greg";
-const THREAD = "thread-xyz";
-
-function readShadowFile(): string {
- try {
- return readFileSync(shadowTranscriptPath(AGENT, THREAD), "utf8");
- } catch {
- return "";
- }
-}
-
-function shadowLines(): Array<Record<string, unknown>> {
- return readShadowFile()
- .split("\n")
- .filter((l) => l.trim().length > 0)
- .map((l) => JSON.parse(l) as Record<string, unknown>);
-}
-
-beforeEach(async () => {
- // Each test starts with a clean shadow file. The tmpRoot itself
- // persists across tests (afterAll cleans it up) so we don't keep
- // recreating new tmpdirs.
- await rm(shadowTranscriptPath(AGENT, THREAD), { force: true });
-});
-
-afterAll(async () => {
- await rm(tmpRoot, { recursive: true, force: true });
-});
-
-describe("shadowTranscriptPath + shadowTranscriptExists", () => {
- it("resolves under the data dir", () => {
- const p = shadowTranscriptPath(AGENT, THREAD);
- expect(p).toBe(join(tmpRoot, "agents", AGENT, "shadow", `${THREAD}.jsonl`));
- });
-
- it("exists() is false before any write", () => {
- expect(shadowTranscriptExists(AGENT, THREAD)).toBe(false);
- });
-});
-
-describe("openShadowWriter — basic message writing", () => {
- it("flushes accumulated deltas as a single assistant message", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- w.appendDelta("hello ");
- w.appendDelta("world");
- await w.flushAssistant();
- await w.close();
-
- const lines = shadowLines();
- expect(lines).toHaveLength(1);
- const line = lines[0]!;
- expect(line.type).toBe("message");
- expect(line.id).toMatch(/^shadow-/);
- expect(typeof line.timestamp).toBe("string");
- const msg = line.message as { role: string; content: Array<{ type: string; text: string }> };
- expect(msg.role).toBe("assistant");
- expect(msg.content).toEqual([{ type: "text", text: "hello world" }]);
- });
-
- it("flushAssistant on an empty buffer is a no-op (no file write)", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- await w.flushAssistant();
- await w.close();
- expect(shadowLines()).toHaveLength(0);
- });
-
- it("close() flushes any pending assistant text", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- w.appendDelta("a final thought");
- // Note: NO explicit flushAssistant; close() must commit.
- await w.close();
- const lines = shadowLines();
- expect(lines).toHaveLength(1);
- const msg = (lines[0] as { message: { content: Array<{ text: string }> } })
- .message;
- expect(msg.content[0]!.text).toBe("a final thought");
- });
-
- it("replaceAssistant overwrites the buffer (single committed message)", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- w.appendDelta("partial deltas...");
- // The gateway's `final` event carries the canonical cumulative text;
- // replaceAssistant is how we make `final` authoritative without
- // double-counting the deltas we already saw.
- w.replaceAssistant("the canonical final reply");
- await w.flushAssistant();
- await w.close();
-
- const lines = shadowLines();
- expect(lines).toHaveLength(1);
- const msg = (lines[0] as { message: { content: Array<{ text: string }> } })
- .message;
- expect(msg.content[0]!.text).toBe("the canonical final reply");
- });
-});
-
-describe("openShadowWriter — tool calls + results", () => {
- it("toolStart flushes pending assistant text first, then writes the tool call", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- w.appendDelta("looking up the data");
- await w.toolStart("tc-1", "ads.gaql", "SELECT name FROM customer");
- await w.close();
-
- const lines = shadowLines();
- expect(lines).toHaveLength(2);
- // Order matters — assistant text before tool call.
- const firstMsg = (
- lines[0] as { message: { role: string; content: Array<{ text: string }> } }
- ).message;
- expect(firstMsg.role).toBe("assistant");
- expect(firstMsg.content[0]!.text).toBe("looking up the data");
-
- const secondMsg = (
- lines[1] as {
- message: {
- role: string;
- content: Array<{
- type: string;
- id: string;
- name: string;
- arguments?: { __label?: string };
- }>;
- };
- }
- ).message;
- expect(secondMsg.role).toBe("assistant");
- expect(secondMsg.content[0]!.type).toBe("toolCall");
- expect(secondMsg.content[0]!.id).toBe("tc-1");
- expect(secondMsg.content[0]!.name).toBe("ads.gaql");
- expect(secondMsg.content[0]!.arguments?.__label).toBe(
- "SELECT name FROM customer",
- );
- });
-
- it("toolResult writes a toolResult message keyed by tool_call_id", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- await w.toolResult("tc-1", "ads.gaql", true, "5 rows");
- await w.toolResult("tc-2", "ads.gaql", false);
- await w.close();
-
- const lines = shadowLines();
- expect(lines).toHaveLength(2);
-
- const ok = (lines[0] as {
- message: {
- role: string;
- toolCallId: string;
- toolName: string;
- isError: boolean;
- content: Array<{ text: string }>;
- };
- }).message;
- expect(ok.role).toBe("toolResult");
- expect(ok.toolCallId).toBe("tc-1");
- expect(ok.toolName).toBe("ads.gaql");
- expect(ok.isError).toBe(false);
- expect(ok.content[0]!.text).toBe("5 rows");
-
- const err = (lines[1] as {
- message: {
- role: string;
- toolCallId: string;
- isError: boolean;
- content?: unknown;
- };
- }).message;
- expect(err.toolCallId).toBe("tc-2");
- expect(err.isError).toBe(true);
- expect(err.content).toBeUndefined();
- });
-});
-
-describe("shadowStreamEvent — gateway → shadow translation", () => {
- it("delta events buffer; flushAssistant emits one message", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- await shadowStreamEvent(w, { kind: "delta", text: "hel" } as ChatStreamEvent);
- await shadowStreamEvent(w, { kind: "delta", text: "lo" } as ChatStreamEvent);
- await w.flushAssistant();
- await w.close();
- const lines = shadowLines();
- expect(lines).toHaveLength(1);
- const msg = (lines[0] as { message: { content: Array<{ text: string }> } }).message;
- expect(msg.content[0]!.text).toBe("hello");
- });
-
- it("final events REPLACE the delta buffer — no double-write (Bug 2 regression)", async () => {
- // Reproduces the bug: provider emits deltas + a cumulative `final`.
- // Naive append would commit "hello world" then again "hello world",
- // producing two assistant messages in the shadow.
- const w = await openShadowWriter(AGENT, THREAD);
- await shadowStreamEvent(w, { kind: "delta", text: "hello " } as ChatStreamEvent);
- await shadowStreamEvent(w, { kind: "delta", text: "world" } as ChatStreamEvent);
- await shadowStreamEvent(w, {
- kind: "final",
- text: "hello world",
- } as ChatStreamEvent);
- await w.close();
-
- const lines = shadowLines();
- // ONE message, not two.
- expect(lines).toHaveLength(1);
- const msg = (lines[0] as { message: { content: Array<{ text: string }> } }).message;
- expect(msg.content[0]!.text).toBe("hello world");
- });
-
- it("tool start + result events route to writer methods", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- await shadowStreamEvent(w, {
- kind: "tool",
- phase: "start",
- toolCallId: "tc-9",
- name: "exec",
- label: "ls -la",
- } as ChatStreamEvent);
- await shadowStreamEvent(w, {
- kind: "tool",
- phase: "result",
- toolCallId: "tc-9",
- name: "exec",
- label: "done",
- } as ChatStreamEvent);
- await w.close();
- const lines = shadowLines();
- expect(lines).toHaveLength(2);
- const first = (
- lines[0] as { message: { content: Array<{ type: string; id: string }> } }
- ).message;
- expect(first.content[0]!.type).toBe("toolCall");
- expect(first.content[0]!.id).toBe("tc-9");
- const second = (lines[1] as { message: { role: string; toolCallId: string } })
- .message;
- expect(second.role).toBe("toolResult");
- expect(second.toolCallId).toBe("tc-9");
- });
-
- it("lifecycle + error events are skipped (no shadow side-effects)", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- await shadowStreamEvent(w, {
- kind: "lifecycle",
- phase: "start",
- } as ChatStreamEvent);
- await shadowStreamEvent(w, {
- kind: "error",
- message: "boom",
- } as ChatStreamEvent);
- await w.close();
- expect(shadowLines()).toHaveLength(0);
- });
-});
-
-describe("readShadowFromOffset", () => {
- it("returns empty for a missing file without throwing", async () => {
- const r = await readShadowFromOffset(AGENT, "no-such-thread", 0);
- expect(r).toEqual({ bytes: "", byteOffset: 0, fileSize: 0 });
- });
-
- it("returns the new bytes since the supplied byteOffset", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- w.appendDelta("first");
- await w.flushAssistant();
- const after1 = await readShadowFromOffset(AGENT, THREAD, 0);
- expect(after1.bytes.length).toBeGreaterThan(0);
- expect(after1.byteOffset).toBe(after1.fileSize);
-
- // Append a second event; calling with the prior byteOffset should
- // return only the new line.
- w.appendDelta("second");
- await w.flushAssistant();
- const after2 = await readShadowFromOffset(AGENT, THREAD, after1.byteOffset);
- expect(after2.bytes.length).toBeGreaterThan(0);
- expect(after2.bytes).toContain("second");
- expect(after2.bytes).not.toContain("first");
- await w.close();
- });
-
- it("truncation resets the offset (defensive — file rotated/cleared)", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- w.appendDelta("one");
- await w.flushAssistant();
- const offsetPastEnd = 9999;
- const r = await readShadowFromOffset(AGENT, THREAD, offsetPastEnd);
- // byteOffset higher than fileSize ⇒ reset to 0 + read everything.
- expect(r.bytes).toContain("one");
- await w.close();
- });
-
- it("only consumes complete lines — a partial trailing line stays unconsumed", async () => {
- // Build the file by hand to simulate a writer mid-append. The
- // appendFile path always writes a full JSON+\n line atomically per
- // call, so this is a pathological case; the parser must still be
- // resilient against it.
- const w = await openShadowWriter(AGENT, THREAD);
- w.appendDelta("a complete line");
- await w.flushAssistant();
- await w.close();
-
- // Manually splice a partial line on at the end.
- const fs = await import("node:fs/promises");
- await fs.appendFile(
- shadowTranscriptPath(AGENT, THREAD),
- '{"partial":"no newline yet"',
- "utf8",
- );
- const r = await readShadowFromOffset(AGENT, THREAD, 0);
- // The complete line ends in \n; the partial bytes after the last \n
- // must NOT be in `bytes` — they'll be picked up on a later poll once
- // the writer finishes.
- expect(r.bytes.endsWith("\n")).toBe(true);
- expect(r.bytes).not.toContain("partial");
- expect(r.byteOffset).toBeLessThan(r.fileSize);
- });
-});
-
-describe("end-to-end: shadow lines round-trip through rawEntryToEvents", () => {
- it("produces TranscriptEvents the polling path already knows how to render", async () => {
- const w = await openShadowWriter(AGENT, THREAD);
- await shadowStreamEvent(w, { kind: "delta", text: "thinking..." } as ChatStreamEvent);
- await shadowStreamEvent(w, {
- kind: "tool",
- phase: "start",
- toolCallId: "tc-1",
- name: "ads.gaql",
- label: "SELECT 1",
- } as ChatStreamEvent);
- await shadowStreamEvent(w, {
- kind: "tool",
- phase: "result",
- toolCallId: "tc-1",
- name: "ads.gaql",
- label: "ok",
- } as ChatStreamEvent);
- await shadowStreamEvent(w, {
- kind: "final",
- text: "done — final answer",
- } as ChatStreamEvent);
- await w.close();
-
- const events = shadowLines().flatMap((line, idx) => {
- const raw = line as Parameters<typeof rawEntryToEvents>[0];
- return rawEntryToEvents(raw, `${raw.id ?? "anon"}-${idx}`);
- });
-
- // We expect (in order):
- // 1. assistant_text "thinking..." — flushed by toolStart
- // 2. tool_call tc-1
- // 3. tool_result tc-1
- // 4. assistant_text "done — final answer" — from `final` via replace
- const kinds = events.map((e) => e.kind);
- expect(kinds).toEqual([
- "assistant_text",
- "tool_call",
- "tool_result",
- "assistant_text",
- ]);
- const finalText = events[3] as { kind: "assistant_text"; body: string };
- expect(finalText.body).toBe("done — final answer");
- const toolCall = events[1] as {
- kind: "tool_call";
- tool_call_id: string;
- name: string;
- };
- expect(toolCall.tool_call_id).toBe("tc-1");
- expect(toolCall.name).toBe("ads.gaql");
- const toolResult = events[2] as {
- kind: "tool_result";
- tool_call_id: string;
- ok: boolean;
- };
- expect(toolResult.tool_call_id).toBe("tc-1");
- expect(toolResult.ok).toBe(true);
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/shadow-transcript.ts b/notfair-cmo/src/server/openclaw/shadow-transcript.ts
deleted file mode 100644
index e027c4e2..00000000
--- a/notfair-cmo/src/server/openclaw/shadow-transcript.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-import { mkdir, appendFile, stat, readFile } from "node:fs/promises";
-import { existsSync, readFileSync, statSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, join } from "node:path";
-import { randomUUID } from "node:crypto";
-
-import type { ChatStreamEvent } from "@/server/openclaw/gateway-client";
-
-/**
- * Per-thread shadow transcript that runTaskKickoffServerSide writes as
- * gateway-stream events arrive. Exists because OpenClaw's codex-app-server
- * backend buffers the agent's whole turn in memory and writes the
- * session.jsonl in one shot at session-end via mirrorTranscriptBestEffort
- * — which means `sessions.messages.subscribe` over the WS gateway never
- * fires `session.message` events DURING a turn, even though the agent is
- * producing tokens. Our shadow log fills that gap: we append OpenClaw-
- * shaped lines as soon as we see each delta / tool call / tool result,
- * the SSE bridge tails this file with fs.watch, and the browser renders
- * tokens live just like /api/chat already does.
- *
- * The format is intentionally a subset of OpenClaw's session.jsonl
- * schema so readTranscriptTail's existing parser (rawEntryToEvents)
- * works on both files. The same TranscriptEvent.id space means the
- * client's seenEventIdsRef dedups when OpenClaw eventually flushes its
- * own copy of the transcript at session-end.
- *
- * Location: `~/.notfair-cmo/agents/<agentFullId>/shadow/<threadId>.jsonl`.
- * Living under .notfair-cmo (not .openclaw) so OpenClaw's writers can't
- * race ours; readTranscriptTail explicitly merges both files.
- */
-
-function dataDir(): string {
- return process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
-}
-
-export function shadowTranscriptPath(
- agentFullId: string,
- threadId: string,
-): string {
- return join(dataDir(), "agents", agentFullId, "shadow", `${threadId}.jsonl`);
-}
-
-export function shadowTranscriptExists(
- agentFullId: string,
- threadId: string,
-): boolean {
- return existsSync(shadowTranscriptPath(agentFullId, threadId));
-}
-
-export async function ensureShadowDir(
- agentFullId: string,
- threadId: string,
-): Promise<void> {
- await mkdir(dirname(shadowTranscriptPath(agentFullId, threadId)), {
- recursive: true,
- });
-}
-
-/**
- * State machine the gateway-stream consumer keeps per turn. Deltas
- * accumulate into a single assistant text event committed when the
- * stream emits `final` (or the turn ends). Tool starts/results write
- * dedicated entries with the gateway's toolCallId so the client can
- * pair them.
- */
-export type ShadowWriter = {
- /** Append `assistantBuffer` as a single assistant message + clear. */
- flushAssistant(): Promise<void>;
- /** Push another delta of token text onto the assistant buffer. */
- appendDelta(text: string): void;
- /**
- * Replace the assistant buffer with `text`. Used on the gateway's
- * `final` event — for providers that emit BOTH per-token deltas and
- * a cumulative final, appending would double-count. Replace makes the
- * final authoritative.
- */
- replaceAssistant(text: string): void;
- /** Record a tool call start. */
- toolStart(toolCallId: string, name: string, label?: string): Promise<void>;
- /** Record a tool result (success or error). */
- toolResult(
- toolCallId: string,
- name: string,
- ok: boolean,
- summary?: string,
- ): Promise<void>;
- /** Close the writer — flushes any pending assistant text. */
- close(): Promise<void>;
-};
-
-export async function openShadowWriter(
- agentFullId: string,
- threadId: string,
-): Promise<ShadowWriter> {
- await ensureShadowDir(agentFullId, threadId);
- const path = shadowTranscriptPath(agentFullId, threadId);
- let assistantBuffer = "";
-
- async function writeEntry(entry: object): Promise<void> {
- await appendFile(path, `${JSON.stringify(entry)}\n`, "utf8");
- }
-
- async function flushAssistant(): Promise<void> {
- const body = assistantBuffer.trim();
- assistantBuffer = "";
- if (!body) return;
- await writeEntry({
- type: "message",
- id: `shadow-${randomUUID()}`,
- timestamp: new Date().toISOString(),
- message: {
- role: "assistant",
- content: [{ type: "text", text: body }],
- },
- });
- }
-
- return {
- appendDelta(text: string) {
- assistantBuffer += text;
- },
- replaceAssistant(text: string) {
- assistantBuffer = text;
- },
- flushAssistant,
- async toolStart(toolCallId, name, label) {
- // Flush any preceding assistant text so the tool call shows in the
- // right order in the transcript.
- await flushAssistant();
- await writeEntry({
- type: "message",
- id: `shadow-${randomUUID()}`,
- timestamp: new Date().toISOString(),
- message: {
- role: "assistant",
- content: [
- {
- type: "toolCall",
- id: toolCallId,
- name,
- ...(label ? { arguments: { __label: label } } : {}),
- },
- ],
- },
- });
- },
- async toolResult(toolCallId, name, ok, summary) {
- await writeEntry({
- type: "message",
- id: `shadow-${randomUUID()}`,
- timestamp: new Date().toISOString(),
- message: {
- role: "toolResult",
- toolCallId,
- toolName: name,
- isError: !ok,
- content: summary
- ? [{ type: "text", text: summary }]
- : undefined,
- },
- });
- },
- async close() {
- await flushAssistant();
- },
- };
-}
-
-/**
- * Hook into runTaskKickoffServerSide's stream: forward each event to
- * the shadow writer with reasonable bucketing. Returns a function that
- * closes the writer (flush any buffered assistant text).
- */
-export async function shadowStreamEvent(
- writer: ShadowWriter,
- evt: ChatStreamEvent,
-): Promise<void> {
- switch (evt.kind) {
- case "delta":
- writer.appendDelta(evt.text);
- return;
- case "final":
- // `final.text` is the cumulative assistant turn — for providers
- // that ALSO emit per-token deltas, naive appending would
- // double-count the same text. Replace the buffer with `final`
- // and flush exactly once. Providers that only emit final
- // (deltaless backends) land in the same place.
- writer.replaceAssistant(evt.text);
- await writer.flushAssistant();
- return;
- case "tool":
- if (evt.phase === "start") {
- await writer.toolStart(evt.toolCallId, evt.name, evt.label);
- } else if (evt.phase === "result") {
- // We don't know ok/summary from the result event shape; treat
- // as ok with no summary. Errors will surface via the gateway's
- // own `error` events.
- await writer.toolResult(evt.toolCallId, evt.name, true, evt.label);
- }
- return;
- case "lifecycle":
- case "error":
- return;
- }
-}
-
-/**
- * Read the shadow JSONL from `byteOffset` to EOF. Mirrors the API of
- * readTranscriptTail so the polling path can merge shadow + OpenClaw
- * transcripts.
- */
-export type ShadowTailResult = {
- bytes: string;
- byteOffset: number;
- fileSize: number;
-};
-
-export function readShadowTail(
- agentFullId: string,
- threadId: string,
- byteOffset: number,
-): ShadowTailResult {
- const path = shadowTranscriptPath(agentFullId, threadId);
- if (!existsSync(path)) return { bytes: "", byteOffset, fileSize: 0 };
- let size: number;
- try {
- size = statSync(path).size;
- } catch {
- return { bytes: "", byteOffset, fileSize: 0 };
- }
- if (byteOffset > size) byteOffset = 0;
- if (byteOffset === size) return { bytes: "", byteOffset, fileSize: size };
- let raw: string;
- try {
- const buf = readFileSync(path);
- raw = buf.slice(byteOffset).toString("utf8");
- } catch {
- return { bytes: "", byteOffset, fileSize: size };
- }
- const lastNl = raw.lastIndexOf("\n");
- const consumable = lastNl < 0 ? "" : raw.slice(0, lastNl + 1);
- const newByteOffset = byteOffset + Buffer.byteLength(consumable, "utf8");
- return { bytes: consumable, byteOffset: newByteOffset, fileSize: size };
-}
-
-/** Async read for SSE tailer that wants non-blocking IO. */
-export async function readShadowFromOffset(
- agentFullId: string,
- threadId: string,
- byteOffset: number,
-): Promise<ShadowTailResult> {
- const path = shadowTranscriptPath(agentFullId, threadId);
- let size: number;
- try {
- size = (await stat(path)).size;
- } catch {
- return { bytes: "", byteOffset, fileSize: 0 };
- }
- if (byteOffset > size) byteOffset = 0;
- if (byteOffset === size) return { bytes: "", byteOffset, fileSize: size };
- let raw: string;
- try {
- const buf = await readFile(path);
- raw = buf.slice(byteOffset).toString("utf8");
- } catch {
- return { bytes: "", byteOffset, fileSize: size };
- }
- const lastNl = raw.lastIndexOf("\n");
- const consumable = lastNl < 0 ? "" : raw.slice(0, lastNl + 1);
- const newByteOffset = byteOffset + Buffer.byteLength(consumable, "utf8");
- return { bytes: consumable, byteOffset: newByteOffset, fileSize: size };
-}
diff --git a/notfair-cmo/src/server/openclaw/thread-origins.test.ts b/notfair-cmo/src/server/openclaw/thread-origins.test.ts
deleted file mode 100644
index 23093b16..00000000
--- a/notfair-cmo/src/server/openclaw/thread-origins.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- isTaskOrCronSession,
- pickLatestChatSession,
-} from "./thread-origins";
-
-describe("isTaskOrCronSession", () => {
- it("returns true for cron labels", () => {
- expect(
- isTaskOrCronSession("cron:7f879fba:run:abc", new Set()),
- ).toBe(true);
- });
-
- it("returns true when the label matches a known task thread_id", () => {
- const taskIds = new Set(["task-thread-uuid"]);
- expect(isTaskOrCronSession("task-thread-uuid", taskIds)).toBe(true);
- });
-
- it("returns false for plain chat labels", () => {
- expect(isTaskOrCronSession("random-uuid", new Set())).toBe(false);
- expect(isTaskOrCronSession("main", new Set())).toBe(false);
- });
-
- it("does not treat 'cron' as cron prefix without the colon", () => {
- // Defensive: a chat thread that happens to start with the letters
- // "cron" but isn't an OpenClaw cron-run label should not be filtered.
- expect(isTaskOrCronSession("crontab-discussion", new Set())).toBe(false);
- });
-});
-
-describe("pickLatestChatSession", () => {
- // listSessionsForAgent returns newest-first; tests mirror that order.
- const taskIds = new Set(["task-1-thread"]);
-
- it("returns the first chat session, skipping leading task/cron rows", () => {
- const sessions = [
- { label: "cron:abc:run:1" }, // cron — skip
- { label: "task-1-thread" }, // task — skip
- { label: "uuid-newest-chat" }, // pick this
- { label: "uuid-older-chat" },
- ];
- expect(pickLatestChatSession(sessions, taskIds)?.label).toBe(
- "uuid-newest-chat",
- );
- });
-
- it("returns undefined when every session is a task or cron", () => {
- const sessions = [
- { label: "cron:abc:run:1" },
- { label: "task-1-thread" },
- ];
- expect(pickLatestChatSession(sessions, taskIds)).toBeUndefined();
- });
-
- it("returns undefined for an empty list (caller mints a fresh id)", () => {
- expect(pickLatestChatSession([], taskIds)).toBeUndefined();
- });
-
- it("works with the OpenClawSession shape, not just bare labels", () => {
- // Generic over { label: string } — calling with the full session
- // shape returns the same object so the caller can read sessionId.
- const sessions = [
- {
- label: "task-1-thread",
- sessionId: "internal-1",
- sessionKey: "agent:x:task-1-thread",
- lastInteractionAt: 200,
- pending: false,
- },
- {
- label: "chat-uuid",
- sessionId: "internal-2",
- sessionKey: "agent:x:chat-uuid",
- lastInteractionAt: 100,
- pending: false,
- },
- ];
- const picked = pickLatestChatSession(sessions, taskIds);
- expect(picked?.sessionId).toBe("internal-2");
- });
-});
diff --git a/notfair-cmo/src/server/openclaw/thread-origins.ts b/notfair-cmo/src/server/openclaw/thread-origins.ts
deleted file mode 100644
index 41527b13..00000000
--- a/notfair-cmo/src/server/openclaw/thread-origins.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-import {
- closeSync,
- existsSync,
- openSync,
- readSync,
- statSync,
-} from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-
-import { listTasksByAgent } from "@/server/db/tasks";
-import { listCronsForProject } from "./crons";
-import type { OpenClawSession } from "./sessions";
-
-const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");
-
-/**
- * What spawned a chat thread. Used by the thread dropdown to label each row
- * with something meaningful — a task's display_id, a cron's short name, or
- * the first user message of a free-form chat — instead of an opaque UUID.
- */
-export type SessionOrigin =
- | { kind: "task"; display_id: string; title: string | null }
- | { kind: "cron"; cron_name: string }
- | { kind: "chat"; preview: string };
-
-/** OpenClaw cron-run session labels are `cron:<jobId>:run:<runSessionId>`. */
-const CRON_LABEL_PREFIX = "cron:";
-
-/**
- * True when the session belongs to a kanban task (label matches a task's
- * `thread_id`) or a cron run (label starts with `cron:`). Used by the chat
- * landing redirect to skip those rows so the user lands on a free-form
- * chat instead of a task workspace.
- */
-export function isTaskOrCronSession(
- label: string,
- taskThreadIds: ReadonlySet<string>,
-): boolean {
- return label.startsWith(CRON_LABEL_PREFIX) || taskThreadIds.has(label);
-}
-
-/**
- * Pick the most-recent free-form chat session (skipping task + cron rows).
- * Assumes `sessions` is already sorted newest-first, which is the order
- * `listSessionsForAgent` returns. Returns `undefined` when no chat exists.
- */
-export function pickLatestChatSession<
- S extends { label: string },
->(sessions: readonly S[], taskThreadIds: ReadonlySet<string>): S | undefined {
- return sessions.find((s) => !isTaskOrCronSession(s.label, taskThreadIds));
-}
-const PREVIEW_MAX_CHARS = 40;
-/**
- * Cap the file read used to find a chat thread's first user message. The
- * first message is always at the top of the JSONL; 32 KB is enough to span
- * the session header + first message + slack, without dragging in the full
- * transcript (which can run into MB on a long chat).
- */
-const FIRST_MESSAGE_PROBE_BYTES = 32 * 1024;
-
-/**
- * Classify each session by origin so the dropdown can show meaningful labels.
- * Tasks come from the project DB (`tasks.thread_id === session.label`); crons
- * come from OpenClaw's cron list keyed by jobId parsed out of the label; free
- * chats fall back to a preview of the first user message in the JSONL.
- *
- * Returns a map keyed by session label (the part after `agent:<id>:`). Pending
- * sessions are skipped — they have no transcript yet and no kanban/cron link.
- */
-export async function classifySessions(
- agentFullId: string,
- projectSlug: string,
- sessions: OpenClawSession[],
-): Promise<Map<string, SessionOrigin>> {
- const out = new Map<string, SessionOrigin>();
- if (sessions.length === 0) return out;
-
- const cronJobIds = new Set<string>();
- const chatLikeLabels: string[] = [];
- for (const s of sessions) {
- if (s.pending) continue;
- if (s.label.startsWith(CRON_LABEL_PREFIX)) {
- const jobId = s.label.split(":")[1];
- if (jobId) cronJobIds.add(jobId);
- } else {
- chatLikeLabels.push(s.label);
- }
- }
-
- // Tasks — one DB read for the agent's queue, then a map lookup per session.
- const taskByThread = new Map<
- string,
- { display_id: string; title: string | null }
- >();
- if (chatLikeLabels.length > 0) {
- const tasks = listTasksByAgent(agentFullId);
- for (const t of tasks) {
- if (t.thread_id) {
- taskByThread.set(t.thread_id, {
- display_id: t.display_id,
- title: t.title,
- });
- }
- }
- }
-
- // Crons — only hit the cron list if at least one label looks cron-shaped.
- const cronByJobId = new Map<string, string>();
- if (cronJobIds.size > 0) {
- const view = await listCronsForProject(projectSlug);
- for (const g of view.groups) {
- for (const c of g.crons) {
- cronByJobId.set(c.id, c.short_name || c.name);
- }
- }
- }
-
- for (const s of sessions) {
- if (s.pending) continue;
- if (s.label.startsWith(CRON_LABEL_PREFIX)) {
- const jobId = s.label.split(":")[1] ?? "";
- const name = cronByJobId.get(jobId);
- out.set(s.label, {
- kind: "cron",
- cron_name: name ?? `cron · ${jobId.slice(0, 8)}`,
- });
- continue;
- }
- const task = taskByThread.get(s.label);
- if (task) {
- out.set(s.label, {
- kind: "task",
- display_id: task.display_id,
- title: task.title,
- });
- continue;
- }
- out.set(s.label, {
- kind: "chat",
- preview: readFirstUserMessagePreview(agentFullId, s.sessionId),
- });
- }
- return out;
-}
-
-/**
- * Peek at a session's JSONL transcript and return a short preview of the
- * first user message. Reads only the first ~32 KB rather than the full file
- * — the first user turn is always at the top, and long transcripts can run
- * into the MBs.
- */
-function readFirstUserMessagePreview(
- agentFullId: string,
- sessionId: string,
-): string {
- const path = join(
- OPENCLAW_HOME,
- "agents",
- agentFullId,
- "sessions",
- `${sessionId}.jsonl`,
- );
- if (!existsSync(path)) return "";
- let fd: number;
- try {
- fd = openSync(path, "r");
- } catch {
- return "";
- }
- let raw: string;
- try {
- const size = statSync(path).size;
- const len = Math.min(size, FIRST_MESSAGE_PROBE_BYTES);
- const buf = Buffer.alloc(len);
- readSync(fd, buf, 0, len, 0);
- raw = buf.toString("utf8");
- } catch {
- return "";
- } finally {
- try {
- closeSync(fd);
- } catch {
- // ignore — closing a stale fd shouldn't break the dropdown.
- }
- }
- for (const line of raw.split("\n")) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- let entry: {
- type?: string;
- message?: { role?: string; content?: unknown };
- };
- try {
- entry = JSON.parse(trimmed) as typeof entry;
- } catch {
- continue;
- }
- if (entry.type !== "message") continue;
- const msg = entry.message;
- if (!msg || msg.role !== "user") continue;
- const text = extractText(msg.content);
- if (text) return shorten(stripUserTimestampPrefix(text));
- }
- return "";
-}
-
-function extractText(content: unknown): string {
- if (typeof content === "string") return content;
- if (!Array.isArray(content)) return "";
- const parts: string[] = [];
- for (const c of content) {
- if (typeof c === "string") parts.push(c);
- else if (c && typeof c === "object") {
- const obj = c as { type?: string; text?: string };
- if (obj.type === "text" && typeof obj.text === "string") {
- parts.push(obj.text);
- }
- }
- }
- return parts.join(" ");
-}
-
-// Same shape as transcript-tail.stripUserTimestampPrefix — keeps the preview
-// from leading with the bracketed timestamp OpenClaw prepends to user turns.
-function stripUserTimestampPrefix(s: string): string {
- return s.replace(
- /^\[[A-Z][a-z]{2} \d{4}-\d{2}-\d{2} \d{2}:\d{2} [A-Z]{2,5}\] ?/,
- "",
- );
-}
-
-function shorten(s: string): string {
- const flat = s.replace(/\s+/g, " ").trim();
- if (flat.length <= PREVIEW_MAX_CHARS) return flat;
- return flat.slice(0, PREVIEW_MAX_CHARS - 1) + "…";
-}
diff --git a/notfair-cmo/src/server/openclaw/transcript-tail.test.ts b/notfair-cmo/src/server/openclaw/transcript-tail.test.ts
deleted file mode 100644
index 61eaefb1..00000000
--- a/notfair-cmo/src/server/openclaw/transcript-tail.test.ts
+++ /dev/null
@@ -1,629 +0,0 @@
-import { mkdirSync, writeFileSync, rmSync } from "node:fs";
-import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
-
-const { tmpHome, ORIGINAL_HOME } = vi.hoisted(() => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { tmpdir } = require("node:os") as typeof import("node:os");
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { join: joinPath } = require("node:path") as typeof import("node:path");
- const original = process.env.OPENCLAW_HOME;
- const tmp = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-transcript-"));
- process.env.OPENCLAW_HOME = tmp;
- return { tmpHome: tmp, ORIGINAL_HOME: original };
-});
-
-const findSessionMock = vi.fn();
-vi.mock("@/server/openclaw/sessions", () => ({
- findSessionBySessionId: (...args: unknown[]) => findSessionMock(...args),
-}));
-
-import { resolveTranscriptPath, readTranscriptTail } from "./transcript-tail";
-import { join } from "node:path";
-
-function transcriptPath(agentFullId: string, sessionId: string): string {
- return join(tmpHome, "agents", agentFullId, "sessions", `${sessionId}.jsonl`);
-}
-
-function writeTranscript(agentFullId: string, sessionId: string, lines: string[]): string {
- const p = transcriptPath(agentFullId, sessionId);
- mkdirSync(join(tmpHome, "agents", agentFullId, "sessions"), { recursive: true });
- writeFileSync(p, lines.join("\n") + (lines.length ? "\n" : ""), "utf8");
- return p;
-}
-
-function setSession(sessionId: string, label = sessionId): void {
- findSessionMock.mockReturnValue({
- sessionId,
- label,
- sessionKey: `agent:demo:${label}`,
- lastInteractionAt: 0,
- pending: false,
- });
-}
-
-describe("resolveTranscriptPath", () => {
- beforeEach(() => {
- findSessionMock.mockReset();
- });
-
- it("returns null when session not found", () => {
- findSessionMock.mockReturnValue(null);
- expect(resolveTranscriptPath("demo", "missing")).toBeNull();
- });
-
- it("returns null when file does not exist on disk", () => {
- setSession("sess-no-file");
- expect(resolveTranscriptPath("demo", "sess-no-file")).toBeNull();
- });
-
- it("returns the absolute path when session exists and file is on disk", () => {
- writeTranscript("demo", "sess-1", []);
- setSession("sess-1");
- expect(resolveTranscriptPath("demo", "sess-1")).toBe(transcriptPath("demo", "sess-1"));
- });
-});
-
-describe("readTranscriptTail", () => {
- beforeEach(() => {
- findSessionMock.mockReset();
- });
-
- it("returns empty events + same byteOffset when the file does not exist", () => {
- findSessionMock.mockReturnValue(null);
- const r = readTranscriptTail("demo", "x", 42);
- expect(r).toEqual({ events: [], byteOffset: 42, fileSize: 0 });
- });
-
- it("returns empty when byteOffset === fileSize (no new bytes)", () => {
- const lines = [JSON.stringify({ type: "message", id: "m1" })];
- writeTranscript("demo", "sess-2", lines);
- setSession("sess-2");
- const first = readTranscriptTail("demo", "sess-2", 0);
- expect(first.events.length).toBeGreaterThanOrEqual(0);
- const second = readTranscriptTail("demo", "sess-2", first.byteOffset);
- expect(second.events).toEqual([]);
- expect(second.byteOffset).toBe(first.byteOffset);
- });
-
- it("resets the byteOffset when it's beyond fileSize (rotation/truncation)", () => {
- writeTranscript("demo", "sess-3", [JSON.stringify({ type: "x" })]);
- setSession("sess-3");
- const r = readTranscriptTail("demo", "sess-3", 1_000_000);
- expect(r.events.length).toBe(1);
- });
-
- it("emits a user_message for role:user with string content", () => {
- writeTranscript("demo", "sess-4", [
- JSON.stringify({
- type: "message",
- id: "u1",
- timestamp: 1700000000,
- message: { role: "user", content: "hello there" },
- }),
- ]);
- setSession("sess-4");
- const r = readTranscriptTail("demo", "sess-4", 0);
- expect(r.events.length).toBe(1);
- const e = r.events[0]!;
- expect(e.kind).toBe("user_message");
- if (e.kind === "user_message") {
- expect(e.body).toBe("hello there");
- expect(e.ts).toBe(1700000000);
- }
- });
-
- it("strips a timestamp prefix from user messages", () => {
- writeTranscript("demo", "sess-5", [
- JSON.stringify({
- type: "message",
- id: "u1",
- message: {
- role: "user",
- content: "[Mon 2026-05-19 09:00 PDT] real body",
- },
- }),
- ]);
- setSession("sess-5");
- const r = readTranscriptTail("demo", "sess-5", 0);
- const e = r.events[0]!;
- if (e.kind === "user_message") {
- expect(e.body).toBe("real body");
- }
- });
-
- it("emits user_message with array-of-text content joined", () => {
- writeTranscript("demo", "sess-6", [
- JSON.stringify({
- type: "message",
- id: "u1",
- message: {
- role: "user",
- content: [
- { type: "text", text: "first" },
- "raw-string-part",
- { type: "text", text: "second" },
- ],
- },
- }),
- ]);
- setSession("sess-6");
- const r = readTranscriptTail("demo", "sess-6", 0);
- const e = r.events[0]!;
- if (e.kind === "user_message") {
- expect(e.body).toContain("first");
- expect(e.body).toContain("raw-string-part");
- expect(e.body).toContain("second");
- }
- });
-
- it("skips user messages whose body is empty after extraction", () => {
- writeTranscript("demo", "sess-empty-user", [
- JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: "" } }),
- ]);
- setSession("sess-empty-user");
- const r = readTranscriptTail("demo", "sess-empty-user", 0);
- expect(r.events).toEqual([]);
- });
-
- it("emits tool_result for top-level role:toolResult messages", () => {
- writeTranscript("demo", "sess-7", [
- JSON.stringify({
- type: "message",
- id: "tr1",
- timestamp: 1000,
- message: {
- role: "toolResult",
- toolCallId: "call-1",
- toolName: "exec",
- isError: false,
- content: "stdout: ok",
- },
- }),
- ]);
- setSession("sess-7");
- const r = readTranscriptTail("demo", "sess-7", 0);
- expect(r.events.length).toBe(1);
- const e = r.events[0]!;
- expect(e.kind).toBe("tool_result");
- if (e.kind === "tool_result") {
- expect(e.tool_call_id).toBe("call-1");
- expect(e.ok).toBe(true);
- expect(e.summary).toBe("stdout: ok");
- expect(e.name).toBe("exec");
- }
- });
-
- it("marks isError:true toolResults as ok:false", () => {
- writeTranscript("demo", "sess-7-err", [
- JSON.stringify({
- type: "message",
- id: "tr1",
- message: {
- role: "toolResult",
- toolCallId: "call-1",
- isError: true,
- content: "boom",
- },
- }),
- ]);
- setSession("sess-7-err");
- const r = readTranscriptTail("demo", "sess-7-err", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_result") {
- expect(e.ok).toBe(false);
- expect(e.name).toBe("tool");
- }
- });
-
- it("skips toolResult messages without a toolCallId", () => {
- writeTranscript("demo", "sess-7-no-id", [
- JSON.stringify({
- type: "message",
- id: "tr1",
- message: { role: "toolResult", content: "x" },
- }),
- ]);
- setSession("sess-7-no-id");
- const r = readTranscriptTail("demo", "sess-7-no-id", 0);
- expect(r.events).toEqual([]);
- });
-
- it("emits assistant_text for assistant text-part content", () => {
- writeTranscript("demo", "sess-8", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- { type: "text", text: "Sure, here we go." },
- ],
- },
- }),
- ]);
- setSession("sess-8");
- const r = readTranscriptTail("demo", "sess-8", 0);
- expect(r.events.length).toBe(1);
- const e = r.events[0]!;
- expect(e.kind).toBe("assistant_text");
- if (e.kind === "assistant_text") expect(e.body).toBe("Sure, here we go.");
- });
-
- it("emits assistant_text for string parts in assistant content", () => {
- writeTranscript("demo", "sess-8-str", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: { role: "assistant", content: ["raw string body"] },
- }),
- ]);
- setSession("sess-8-str");
- const r = readTranscriptTail("demo", "sess-8-str", 0);
- expect(r.events[0]!.kind).toBe("assistant_text");
- });
-
- it("skips empty/whitespace text parts in assistant content", () => {
- writeTranscript("demo", "sess-8-blank", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- { type: "text", text: " " },
- " ",
- { type: "text", text: "real" },
- ],
- },
- }),
- ]);
- setSession("sess-8-blank");
- const r = readTranscriptTail("demo", "sess-8-blank", 0);
- expect(r.events.length).toBe(1);
- });
-
- it("emits tool_call with command label for exec-shaped args", () => {
- writeTranscript("demo", "sess-9", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- {
- type: "toolCall",
- id: "call-1",
- name: "exec",
- arguments: { command: "pnpm test\nfoo" },
- },
- ],
- },
- }),
- ]);
- setSession("sess-9");
- const r = readTranscriptTail("demo", "sess-9", 0);
- const e = r.events[0]!;
- expect(e.kind).toBe("tool_call");
- if (e.kind === "tool_call") {
- expect(e.label).toContain("pnpm test");
- expect(e.tool_call_id).toBe("call-1");
- expect(e.name).toBe("exec");
- }
- });
-
- it("falls back to JSON preview label when no known arg shape matches", () => {
- writeTranscript("demo", "sess-10", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- {
- type: "toolCall",
- id: "call-x",
- name: "unknown",
- arguments: { random: { nested: 1 } },
- },
- ],
- },
- }),
- ]);
- setSession("sess-10");
- const r = readTranscriptTail("demo", "sess-10", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_call") expect(e.label).toContain("random");
- });
-
- it("returns null label when toolCall has no args", () => {
- writeTranscript("demo", "sess-noargs", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [{ type: "toolCall", id: "call-x", name: "x" }],
- },
- }),
- ]);
- setSession("sess-noargs");
- const r = readTranscriptTail("demo", "sess-noargs", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_call") expect(e.label).toBeNull();
- });
-
- it("uses input field when arguments missing on toolCall", () => {
- writeTranscript("demo", "sess-input", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- {
- type: "toolCall",
- id: "c1",
- name: "read",
- input: { path: "/foo/bar.ts" },
- },
- ],
- },
- }),
- ]);
- setSession("sess-input");
- const r = readTranscriptTail("demo", "sess-input", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_call") expect(e.label).toBe("/foo/bar.ts");
- });
-
- it("emits inline toolResult inside assistant content", () => {
- writeTranscript("demo", "sess-11", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- {
- type: "toolResult",
- toolCallId: "call-1",
- name: "exec",
- isError: false,
- content: [{ text: "result text" }],
- },
- ],
- },
- }),
- ]);
- setSession("sess-11");
- const r = readTranscriptTail("demo", "sess-11", 0);
- const e = r.events[0]!;
- expect(e.kind).toBe("tool_result");
- if (e.kind === "tool_result") {
- expect(e.tool_call_id).toBe("call-1");
- expect(e.summary).toBe("result text");
- expect(e.ok).toBe(true);
- }
- });
-
- it("uses tool_call_id (snake) and is_error (snake) as fallbacks", () => {
- writeTranscript("demo", "sess-snake", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- {
- type: "toolResult",
- tool_call_id: "snake-id",
- name: "x",
- is_error: true,
- output: "x output",
- },
- ],
- },
- }),
- ]);
- setSession("sess-snake");
- const r = readTranscriptTail("demo", "sess-snake", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_result") {
- expect(e.tool_call_id).toBe("snake-id");
- expect(e.ok).toBe(false);
- expect(e.summary).toBe("x output");
- }
- });
-
- it("emits an unknown event for non-message rows", () => {
- writeTranscript("demo", "sess-12", [
- JSON.stringify({ type: "session-meta", id: "m1", foo: "bar" }),
- ]);
- setSession("sess-12");
- const r = readTranscriptTail("demo", "sess-12", 0);
- const e = r.events[0]!;
- expect(e.kind).toBe("unknown");
- if (e.kind === "unknown") expect(e.raw_type).toBe("session-meta");
- });
-
- it("skips non-message entries with missing type (raw_type defaults to ?)", () => {
- writeTranscript("demo", "sess-noType", [JSON.stringify({ id: "m1", foo: 1 })]);
- setSession("sess-noType");
- const r = readTranscriptTail("demo", "sess-noType", 0);
- const e = r.events[0]!;
- if (e.kind === "unknown") expect(e.raw_type).toBe("?");
- });
-
- it("skips lines that are not valid JSON", () => {
- writeTranscript("demo", "sess-bad", [
- "not json",
- JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: "hi" } }),
- ]);
- setSession("sess-bad");
- const r = readTranscriptTail("demo", "sess-bad", 0);
- expect(r.events.length).toBe(1);
- expect(r.events[0]!.kind).toBe("user_message");
- });
-
- it("only consumes up to the last newline (leaves partial line unconsumed)", () => {
- const p = transcriptPath("demo", "sess-partial");
- mkdirSync(join(tmpHome, "agents", "demo", "sessions"), { recursive: true });
- const completeLine =
- JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: "hello" } }) +
- "\n";
- const partial =
- JSON.stringify({ type: "message", id: "u2", message: { role: "user", content: "world" } });
- writeFileSync(p, completeLine + partial, "utf8");
- setSession("sess-partial");
- const r = readTranscriptTail("demo", "sess-partial", 0);
- expect(r.events.length).toBe(1);
- expect(r.byteOffset).toBe(Buffer.byteLength(completeLine, "utf8"));
- expect(r.byteOffset).toBeLessThan(r.fileSize);
- });
-
- it("returns events:[] when buffer has no newline at all", () => {
- const p = transcriptPath("demo", "sess-noNL");
- mkdirSync(join(tmpHome, "agents", "demo", "sessions"), { recursive: true });
- writeFileSync(p, "no newline here", "utf8");
- setSession("sess-noNL");
- const r = readTranscriptTail("demo", "sess-noNL", 0);
- expect(r.events).toEqual([]);
- expect(r.byteOffset).toBe(0);
- });
-
- it("parses string timestamps via Date.parse", () => {
- writeTranscript("demo", "sess-tsstr", [
- JSON.stringify({
- type: "message",
- id: "u1",
- timestamp: "2026-01-01T00:00:00Z",
- message: { role: "user", content: "hi" },
- }),
- ]);
- setSession("sess-tsstr");
- const r = readTranscriptTail("demo", "sess-tsstr", 0);
- expect(r.events[0]!.ts).toBe(Date.parse("2026-01-01T00:00:00Z"));
- });
-
- it("ts defaults to 0 when timestamp is missing", () => {
- writeTranscript("demo", "sess-nots", [
- JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: "hi" } }),
- ]);
- setSession("sess-nots");
- const r = readTranscriptTail("demo", "sess-nots", 0);
- expect(r.events[0]!.ts).toBe(0);
- });
-
- it("skips messages with role other than user/assistant/toolResult", () => {
- writeTranscript("demo", "sess-role", [
- JSON.stringify({ type: "message", id: "x", message: { role: "system", content: "noise" } }),
- ]);
- setSession("sess-role");
- const r = readTranscriptTail("demo", "sess-role", 0);
- expect(r.events).toEqual([]);
- });
-
- it("skips message entries with no message body", () => {
- writeTranscript("demo", "sess-nobody", [JSON.stringify({ type: "message", id: "x" })]);
- setSession("sess-nobody");
- const r = readTranscriptTail("demo", "sess-nobody", 0);
- expect(r.events).toEqual([]);
- });
-
- it("uses url label when toolCall has url arg", () => {
- writeTranscript("demo", "sess-url", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- {
- type: "toolCall",
- id: "c1",
- name: "fetch",
- arguments: { url: "https://example.com/api" },
- },
- ],
- },
- }),
- ]);
- setSession("sess-url");
- const r = readTranscriptTail("demo", "sess-url", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_call") expect(e.label).toBe("https://example.com/api");
- });
-
- it("summarizes string content for inline toolResult", () => {
- writeTranscript("demo", "sess-strsum", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- {
- type: "toolResult",
- toolCallId: "c1",
- content: "single string output",
- },
- ],
- },
- }),
- ]);
- setSession("sess-strsum");
- const r = readTranscriptTail("demo", "sess-strsum", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_result") expect(e.summary).toBe("single string output");
- });
-
- it("returns null summary when toolResult content is null/empty array", () => {
- writeTranscript("demo", "sess-nullsum", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [{ type: "toolResult", toolCallId: "c1", content: [] }],
- },
- }),
- ]);
- setSession("sess-nullsum");
- const r = readTranscriptTail("demo", "sess-nullsum", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_result") expect(e.summary).toBeNull();
- });
-
- it("summarizes object content as JSON preview", () => {
- writeTranscript("demo", "sess-objsum", [
- JSON.stringify({
- type: "message",
- id: "a1",
- message: {
- role: "assistant",
- content: [
- {
- type: "toolResult",
- toolCallId: "c1",
- content: { ok: true, lines: 42 },
- },
- ],
- },
- }),
- ]);
- setSession("sess-objsum");
- const r = readTranscriptTail("demo", "sess-objsum", 0);
- const e = r.events[0]!;
- if (e.kind === "tool_result") expect(e.summary).toMatch(/ok/);
- });
-});
-
-afterAll(() => {
- try {
- rmSync(tmpHome, { recursive: true, force: true });
- } catch {}
- if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;
- else delete process.env.OPENCLAW_HOME;
-});
diff --git a/notfair-cmo/src/server/openclaw/transcript-tail.ts b/notfair-cmo/src/server/openclaw/transcript-tail.ts
deleted file mode 100644
index 8af8e020..00000000
--- a/notfair-cmo/src/server/openclaw/transcript-tail.ts
+++ /dev/null
@@ -1,325 +0,0 @@
-import { existsSync, readFileSync, statSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { findSessionBySessionId } from "@/server/openclaw/sessions";
-
-const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");
-
-export type TranscriptEvent =
- | { kind: "user_message"; id: string; ts: number; body: string }
- | {
- kind: "assistant_text";
- id: string;
- ts: number;
- body: string;
- }
- | {
- kind: "tool_call";
- id: string;
- ts: number;
- tool_call_id: string;
- name: string;
- label: string | null;
- }
- | {
- kind: "tool_result";
- id: string;
- ts: number;
- tool_call_id: string;
- name: string;
- summary: string | null;
- ok: boolean;
- }
- | { kind: "unknown"; id: string; ts: number; raw_type: string };
-
-type RawMessageContentPart =
- | { type: "text"; text?: string }
- | {
- type: "toolCall";
- id?: string;
- name?: string;
- arguments?: Record<string, unknown>;
- input?: Record<string, unknown>;
- }
- | {
- type: "toolResult";
- toolCallId?: string;
- tool_call_id?: string;
- name?: string;
- content?: unknown;
- output?: unknown;
- isError?: boolean;
- is_error?: boolean;
- }
- | string;
-
-type RawMessage = {
- role?: string;
- content?: string | RawMessageContentPart[];
- timestamp?: number;
- // Present on top-level toolResult messages (role: "toolResult"). OpenClaw
- // doesn't nest these inside the assistant turn's content array — they're
- // sibling entries with their own role.
- toolCallId?: string;
- toolName?: string;
- isError?: boolean;
-};
-
-export type RawEntry = {
- type?: string;
- id?: string;
- timestamp?: string | number;
- message?: RawMessage;
-};
-
-function sessionJsonlPath(agentFullId: string, sessionId: string): string {
- return join(
- OPENCLAW_HOME,
- "agents",
- agentFullId,
- "sessions",
- `${sessionId}.jsonl`,
- );
-}
-
-/** Resolve URL threadId (label) → on-disk transcript file path. */
-export function resolveTranscriptPath(
- agentFullId: string,
- threadId: string,
-): string | null {
- const session = findSessionBySessionId(agentFullId, threadId);
- if (!session) return null;
- const path = sessionJsonlPath(agentFullId, session.sessionId);
- if (!existsSync(path)) return null;
- return path;
-}
-
-/**
- * Read the JSONL transcript from `byteOffset` to EOF, parse new lines into
- * structured events the client can render. Returns the new byte offset so the
- * caller can stitch incremental polls together without re-reading prior bytes.
- *
- * Returns `{ events: [], byteOffset, fileSize }` when the file doesn't exist
- * yet or no new bytes are available — caller treats it as a no-op.
- */
-export function readTranscriptTail(
- agentFullId: string,
- threadId: string,
- byteOffset: number,
-): { events: TranscriptEvent[]; byteOffset: number; fileSize: number } {
- const path = resolveTranscriptPath(agentFullId, threadId);
- if (!path) return { events: [], byteOffset, fileSize: 0 };
-
- let size: number;
- try {
- size = statSync(path).size;
- } catch {
- return { events: [], byteOffset, fileSize: 0 };
- }
-
- // Defensive: if the file got truncated/rotated, reset to 0.
- if (byteOffset > size) byteOffset = 0;
- if (byteOffset === size) return { events: [], byteOffset, fileSize: size };
-
- let raw: string;
- try {
- const buf = readFileSync(path);
- raw = buf.slice(byteOffset).toString("utf8");
- } catch {
- return { events: [], byteOffset, fileSize: size };
- }
-
- // Only consume up to the last newline; whatever's after is a partial line
- // the writer is still flushing. Leave its bytes unconsumed by reporting an
- // offset that points right after the last complete line.
- const lastNl = raw.lastIndexOf("\n");
- const consumable = lastNl < 0 ? "" : raw.slice(0, lastNl + 1);
- const newByteOffset = byteOffset + Buffer.byteLength(consumable, "utf8");
-
- const events: TranscriptEvent[] = [];
- let lineIdx = 0;
- for (const line of consumable.split("\n")) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- let entry: RawEntry;
- try {
- entry = JSON.parse(trimmed) as RawEntry;
- } catch {
- continue;
- }
- events.push(...rawEntryToEvents(entry, `${entry.id ?? "anon"}-${lineIdx++}`));
- }
-
- return { events, byteOffset: newByteOffset, fileSize: size };
-}
-
-/**
- * Convert one raw JSONL entry (or session.message broadcast payload) into
- * the TranscriptEvents we render. Extracted so the SSE re-attach bridge
- * (which receives `session.message` events from the gateway) can produce
- * the same shapes the polling path already emits.
- */
-export function rawEntryToEvents(entry: RawEntry, baseId: string): TranscriptEvent[] {
- const events: TranscriptEvent[] = [];
- const ts =
- typeof entry.timestamp === "string"
- ? Date.parse(entry.timestamp)
- : typeof entry.timestamp === "number"
- ? entry.timestamp
- : 0;
-
- if (entry.type !== "message") {
- events.push({ kind: "unknown", id: baseId, ts, raw_type: entry.type ?? "?" });
- return events;
- }
- const msg = entry.message;
- if (!msg) return events;
-
- if (msg.role === "user") {
- const body = extractUserText(msg.content);
- if (!body) return events;
- events.push({ kind: "user_message", id: baseId, ts, body });
- return events;
- }
- if (msg.role === "toolResult") {
- const callId = msg.toolCallId ?? "";
- const name = msg.toolName ?? "tool";
- const ok = !msg.isError;
- const summary = summarizeToolResult(msg.content);
- if (callId) {
- events.push({
- kind: "tool_result",
- id: baseId,
- ts,
- tool_call_id: callId,
- name,
- summary,
- ok,
- });
- }
- return events;
- }
- if (msg.role !== "assistant") return events;
-
- const parts = Array.isArray(msg.content) ? msg.content : [];
- let partIdx = 0;
- for (const part of parts) {
- const partId = `${baseId}:${partIdx++}`;
- if (typeof part === "string") {
- if (part.trim()) {
- events.push({ kind: "assistant_text", id: partId, ts, body: part });
- }
- continue;
- }
- if (part?.type === "text") {
- const text = (part.text ?? "").trim();
- if (text) {
- events.push({ kind: "assistant_text", id: partId, ts, body: text });
- }
- continue;
- }
- if (part?.type === "toolCall") {
- const callId = part.id ?? partId;
- const name = part.name ?? "tool";
- const label = formatToolLabel(name, part.arguments ?? part.input);
- events.push({
- kind: "tool_call",
- id: partId,
- ts,
- tool_call_id: callId,
- name,
- label,
- });
- continue;
- }
- if (part?.type === "toolResult") {
- const callId = part.toolCallId ?? part.tool_call_id ?? partId;
- const name = part.name ?? "tool";
- const ok = !(part.isError ?? part.is_error ?? false);
- const summary = summarizeToolResult(part.content ?? part.output);
- events.push({
- kind: "tool_result",
- id: partId,
- ts,
- tool_call_id: callId,
- name,
- summary,
- ok,
- });
- continue;
- }
- }
- return events;
-}
-
-function extractUserText(content: RawMessage["content"]): string {
- if (typeof content === "string") return stripUserTimestampPrefix(content);
- if (!Array.isArray(content)) return "";
- const out: string[] = [];
- for (const c of content) {
- if (typeof c === "string") out.push(c);
- else if (c?.type === "text" && typeof c.text === "string") out.push(c.text);
- }
- return stripUserTimestampPrefix(out.join("\n").trim());
-}
-
-function stripUserTimestampPrefix(s: string): string {
- return s.replace(
- /^\[[A-Z][a-z]{2} \d{4}-\d{2}-\d{2} \d{2}:\d{2} [A-Z]{2,5}\] ?/,
- "",
- );
-}
-
-function formatToolLabel(
- name: string,
- args: Record<string, unknown> | undefined,
-): string | null {
- if (!args) return null;
- // Pick the most informative single field from common tool shapes.
- if (typeof args.command === "string") return shortenLine(args.command);
- if (typeof args.path === "string") return args.path;
- if (typeof args.file_path === "string") return args.file_path;
- if (typeof args.url === "string") return args.url;
- if (typeof args.query === "string") return shortenLine(args.query);
- if (typeof args.pattern === "string") return args.pattern;
- // MCP tools tend to use namespaced names; fall back to a JSON preview.
- try {
- return shortenLine(JSON.stringify(args));
- } catch {
- return null;
- }
-}
-
-function summarizeToolResult(content: unknown): string | null {
- if (content == null) return null;
- if (typeof content === "string") return shortenLine(content);
- if (Array.isArray(content)) {
- const text = content
- .map((c) => {
- if (typeof c === "string") return c;
- if (!c || typeof c !== "object") return "";
- const obj = c as { text?: unknown; content?: unknown };
- // Prefer `text`, fall back to `content` (some MCPs put the payload
- // under `content` directly without splitting into a text/data union).
- if (typeof obj.text === "string" && obj.text) return obj.text;
- if (typeof obj.content === "string" && obj.content) return obj.content;
- return "";
- })
- .filter(Boolean)
- .join("\n");
- return text ? shortenLine(text) : null;
- }
- if (typeof content === "object") {
- try {
- return shortenLine(JSON.stringify(content));
- } catch {
- return null;
- }
- }
- return null;
-}
-
-function shortenLine(s: string, max = 140): string {
- const flat = s.replace(/\s+/g, " ").trim();
- return flat.length > max ? flat.slice(0, max - 1) + "…" : flat;
-}
diff --git a/notfair-cmo/src/server/orchestration/approval-wakeup.test.ts b/notfair-cmo/src/server/orchestration/approval-wakeup.test.ts
deleted file mode 100644
index 7f113e43..00000000
--- a/notfair-cmo/src/server/orchestration/approval-wakeup.test.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-// ── Mocks ──────────────────────────────────────────────────────────
-// approval-wakeup pulls in the gateway, sessions, tasks DB, and approval
-// comments. We don't want any real I/O here — every dependency is stubbed.
-
-const getTaskMock = vi.fn();
-const unblockTaskMock = vi.fn();
-const setTaskThreadIfMissingMock = vi.fn();
-vi.mock("@/server/db/tasks", () => ({
- getTask: (...a: unknown[]) => getTaskMock(...a),
- unblockTask: (...a: unknown[]) => unblockTaskMock(...a),
- setTaskThreadIfMissing: (...a: unknown[]) => setTaskThreadIfMissingMock(...a),
-}));
-
-const appendCommentMock = vi.fn();
-const listCommentsMock = vi.fn();
-vi.mock("@/server/db/approvals", () => ({
- appendComment: (...a: unknown[]) => appendCommentMock(...a),
- listComments: (...a: unknown[]) => listCommentsMock(...a),
-}));
-
-const buildPendingSessionKeyMock = vi.fn(
- (agent: string, session: string) => `agent:${agent}:${session}`,
-);
-const findSessionBySessionIdMock = vi.fn();
-vi.mock("@/server/openclaw/sessions", () => ({
- buildPendingSessionKey: (...a: unknown[]) => buildPendingSessionKeyMock(...(a as [string, string])),
- findSessionBySessionId: (...a: unknown[]) => findSessionBySessionIdMock(...a),
-}));
-
-// streamChatViaGateway is an async iterable. The stub yields a single delta
-// event so the wakeup body has something to drain.
-const streamMock = vi.fn();
-vi.mock("@/server/openclaw/gateway-client", () => ({
- streamChatViaGateway: (...a: unknown[]) => streamMock(...a),
-}));
-
-vi.mock("./task-kickoff", async () => {
- const actual =
- await vi.importActual<typeof import("./task-kickoff")>("./task-kickoff");
- return {
- ...actual,
- generateTaskThreadId: () => "minted-thread-id",
- };
-});
-
-import { wakeTaskOnApprovalResolution } from "./approval-wakeup";
-
-function makeApproval(overrides: Record<string, unknown> = {}) {
- return {
- id: "ap-deadbeef0123",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- task_id: "task-1",
- action_summary: "Raise CPC bid",
- action_type: "bid_change" as const,
- cost_estimate_usd: 0,
- reasoning: null,
- payload_json: "{}",
- status: "approved" as const,
- decision_note: "ok",
- decided_by_kind: "user" as const,
- decided_by_id: null,
- created_at: "2026-05-01T00:00:00Z",
- resolved_at: "2026-05-02T00:00:00Z",
- ...overrides,
- };
-}
-
-function makeTask(overrides: Record<string, unknown> = {}) {
- return {
- id: "task-1",
- display_id: "demo-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- title: "t",
- brief: "b",
- success_criteria: null,
- deadline_iso: null,
- status: "blocked" as const,
- result_json: null,
- error_message: null,
- thread_id: "thread-abc",
- assigner_agent_id: null,
- created_at: "2026-05-01T00:00:00Z",
- updated_at: "2026-05-01T00:00:00Z",
- ...overrides,
- };
-}
-
-async function* yieldDelta(text: string) {
- yield { kind: "delta", text } as const;
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- streamMock.mockImplementation(() => yieldDelta("agent reply"));
-});
-
-describe("wakeTaskOnApprovalResolution", () => {
- it("is a no-op when the approval has no task_id", async () => {
- await wakeTaskOnApprovalResolution(makeApproval({ task_id: null }));
- expect(getTaskMock).not.toHaveBeenCalled();
- expect(streamMock).not.toHaveBeenCalled();
- });
-
- it("is a no-op when the task is terminal (succeeded/failed/cancelled)", async () => {
- getTaskMock.mockReturnValue(makeTask({ status: "done" }));
- await wakeTaskOnApprovalResolution(makeApproval());
- expect(streamMock).not.toHaveBeenCalled();
- expect(unblockTaskMock).not.toHaveBeenCalled();
- });
-
- it("unblocks the task on approve and streams a green-light message", async () => {
- getTaskMock.mockReturnValue(makeTask());
- await wakeTaskOnApprovalResolution(makeApproval({ status: "approved" }));
- expect(unblockTaskMock).toHaveBeenCalledWith("task-1");
- expect(streamMock).toHaveBeenCalledTimes(1);
- const arg = streamMock.mock.calls[0]![0]!;
- expect(arg.message).toMatch(/APPROVED/);
- });
-
- it("unblocks on reject too (agent decides next step)", async () => {
- getTaskMock.mockReturnValue(makeTask());
- await wakeTaskOnApprovalResolution(makeApproval({ status: "rejected" }));
- expect(unblockTaskMock).toHaveBeenCalledWith("task-1");
- const arg = streamMock.mock.calls[0]![0]!;
- expect(arg.message).toMatch(/REJECTED/);
- });
-
- it("does NOT unblock on revision_requested (task stays blocked)", async () => {
- getTaskMock.mockReturnValue(makeTask());
- await wakeTaskOnApprovalResolution(
- makeApproval({ status: "revision_requested", decision_note: "narrow scope" }),
- );
- expect(unblockTaskMock).not.toHaveBeenCalled();
- const arg = streamMock.mock.calls[0]![0]!;
- expect(arg.message).toMatch(/needs revision/);
- expect(arg.message).toMatch(/narrow scope/);
- });
-
- it("appends a system comment recording the delivery", async () => {
- getTaskMock.mockReturnValue(makeTask());
- await wakeTaskOnApprovalResolution(makeApproval({ status: "approved" }));
- expect(appendCommentMock).toHaveBeenCalledWith(
- expect.objectContaining({
- approval_id: "ap-deadbeef0123",
- author_kind: "system",
- body: expect.stringContaining("Delivered to demo-google-ads"),
- }),
- );
- });
-
- it("mints a thread when the task has none yet", async () => {
- getTaskMock.mockReturnValue(makeTask({ thread_id: null }));
- setTaskThreadIfMissingMock.mockReturnValue({
- ...makeTask(),
- thread_id: "minted-thread-id",
- });
- await wakeTaskOnApprovalResolution(makeApproval());
- expect(setTaskThreadIfMissingMock).toHaveBeenCalledWith(
- "task-1",
- "minted-thread-id",
- );
- const arg = streamMock.mock.calls[0]![0]!;
- expect(arg.sessionId).toBe("minted-thread-id");
- });
-
- it("drains the gateway stream so the agent's MCP tool calls during the turn can fire", async () => {
- getTaskMock.mockReturnValue(makeTask());
- streamMock.mockImplementation(() => yieldDelta("ack — proceeding"));
- await wakeTaskOnApprovalResolution(makeApproval({ status: "approved" }));
- expect(streamMock).toHaveBeenCalledTimes(1);
- });
-
- it("swallows gateway stream errors without throwing", async () => {
- getTaskMock.mockReturnValue(makeTask());
- streamMock.mockImplementation(async function* () {
- yield { kind: "error", message: "boom" } as const;
- });
- await expect(
- wakeTaskOnApprovalResolution(makeApproval({ status: "approved" })),
- ).resolves.toBeUndefined();
- // Comment about delivery is still recorded so the inbox thread has a trail.
- expect(appendCommentMock).toHaveBeenCalled();
- });
-});
diff --git a/notfair-cmo/src/server/orchestration/approval-wakeup.ts b/notfair-cmo/src/server/orchestration/approval-wakeup.ts
index f3637355..cfa03c72 100644
--- a/notfair-cmo/src/server/orchestration/approval-wakeup.ts
+++ b/notfair-cmo/src/server/orchestration/approval-wakeup.ts
@@ -1,8 +1,11 @@
+import { getProject } from "@/server/db/projects";
+import { requireAdapter } from "@/server/adapters/registry";
+import { workspaceDirFor } from "@/server/agents/provisioning";
import {
- buildPendingSessionKey,
- findSessionBySessionId,
-} from "@/server/openclaw/sessions";
-import { streamChatViaGateway } from "@/server/openclaw/gateway-client";
+ 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";
@@ -57,31 +60,47 @@ export async function wakeTaskOnApprovalResolution(approval: Approval): Promise<
return;
}
- const known = findSessionBySessionId(task.agent_id, threadId);
- const sessionKey =
- known?.sessionKey ?? buildPendingSessionKey(task.agent_id, threadId);
+ 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);
- // Persist the wake-up payload as a system comment for the inbox thread.
appendComment({
approval_id: approval.id,
author_kind: "system",
body: `Delivered to ${task.agent_id} on thread ${threadId}.`,
});
+ appendTranscriptEvent(session.id, "user", { text: message, source: "approval-wakeup" });
- // Drain the gateway stream so the agent's turn fully runs. Side effects
- // (submit_task_status etc.) happen via MCP tool calls during the turn —
- // we no longer regex-scan the reply.
try {
- for await (const evt of streamChatViaGateway({
- sessionKey,
- sessionId: threadId,
+ 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] gateway stream failed for task ${task.id}:`, err);
+ console.error(`[approval-wakeup] adapter stream failed for task ${task.id}:`, err);
}
}
diff --git a/notfair-cmo/src/server/orchestration/question-wakeup.ts b/notfair-cmo/src/server/orchestration/question-wakeup.ts
index f842d30d..9a05b201 100644
--- a/notfair-cmo/src/server/orchestration/question-wakeup.ts
+++ b/notfair-cmo/src/server/orchestration/question-wakeup.ts
@@ -1,11 +1,12 @@
+import { getProject } from "@/server/db/projects";
+import { requireAdapter } from "@/server/adapters/registry";
+import { workspaceDirFor } from "@/server/agents/provisioning";
import {
- buildPendingSessionKey,
- findSessionBySessionId,
-} from "@/server/openclaw/sessions";
-import { streamChatViaGateway } from "@/server/openclaw/gateway-client";
-import {
- parseQuestionOptions,
-} from "@/server/db/questions";
+ 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";
@@ -55,23 +56,43 @@ export async function wakeTaskOnQuestionResolution(question: Question): Promise<
return;
}
- const known = findSessionBySessionId(task.agent_id, threadId);
- const sessionKey =
- known?.sessionKey ?? buildPendingSessionKey(task.agent_id, threadId);
+ 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 streamChatViaGateway({
- sessionKey,
- sessionId: threadId,
+ 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] gateway stream failed for task ${task.id}:`,
+ `[question-wakeup] adapter stream failed for task ${task.id}:`,
err,
);
}
diff --git a/notfair-cmo/src/server/orchestration/run-task.test.ts b/notfair-cmo/src/server/orchestration/run-task.test.ts
deleted file mode 100644
index e5bc172c..00000000
--- a/notfair-cmo/src/server/orchestration/run-task.test.ts
+++ /dev/null
@@ -1,277 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { Task } from "@/types";
-
-// --- Module mocks (must be set up before importing the SUT). ---
-
-const claimProposedTaskMock = vi.fn();
-const setTaskThreadIfMissingMock = vi.fn();
-const updateTaskMock = vi.fn();
-vi.mock("@/server/db/tasks", () => ({
- claimProposedTask: (...a: unknown[]) => claimProposedTaskMock(...a),
- setTaskThreadIfMissing: (...a: unknown[]) => setTaskThreadIfMissingMock(...a),
- updateTask: (...a: unknown[]) => updateTaskMock(...a),
-}));
-
-const streamChatViaGatewayMock = vi.fn();
-vi.mock("@/server/openclaw/gateway-client", () => ({
- streamChatViaGateway: (...a: unknown[]) => streamChatViaGatewayMock(...a),
-}));
-
-vi.mock("@/server/openclaw/sessions", () => ({
- buildPendingSessionKey: (agent: string, thread: string) =>
- `agent:${agent}:${thread}`,
-}));
-
-// Shadow transcript writes to ~/.notfair-cmo by default — stub to keep
-// the unit test isolated from disk. Functional behavior is covered by
-// the e2e browser test.
-vi.mock("@/server/openclaw/shadow-transcript", () => ({
- openShadowWriter: async () => ({
- appendDelta: () => {},
- flushAssistant: async () => {},
- toolStart: async () => {},
- toolResult: async () => {},
- close: async () => {},
- }),
- shadowStreamEvent: async () => {},
-}));
-
-// generateTaskThreadId lives on task-kickoff now. Mock just that one symbol
-// while letting the real buildTaskKickoffMessage run — we want to catch
-// contract drift between run-task and the kickoff format.
-const generateTaskThreadIdMock = vi.fn(() => "thread-fresh");
-vi.mock("./task-kickoff", async () => {
- const actual =
- await vi.importActual<typeof import("./task-kickoff")>("./task-kickoff");
- return {
- ...actual,
- generateTaskThreadId: () => generateTaskThreadIdMock(),
- };
-});
-
-import { runTaskKickoffServerSide, startTaskIfProposed } from "./run-task";
-
-function makeTask(overrides: Partial<Task> = {}): Task {
- return {
- id: "task-1",
- display_id: "demo-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- title: "Install conversion tracking",
- brief: "Add the Google Ads conversion tag.",
- success_criteria: "Tag fires on /thanks; conv appears in Google Ads.",
- deadline_iso: null,
- status: "proposed",
- result_json: null,
- error_message: null,
- thread_id: "thread-existing",
- assigner_agent_id: "demo-cmo",
- blocked_by_task_id: null,
- created_at: "2026-05-19T00:00:00Z",
- updated_at: "2026-05-19T00:00:00Z",
- ...overrides,
- };
-}
-
-// Helper: build an async-iterable matching the StreamChatInput contract.
-async function* eventStream(
- events: Array<{ kind: "delta"; text: string } | { kind: "error"; message: string }>,
-): AsyncGenerator<unknown, void, void> {
- for (const evt of events) yield evt;
-}
-
-describe("startTaskIfProposed", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- // Default: streaming returns no text so the kickoff is a no-op past the
- // claim. Individual tests override.
- streamChatViaGatewayMock.mockImplementation(() => eventStream([]));
- });
-
- it("returns the input task untouched when the claim fails (already running)", () => {
- claimProposedTaskMock.mockReturnValue(null);
- const task = makeTask({ status: "working" });
- const result = startTaskIfProposed(task);
- expect(result).toBe(task);
- // Kickoff must not be triggered when the claim doesn't succeed.
- expect(streamChatViaGatewayMock).not.toHaveBeenCalled();
- });
-
- it("returns the claimed task and fires kickoff in the background when claim succeeds", async () => {
- const claimed = makeTask({ status: "working" });
- claimProposedTaskMock.mockReturnValue(claimed);
-
- const result = startTaskIfProposed(makeTask({ status: "proposed" }));
- expect(result).toBe(claimed);
- expect(claimProposedTaskMock).toHaveBeenCalledWith("task-1");
-
- // The kickoff is fire-and-forget; let microtasks drain so it actually runs.
- await new Promise((r) => setImmediate(r));
- expect(streamChatViaGatewayMock).toHaveBeenCalledTimes(1);
- });
-
- it("swallows kickoff errors so the caller (synchronous) never throws", async () => {
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- const claimed = makeTask({ status: "working", thread_id: null });
- claimProposedTaskMock.mockReturnValue(claimed);
- // Force the kickoff to throw — thread assignment will fail because both
- // claim + setTaskThreadIfMissing return null.
- setTaskThreadIfMissingMock.mockReturnValue(null);
-
- expect(() =>
- startTaskIfProposed(makeTask({ status: "proposed", thread_id: null })),
- ).not.toThrow();
-
- // Wait for the background error to surface via console.error.
- await new Promise((r) => setImmediate(r));
- await new Promise((r) => setImmediate(r));
- expect(errSpy).toHaveBeenCalledWith(
- "[start-task] kickoff failed:",
- expect.any(Error),
- );
- errSpy.mockRestore();
- });
-});
-
-describe("runTaskKickoffServerSide", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("consumes the gateway stream and passes the kickoff message + session context", async () => {
- streamChatViaGatewayMock.mockImplementation(() =>
- eventStream([
- { kind: "delta", text: "On it." },
- { kind: "delta", text: " Wrapping up." },
- ]),
- );
-
- await runTaskKickoffServerSide(makeTask());
-
- expect(streamChatViaGatewayMock).toHaveBeenCalledTimes(1);
- const [call] = streamChatViaGatewayMock.mock.calls;
- expect(call?.[0]).toEqual(
- expect.objectContaining({
- sessionKey: "agent:demo-google-ads:thread-existing",
- sessionId: "thread-existing",
- // The kickoff message is built by buildTaskKickoffMessage — sanity-check
- // it carries the brief without locking the prose to a snapshot.
- message: expect.stringContaining("Add the Google Ads conversion tag."),
- }),
- );
- expect(call?.[0].message).toContain("task_id: task-1");
-
- // run-task no longer post-processes the buffer — side effects now happen
- // via MCP tool calls during the stream.
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it("lazily assigns a fresh thread_id when the task has none yet", async () => {
- const refreshed = makeTask({ thread_id: "thread-fresh" });
- setTaskThreadIfMissingMock.mockReturnValue(refreshed);
- streamChatViaGatewayMock.mockImplementation(() => eventStream([]));
-
- await runTaskKickoffServerSide(makeTask({ thread_id: null }));
-
- expect(setTaskThreadIfMissingMock).toHaveBeenCalledWith(
- "task-1",
- "thread-fresh",
- );
- expect(streamChatViaGatewayMock).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: "thread-fresh",
- sessionKey: "agent:demo-google-ads:thread-fresh",
- }),
- );
- });
-
- it("throws when no thread_id can be assigned (and does not call the gateway)", async () => {
- setTaskThreadIfMissingMock.mockReturnValue(null);
- await expect(
- runTaskKickoffServerSide(makeTask({ thread_id: null })),
- ).rejects.toThrow(/Failed to assign thread_id/);
- expect(streamChatViaGatewayMock).not.toHaveBeenCalled();
- });
-
- it("on gateway error event: marks task failed with the gateway's message", async () => {
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- streamChatViaGatewayMock.mockImplementation(() =>
- eventStream([
- { kind: "delta", text: "partial..." },
- { kind: "error", message: "gateway exploded" },
- ]),
- );
-
- await runTaskKickoffServerSide(makeTask());
-
- expect(updateTaskMock).toHaveBeenCalledWith(
- "task-1",
- expect.objectContaining({
- status: "failed",
- error_message: "gateway exploded",
- }),
- );
- errSpy.mockRestore();
- });
-
- it("on gateway iterator throw: marks task failed with the thrown message", async () => {
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- streamChatViaGatewayMock.mockImplementation(async function* () {
- yield { kind: "delta", text: "starting..." };
- throw new Error("socket closed");
- });
-
- await runTaskKickoffServerSide(makeTask());
-
- expect(updateTaskMock).toHaveBeenCalledWith(
- "task-1",
- expect.objectContaining({
- status: "failed",
- error_message: "socket closed",
- }),
- );
- errSpy.mockRestore();
- });
-
- it("on non-Error throw from gateway: stringifies the value into error_message", async () => {
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- streamChatViaGatewayMock.mockImplementation(async function* () {
- // Some libraries reject with non-Error sentinels (e.g. plain strings).
- // eslint-disable-next-line @typescript-eslint/only-throw-error
- throw "string-reason";
- yield { kind: "delta", text: "" }; // keep async generator type happy
- });
-
- await runTaskKickoffServerSide(makeTask());
-
- expect(updateTaskMock).toHaveBeenCalledWith(
- "task-1",
- expect.objectContaining({
- status: "failed",
- error_message: "string-reason",
- }),
- );
- errSpy.mockRestore();
- });
-
- it("no-ops cleanly when the stream is blank (no failure update)", async () => {
- streamChatViaGatewayMock.mockImplementation(() =>
- eventStream([
- { kind: "delta", text: " " },
- { kind: "delta", text: "\n\n" },
- ]),
- );
- await runTaskKickoffServerSide(makeTask());
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it("keeps the existing thread_id when the task already has one (no lazy mint)", async () => {
- streamChatViaGatewayMock.mockImplementation(() => eventStream([]));
- await runTaskKickoffServerSide(makeTask({ thread_id: "thread-existing" }));
- expect(setTaskThreadIfMissingMock).not.toHaveBeenCalled();
- expect(streamChatViaGatewayMock).toHaveBeenCalledWith(
- expect.objectContaining({ sessionId: "thread-existing" }),
- );
- });
-});
diff --git a/notfair-cmo/src/server/orchestration/run-task.ts b/notfair-cmo/src/server/orchestration/run-task.ts
index 1762ebb2..6daecb94 100644
--- a/notfair-cmo/src/server/orchestration/run-task.ts
+++ b/notfair-cmo/src/server/orchestration/run-task.ts
@@ -1,12 +1,12 @@
-import {
- buildPendingSessionKey,
-} from "@/server/openclaw/sessions";
-import { streamChatViaGateway } from "@/server/openclaw/gateway-client";
-import {
- openShadowWriter,
- shadowStreamEvent,
-} from "@/server/openclaw/shadow-transcript";
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 {
@@ -16,16 +16,8 @@ import {
/**
* Idempotent "claim and kickoff" — atomically flips a proposed task to
- * running and fires the server-side kickoff. No-op when the row is already
- * running, terminal, or missing. Used by `<create_task>` handling and the
- * onboarding audit-task path; both callers operate on freshly-created tasks.
- *
- * The claim is a conditional SQL UPDATE (`WHERE status = 'proposed'`), so
- * even if a stale in-memory `task` snapshot is passed in, the DB cannot
- * regress a terminal row back to running.
- *
- * Returns the post-transition task (running on success, the input task
- * otherwise). The kickoff runs fire-and-forget — callers shouldn't await it.
+ * 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);
@@ -37,18 +29,12 @@ export function startTaskIfProposed(task: Task): Task {
}
/**
- * Server-side kickoff for a task. Consumes the full gateway stream (no SSE
- * pipe to a client) and applies orchestration blocks the assignee emits.
- * Used by the "Start all" button on the agent Tasks tab so the agent
- * starts working immediately without the user opening each task's
- * detail page.
- *
- * Returns when the agent has finished its turn AND orchestration blocks
- * have been processed. Errors are logged + the task is marked failed.
+ * 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> {
- // Lazily mint the thread on first kickoff if the task didn't have one
- // (e.g., user never opened /tasks/[id]). Stable forever after.
let finalTask = task;
if (!finalTask.thread_id) {
const updated = setTaskThreadIfMissing(task.id, generateTaskThreadId());
@@ -58,85 +44,83 @@ export async function runTaskKickoffServerSide(task: Task): Promise<void> {
}
}
- const sessionKey = buildPendingSessionKey(finalTask.agent_id, finalTask.thread_id);
- const kickoffMessage = buildTaskKickoffMessage(finalTask);
+ 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);
- // Tee gateway events to a shadow JSONL the browser can tail. OpenClaw's
- // codex-app-server backend buffers session.jsonl until session-end and
- // doesn't emit per-message broadcasts during the turn, so without the
- // shadow there's no way for the UI to render tokens live for tasks
- // kicked off server-side. The shadow uses the same OpenClaw-style
- // schema as session.jsonl so transcript-tail can read both with the
- // same parser.
- const shadow = await openShadowWriter(finalTask.agent_id, finalTask.thread_id);
+ 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);
+ appendTranscriptEvent(session.id, "user", { text: kickoffMessage, source: "kickoff" });
- // We drain the stream so the agent's turn fully runs, but we no longer
- // post-process the buffer for pseudo-XML blocks — any side effects
- // (task_status, comments, approvals) happen via the agent calling
- // notfair-orchestration MCP tools mid-stream.
console.log(
`[run-task] kickoff start task=${finalTask.id} agent=${finalTask.agent_id} thread=${finalTask.thread_id}`,
);
- // Retry on the post-provisioning race: `openclaw agents add` updates the
- // config file but the gateway's pinned runtime snapshot needs a moment
- // before it sees the new agent. Until that catches up, chat.send fails
- // with INVALID_REQUEST "Agent '<id>' no longer exists in configuration".
- // 2s/4s/8s backoff covers a ~14s race window we've observed in dev.
- const RETRY_DELAYS_MS = [2_000, 4_000, 8_000];
- let lastError: unknown = null;
- let streamed = false;
- for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt += 1) {
- try {
- for await (const evt of streamChatViaGateway({
- sessionKey,
- sessionId: finalTask.thread_id,
- message: kickoffMessage,
- })) {
- try {
- await shadowStreamEvent(shadow, evt);
- } catch (err) {
- console.error("[run-task] shadow write failed:", err);
- }
- if (evt.kind === "error") {
- throw new Error(evt.message);
- }
+
+ 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;
}
- streamed = true;
- break;
- } catch (err) {
- lastError = err;
- const message = err instanceof Error ? err.message : String(err);
- if (!isAgentNotInConfigError(message) || attempt >= RETRY_DELAYS_MS.length) {
- break;
+ appendTranscriptEvent(session.id, evt.kind, evt);
+ if (evt.kind === "error") {
+ throw new Error(evt.message);
}
- const delay = RETRY_DELAYS_MS[attempt]!;
+ }
+ 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] gateway snapshot stale for ${finalTask.agent_id}; retrying in ${delay}ms (attempt ${attempt + 1}/${RETRY_DELAYS_MS.length})`,
+ `[run-task] turn ended but agent did not call submit_task_status (task=${finalTask.id}); marking blocked`,
);
- await new Promise((r) => setTimeout(r, delay));
+ 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,
+ });
}
- if (streamed) {
- await shadow.close();
- console.log(`[run-task] kickoff stream done task=${finalTask.id}`);
- return;
- }
- await shadow.close().catch(() => undefined);
- const message = lastError instanceof Error ? lastError.message : String(lastError);
- console.error(
- `[run-task] kickoff failed task=${finalTask.id} agent=${finalTask.agent_id}: ${message}`,
- );
- updateTask(finalTask.id, {
- status: "failed",
- error_message: message,
- });
-}
-
-/**
- * Matches the gateway's "Agent '<id>' no longer exists in configuration"
- * INVALID_REQUEST. Surfaced when the gateway hasn't refreshed its agents
- * snapshot yet after a fresh `openclaw agents add`. Idempotently retryable.
- */
-function isAgentNotInConfigError(message: string): boolean {
- return message.includes("no longer exists in configuration");
}
diff --git a/notfair-cmo/src/server/scheduler/display.ts b/notfair-cmo/src/server/scheduler/display.ts
new file mode 100644
index 00000000..9aeb8dc6
--- /dev/null
+++ b/notfair-cmo/src/server/scheduler/display.ts
@@ -0,0 +1,338 @@
+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;
+}
+
+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 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 = recent?.status === "done" ? "ok" : 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,
+ };
+}
+
+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: r.status === "done" ? "ok" : r.status,
+ 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
new file mode 100644
index 00000000..0ff2fbcd
--- /dev/null
+++ b/notfair-cmo/src/server/scheduler/index.ts
@@ -0,0 +1,174 @@
+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;
+}
+
+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) VALUES (?, ?, ?, NULL, 'running', 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,
+): void {
+ getDb()
+ .prepare(
+ "UPDATE scheduled_job_runs SET finished_at = ?, status = ?, error_message = ? WHERE id = ?",
+ )
+ .run(new Date().toISOString(), status, error_message, 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
new file mode 100644
index 00000000..9fd0d3cd
--- /dev/null
+++ b/notfair-cmo/src/server/scheduler/tick.ts
@@ -0,0 +1,97 @@
+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 {
+ await dispatchJob(job);
+ finishJobRun(runId, "done");
+ } 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<void> {
+ 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" });
+
+ 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 === "error") {
+ throw new Error(evt.message);
+ }
+ }
+ touchSession(session.id);
+}
diff --git a/notfair-cmo/src/server/sessions/index.ts b/notfair-cmo/src/server/sessions/index.ts
new file mode 100644
index 00000000..31814e51
--- /dev/null
+++ b/notfair-cmo/src/server/sessions/index.ts
@@ -0,0 +1,166 @@
+import { randomUUID } from "node:crypto";
+import { getDb } from "@/server/db/db";
+import type { HarnessAdapterId } from "@/server/adapters/types";
+
+/**
+ * Session / thread management.
+ *
+ * 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
+ * (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;
+ project_slug: string;
+ agent_id: string;
+ label: string;
+ harness_adapter: HarnessAdapterId;
+ harness_session_id: string | null;
+ task_id: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface TranscriptEvent {
+ id: string;
+ session_id: string;
+ seq: number;
+ kind: "user" | "delta" | "tool" | "lifecycle" | "final" | "error";
+ payload_json: string;
+ created_at: string;
+}
+
+interface SessionRow {
+ id: string;
+ project_slug: string;
+ agent_id: string;
+ label: string;
+ harness_adapter: string;
+ harness_session_id: string | null;
+ task_id: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+function rowToSession(row: SessionRow): Session {
+ return { ...row, harness_adapter: row.harness_adapter as HarnessAdapterId };
+}
+
+export function getOrCreateSession(input: {
+ project_slug: string;
+ agent_id: string;
+ label: string;
+ harness_adapter: HarnessAdapterId;
+ task_id?: string | null;
+}): Session {
+ const db = getDb();
+ const existing = db
+ .prepare(
+ "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ?",
+ )
+ .get(input.project_slug, input.agent_id, input.label) as SessionRow | undefined;
+ if (existing) return rowToSession(existing);
+
+ const session: Session = {
+ id: randomUUID(),
+ project_slug: input.project_slug,
+ agent_id: input.agent_id,
+ label: input.label,
+ harness_adapter: input.harness_adapter,
+ harness_session_id: null,
+ task_id: input.task_id ?? null,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ };
+
+ db.prepare(
+ "INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, harness_session_id, task_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,
+ );
+ return session;
+}
+
+export function getSession(id: string): Session | null {
+ const row = getDb()
+ .prepare("SELECT * FROM sessions WHERE id = ?")
+ .get(id) as SessionRow | undefined;
+ return row ? rowToSession(row) : null;
+}
+
+export function listAgentSessions(project_slug: string, agent_id: string): Session[] {
+ const rows = getDb()
+ .prepare(
+ "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? ORDER BY updated_at DESC",
+ )
+ .all(project_slug, agent_id) as SessionRow[];
+ return rows.map(rowToSession);
+}
+
+export function touchSession(id: string, harness_session_id?: string): void {
+ const now = new Date().toISOString();
+ if (harness_session_id) {
+ getDb()
+ .prepare(
+ "UPDATE sessions SET updated_at = ?, harness_session_id = COALESCE(harness_session_id, ?) WHERE id = ?",
+ )
+ .run(now, harness_session_id, id);
+ } else {
+ getDb().prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, id);
+ }
+}
+
+export function appendTranscriptEvent(
+ session_id: string,
+ kind: TranscriptEvent["kind"],
+ payload: unknown,
+): void {
+ const db = getDb();
+ const seqRow = db
+ .prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM transcript_events WHERE session_id = ?")
+ .get(session_id) as { next: number };
+ const id = randomUUID();
+ const seq = seqRow.next;
+ const created_at = new Date().toISOString();
+ const payload_json = JSON.stringify(payload);
+ 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,
+ });
+}
+
+export function listTranscriptEvents(
+ session_id: string,
+ opts: { sinceSeq?: number; limit?: number } = {},
+): TranscriptEvent[] {
+ const limit = opts.limit ?? 1000;
+ const since = opts.sinceSeq ?? 0;
+ return getDb()
+ .prepare(
+ "SELECT * FROM transcript_events WHERE session_id = ? AND seq > ? ORDER BY seq ASC LIMIT ?",
+ )
+ .all(session_id, since, limit) as TranscriptEvent[];
+}
diff --git a/notfair-cmo/src/server/sessions/transcript-tail.ts b/notfair-cmo/src/server/sessions/transcript-tail.ts
new file mode 100644
index 00000000..c821aace
--- /dev/null
+++ b/notfair-cmo/src/server/sessions/transcript-tail.ts
@@ -0,0 +1,152 @@
+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.
+ */
+export type TranscriptEvent =
+ | { kind: "user_message"; id: string; ts: number; body: string }
+ | { kind: "assistant_text"; id: string; ts: number; body: string }
+ | {
+ kind: "tool_call";
+ id: string;
+ ts: number;
+ tool_call_id: string;
+ name: string;
+ label: string | null;
+ }
+ | {
+ kind: "tool_result";
+ id: string;
+ ts: number;
+ tool_call_id: string;
+ name: string;
+ summary: string | null;
+ ok: boolean;
+ }
+ | { kind: "lifecycle"; id: string; ts: number; phase: string }
+ | { kind: "unknown"; id: string; ts: number; raw_type: string };
+
+/**
+ * Resolve a URL thread id to a notfair-cmo `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).
+ */
+export function resolveSessionForThread(
+ project_slug: string,
+ agent_id: string,
+ thread: string,
+): Session | null {
+ const row = getDb()
+ .prepare(
+ "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ?",
+ )
+ .get(project_slug, agent_id, thread) as
+ | (Session & { harness_adapter: string })
+ | undefined;
+ if (!row) return null;
+ return row as Session;
+}
+
+/**
+ * Read transcript events for a thread after `cursor`. We expose the same
+ * shape the JSONL tail used (an `byteOffset` 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.
+ */
+export function readTranscriptTail(
+ project_slug: string,
+ agent_id: string,
+ thread: string,
+ cursor: number,
+): { events: TranscriptEvent[]; byteOffset: number; fileSize: number } {
+ const session = resolveSessionForThread(project_slug, agent_id, thread);
+ if (!session) return { events: [], byteOffset: cursor, fileSize: 0 };
+
+ const rows = getDb()
+ .prepare(
+ "SELECT * FROM transcript_events WHERE session_id = ? AND seq > ? ORDER BY seq ASC",
+ )
+ .all(session.id, cursor) as RawEvent[];
+
+ const events: TranscriptEvent[] = [];
+ let last = cursor;
+ for (const row of rows) {
+ last = row.seq;
+ const ts = Date.parse(row.created_at) || Date.now();
+ const payload = safeParse(row.payload_json);
+ 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 });
+ } else if (row.kind === "delta") {
+ const text = typeof payload.text === "string" ? payload.text : "";
+ events.push({ kind: "assistant_text", id, ts, body: text });
+ } else if (row.kind === "tool") {
+ const phase = typeof payload.phase === "string" ? payload.phase : "start";
+ const tool_call_id =
+ typeof payload.toolCallId === "string" ? payload.toolCallId : "";
+ const name = typeof payload.name === "string" ? payload.name : "tool";
+ if (phase === "result") {
+ events.push({
+ kind: "tool_result",
+ id,
+ ts,
+ tool_call_id,
+ name,
+ summary: null,
+ ok: true,
+ });
+ } else {
+ const label = typeof payload.label === "string" ? payload.label : null;
+ events.push({
+ kind: "tool_call",
+ id,
+ ts,
+ tool_call_id,
+ name,
+ label,
+ });
+ }
+ } else if (row.kind === "lifecycle") {
+ const phase = typeof payload.phase === "string" ? payload.phase : "unknown";
+ events.push({ kind: "lifecycle", id, ts, phase });
+ } else if (row.kind === "final") {
+ // Already covered by the accumulated delta stream; surface as a no-op
+ // lifecycle so clients can show "done" if they want.
+ events.push({ kind: "lifecycle", id, ts, phase: "done" });
+ } else if (row.kind === "error") {
+ const text = typeof payload.message === "string" ? payload.message : "";
+ events.push({ kind: "assistant_text", id, ts, body: `⚠ ${text}` });
+ } else {
+ events.push({ kind: "unknown", id, ts, raw_type: row.kind });
+ }
+ }
+
+ // 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 };
+}
+
+function safeParse(json: string): Record<string, unknown> {
+ try {
+ const v = JSON.parse(json);
+ return v && typeof v === "object" ? (v as Record<string, unknown>) : {};
+ } catch {
+ 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-cmo/src/server/sessions/view.ts
new file mode 100644
index 00000000..e1c1d222
--- /dev/null
+++ b/notfair-cmo/src/server/sessions/view.ts
@@ -0,0 +1,279 @@
+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.
+ */
+export interface SessionView {
+ /** Stable thread label used in URLs (`/chat/<label>`). */
+ sessionId: string;
+ /** Short label shown in the dropdown. */
+ label: string;
+ /** Compatibility — earlier code carried a backend session-key string. */
+ sessionKey: string;
+ /** Last interaction (ms epoch). 0 when freshly minted. */
+ lastInteractionAt: number;
+ /** True when the row exists only in our cookie (no turns yet). */
+ pending: 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,
+ label: s.label,
+ sessionKey: s.id,
+ lastInteractionAt: Date.parse(s.updated_at) || 0,
+ pending: false,
+ };
+}
+
+export function listSessionsForAgent(
+ project_slug: string,
+ agent_id: string,
+): SessionView[] {
+ const rows = listAgentSessions(project_slug, agent_id);
+ return rows.map(sessionRowToView);
+}
+
+export function buildPendingSessionKey(_agent_id: string, label: string): string {
+ return label;
+}
+
+export function newSessionId(): string {
+ return randomUUID();
+}
+
+export function findSessionBySessionId(
+ project_slug: string,
+ agent_id: string,
+ label: string,
+): SessionView | null {
+ // Always scope by project_slug — even though agent_id encodes the slug,
+ // a project whose slug is a prefix of another's (e.g. "acme" vs "acme-q4")
+ // can produce overlapping agent_id patterns. Querying by project_slug
+ // closes that hole.
+ const row = getDb()
+ .prepare(
+ "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ? LIMIT 1",
+ )
+ .get(project_slug, agent_id, label) as Session | undefined;
+ 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,
+ };
+ }
+ }
+
+ if (!active) {
+ if (existing.length > 0) {
+ active = existing[0]!;
+ } else {
+ const newLabel = "main";
+ active = {
+ sessionId: newLabel,
+ label: newLabel,
+ sessionKey: newLabel,
+ lastInteractionAt: 0,
+ pending: true,
+ };
+ }
+ }
+
+ 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
+ * to the project's chosen harness adapter when one isn't passed.
+ */
+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;
+ return getOrCreateSession({
+ project_slug: input.project_slug,
+ 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: "chat"; preview: string };
+
+const CRON_LABEL_PREFIX = "cron:";
+
+export function isTaskOrCronSession(
+ label: string,
+ taskThreadIds: ReadonlySet<string>,
+): boolean {
+ return label.startsWith(CRON_LABEL_PREFIX) || taskThreadIds.has(label);
+}
+
+export function pickLatestChatSession<S extends { label: string }>(
+ sessions: readonly S[],
+ taskThreadIds: ReadonlySet<string>,
+): S | undefined {
+ return sessions.find((s) => !isTaskOrCronSession(s.label, taskThreadIds));
+}
+
+const PREVIEW_MAX_CHARS = 40;
+
+/**
+ * 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`.
+ */
+export async function classifySessions(
+ agent_id: string,
+ project_slug: string,
+ sessions: SessionView[],
+): Promise<Map<string, SessionOrigin>> {
+ 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,
+ });
+ continue;
+ }
+ out.set(s.label, {
+ kind: "chat",
+ preview: readFirstUserMessagePreview(project_slug, agent_id, s.label),
+ });
+ }
+ return out;
+}
+
+function readFirstUserMessagePreview(
+ project_slug: string,
+ agent_id: string,
+ label: string,
+): string {
+ const session = getDb()
+ .prepare(
+ "SELECT id FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ?",
+ )
+ .get(project_slug, agent_id, label) as { id: string } | undefined;
+ if (!session) return "";
+ const row = getDb()
+ .prepare(
+ "SELECT payload_json FROM transcript_events WHERE session_id = ? AND kind = 'user' ORDER BY seq ASC LIMIT 1",
+ )
+ .get(session.id) as { payload_json: string } | undefined;
+ if (!row) return "";
+ try {
+ const payload = JSON.parse(row.payload_json) as { text?: string };
+ if (typeof payload.text !== "string") return "";
+ return shorten(payload.text);
+ } catch {
+ return "";
+ }
+}
+
+function shorten(s: string): string {
+ const flat = s.replace(/\s+/g, " ").trim();
+ if (flat.length <= PREVIEW_MAX_CHARS) return flat;
+ return flat.slice(0, PREVIEW_MAX_CHARS - 1) + "…";
+}
diff --git a/notfair-cmo/src/server/skills/orchestration-skill.test.ts b/notfair-cmo/src/server/skills/orchestration-skill.test.ts
index 3113db5d..627d8f59 100644
--- a/notfair-cmo/src/server/skills/orchestration-skill.test.ts
+++ b/notfair-cmo/src/server/skills/orchestration-skill.test.ts
@@ -65,18 +65,25 @@ describe("ORCHESTRATION_SKILL", () => {
expect(s).toMatch(/can NOT close a task.*pending approval/i);
});
- it("teaches cron CLI shape including --name '<project> / <agent> / <cron>'", () => {
+ it("teaches the schedule_recurring_work MCP tool, not the dead openclaw CLI", () => {
const s = getOrchestrationSkill();
- expect(s).toContain("openclaw cron add");
- expect(s).toContain("--no-deliver");
- expect(s).toContain("--json");
- expect(s).toContain(`"<project-slug> / <agent-slug> / <cron-name>"`);
+ 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_cron> as the ONE pseudo-XML block still parsed (UI-only)", () => {
+ it("documents propose-then-call flow for recurring schedules after one-time approvals", () => {
const s = getOrchestrationSkill();
- expect(s).toContain("<propose_cron>");
- expect(s).toMatch(/ONLY pseudo-XML block/);
+ 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("includes a 'Your role:' section selector so role-specific content sits ABOVE", () => {
diff --git a/notfair-cmo/src/server/skills/orchestration-skill.ts b/notfair-cmo/src/server/skills/orchestration-skill.ts
index fa67ade0..8affb48d 100644
--- a/notfair-cmo/src/server/skills/orchestration-skill.ts
+++ b/notfair-cmo/src/server/skills/orchestration-skill.ts
@@ -93,74 +93,54 @@ recover instead of asking the user:
## Scheduling recurring work
When the user asks for "every day", "every Monday", "every hour", etc.,
-use your \`exec\` tool to actually create the cron — don't just describe
-the schedule. Two equivalent CLI shapes:
-
- openclaw cron add \\
- --name "<project-slug> / <agent-slug> / <cron-name>" \\
- --description "<one line: what this cron does>" \\
- --agent <project-slug>-<agent-slug> \\
- --cron "<5-field cron expr>" \\
- --tz "America/Los_Angeles" \\
- --message "RUN: instructions to your future self" \\
- --no-deliver \\
- --json
-
- openclaw cron add \\
- --name "<project-slug> / <agent-slug> / <cron-name>" \\
- --description "<one line>" \\
- --agent <project-slug>-<agent-slug> \\
- --every "1h" \\
- --message "RUN: instructions" \\
- --no-deliver \\
- --json
-
-Field rules:
-- \`--name "<project> / <agent> / <cron>"\` — literal \`/\` with spaces is
- the separator the UI parses for grouping. project = your project_slug.
- agent = url-slug ("cmo" | "google-ads" | "seo"). cron = kebab-case verb.
-- \`--agent <project>-<agent>\` — no slashes, hyphenated. Example:
- \`demo1-google-ads\`, \`demo1-cmo\`.
-- \`--cron\` XOR \`--every\` — never both.
-- \`--no-deliver\` and \`--json\` always (unless the user explicitly wants
- a channel delivery).
-
-Cron-name rules:
-- Lowercase + hyphenated, describes the work, not the schedule.
-- Good: \`daily-bid-opt\`, \`weekly-rank-check\`, \`hourly-metrics\`.
-- Bad: \`9am-cron\`, \`every-monday\`.
-
-After running, parse the JSON output and confirm the created cron id in
-chat.
+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 cron to catch the same kind of issue in the future.
-Append this block at the END of your reply so the UI can render an
-inline accept button:
-
-<propose_cron>
-name: <project>/<agent>/<kebab-case-cron-name>
-agent: <project-slug>-<agent-slug>
-schedule: cron 0 9 * * * America/Los_Angeles
-message: RUN: instructions to your future self on each tick
-description: one-line description for the cron tab
-</propose_cron>
+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 cron per turn. Quality over quantity.
+- 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.
-- Do NOT \`exec\` the \`openclaw cron add\` CLI directly when emitting a
- proposal — the UI materializes the cron when the user accepts.
-- Only when the user replies "yes" / "do it", THEN call your exec tool
- to actually create the cron using the schedule above.
-
-\`<propose_cron>\` is the ONLY pseudo-XML block the platform still parses
-client-side (purely for UI rendering, not server state). Every other
-coordination action goes through MCP tools.
+- 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
diff --git a/notfair-cmo/src/types/index.ts b/notfair-cmo/src/types/index.ts
index d55bd85b..a59188d3 100644
--- a/notfair-cmo/src/types/index.ts
+++ b/notfair-cmo/src/types/index.ts
@@ -21,6 +21,12 @@ export type Project = {
*/
website_url: string | null;
codebase_path: string | null;
+ /**
+ * Which harness adapter runs this project's agents. Picked at
+ * onboarding. "claude-code-local" is the default and recommended;
+ * "codex-local" runs through OpenAI's Codex CLI instead.
+ */
+ harness_adapter: "claude-code-local" | "codex-local";
};
export type TaskStatus =