Skip to content

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

refactor(agents): encode personal name in agent_id; fix onboarding task race

Yuting Zhong476828856652
diff --git a/src/server/actions/crons.test.ts b/src/server/actions/crons.test.ts
index 28569364..94655779 100644
--- a/src/server/actions/crons.test.ts
+++ b/src/server/actions/crons.test.ts
@@ -28,6 +28,36 @@ 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 () => [
+ {
+ 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,
@@ -56,15 +86,15 @@ describe("scheduleCronAction", () => {
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",
- agent_full_id: "demo-google-ads",
+ 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",
+ agent_id: "demo-google-ads-ana",
action_type: "cron_created",
summary: "Scheduled 'morning-audit' (cron 0 9 * * *)",
payload: {
@@ -87,14 +117,14 @@ describe("scheduleCronAction", () => {
});
expect(createCronMock).toHaveBeenCalledWith(
expect.objectContaining({
- agent_slug: "seo",
- agent_full_id: "demo-seo",
+ agent_slug: "seo-sam",
+ agent_full_id: "demo-seo-sam",
schedule: { kind: "every", duration: "1h" },
}),
);
});
- it("converts underscore specialist key to hyphenated agent_slug", async () => {
+ it("resolves agent_full_id from the project roster (encodes role + personal name)", async () => {
await scheduleCronAction({
project_slug: "demo",
specialist: "google_ads",
@@ -104,8 +134,8 @@ describe("scheduleCronAction", () => {
brief: "x",
});
const call = createCronMock.mock.calls[0]?.[0] as Record<string, unknown>;
- expect(call.agent_slug).toBe("google-ads");
- expect(call.agent_full_id).toBe("demo-google-ads");
+ 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 () => {
diff --git a/src/server/actions/crons.ts b/src/server/actions/crons.ts
index e6684148..741e36c1 100644
--- a/src/server/actions/crons.ts
+++ b/src/server/actions/crons.ts
@@ -9,7 +9,8 @@ import {
removeCron,
} from "@/server/openclaw/crons";
import { updateCronMessage } from "@/server/openclaw/gateway-rpc";
-import { agentNameFor, type AgentTemplate } from "@/server/agent-templates";
+import { type AgentTemplate } from "@/server/agent-templates";
+import { listProjectAgents } from "@/server/agent-meta";
import { slugify } from "@/lib/slug";
import { logAgentAction } from "@/server/db/agent-actions";
@@ -37,8 +38,19 @@ export async function scheduleCronAction(input: ScheduleCronInput): Promise<Sche
const scheduleValueTrimmed = input.schedule_value.trim();
if (!scheduleValueTrimmed) return { ok: false, error: "Schedule is required." };
- const agent_slug = input.specialist.replace(/_/g, "-");
- const agent_full_id = agentNameFor(input.project_slug, input.specialist);
+ // Look up the agent's actual id/slug from the project — agent_ids now
+ // encode the personal name (e.g. `demo3-cmo-greg`) so we can't
+ // synthesize them from the template key alone.
+ const projectAgents = await listProjectAgents(input.project_slug);
+ const target = projectAgents.find((a) => a.template_key === input.specialist);
+ if (!target) {
+ return {
+ ok: false,
+ error: `No '${input.specialist}' agent found in project ${input.project_slug}.`,
+ };
+ }
+ const agent_slug = target.slug;
+ const agent_full_id = target.agent_id;
try {
const result = await createCron({
diff --git a/src/server/actions/projects.test.ts b/src/server/actions/projects.test.ts
index 8b66a6a4..1ac53603 100644
--- a/src/server/actions/projects.test.ts
+++ b/src/server/actions/projects.test.ts
@@ -53,6 +53,34 @@ vi.mock("@/server/agent-templates", () => ({
// 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();
diff --git a/src/server/actions/projects.ts b/src/server/actions/projects.ts
index f33012ac..ce1ab9b2 100644
--- a/src/server/actions/projects.ts
+++ b/src/server/actions/projects.ts
@@ -114,6 +114,36 @@ export async function createProjectForOnboardingAction(
const result = createProject({ display_name, website_url, codebase_path });
if (!result.ok) return { ok: false, error: result.reason };
+ // Mint the onboarding task SYNCHRONOUSLY — before provisioning kicks
+ // off — so the task row (and its display_id, e.g. `demo3-1`) exists
+ // immediately. If the user races through OAuth and lands on
+ // setOnboardingAccountAction before provisioning resolves, that flow
+ // can still find this task by title and set blocked_by_task_id
+ // correctly. Kickoff (which needs the OpenClaw agent to exist) is
+ // deferred to the provisionPromise.then() below.
+ const { agentNameFor } = await import("@/server/agent-templates");
+ const cmoName = agent_name_cmo || "Greg";
+ const cmoAgentId = agentNameFor(result.project.slug, "cmo", cmoName);
+ const { buildProjectOnboardingBrief } = await import(
+ "@/server/onboarding/cmo-task-brief"
+ );
+ const { createTask } = await import("@/server/db/tasks");
+ const { title, brief, success_criteria } = buildProjectOnboardingBrief({
+ project_slug: result.project.slug,
+ project_display_name: result.project.display_name,
+ website_url,
+ codebase_path,
+ });
+ const onboardingTask = createTask({
+ project_slug: result.project.slug,
+ agent_id: cmoAgentId,
+ title,
+ brief,
+ success_criteria,
+ assigner_agent_id: null,
+ status: "proposed",
+ });
+
// Same async-provisioning policy as createProjectAction (D4 + D6).
const provisionPromise = ensureProjectAgents(
result.project.slug,
@@ -121,10 +151,9 @@ export async function createProjectForOnboardingAction(
agent_names,
);
startProvisioning(result.project.slug, provisionPromise);
- // After provisioning resolves, mint + start the CMO's project-onboarding
- // task. We chain off provisionPromise (not Promise.all) so a failed
- // provision doesn't try to assign a task to an agent that doesn't exist;
- // logAgentAction still fires regardless.
+ // After provisioning resolves, log + kick off the onboarding task.
+ // We chain off provisionPromise (not Promise.all) so a failed provision
+ // doesn't try to kickoff against an agent that doesn't exist.
provisionPromise
.then(async (prov) => {
logAgentAction({
@@ -135,40 +164,19 @@ export async function createProjectForOnboardingAction(
payload: prov,
});
// Only kick off the onboarding task when the CMO agent actually exists.
- const { agentNameFor } = await import("@/server/agent-templates");
- const cmoAgentId = agentNameFor(result.project.slug, "cmo");
const cmoOk =
prov.created.includes(cmoAgentId) || prov.existed.includes(cmoAgentId);
if (!cmoOk) {
console.error(
- `[onboarding] CMO agent ${cmoAgentId} not provisioned; skipping onboarding task creation`,
+ `[onboarding] CMO agent ${cmoAgentId} not provisioned; skipping onboarding task kickoff`,
);
return;
}
try {
- const { buildProjectOnboardingBrief } = await import(
- "@/server/onboarding/cmo-task-brief"
- );
- const { createTask } = await import("@/server/db/tasks");
const { startTaskIfProposed } = await import(
"@/server/orchestration/run-task"
);
- const { title, brief, success_criteria } = buildProjectOnboardingBrief({
- project_slug: result.project.slug,
- project_display_name: result.project.display_name,
- website_url,
- codebase_path,
- });
- const task = createTask({
- project_slug: result.project.slug,
- agent_id: cmoAgentId,
- title,
- brief,
- success_criteria,
- assigner_agent_id: null,
- status: "proposed",
- });
- startTaskIfProposed(task);
+ startTaskIfProposed(onboardingTask);
} catch (err) {
console.error("[onboarding] failed to create CMO onboarding task:", err);
}
diff --git a/src/server/agent-meta.ts b/src/server/agent-meta.ts
index 3dfb0037..cc5e813b 100644
--- a/src/server/agent-meta.ts
+++ b/src/server/agent-meta.ts
@@ -100,11 +100,11 @@ export async function listProjectAgents(project_slug: string): Promise<ProjectAg
// pretending SEO exists when the onboarding scope is cmo+google-ads.
for (const t of TEMPLATES) {
if (!t.default_onboarding) continue;
- const agentId = agentNameFor(project_slug, t.key);
// Placeholder entry shown before a meta sidecar exists on disk.
- // Uses the template's default_name as the personal name so the
- // sidebar reads sensibly even during the brief window between
- // project-create and ensureProjectAgents finishing.
+ // Both the agent_id and the URL slug encode the template's
+ // default_name; the moment ensureProjectAgents writes a sidecar
+ // with the user-chosen name, the overlay below replaces this row.
+ const agentId = agentNameFor(project_slug, t.key, t.default_name);
result.set(agentId, {
agent_id: agentId,
slug: agentUrlSlug(t.key, t.default_name),
diff --git a/src/server/agent-templates.test.ts b/src/server/agent-templates.test.ts
index 4ee30767..cff4a7be 100644
--- a/src/server/agent-templates.test.ts
+++ b/src/server/agent-templates.test.ts
@@ -70,8 +70,8 @@ function read(slug: string, file: "IDENTITY.md" | "SKILL.md"): string {
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");
- for (const key of ["cmo", "google-ads", "seo"]) {
- const slug = `demo-${key}`;
+ // 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,
);
@@ -96,7 +96,7 @@ describe("ensureProjectAgents — IDENTITY.md per-agent + SKILL.md shared", () =
"USER.md",
"HEARTBEAT.md",
]) {
- const path = join(tmpDataDir, "agents", "demo-cmo", fname);
+ 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
@@ -107,9 +107,9 @@ describe("ensureProjectAgents — IDENTITY.md per-agent + SKILL.md shared", () =
it("SKILL.md is byte-identical across all three agents (shared source of truth)", async () => {
await ensureProjectAgents("demo");
- const cmo = read("demo-cmo", "SKILL.md");
- const ga = read("demo-google-ads", "SKILL.md");
- const seo = read("demo-seo", "SKILL.md");
+ 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.
@@ -118,33 +118,33 @@ describe("ensureProjectAgents — IDENTITY.md per-agent + SKILL.md shared", () =
it("each IDENTITY.md pins the correct per-agent runtime identity", async () => {
await ensureProjectAgents("demo");
- const cmo = read("demo-cmo", "IDENTITY.md");
- const ga = read("demo-google-ads", "IDENTITY.md");
- const seo = read("demo-seo", "IDENTITY.md");
+ 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`/);
+ expect(cmo).toMatch(/`agent_id`: `demo-cmo-greg`/);
expect(ga).toMatch(/`project_slug`: `demo`/);
- expect(ga).toMatch(/`agent_id`: `demo-google-ads`/);
+ expect(ga).toMatch(/`agent_id`: `demo-google-ads-ana`/);
expect(seo).toMatch(/`project_slug`: `demo`/);
- expect(seo).toMatch(/`agent_id`: `demo-seo`/);
+ 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`");
- expect(cmo).not.toContain("`agent_id`: `demo-seo`");
- expect(ga).not.toContain("`agent_id`: `demo-cmo`");
- expect(ga).not.toContain("`agent_id`: `demo-seo`");
- expect(seo).not.toContain("`agent_id`: `demo-cmo`");
- expect(seo).not.toContain("`agent_id`: `demo-google-ads`");
+ 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", "demo-google-ads", "demo-seo"]) {
+ 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");
@@ -156,9 +156,9 @@ describe("ensureProjectAgents — IDENTITY.md per-agent + SKILL.md shared", () =
it("CMO's role section says 'orchestrator' and specialist sections say 'specialist worker'", async () => {
await ensureProjectAgents("demo");
- const cmo = read("demo-cmo", "IDENTITY.md");
- const ga = read("demo-google-ads", "IDENTITY.md");
- const seo = read("demo-seo", "IDENTITY.md");
+ 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");
@@ -172,49 +172,57 @@ describe("ensureProjectAgents — IDENTITY.md per-agent + SKILL.md shared", () =
it("specialist IDENTITY.md mentions its domain tool (notfair-googleads / GSC)", async () => {
await ensureProjectAgents("demo");
- const ga = read("demo-google-ads", "IDENTITY.md");
+ 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", "IDENTITY.md");
+ 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", "IDENTITY.md");
- const ga = read("demo-google-ads", "IDENTITY.md");
+ 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", "IDENTITY.md");
+ const before = read("demo-cmo-greg", "IDENTITY.md");
await ensureProjectAgents("demo");
- const after = read("demo-cmo", "IDENTITY.md");
+ 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", "IDENTITY.md");
- const betaCmo = read("beta-cmo", "IDENTITY.md");
+ 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`");
+ expect(alphaCmo).toContain("`agent_id`: `alpha-cmo-greg`");
expect(alphaCmo).not.toMatch(/`project_slug`: `beta`/);
- expect(alphaCmo).not.toMatch(/`agent_id`: `beta-cmo`/);
+ expect(alphaCmo).not.toMatch(/`agent_id`: `beta-cmo-greg`/);
expect(betaCmo).toContain("`project_slug`: `beta`");
- expect(betaCmo).toContain("`agent_id`: `beta-cmo`");
+ 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("normalizes underscores in template keys to hyphens for agent ids", () => {
- expect(agentNameFor("demo", "google_ads")).toBe("demo-google-ads");
- expect(agentNameFor("demo", "cmo")).toBe("demo-cmo");
- expect(agentNameFor("demo", "seo")).toBe("demo-seo");
+ 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/src/server/agent-templates.ts b/src/server/agent-templates.ts
index e8f9419e..e05c1994 100644
--- a/src/server/agent-templates.ts
+++ b/src/server/agent-templates.ts
@@ -231,13 +231,16 @@ for files in your workspace, and the orchestration MCP for coordination.`,
},
];
-export function agentNameFor(project_slug: string, template_key: AgentTemplate["key"]): string {
- // OpenClaw agent name format: <project-slug>-<template-key>
- // Avoids reserved names; lowercase + hyphen-only. Note this is the
- // BACKEND id used by OpenClaw — distinct from the URL slug, which
- // also encodes the personal name (see agentUrlSlug).
- const safe_template = template_key.replace(/_/g, "-");
- return `${project_slug}-${safe_template}`;
+export function agentNameFor(
+ project_slug: string,
+ template_key: AgentTemplate["key"],
+ name: string,
+): string {
+ // OpenClaw agent name format: <project-slug>-<role>-<slugified-name>
+ // (e.g. `acme-cmo-greg`). Encoding the personal name in the backend
+ // id keeps the agent_id and URL slug in lockstep: the URL slug is
+ // exactly `<role>-<slugified-name>`, the project-prefix dropped.
+ return `${project_slug}-${agentUrlSlug(template_key, name)}`;
}
/**
@@ -313,7 +316,10 @@ export async function ensureProjectAgents(
: TEMPLATES;
for (const template of templates) {
- const agentId = agentNameFor(project_slug, template.key);
+ // 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) {
@@ -324,12 +330,11 @@ export async function ensureProjectAgents(
// (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 personalName =
- existing?.name ?? names?.[template.key] ?? template.default_name;
+ const finalName = existing?.name ?? personalName;
await writeAgentMeta({
agent_id: agentId,
project_slug,
- name: personalName,
+ name: finalName,
template_key: template.key,
created_at: existing?.created_at ?? new Date().toISOString(),
});
@@ -353,7 +358,6 @@ export async function ensureProjectAgents(
workspaceAbs,
]);
await writeIdentityFile(workspaceAbs, template, project_slug, agentId);
- const personalName = names?.[template.key] ?? template.default_name;
await writeAgentMeta({
agent_id: agentId,
project_slug,
diff --git a/src/server/onboarding/accounts.test.ts b/src/server/onboarding/accounts.test.ts
index d83868b1..fb65b70d 100644
--- a/src/server/onboarding/accounts.test.ts
+++ b/src/server/onboarding/accounts.test.ts
@@ -32,7 +32,7 @@ vi.mock("@/server/db/tasks", () => ({
id: "task-uuid",
display_id: "acme-1",
project_slug: "acme",
- agent_id: "acme-cmo",
+ agent_id: "acme-cmo-greg",
title: "Audit the account and propose a starter playbook",
brief: "...",
success_criteria: null,
@@ -49,7 +49,10 @@ vi.mock("@/server/db/tasks", () => ({
listTasks: (slug: string) => listTasksMock(slug),
}));
vi.mock("@/server/agent-templates", () => ({
- agentNameFor: (slug: string, key: string) => `${slug}-${key.replace(/_/g, "-")}`,
+ agentNameFor: (slug: string, key: string, name: string) =>
+ `${slug}-${key.replace(/_/g, "-")}-${name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")}`,
agentUrlSlug: (key: string, name: string) =>
`${key.replace(/_/g, "-")}-${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`,
TEMPLATES: [
@@ -59,8 +62,19 @@ vi.mock("@/server/agent-templates", () => ({
],
}));
+// setOnboardingAccountAction resolves the CMO via listProjectAgents now —
+// agent_ids encode the personal name, so it can't be synthesized.
vi.mock("@/server/agent-meta", () => ({
readAgentMeta: () => null,
+ listProjectAgents: async () => [
+ {
+ agent_id: "acme-cmo-greg",
+ slug: "cmo-greg",
+ name: "Greg",
+ template_key: "cmo",
+ is_template_default: true,
+ },
+ ],
}));
import {
@@ -210,7 +224,7 @@ describe("setOnboardingAccountAction", () => {
expect(createTaskMock).toHaveBeenCalledWith(
expect.objectContaining({
project_slug: "acme",
- agent_id: "acme-cmo",
+ agent_id: "acme-cmo-greg",
status: "proposed",
title: expect.stringContaining("Audit"),
brief: expect.stringContaining("3251706605"),
@@ -224,7 +238,7 @@ describe("setOnboardingAccountAction", () => {
id: "prior-uuid",
display_id: "acme-7",
project_slug: "acme",
- agent_id: "acme-cmo",
+ agent_id: "acme-cmo-greg",
title: "Audit the account and propose a starter playbook",
status: "working",
},
diff --git a/src/server/onboarding/accounts.ts b/src/server/onboarding/accounts.ts
index 16ae09ac..b4d998ff 100644
--- a/src/server/onboarding/accounts.ts
+++ b/src/server/onboarding/accounts.ts
@@ -186,8 +186,15 @@ export async function setOnboardingAccountAction(
// the existing one when a CMO audit task is already present.
const { buildOnboardingBrief } = await import("./cmo-task-brief");
const { listTasks, createTask } = await import("@/server/db/tasks");
- const { agentNameFor } = await import("@/server/agent-templates");
- const cmoAgentId = agentNameFor(project_slug, "cmo");
+ const { listProjectAgents } = await import("@/server/agent-meta");
+ // Resolve the CMO agent by template_key — agent_ids now encode the
+ // personal name, so we can't synthesize one from project_slug alone.
+ const projectAgents = await listProjectAgents(project_slug);
+ const cmo = projectAgents.find((a) => a.template_key === "cmo");
+ if (!cmo) {
+ return { ok: false, error: "CMO agent has not been provisioned yet." };
+ }
+ const cmoAgentId = cmo.agent_id;
const allTasks = listTasks(project_slug);
const existingAudit = allTasks.find(
(t) => t.agent_id === cmoAgentId && t.title?.startsWith("Audit the account"),
@@ -231,20 +238,14 @@ export async function setOnboardingAccountAction(
// /api/chat (which atomically claims). For the resubmit branch
// (audit already running/done) /api/chat is a safe no-op.
- // Resolve the CMO's URL slug so the client can land on its tasks page
- // without computing the role-name slug itself.
- const { readAgentMeta } = await import("@/server/agent-meta");
- const { agentUrlSlug, TEMPLATES } = await import("@/server/agent-templates");
- const cmoMeta = readAgentMeta(cmoAgentId);
- const cmoName =
- cmoMeta?.name ?? TEMPLATES.find((t) => t.key === "cmo")!.default_name;
- const cmo_agent_slug = agentUrlSlug("cmo", cmoName);
-
+ // The CMO's URL slug was already resolved above (via listProjectAgents);
+ // hand it to the client so the redirect uses the role-name path without
+ // the client computing anything itself.
revalidatePath("/", "layout");
return {
ok: true,
project: updated,
task_display_id: task.display_id,
- cmo_agent_slug,
+ cmo_agent_slug: cmo.slug,
};
}
diff --git a/src/server/openclaw/sessions.test.ts b/src/server/openclaw/sessions.test.ts
index 3a6030ee..7c442baa 100644
--- a/src/server/openclaw/sessions.test.ts
+++ b/src/server/openclaw/sessions.test.ts
@@ -194,14 +194,14 @@ describe("getSessionsView", () => {
"agent:alpha-cmo:m1": { sessionId: "s1", updatedAt: 100 },
"agent:alpha-cmo:m2": { sessionId: "s2", updatedAt: 200 },
});
- const view = await getSessionsView("alpha", "cmo");
+ 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");
+ 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(
@@ -218,7 +218,7 @@ describe("getSessionsView", () => {
"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");
+ 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.
@@ -230,7 +230,7 @@ describe("getSessionsView", () => {
"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");
+ 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.
diff --git a/src/server/openclaw/sessions.ts b/src/server/openclaw/sessions.ts
index 71bcdebf..eabd82a4 100644
--- a/src/server/openclaw/sessions.ts
+++ b/src/server/openclaw/sessions.ts
@@ -3,7 +3,7 @@ import { homedir } from "node:os";
import { join } from "node:path";
import { randomUUID } from "node:crypto";
import { cookies } from "next/headers";
-import { agentNameFor, type AgentTemplateKey } from "@/server/agent-templates";
+import type { AgentTemplateKey } from "@/server/agent-templates";
/**
* Sessions are owned by OpenClaw. We never persist threads, history, or
@@ -118,16 +118,22 @@ function cookieName(project_slug: string, agent_template_key: string): string {
}
/**
- * Return the active session for (project, agent_template) 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.
+ * 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 = agentNameFor(project_slug, agent_template_key);
+ const agentFullId = agent_full_id;
const existing = listSessionsForAgent(agentFullId);
const c = await cookies();
diff --git a/src/server/orchestration/handlers.ts b/src/server/orchestration/handlers.ts
index 533e93d0..376c71e1 100644
--- a/src/server/orchestration/handlers.ts
+++ b/src/server/orchestration/handlers.ts
@@ -1,6 +1,5 @@
import {
agentExists,
- agentNameFor,
templateForKey,
type AgentTemplateKey,
} from "@/server/agent-templates";
@@ -103,16 +102,19 @@ export async function handleCreateTask(
return { ok: false, error: "CMO cannot assign tasks to itself — pick a specialist" };
}
- const assigneeAgentId = agentNameFor(
- ctx.project_slug,
- template.key as AgentTemplateKey,
+ // Look up the assignee by template_key — agent_ids encode the
+ // personal name (e.g. `acme-google-ads-ana`), so we can't synthesize
+ // one from the role alone.
+ const assigneeEntry = (await listProjectAgents(ctx.project_slug)).find(
+ (a) => a.template_key === template.key,
);
- if (!(await agentExists(assigneeAgentId))) {
+ if (!assigneeEntry || !(await agentExists(assigneeEntry.agent_id))) {
return {
ok: false,
- error: `Assignee agent ${assigneeAgentId} is not provisioned for this project`,
+ error: `Assignee agent for role '${template.key}' is not provisioned for this project`,
};
}
+ const assigneeAgentId = assigneeEntry.agent_id;
const task = createTask({
project_slug: ctx.project_slug,