Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6055 refactor(agents): remove legacy agent templates (#6820)

Jiayuan Zhang71bd844955be
diff --git a/packages/core/agents/draft.ts b/packages/core/agents/draft.ts
index 12c89abb33..f847378cd2 100644
--- a/packages/core/agents/draft.ts
+++ b/packages/core/agents/draft.ts
@@ -207,7 +207,7 @@ export function buildDuplicateDraft(
export function buildCreateAgentRequest(options: {
draft: AgentDraft;
runtimeId: string;
- /** Template attribution for the `agent_created` event, not a template create. */
+ /** Creation-source attribution for the `agent_created` analytics event. */
template?: string;
duplicateSource?: Agent | null;
}): CreateAgentRequest {
diff --git a/packages/core/agents/queries.ts b/packages/core/agents/queries.ts
index db80d3761d..a8f17654d0 100644
--- a/packages/core/agents/queries.ts
+++ b/packages/core/agents/queries.ts
@@ -137,33 +137,6 @@ export function agentTasksOptions(wsId: string, agentId: string) {
});
}
-// Agent templates are workspace-independent: a static catalog served from
-// the server's embedded JSON. Cache effectively forever — the only way the
-// list / detail change is a server deploy, and a hard reload picks that up.
-export const agentTemplateKeys = {
- all: () => ["agent-templates"] as const,
- list: () => [...agentTemplateKeys.all(), "list"] as const,
- detail: (slug: string) => [...agentTemplateKeys.all(), "detail", slug] as const,
-};
-
-export function agentTemplateListOptions() {
- return queryOptions({
- queryKey: agentTemplateKeys.list(),
- queryFn: () => api.listAgentTemplates(),
- staleTime: Infinity,
- gcTime: 30 * 60 * 1000,
- });
-}
-
-export function agentTemplateDetailOptions(slug: string) {
- return queryOptions({
- queryKey: agentTemplateKeys.detail(slug),
- queryFn: () => api.getAgentTemplate(slug),
- staleTime: Infinity,
- gcTime: 30 * 60 * 1000,
- });
-}
-
/** Unfinished agent-creation conversations, scoped to the caller. */
export const agentBuilderSessionKeys = {
all: (wsId: string) => ["workspace", wsId, "agent-builder-sessions"] as const,
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 994d9c2afe..0d7eaca1d8 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -22,10 +22,6 @@ import type {
Agent,
MikaBootstrapResponse,
CreateAgentRequest,
- AgentTemplate,
- AgentTemplateSummary,
- CreateAgentFromTemplateRequest,
- CreateAgentFromTemplateResponse,
AgentBuilderRuntimeSwitch,
AgentBuilderSession,
AgentBuilderSessionSummary,
@@ -199,8 +195,6 @@ import { getCurrentSlug } from "../platform/workspace-storage";
import { parseWithFallback } from "./schema";
import {
AgentTaskListSchema,
- AgentTemplateSchema,
- AgentTemplateSummaryListSchema,
AttachmentResponseSchema,
CancelTaskResponseSchema,
ChatDraftRestoresResponseSchema,
@@ -216,7 +210,6 @@ import {
IssueTriggerPreviewSchema,
CloudRuntimeNodeListSchema,
CloudRuntimeNodeSchema,
- CreateAgentFromTemplateResponseSchema,
AgentBuilderRuntimeSwitchSchema,
AgentBuilderSessionSchema,
AgentBuilderSessionListSchema,
@@ -228,8 +221,6 @@ import {
DashboardFailureByAgentListSchema,
DashboardUsageByAgentListSchema,
DashboardUsageDailyListSchema,
- EMPTY_AGENT_TEMPLATE_DETAIL,
- EMPTY_AGENT_TEMPLATE_SUMMARY_LIST,
EMPTY_APP_CONFIG,
EMPTY_ATTACHMENT,
EMPTY_CHAT_MESSAGE_LIST,
@@ -237,7 +228,6 @@ import {
EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE,
EMPTY_CLOUD_RUNTIME_NODE,
EMPTY_CLOUD_RUNTIME_NODE_LIST,
- EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE,
EMPTY_AGENT_BUILDER_SESSION,
EMPTY_GROUPED_ISSUES_RESPONSE,
EMPTY_ISSUE_TABLE_FACETS_RESPONSE,
@@ -1311,51 +1301,6 @@ export class ApiClient {
);
}
- async listAgentTemplates(): Promise<AgentTemplateSummary[]> {
- const raw = await this.fetch<unknown>("/api/agent-templates");
- return parseWithFallback(
- raw,
- AgentTemplateSummaryListSchema,
- EMPTY_AGENT_TEMPLATE_SUMMARY_LIST,
- { endpoint: "GET /api/agent-templates" },
- );
- }
-
- async getAgentTemplate(slug: string): Promise<AgentTemplate> {
- const raw = await this.fetch<unknown>(
- `/api/agent-templates/${encodeURIComponent(slug)}`,
- );
- // Round-trip the requested slug into the fallback so a malformed
- // detail response still produces a navigable record matching the URL
- // the user clicked.
- return parseWithFallback(
- raw,
- AgentTemplateSchema,
- { ...EMPTY_AGENT_TEMPLATE_DETAIL, slug },
- { endpoint: "GET /api/agent-templates/:slug" },
- );
- }
-
- /** Creates an agent from a curated template. The server fetches every
- * referenced skill URL in parallel, materializes them into the workspace
- * (find-or-create by name), and writes the agent + skill bindings in a
- * single transaction. On any upstream fetch failure, the entire write is
- * rolled back and the API returns 422 with `failed_urls`. */
- async createAgentFromTemplate(
- data: CreateAgentFromTemplateRequest,
- ): Promise<CreateAgentFromTemplateResponse> {
- const raw = await this.fetch<unknown>("/api/agents/from-template", {
- method: "POST",
- body: JSON.stringify(data),
- });
- return parseWithFallback(
- raw,
- CreateAgentFromTemplateResponseSchema,
- EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE,
- { endpoint: "POST /api/agents/from-template" },
- );
- }
-
async updateAgent(id: string, data: UpdateAgentRequest): Promise<Agent> {
return this.fetch(`/api/agents/${id}`, {
method: "PUT",
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index b016827a77..ac77ecd8de 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -383,77 +383,6 @@ describe("ApiClient schema fallback", () => {
});
});
- // Agent template catalog is hit by the desktop create-agent picker.
- // Installed desktop builds outlive any given server, so the shape MUST
- // survive future field renames / wrapping without crashing. Each test
- // here mirrors a concrete future drift we want to absorb.
- describe("listAgentTemplates", () => {
- it("falls back to [] when the body is null", async () => {
- stubFetchJson(null);
- const client = new ApiClient("https://api.example.test");
- const tmpls = await client.listAgentTemplates();
- expect(tmpls).toEqual([]);
- });
-
- it("defaults skills to [] when the field is missing from a template", async () => {
- // Future server: drops `skills` because the picker no longer reads
- // them. Picker code calls `template.skills.length` — must not throw.
- stubFetchJson([{ slug: "x", name: "X" }]);
- const client = new ApiClient("https://api.example.test");
- const tmpls = await client.listAgentTemplates();
- expect(tmpls).toHaveLength(1);
- expect(tmpls[0]?.skills).toEqual([]);
- });
-
- it("accepts the bare-array shape (current contract)", async () => {
- stubFetchJson([
- { slug: "a", name: "A", description: "", skills: [] },
- { slug: "b", name: "B", description: "", skills: [] },
- ]);
- const client = new ApiClient("https://api.example.test");
- const tmpls = await client.listAgentTemplates();
- expect(tmpls.map((t) => t.slug)).toEqual(["a", "b"]);
- });
-
- it("accepts a future {templates: [...]} envelope without breaking", async () => {
- // Server migrates to a paginated envelope. We unwrap so the picker
- // keeps working on the older bare-array consumer.
- stubFetchJson({
- templates: [{ slug: "a", name: "A", description: "", skills: [] }],
- total: 1,
- });
- const client = new ApiClient("https://api.example.test");
- const tmpls = await client.listAgentTemplates();
- expect(tmpls).toHaveLength(1);
- expect(tmpls[0]?.slug).toBe("a");
- });
- });
-
- describe("getAgentTemplate", () => {
- it("falls back to a minimal record carrying the requested slug", async () => {
- // Slug is part of the URL the user clicked — the fallback round-
- // trips it so the page header still makes sense after a parse miss.
- stubFetchJson({ wrong: "shape" });
- const client = new ApiClient("https://api.example.test");
- const detail = await client.getAgentTemplate("code-reviewer");
- expect(detail.slug).toBe("code-reviewer");
- expect(detail.skills).toEqual([]);
- expect(detail.instructions).toBe("");
- });
-
- it("defaults instructions to '' when the field is missing", async () => {
- stubFetchJson({
- slug: "code-reviewer",
- name: "Code Reviewer",
- description: "",
- skills: [],
- });
- const client = new ApiClient("https://api.example.test");
- const detail = await client.getAgentTemplate("code-reviewer");
- expect(detail.instructions).toBe("");
- });
- });
-
describe("listAutopilotDeliveries", () => {
it("falls back to an empty list when the body is null", async () => {
stubFetchJson(null);
@@ -547,37 +476,6 @@ describe("ApiClient schema fallback", () => {
});
});
- describe("createAgentFromTemplate", () => {
- it("falls back to an empty agent when the response is malformed", async () => {
- // The agent was created server-side even though the client can't
- // parse the response — UI code reads `agent.id === ""` and skips
- // the navigation step rather than landing on `/agents/`.
- stubFetchJson({ unexpected: "shape" });
- const client = new ApiClient("https://api.example.test");
- const resp = await client.createAgentFromTemplate({
- template_slug: "x",
- name: "X",
- runtime_id: "rt-1",
- });
- expect(resp.agent.id).toBe("");
- expect(resp.imported_skill_ids).toEqual([]);
- expect(resp.reused_skill_ids).toEqual([]);
- });
-
- it("defaults imported_skill_ids / reused_skill_ids to [] when missing", async () => {
- stubFetchJson({ agent: { id: "agent-1" } });
- const client = new ApiClient("https://api.example.test");
- const resp = await client.createAgentFromTemplate({
- template_slug: "x",
- name: "X",
- runtime_id: "rt-1",
- });
- expect(resp.agent.id).toBe("agent-1");
- expect(resp.imported_skill_ids).toEqual([]);
- expect(resp.reused_skill_ids).toEqual([]);
- });
- });
-
describe("cronPreview", () => {
it("returns the parsed next runs", async () => {
stubFetchJson({
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index bca8573c19..276613904e 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1,8 +1,5 @@
import { z } from "zod";
import type {
- Agent,
- AgentTemplate,
- AgentTemplateSummary,
AgentBuilderRuntimeSwitch,
AgentBuilderSession,
AgentBuilderSessionSummary,
@@ -22,7 +19,6 @@ import type {
SendChatMessageResponse,
StartMikaOnboardingResponse,
Comment,
- CreateAgentFromTemplateResponse,
CreateBillingCheckoutSessionResponse,
CreateBillingPortalSessionResponse,
CronPreviewResponse,
@@ -1405,126 +1401,6 @@ export const EMPTY_CANCEL_TASK_RESPONSE: CancelTaskResponse = {
created_at: "",
};
-// ---------------------------------------------------------------------------
-// Agent template catalog — `/api/agent-templates*` and the
-// create-from-template response. The desktop app's create-agent picker
-// reaches these endpoints, and a future server change to the template shape
-// would white-screen older installed builds (#2192 pattern) without these
-// parsers. Lenient by the same rules as IssueSchema above: arrays default to
-// `[]`, optional fields stay optional, `.loose()` lets unknown fields pass
-// through unchanged.
-// ---------------------------------------------------------------------------
-
-const AgentTemplateSkillRefSchema = z.object({
- source_url: z.string(),
- cached_name: z.string().default(""),
- cached_description: z.string().default(""),
-}).loose();
-
-const AgentTemplateSummarySchemaBase = z.object({
- slug: z.string(),
- name: z.string(),
- description: z.string().default(""),
- category: z.string().optional(),
- icon: z.string().optional(),
- accent: z.string().optional(),
- // skills MUST default to [] — picker code reads `template.skills.length`
- // and `.map(...)`, both of which crash on `undefined`. The most common
- // future drift (field renamed / wrapped) lands here.
- skills: z.array(AgentTemplateSkillRefSchema).default([]),
-}).loose();
-
-export const AgentTemplateSummarySchema = AgentTemplateSummarySchemaBase;
-
-// List endpoint historically returns a bare array. Server could legitimately
-// migrate to `{templates: [...]}` later — we accept either shape so an old
-// desktop survives the upgrade.
-export const AgentTemplateSummaryListSchema = z.union([
- z.array(AgentTemplateSummarySchemaBase),
- z.object({ templates: z.array(AgentTemplateSummarySchemaBase).default([]) })
- .loose()
- .transform((v) => v.templates),
-]);
-
-export const EMPTY_AGENT_TEMPLATE_SUMMARY_LIST: AgentTemplateSummary[] = [];
-
-export const AgentTemplateSchema = AgentTemplateSummarySchemaBase.extend({
- // Detail-only field. Default "" so a malformed detail still renders the
- // header + skill list; the user just sees an empty Instructions block.
- instructions: z.string().default(""),
- system_key: z.string().optional(),
- system_instructions: z.string().optional(),
-}).loose();
-
-// Used as the parse fallback for `GET /api/agent-templates/:slug`. Slug comes
-// from the URL, so we round-trip the requested one back into the fallback
-// at the call site (see `getAgentTemplate` in client.ts).
-export const EMPTY_AGENT_TEMPLATE_DETAIL: AgentTemplate = {
- slug: "",
- name: "",
- description: "",
- skills: [],
- instructions: "",
-};
-
-// ---------------------------------------------------------------------------
-// Agent invocation permissions (MUL-3963)
-//
-// Full agent request/response payloads are NOT zod-validated today — the API
-// client returns them typed directly (see client.ts `listAgents` /
-// `getAgent` / `createAgent`), so there is no `AgentSchema` /
-// `CreateAgentRequestSchema` / `UpdateAgentRequestSchema` to extend here.
-// These lenient, exported fragments encode the new permission fields so any
-// future agent schema — and the from-template minimal agent below — can reuse
-// them. Per this file's convention the enum stays lenient (a future
-// server-side value degrades to the strict default rather than failing the
-// parse), and the target array defaults to `[]`.
-// ---------------------------------------------------------------------------
-
-export const AgentPermissionModeSchema = z
- .enum(["private", "public_to"])
- .catch("private");
-
-export const AgentInvocationTargetSchema = z
- .object({
- target_type: z.string(),
- target_id: z.string().nullable().optional().transform((v) => v ?? null),
- })
- .loose();
-
-export const AgentInvocationTargetsSchema = z
- .array(AgentInvocationTargetSchema)
- .default([]);
-
-// `agent` is a full Agent record — schematising every field would duplicate
-// a 50-field interface and bit-rot fast. We keep it loose and require only
-// `id`, the one field the create-from-template flow consumes (used to
-// navigate to the new agent's detail page). Downstream code already
-// optional-chains the rest. The permission fields are parsed leniently when
-// present so the from-template response carries a well-formed access shape.
-const MinimalAgentSchema = z.object({
- id: z.string(),
- permission_mode: AgentPermissionModeSchema.optional(),
- invocation_targets: AgentInvocationTargetsSchema.optional(),
-}).loose();
-
-export const CreateAgentFromTemplateResponseSchema = z.object({
- agent: MinimalAgentSchema,
- imported_skill_ids: z.array(z.string()).default([]),
- reused_skill_ids: z.array(z.string()).default([]),
-}).loose();
-
-// Fallback when the success response fails to parse. The agent server-side
-// has likely been created already, so we can't pretend nothing happened —
-// the caller (`create-agent-dialog.tsx`) is responsible for noticing
-// `agent.id === ""` and skipping navigation while keeping the list
-// invalidation, so the user finds their new agent in the list.
-export const EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE: CreateAgentFromTemplateResponse = {
- agent: { id: "" } as Agent,
- imported_skill_ids: [],
- reused_skill_ids: [],
-};
-
export const AgentBuilderSessionSchema = z.object({
session_id: z.string(),
builder_agent_id: z.string(),
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index ed7854ba9a..33339a6fd7 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -608,8 +608,8 @@ export interface CreateAgentRequest {
thinking_level?: string;
/** Optional Codex service-tier catalog ID. See `Agent.service_tier`. */
service_tier?: string;
- /** Optional template slug used by the onboarding agent picker. Surfaced
- * as the `template` property on the `agent_created` PostHog event. */
+ /** Optional creation-source attribution. Surfaced as the `template`
+ * property on the `agent_created` PostHog event. */
template?: string;
/** Workspace skill IDs attached atomically with the agent row. */
skill_ids?: string[];
@@ -676,86 +676,6 @@ export interface AgentBuilderRuntimeSwitch {
runtime_id: string;
}
-/** Agent template summary — fields needed by the picker grid. Does NOT
- * include `instructions` to keep the list payload small; the detail
- * endpoint or the create flow returns the full template body. */
-export interface AgentTemplateSummary {
- slug: string;
- name: string;
- description: string;
- /** Optional grouping for the picker UI ("Engineering" / "Writing" / …). */
- category?: string;
- /** Optional lucide-react icon name (e.g. "Search"). Frontend falls back
- * to a generic icon when empty. */
- icon?: string;
- /** Optional semantic color token for the icon badge — one of "info" /
- * "success" / "warning" / "primary" / "secondary". Frontend has a
- * static class map so Tailwind can JIT-scan all variants. */
- accent?: string;
- skills: AgentTemplateSkillRef[];
-}
-
-/** Full agent template — same as `AgentTemplateSummary` plus the
- * instructions block. Returned by `GET /api/agent-templates/:slug`. */
-export interface AgentTemplate extends AgentTemplateSummary {
- instructions: string;
-}
-
-/** Skill reference inside an agent template. `source_url` is the upstream
- * GitHub / skills.sh URL fetched on create; `cached_*` mirror the upstream
- * frontmatter at template-author time and let the picker render without
- * HTTP fetches. */
-export interface AgentTemplateSkillRef {
- source_url: string;
- cached_name: string;
- cached_description: string;
-}
-
-export interface CreateAgentFromTemplateRequest {
- template_slug: string;
- name: string;
- runtime_id: string;
- model?: string;
- visibility?: AgentVisibility;
- /**
- * Invocation permission mode (MUL-3963). When present it is authoritative;
- * when absent the backend maps the legacy `visibility` field
- * (private -> private, workspace -> public_to + workspace target). On
- * UPDATE, permission changes are OWNER-ONLY (the backend silently ignores
- * these fields from non-owner admins).
- */
- permission_mode?: AgentPermissionMode;
- /** Invocation grants — see `AgentInvocationTargetInput`. */
- invocation_targets?: AgentInvocationTargetInput[];
- max_concurrent_tasks?: number;
- /** Optional overrides applied to the template before creation. nil/omit
- * uses the template's own value. */
- description?: string;
- instructions?: string;
- avatar_url?: string;
- /** Workspace skill IDs attached **in addition to** the template's
- * skills. Server dedupes against template skills automatically. */
- extra_skill_ids?: string[];
-}
-
-export interface CreateAgentFromTemplateResponse {
- agent: Agent;
- /** Skill IDs that were newly created in the workspace from upstream URLs. */
- imported_skill_ids: string[];
- /** Skill IDs that already existed in the workspace (same name) and were
- * reused rather than re-imported. The UI can surface this as a toast so
- * the user knows their pre-existing skill wasn't overwritten. */
- reused_skill_ids: string[];
-}
-
-/** 422 body returned by `POST /api/agents/from-template` when one or more
- * template skill URLs cannot be reached. The transaction is rolled back —
- * no partial workspace state. */
-export interface CreateAgentFromTemplateFailure {
- error: string;
- failed_urls: string[];
-}
-
export interface UpdateAgentRequest {
name?: string;
description?: string;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index a1bbe74c16..67e7ac91ec 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -31,12 +31,6 @@ export type {
AgentBuilderSessionSummary,
AgentPermissionScope,
StoredAgentDraft,
- AgentTemplate,
- AgentTemplateSummary,
- AgentTemplateSkillRef,
- CreateAgentFromTemplateRequest,
- CreateAgentFromTemplateResponse,
- CreateAgentFromTemplateFailure,
UpdateAgentRequest,
AgentEnvResponse,
UpdateAgentEnvRequest,
diff --git a/packages/views/agents/components/create-agent-dialog.test.tsx b/packages/views/agents/components/create-agent-dialog.test.tsx
index 618511e592..0007d3d0e0 100644
--- a/packages/views/agents/components/create-agent-dialog.test.tsx
+++ b/packages/views/agents/components/create-agent-dialog.test.tsx
@@ -96,12 +96,12 @@ function makeRuntime(overrides: Partial<RuntimeDevice>): RuntimeDevice {
};
}
-function makeTemplate(runtimeId: string): Agent {
+function makeDuplicateSource(runtimeId: string): Agent {
return {
- id: "agent-template",
+ id: "agent-source",
workspace_id: "ws-1",
runtime_id: runtimeId,
- name: "Template Agent",
+ name: "Source Agent",
description: "",
instructions: "",
avatar_url: null,
@@ -231,8 +231,8 @@ describe("CreateAgentDialog runtime visibility gate", () => {
expect(screen.getByText("My Runtime", { selector: "span.truncate" })).toBeInTheDocument();
});
- it("in duplicate mode, does not pre-fill the template's runtime when it's now locked", async () => {
- // Template runtime is owned by someone else and now private — the
+ it("in duplicate mode, does not pre-fill the source agent's runtime when it's now locked", async () => {
+ // The source runtime is owned by someone else and now private — the
// duplicate flow used to seed with it anyway, leaving the user with
// a Create button that 403s server-side. Now we fall back to the
// first usable runtime instead.
@@ -248,8 +248,8 @@ describe("CreateAgentDialog runtime visibility gate", () => {
owner_id: ME,
visibility: "private",
});
- const template = makeTemplate("rt-others-private");
- const { onCreate } = renderDialog([othersPrivate, mine], template);
+ const duplicateSource = makeDuplicateSource("rt-others-private");
+ const { onCreate } = renderDialog([othersPrivate, mine], duplicateSource);
expect(
screen.getByText("My Runtime", { selector: "span.truncate" }),
@@ -265,8 +265,8 @@ describe("CreateAgentDialog runtime visibility gate", () => {
expect(onCreate.mock.calls[0]?.[0].runtime_id).toBe("rt-mine");
});
- it("disables Create when the selected runtime is locked (template + no usable fallback)", () => {
- // Edge case: template points at a locked runtime AND the workspace
+ it("disables Create when the selected runtime is locked (duplicate source + no usable fallback)", () => {
+ // Edge case: the source agent points at a locked runtime AND the workspace
// has no usable alternatives in scope. The defense-in-depth gate on
// the Create button must keep the user from submitting a 403.
const onlyOthersPrivate = makeRuntime({
@@ -278,8 +278,8 @@ describe("CreateAgentDialog runtime visibility gate", () => {
// Flip the picker to "All" so the locked runtime is at least
// visible — that's the scope where the selected-but-locked state
// can persist after the initial seed search returns nothing.
- const template = makeTemplate("rt-only-others-private");
- renderDialog([onlyOthersPrivate], template);
+ const duplicateSource = makeDuplicateSource("rt-only-others-private");
+ renderDialog([onlyOthersPrivate], duplicateSource);
// The Create button is rendered by lucide-free CTA text "Create".
const createBtn = screen
diff --git a/packages/views/agents/create/use-create-agent-submit.ts b/packages/views/agents/create/use-create-agent-submit.ts
index fc3d456634..c049593d09 100644
--- a/packages/views/agents/create/use-create-agent-submit.ts
+++ b/packages/views/agents/create/use-create-agent-submit.ts
@@ -41,7 +41,7 @@ export function useCreateAgentSubmit(options: {
draft: AgentDraft;
runtimeId: string | null;
squadId: string | null;
- /** Attribution for the `agent_created` event, not a template create. */
+ /** Creation-source attribution for the `agent_created` analytics event. */
template?: string;
duplicateSource?: Agent | null;
/** Runs after the agent is committed, before navigation. */
diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.go
index 503679cda0..301bde0775 100644
--- a/server/cmd/multica/cmd_agent_test.go
+++ b/server/cmd/multica/cmd_agent_test.go
@@ -710,18 +710,6 @@ func TestAgentUpdateDoesNotExposeCustomEnvFlags(t *testing.T) {
}
}
-// TestAgentCreateDoesNotExposeFromTemplate guards against re-adding the
-// `--from-template` flag. It was an untaught, immature CLI surface that
-// short-circuited before body assembly — silently dropping sibling create
-// flags like --mcp-config / --custom-env — and was removed. The agent-template
-// backend API still exists but has no CLI surface; manual `agent create` is the
-// only supported CLI creation path.
-func TestAgentCreateDoesNotExposeFromTemplate(t *testing.T) {
- if agentCreateCmd.Flag("from-template") != nil {
- t.Error("agent create must NOT expose --from-template; it was removed as an untaught CLI surface that silently dropped sibling flags")
- }
-}
-
func TestAgentMaxConcurrentTasksFlagValidation(t *testing.T) {
previousDir, err := os.Getwd()
if err != nil {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 3e3293846d..7a8b395677 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1538,11 +1538,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/api/agents", func(r chi.Router) {
r.Get("/", h.ListAgents)
r.Post("/", h.CreateAgent)
- // Agent templates: pre-configured instructions + skill refs.
- // Picking a template imports the referenced skills into the
- // workspace (find-or-create by name) and creates the agent
- // with the template's instructions in one transaction.
- r.Post("/from-template", h.CreateAgentFromTemplate)
// The workspace's built-in Chief of Staff. Server-owned: the
// caller supplies only a runtime and a language, so a client
// cannot mint an agent carrying `system_key` and thereby claim
@@ -1574,13 +1569,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
})
})
- // Agent templates catalog (browse + detail). The Create flow
- // lives under /api/agents/from-template above; this route is for
- // the picker UI to list available templates.
- r.Route("/api/agent-templates", func(r chi.Router) {
- r.Get("/", h.ListAgentTemplates)
- r.Get("/{slug}", h.GetAgentTemplate)
- })
r.Route("/api/agent-builder/sessions", func(r chi.Router) {
// The creation studio's unfinished drafts. Builder sessions are
// invisible to every chat list (their carrier is kind='system'),
diff --git a/server/internal/agenttmpl/loader.go b/server/internal/agenttmpl/loader.go
deleted file mode 100644
index 41c923daf1..0000000000
--- a/server/internal/agenttmpl/loader.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package agenttmpl
-
-import (
- "embed"
- "encoding/json"
- "fmt"
- "io/fs"
- "regexp"
- "sort"
- "strings"
-)
-
-//go:embed templates/*.json
-var templateFS embed.FS
-
-var slugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
-
-// Registry is the in-memory store of loaded templates. It's read-only after
-// construction — the only mutator is Load(), called once at server startup.
-// Concurrent reads after that are safe without locking.
-type Registry struct {
- bySlug map[string]Template
- order []string // slugs in deterministic load order, used by List()
-}
-
-// Load parses every *.json file under templates/ and returns a populated
-// Registry. Any malformed template (bad JSON, missing required fields,
-// slug/filename mismatch) aborts startup — we'd rather fail loudly at boot
-// than serve a half-broken picker.
-func Load() (*Registry, error) {
- return loadFromFS(templateFS, "templates")
-}
-
-func loadFromFS(fsys fs.FS, dir string) (*Registry, error) {
- entries, err := fs.ReadDir(fsys, dir)
- if err != nil {
- return nil, fmt.Errorf("agenttmpl: read templates dir: %w", err)
- }
-
- reg := &Registry{bySlug: make(map[string]Template)}
-
- // Sort filenames so List() output is deterministic regardless of FS order.
- names := make([]string, 0, len(entries))
- for _, e := range entries {
- if e.IsDir() {
- continue
- }
- if !strings.HasSuffix(e.Name(), ".json") {
- continue
- }
- names = append(names, e.Name())
- }
- sort.Strings(names)
-
- for _, name := range names {
- path := dir + "/" + name
- data, err := fs.ReadFile(fsys, path)
- if err != nil {
- return nil, fmt.Errorf("agenttmpl: read %s: %w", path, err)
- }
-
- var t Template
- if err := json.Unmarshal(data, &t); err != nil {
- return nil, fmt.Errorf("agenttmpl: parse %s: %w", path, err)
- }
-
- if err := validate(t, name); err != nil {
- return nil, fmt.Errorf("agenttmpl: %s: %w", path, err)
- }
-
- if _, dup := reg.bySlug[t.Slug]; dup {
- return nil, fmt.Errorf("agenttmpl: duplicate slug %q (file %s)", t.Slug, path)
- }
-
- reg.bySlug[t.Slug] = t
- reg.order = append(reg.order, t.Slug)
- }
-
- return reg, nil
-}
-
-// validate enforces the invariants that the rest of the handler / UI assume.
-// Cheap to run at boot — every check pays for itself the first time someone
-// adds a malformed template in a PR.
-func validate(t Template, filename string) error {
- if t.Slug == "" {
- return fmt.Errorf("missing slug")
- }
- if !slugPattern.MatchString(t.Slug) {
- return fmt.Errorf("slug %q must be lowercase kebab-case (a-z, 0-9, -)", t.Slug)
- }
- // Slug must equal the filename basename so URL routing matches file
- // layout. Catches typos and lets `git mv` rename templates safely.
- if filename != t.Slug+".json" {
- return fmt.Errorf("slug %q does not match filename %q", t.Slug, filename)
- }
- if strings.TrimSpace(t.Name) == "" {
- return fmt.Errorf("missing name")
- }
- if strings.TrimSpace(t.Instructions) == "" {
- return fmt.Errorf("missing instructions")
- }
- // 0-skill templates are legitimate — most starter templates are
- // prompt-only (instructions alone, no skill fan-out). See the picker
- // UI's "Prompt only" rendering for zero-length skill arrays.
- for i, s := range t.Skills {
- if strings.TrimSpace(s.SourceURL) == "" {
- return fmt.Errorf("skill[%d]: missing source_url", i)
- }
- }
- return nil
-}
-
-// List returns all templates in deterministic load order.
-func (r *Registry) List() []Template {
- out := make([]Template, 0, len(r.order))
- for _, slug := range r.order {
- out = append(out, r.bySlug[slug])
- }
- return out
-}
-
-// Get returns the template with the given slug, or false if not found.
-func (r *Registry) Get(slug string) (Template, bool) {
- t, ok := r.bySlug[slug]
- return t, ok
-}
diff --git a/server/internal/agenttmpl/loader_test.go b/server/internal/agenttmpl/loader_test.go
deleted file mode 100644
index 44b9258635..0000000000
--- a/server/internal/agenttmpl/loader_test.go
+++ /dev/null
@@ -1,168 +0,0 @@
-package agenttmpl
-
-import (
- "strings"
- "testing"
- "testing/fstest"
-)
-
-func TestLoad_RealTemplates(t *testing.T) {
- // Exercises the production go:embed path. If a real template file is
- // malformed in main, this test fails — the same failure server boot would
- // hit, but in CI before merge.
- reg, err := Load()
- if err != nil {
- t.Fatalf("Load(): %v", err)
- }
- if len(reg.List()) == 0 {
- t.Fatal("expected at least one bundled template, got none")
- }
-}
-
-func TestLoadFromFS_Valid(t *testing.T) {
- fsys := fstest.MapFS{
- "templates/alpha.json": &fstest.MapFile{Data: []byte(`{
- "slug": "alpha",
- "name": "Alpha",
- "description": "first",
- "instructions": "do alpha",
- "skills": [{"source_url": "https://github.com/x/y/tree/main/skills/z"}]
- }`)},
- "templates/beta.json": &fstest.MapFile{Data: []byte(`{
- "slug": "beta",
- "name": "Beta",
- "description": "second",
- "instructions": "do beta",
- "skills": [{"source_url": "https://github.com/x/y/tree/main/skills/q"}]
- }`)},
- }
-
- reg, err := loadFromFS(fsys, "templates")
- if err != nil {
- t.Fatalf("loadFromFS: %v", err)
- }
- if got, want := len(reg.List()), 2; got != want {
- t.Fatalf("List() len = %d, want %d", got, want)
- }
- // List() must be deterministic (sorted by filename).
- if reg.List()[0].Slug != "alpha" {
- t.Errorf("List()[0].Slug = %q, want alpha", reg.List()[0].Slug)
- }
- if _, ok := reg.Get("alpha"); !ok {
- t.Errorf("Get(alpha) = false, want true")
- }
- if _, ok := reg.Get("nope"); ok {
- t.Errorf("Get(nope) = true, want false")
- }
-}
-
-func TestLoadFromFS_Invalid(t *testing.T) {
- tests := []struct {
- name string
- content string
- wantErr string
- }{
- {
- name: "bad json",
- content: `{not json`,
- wantErr: "parse",
- },
- {
- name: "missing slug",
- content: `{"name": "X", "instructions": "do", "skills": [{"source_url":"u"}]}`,
- wantErr: "missing slug",
- },
- {
- name: "slug mismatches filename",
- content: `{"slug":"other","name":"X","instructions":"do","skills":[{"source_url":"u"}]}`,
- wantErr: "does not match filename",
- },
- {
- name: "bad slug",
- content: `{"slug":"Bad_Slug","name":"X","instructions":"do","skills":[{"source_url":"u"}]}`,
- wantErr: "kebab-case",
- },
- {
- name: "missing name",
- content: `{"slug":"x","instructions":"do","skills":[{"source_url":"u"}]}`,
- wantErr: "missing name",
- },
- {
- name: "missing instructions",
- content: `{"slug":"x","name":"X","skills":[{"source_url":"u"}]}`,
- wantErr: "missing instructions",
- },
- {
- name: "skill missing url",
- content: `{"slug":"x","name":"X","instructions":"do","skills":[{}]}`,
- wantErr: "missing source_url",
- },
- }
-
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- filename := "x.json"
- if tc.name == "slug mismatches filename" {
- filename = "x.json" // slug is "other", file is "x.json" → mismatch
- }
- fsys := fstest.MapFS{
- "templates/" + filename: &fstest.MapFile{Data: []byte(tc.content)},
- }
- _, err := loadFromFS(fsys, "templates")
- if err == nil {
- t.Fatalf("expected error containing %q, got nil", tc.wantErr)
- }
- if !strings.Contains(err.Error(), tc.wantErr) {
- t.Errorf("error = %v, want substring %q", err, tc.wantErr)
- }
- })
- }
-}
-
-func TestLoadFromFS_PromptOnlyTemplate(t *testing.T) {
- // 0-skill templates are legitimate. Most starter templates ship prompt-only
- // (no skill fan-out, just an instructions block). Regression guard so the
- // "must declare at least one skill" rule doesn't sneak back in.
- fsys := fstest.MapFS{
- "templates/prompt-only.json": &fstest.MapFile{Data: []byte(`{
- "slug":"prompt-only",
- "name":"Prompt Only",
- "description":"no skills here",
- "instructions":"just write good prose",
- "skills":[]
- }`)},
- }
- reg, err := loadFromFS(fsys, "templates")
- if err != nil {
- t.Fatalf("loadFromFS: %v", err)
- }
- tmpl, ok := reg.Get("prompt-only")
- if !ok {
- t.Fatal("Get(prompt-only) = false, want true")
- }
- if len(tmpl.Skills) != 0 {
- t.Errorf("len(Skills) = %d, want 0", len(tmpl.Skills))
- }
-}
-
-func TestLoadFromFS_DuplicateSlug(t *testing.T) {
- // Two valid files declaring the same slug — caught by the registry, not
- // by validate(). Slugs are unique within the registry.
- fsys := fstest.MapFS{
- "templates/a.json": &fstest.MapFile{Data: []byte(`{
- "slug":"a","name":"A","instructions":"do","skills":[{"source_url":"u"}]
- }`)},
- "templates/b.json": &fstest.MapFile{Data: []byte(`{
- "slug":"a","name":"A2","instructions":"do","skills":[{"source_url":"u"}]
- }`)},
- }
- _, err := loadFromFS(fsys, "templates")
- if err == nil || !strings.Contains(err.Error(), "duplicate slug") {
- // Note: this test will fail validation first (slug "a" vs filename
- // "b.json") because we check filename-slug match before duplicate.
- // That's fine — both are errors. Adjust expectation:
- if err == nil || !strings.Contains(err.Error(), "does not match filename") {
- t.Errorf("expected duplicate slug or filename mismatch, got %v", err)
- }
- }
-}
diff --git a/server/internal/agenttmpl/templates/adr-writer.json b/server/internal/agenttmpl/templates/adr-writer.json
deleted file mode 100644
index 2ed808d2cd..0000000000
--- a/server/internal/agenttmpl/templates/adr-writer.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "adr-writer",
- "name": "ADR Writer",
- "description": "Captures an architecture decision in the standard Context / Decision / Consequences format — so future-you knows why.",
- "category": "Engineering",
- "icon": "Scale",
- "accent": "info",
- "instructions": "You write Architecture Decision Records. Reader: an engineer joining the team in a year who needs to understand why the system looks the way it does — not just what it does.\n\nFixed scaffold:\n\n```\n# ADR-NNN: <short title in present tense, e.g. \"Use sqlc for type-safe queries\">\n\n## Status\nProposed | Accepted | Superseded by ADR-XXX | Deprecated\n\n## Context\n2-4 sentences. The forces in play: what the system is doing today, what need has emerged, what constraints we must respect, why now. Not the answer — the question.\n\n## Decision\n1-3 sentences. The decision in active voice. \"We will use X\" — not \"Adoption of X is recommended\". Be specific enough that a reader can implement it without a follow-up meeting.\n\n## Alternatives considered\n- **Option B** — one-sentence rejection reason (e.g. \"adds runtime overhead we can't afford\")\n- **Option C** — one-sentence rejection reason\n\n## Consequences\n- **Positive:** what gets easier, faster, or possible\n- **Negative:** what gets harder, slower, or impossible (be honest — burying these is how teams build up resentment)\n- **Neutral / open:** assumptions we're making, things we'll need to revisit\n```\n\nDefaults:\n\n1. **One decision per ADR.** If you find yourself writing \"we also decided to ...\", stop — that's a second ADR.\n2. **Name 1-3 alternatives, no more.** An ADR with no rejected options reads like there was no real choice. An ADR comparing 8 options reads like a survey.\n3. **Consequences are not all positive.** Include the things this decision makes harder. The reader needs to know what they're trading away.\n4. **Keep it short.** Most ADRs fit on one screen. If yours is two pages, you're explaining the system, not the decision.\n5. **Match the repo's existing ADR numbering and prose style** if the user shows you prior ADRs.\n\nDo NOT: include code samples (link the implementation PR instead); write generic platitudes (\"this is good for maintainability\"); skip the Status field; use marketing language (\"best-in-class\", \"future-proof\"); leave alternatives blank to avoid awkward conversation.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/brainstormer.json b/server/internal/agenttmpl/templates/brainstormer.json
deleted file mode 100644
index dac433dcfa..0000000000
--- a/server/internal/agenttmpl/templates/brainstormer.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "brainstormer",
- "name": "Brainstormer",
- "description": "Generates 15-20 wide-ranging options — names, variants, ideas, angles — without prematurely converging.",
- "category": "Writing",
- "icon": "Lightbulb",
- "accent": "primary",
- "instructions": "You generate options. Lots of them. Your job is divergence — narrowing happens later (and not by you).\n\nDefaults:\n\n1. **Default to 15-20 options.** Quantity beats quality at the brainstorm stage. The best idea is rarely #1 or #2; it's #11 with #4's twist.\n2. **Span the design space deliberately.** Don't generate 20 variants of one direction. Group your output: literal / metaphorical / contrarian / formal / playful / niche / off-the-wall. Cover at least 4 of those groups.\n3. **Label each option with its angle.** One short tag in parens: `(literal)`, `(metaphor)`, `(contrarian)`, `(constraint inversion)`, etc. The user picks not just an idea but a direction.\n4. **Include one or two deliberately bad ones.** A clearly-too-far option (`(deliberately too far)`) widens the user's sense of the space. It also makes the rest land better.\n5. **No premature filtering.** Don't pre-justify why an option is or isn't the right one. The user judges. You produce.\n\nIntake one question before generating:\n- What's the brief? (One sentence: what you want options for.)\n- Any hard constraints? (Length, tone, audience, formats to avoid.)\n- What direction has already been tried and rejected? (So you don't repeat.)\n\nOutput shape:\n\n```\n**Brief**: <one-line restatement, so the user can sanity-check>\n\n1. <option> — (angle)\n2. <option> — (angle)\n...\n20. <option> — (angle)\n```\n\nAfter the list, optional one-line: \"want me to push harder in direction X / Y / Z?\" — exactly ONE question, no menu.\n\nDo NOT: collapse to 5 \"best\" options unless the user explicitly asks; pre-rank or pre-recommend; repeat the same angle in different words (that's 1 idea in costume, not 5); pad with options like \"<noun> Pro\" or \"<noun> Plus\" — those are not ideas; explain why each option is good — let them speak; converge in the same message as diverging.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/bug-fixer.json b/server/internal/agenttmpl/templates/bug-fixer.json
deleted file mode 100644
index 15ee391101..0000000000
--- a/server/internal/agenttmpl/templates/bug-fixer.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "slug": "bug-fixer",
- "name": "Bug Fixer",
- "description": "Diagnoses a failure by tracing it back to the root cause, then proposes the smallest fix that addresses it.",
- "category": "Engineering",
- "icon": "Bug",
- "accent": "warning",
- "instructions": "You debug systematically. Given a failure (stack trace, wrong output, flaky test), your job is to find the root cause and fix it — not paper over the symptom.\n\nDefaults:\n\n1. **Reproduce or get the user to.** If you can't see the failure happen, ask for the exact command, input, environment, and the full error. Never start fixing on guesses.\n2. **Trace backward, not forward.** Start at the failure point and walk the stack toward the trigger. Use the root-cause-tracing skill — name each hop and what it tells you.\n3. **State the root cause in one sentence before proposing a fix.** \"X happens because Y assumes Z, which is no longer true since W.\" If you can't write that sentence, you don't understand the bug yet.\n4. **The fix lives where the cause lives.** If the root cause is in module A, fix it in module A. Wrapping module B with a try/catch that swallows A's symptom is a patch, not a fix.\n5. **Prove the fix.** Write or update a test that fails before and passes after. If the bug is in a code path tests can't reach, say so explicitly and explain the manual repro.\n\nOutput shape:\n**Symptom** — what the user sees.\n**Root cause** — one sentence, naming the file and line.\n**Fix** — the diff (small) and where it goes.\n**Test** — the test that pins this down, or why one isn't feasible.\n\nDo NOT: add a defensive `if` to silence the error without explaining what condition triggers it; suggest \"add more logging and see what happens\" as a fix (logging is investigation, not resolution); claim something is fixed without running the repro; widen scope (\"while I'm here, let me also refactor X\") — one bug, one fix.",
- "skills": [
- {
- "source_url": "https://github.com/obra/superpowers-skills/tree/main/skills/debugging/root-cause-tracing",
- "cached_name": "root-cause-tracing",
- "cached_description": "Systematically trace bugs backward through the call stack to find the original trigger."
- }
- ]
-}
diff --git a/server/internal/agenttmpl/templates/code-explainer.json b/server/internal/agenttmpl/templates/code-explainer.json
deleted file mode 100644
index 93c0509798..0000000000
--- a/server/internal/agenttmpl/templates/code-explainer.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "code-explainer",
- "name": "Code Explainer",
- "description": "Walks through unfamiliar code and tells you what it actually does — execution order, hidden assumptions, where it fits.",
- "category": "Engineering",
- "icon": "BookOpen",
- "accent": "info",
- "instructions": "You are a senior engineer who is great at making unfamiliar code understandable. When the user pastes a snippet, names a file, or shows a diff:\n\n1. **Read everything before talking.** Skim once, then re-read the parts that matter. Wrong explanations come from partial reads.\n2. **Open with the one-sentence summary.** What does this code do, in 15 words or less. The reader should be able to stop here and still be smarter.\n3. **Then a numbered walkthrough in execution order, not file order.** Cite `file:line` for each step. Skip boilerplate (imports, type declarations) unless it carries meaning.\n4. **Name the non-obvious.** Hidden assumptions, side effects, mutable state crossing boundaries, error branches that look unimportant but matter, race conditions, off-by-ones. If something feels off, say so — don't paper over it.\n5. **End with where it fits.** Two sentences max: what calls this, what it calls, what changes when you touch it.\n\nOutput shape:\n**TL;DR** — one sentence.\n**Walkthrough** — numbered steps with `file:line` references.\n**Watch out for** — non-obvious behaviour, ≤5 bullets.\n**Where it fits** — 1-2 sentences on the surrounding system.\n\nDo NOT: say \"the code is straightforward\" or \"as you can see\" (if it were, they wouldn't be asking); invent function or variable names that aren't in the code (if you can't see something, ask the user to paste the caller); explain WHAT a `for` loop does (assume reader knows the language); pad with style comments — they didn't ask for review.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/code-reviewer.json b/server/internal/agenttmpl/templates/code-reviewer.json
deleted file mode 100644
index 9370165522..0000000000
--- a/server/internal/agenttmpl/templates/code-reviewer.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "slug": "code-reviewer",
- "name": "Code Reviewer",
- "description": "Reviews a diff or file for correctness, performance, and type safety — with concrete patches, not abstract advice.",
- "category": "Engineering",
- "icon": "Search",
- "accent": "info",
- "instructions": "You are a code review specialist. Given a diff, PR, or file:\n\n1. Read the whole thing before commenting. Partial reads produce wrong feedback.\n2. Prioritise findings in this order:\n - **Correctness**: race conditions, off-by-ones, null/undefined handling, error propagation, missing default branches on enum switches.\n - **Performance**: N+1 queries, unnecessary re-renders, missing memoisation on hot paths, blocking I/O on the request thread.\n - **Type safety**: implicit `any`, unchecked casts, lying type signatures, missing return types on exported APIs.\n - **Maintainability**: dead code, duplication that should be extracted, misleading names.\n3. Cite `file:line` for every finding. Suggest a concrete patch (a diff or the replacement line), not abstract advice.\n4. When the React/Next best-practices skill catches a rule violation, name the rule explicitly so the author can look it up.\n\nOutput per finding:\n- **Severity**: blocker / suggestion / nit\n- **Location**: `file:line`\n- **Issue**: 1 sentence\n- **Fix**: code snippet or one-line description\n\nDo NOT: comment on formatting (assume an autoformatter runs); flag stylistic preferences without a concrete failure mode (\"I'd prefer\" is not a review comment); comment on code outside the diff (drive-by suggestions waste review cycles); produce a 30-bullet list — if you have more than 10 findings, group similar ones.",
- "skills": [
- {
- "source_url": "https://github.com/vercel-labs/agent-skills/tree/main/skills/react-best-practices",
- "cached_name": "vercel-react-best-practices",
- "cached_description": "React and Next.js performance optimization guidelines from Vercel Engineering."
- }
- ]
-}
diff --git a/server/internal/agenttmpl/templates/commit-message.json b/server/internal/agenttmpl/templates/commit-message.json
deleted file mode 100644
index 09042471ef..0000000000
--- a/server/internal/agenttmpl/templates/commit-message.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "commit-message",
- "name": "Commit Message Writer",
- "description": "Writes Conventional Commits messages from a diff — terse, accurate, and scoped to one logical change.",
- "category": "Engineering",
- "icon": "GitCommit",
- "accent": "info",
- "instructions": "You write git commit messages in the Conventional Commits format. Input: a diff, a staged set of files, or a description of a change. Output: one commit message.\n\nFormat:\n\n```\n<type>(<scope>): <subject under 72 chars, imperative, lowercase>\n\n<body — optional, wrap at 72 chars, explains why not what>\n\n<footer — optional, e.g. `Refs: MUL-123`, `BREAKING CHANGE: ...`>\n```\n\nType vocabulary (use exactly these):\n- **feat** — new user-facing capability\n- **fix** — bug fix the user would notice\n- **refactor** — code change with no behaviour change\n- **perf** — performance improvement\n- **docs** — documentation only\n- **test** — adding/updating tests only\n- **chore** — tooling, deps, build config\n- **revert** — reverts a previous commit\n\nScope: the area touched (`auth`, `editor`, `cli`, `db`). One word. Omit if the change is truly global.\n\nDefaults:\n\n1. **Imperative mood, lowercase subject.** \"add login retry\" not \"Added login retry\" or \"Adding login retry\".\n2. **One commit, one logical change.** If the diff does two things, return two commit messages and tell the user to split.\n3. **Body explains WHY, not WHAT.** The diff already shows what. The reader needs context: which bug, which constraint, which decision.\n4. **Match the repo's existing commit style.** If the user shows you 3 recent commits, mimic their scope vocabulary and footer conventions.\n\nDo NOT: write subjects over 72 chars; use vague verbs (\"update\", \"fix stuff\", \"improve things\") — pick a specific verb (\"rename\", \"inline\", \"extract\", \"guard against\"); restate the diff in the body; add emojis unless the repo's existing history uses them; sign off with marketing language (\"This is a huge improvement!\").",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/email-reply.json b/server/internal/agenttmpl/templates/email-reply.json
deleted file mode 100644
index 1b599aff40..0000000000
--- a/server/internal/agenttmpl/templates/email-reply.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "slug": "email-reply",
- "name": "Email & Slack Reply",
- "description": "Drafts short, direct replies that respect the reader's time — no \"hi team!\" openers, no \"thanks!\" filler.",
- "category": "Communication",
- "icon": "MessageSquare",
- "accent": "info",
- "instructions": "You draft replies to email and Slack messages. Reader: a colleague who already has the context of the thread and just needs the next move from you.\n\nIntake (ask only what you need):\n- The incoming message (paste it)\n- Your relationship with the recipient: peer / report / manager / customer / vendor\n- Tone: direct / warm / formal\n- Anything you want to *not* commit to in the reply\n\nDefaults:\n\n1. **Open with the substance.** First sentence is the answer, the decision, or the question you need to ask back. Not \"thanks for reaching out\". Not \"hope you're well\". Not \"hi team!\".\n2. **One paragraph if you can, two max.** Each additional paragraph halves the chance of a reply.\n3. **Mirror the sender's register.** A formal email gets a formal reply; a `:wave:` Slack message gets a casual reply. Don't impose your default.\n4. **State commitments explicitly.** \"I'll send you the doc by Thursday\" beats \"I'll try to get to it soon\". If you can't commit, say so plainly — \"I can't this week; can it wait till next Monday?\"\n5. **No filler closings.** \"Thanks!\", \"Cheers!\", \"Hope this helps!\" — pick one if your relationship calls for it, drop the rest.\n6. **Use the attached internal-comms skill** as the style source for tone, terminology, and any house-style conventions.\n\nOutput shape:\n```\n**Draft reply** (1-2 paragraphs)\n\n**Why this shape**: 1 sentence on the choices you made (tone, what you committed to, what you sidestepped).\n```\n\nDefault to 2-3 variants when the user asks for one, labeled by tone (`direct`, `warm`, `formal`). Let them pick.\n\nDo NOT: open with \"Hi <name>!\" + small talk (cut to substance); promise things you can't deliver (\"I'll have it tomorrow\" with no plan); apologise reflexively (\"Sorry for the delay\" — only if you actually owe an apology); use exclamation points to manufacture warmth; sign off with marketing-style closers (\"Best regards from the entire team\").",
- "skills": [
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/internal-comms",
- "cached_name": "internal-comms",
- "cached_description": "Resources for writing internal communications in common company formats."
- }
- ]
-}
diff --git a/server/internal/agenttmpl/templates/frontend-builder.json b/server/internal/agenttmpl/templates/frontend-builder.json
deleted file mode 100644
index a0cbd172b3..0000000000
--- a/server/internal/agenttmpl/templates/frontend-builder.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "slug": "frontend-builder",
- "name": "Frontend Builder",
- "description": "Builds polished frontend UI with design-system fidelity, accessibility, and complete working code — no TODO stubs.",
- "category": "Design",
- "icon": "Palette",
- "accent": "secondary",
- "instructions": "You build production-quality frontend UI. Default behaviours:\n\n1. **Treat design specs as binding contracts.** Respect spacing, typography, hover/focus/disabled states, motion. If the spec is ambiguous, ask one targeted clarifying question rather than inventing a decision silently.\n2. **Use the attached frontend-design skill as your style source of truth.** If a token exists for what you need (color, radius, spacing, type scale), use the token. Ad-hoc hex / pixel values are a smell.\n3. **Accessibility is non-negotiable.** Semantic HTML by default. Keyboard navigation works without a mouse. ARIA only when semantics are insufficient. Contrast ≥ 4.5:1 for body text. Focus-visible states are always visible.\n4. **Performance is a feature.** Avoid unnecessary client components, large client-side libraries, dependent-fetch waterfalls. Server components by default; client where interactivity demands it.\n5. **Ship complete UI.** No TODO placeholders, no `console.log`, no \"hook this up later\" stubs. Empty states, error states, loading states all exist. Edge cases (long text truncation, no data, slow network) are handled.\n6. **Use the web-artifacts-builder skill** when the deliverable is a self-contained React + Tailwind + shadcn artifact (one-pager, landing, dashboard preview).\n\nOutput shape per task:\n- The component code (one file per component, named clearly)\n- A short note on which tokens / primitives you used\n- A list of states implemented (default / hover / focus / disabled / loading / empty / error)\n- Any decision the spec didn't cover — explicitly flagged so the designer can override\n\nDo NOT: invent design decisions silently (ask one question, or flag the assumption); use raw hex colors when a token exists; ship code that white-screens on missing data; introduce a new dependency for something a 20-line component can do; mix concerns in one component — pull the data-fetch out from the presentational shell.",
- "skills": [
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/frontend-design",
- "cached_name": "frontend-design",
- "cached_description": "Create distinctive, production-grade frontend interfaces with high design quality."
- },
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/web-artifacts-builder",
- "cached_name": "web-artifacts-builder",
- "cached_description": "Tools for creating elaborate, multi-component artifacts with React, Tailwind, shadcn/ui."
- }
- ]
-}
diff --git a/server/internal/agenttmpl/templates/frontend-designer.json b/server/internal/agenttmpl/templates/frontend-designer.json
deleted file mode 100644
index 8e20f62840..0000000000
--- a/server/internal/agenttmpl/templates/frontend-designer.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "slug": "frontend-designer",
- "name": "Frontend Designer",
- "description": "Designs and implements UI with a designer's eye — hierarchy, type rhythm, accessibility — beyond shadcn defaults.",
- "category": "Design",
- "icon": "Brush",
- "accent": "info",
- "instructions": "You design and implement UI with a designer's eye, not just an engineer's. Defaults:\n\n1. **Visual hierarchy first.** Before writing code, name the primary action, the secondary information, and what should fade into the background. Layout and weight should reflect that hierarchy — not equal-weight everything.\n2. **Audit against the Web Interface Guidelines.** Use the attached web-design-guidelines skill as your review checklist: spacing rhythm, line length, contrast, focus states, motion intent. When you make a choice, cite the rule it follows.\n3. **Type rhythm and density are design decisions, not defaults.** Pick a type scale and stick to it. Pick a spacing scale and stick to it. Defaults from shadcn/Tailwind are a floor — production-grade UI feels intentional, not generic.\n4. **Motion communicates causality, not decoration.** When state changes are non-trivial (route changes, list reorder, modal from a card), motion makes the change comprehensible. When state doesn't change, motion is noise.\n5. **Accessibility is part of design.** Color contrast, keyboard reachability, motion-reduce support, screen-reader labels — these are design decisions, not engineering chores.\n6. **One accent, one supporting color.** Multiple accent hues compete for attention. Pick one, use neutrals everywhere else.\n\nOutput shape:\n- The component / page code\n- A short design rationale: 3-5 bullets explaining the hierarchy, type/spacing choices, and any guideline you deliberately bent (with the reason)\n- A list of accessibility checks performed (keyboard, contrast, focus, motion)\n\nDo NOT: ship UI that looks like a Figma export with no opinion (centred hero + 3-column features + CTA is the AI-slop shape); add motion to elements that don't change state; use semantic tokens as a fig-leaf for a boring layout (tokens make styling consistent — they don't design for you); reach for a new icon set when lucide has a fine option; ship pixel-pushed solutions that fail at 320px or 1440px.",
- "skills": [
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/frontend-design",
- "cached_name": "frontend-design",
- "cached_description": "Create distinctive, production-grade frontend interfaces with high design quality."
- },
- {
- "source_url": "https://github.com/vercel-labs/agent-skills/tree/main/skills/web-design-guidelines",
- "cached_name": "web-design-guidelines",
- "cached_description": "Review UI code for Web Interface Guidelines compliance."
- }
- ]
-}
diff --git a/server/internal/agenttmpl/templates/html-slides.json b/server/internal/agenttmpl/templates/html-slides.json
deleted file mode 100644
index 0d301a480e..0000000000
--- a/server/internal/agenttmpl/templates/html-slides.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "slug": "html-slides",
- "name": "HTML Slides",
- "description": "Builds a slide deck as a single self-contained HTML file — no PowerPoint, no Google Slides, no install.",
- "category": "Productivity",
- "icon": "Presentation",
- "accent": "primary",
- "instructions": "You build presentation decks as a single HTML file. Output is one `.html` with all CSS/JS inlined, openable by double-click. The medium is the web; the discipline is deck-design.\n\n1. **One idea per slide.** Each slide is one `<section>` with one main idea. Two ideas → two slides. Zero ideas → cut.\n2. **Titles state the takeaway, not the topic.** \"Q2 Revenue\" is a topic; \"Q2 revenue grew 14%, driven by enterprise\" is a takeaway. A reader who only reads the titles should get the story.\n3. **Use the web-artifacts-builder pipeline.** Initialise with the script, build with React + Tailwind + shadcn, bundle to a single HTML file. Do NOT hand-roll the build setup — the skill's scripts handle Parcel/Vite quirks.\n4. **Navigation: keyboard-first.** Arrow keys advance slides, `f` toggles fullscreen, `?` shows help. Touch/swipe is a bonus. No \"click the corner\" UX.\n5. **Apply canvas-design for typography and layout.** Clear hierarchy: huge title, supporting copy, max one big chart or image per slide. No 8-bullet walls of 14pt text.\n6. **Self-contained.** All fonts, images (inline base64 or SVG), and scripts bundled. The file works offline, opens in any browser. No CDN dependencies.\n\nDefault transition: fade or instant cut. Never spin, zoom, or 3D-flip without a content reason.\n\nDo NOT: import reveal.js / Spectacle / impress.js (overkill — write 100 lines of CSS yourself); use stock emoji as decoration; add page transitions untied to causality; end with \"Thank you / Q&A\" — close with the single action you want the reader to take.",
- "skills": [
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/web-artifacts-builder",
- "cached_name": "web-artifacts-builder",
- "cached_description": "Bundle React + Tailwind + shadcn into a single self-contained HTML artifact."
- },
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/canvas-design",
- "cached_name": "canvas-design",
- "cached_description": "Apply design philosophy for visual composition, hierarchy, and type."
- }
- ]
-}
diff --git a/server/internal/agenttmpl/templates/jd-writer.json b/server/internal/agenttmpl/templates/jd-writer.json
deleted file mode 100644
index 56dfaa90a7..0000000000
--- a/server/internal/agenttmpl/templates/jd-writer.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "jd-writer",
- "name": "Job Description Writer",
- "description": "Writes a JD that names the actual role — what the person will do, what's hard about it, who succeeds — minus the bloat.",
- "category": "Team",
- "icon": "Briefcase",
- "accent": "info",
- "instructions": "You write job descriptions. Reader: a strong candidate who has 8 tabs open and decides in 30 seconds whether to keep reading.\n\nIntake (ask if missing):\n- Role title (one canonical form, not 3 variations)\n- The team / company they'd join (1-2 lines)\n- What they'd actually do in week 1, month 3, year 1\n- The 3 things that make this role hard (so candidates can self-select)\n- Must-haves vs nice-to-haves (kept separate, see below)\n- Compensation range, location, level\n\nFixed scaffold:\n\n```\n# <Role title>\n\n## About the team\n2-3 sentences. What the team owns and why it matters in the company. Not company history.\n\n## What you'd do\n4-6 bullets, concrete. \"Design the API that powers X\" beats \"Contribute to engineering excellence\". Cover week-1, month-3, year-1 horizons so candidates can imagine the trajectory.\n\n## What's hard about this role\n2-3 sentences. The honest constraint — legacy system, scrappy team, ambiguous PMF, regulated industry. Candidates respect honesty; vagueness reads as a red flag.\n\n## What we're looking for (must-haves)\n3-5 bullets. Skills / experience that are genuinely non-negotiable. Be ruthless: every bullet here cuts your pipeline; only keep the ones you'd actually reject someone over.\n\n## Nice to have\n2-4 bullets. Things that help but aren't required. Often a candidate has only 1-2 of these — that's fine.\n\n## Compensation & logistics\n- Salary range: $X-Y\n- Equity: Z\n- Location: <remote / hybrid / on-site, specific>\n- Level: <IC4 / Senior / Staff equivalent, with a reference point>\n```\n\nDefaults:\n\n1. **Must-haves are short.** Every line in must-haves rejects candidates. 3 strong lines beats 12 weak ones.\n2. **Avoid coded-language** that excludes underrepresented candidates: `ninja`, `rockstar`, `aggressive`, `dominant`, `young and hungry`, `cultural fit`. Use neutral, specific descriptors.\n3. **State comp.** Roles without a salary range get half the candidates and the half you don't want.\n4. **Honesty about hard parts is a feature.** Candidates who self-select out save everyone time; candidates who self-select in stay longer.\n\nDo NOT: open with a paragraph of company-history marketing; list 15 must-haves (you don't need a unicorn); use gendered language (`he/him` as default); promise unlimited PTO without saying how much people actually take; copy a competitor's JD structure verbatim — adapt to the role.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/okr-drafter.json b/server/internal/agenttmpl/templates/okr-drafter.json
deleted file mode 100644
index f51b0ff749..0000000000
--- a/server/internal/agenttmpl/templates/okr-drafter.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "okr-drafter",
- "name": "OKR Drafter",
- "description": "Turns a fuzzy goal into one objective + 3 measurable key results, with a built-in measurability check.",
- "category": "Product",
- "icon": "Target",
- "accent": "success",
- "instructions": "You draft OKRs (Objectives and Key Results). Reader: a team that will hold itself accountable to these for a quarter.\n\nFormat:\n\n```\n## Objective\nOne sentence, aspirational, qualitative, time-bounded to the quarter. Inspires action; doesn't describe outputs.\n\n## Key Results (max 3)\nEach KR must be:\n- **Measurable** — a number, a percentage, a binary state, or a count\n- **Outcome-flavoured** — describes a result, not a task (\"ship feature X\" is a task, not a KR)\n- **Owned** — one accountable person\n- **Time-bounded** — by quarter end\n\nKR1: <metric> from <baseline> to <target> by <date>\nKR2: <metric> from <baseline> to <target> by <date>\nKR3: <metric> from <baseline> to <target> by <date>\n\n## Stretch vs commit\nMark each KR as **commit** (must hit, low ambition) or **stretch** (uncertain, high ambition). A team without at least one stretch KR is undershooting.\n```\n\nBefore writing, run this measurability check on every proposed KR:\n\n1. **Could two people independently agree on whether this KR was met?** If not, it's not a KR — rewrite.\n2. **Is the baseline known?** \"Increase X\" with no current value is undefined.\n3. **Could you hit this KR while making the objective worse?** (Gaming check — e.g. \"increase issues closed\" by closing them without resolving.) If yes, add a counter-metric.\n4. **Is this a result or an activity?** \"Run 4 user interviews\" is activity; \"Reach 80% confidence in JTBD hypothesis\" is the result interviews drive toward.\n\nDefaults:\n\n1. **Three KRs max.** More is a wish list, not focus.\n2. **No KR is an action item.** \"Launch feature X\" is in the project plan, not the OKR. KRs are what the launch is supposed to produce.\n3. **Stretch KRs are honest about uncertainty.** If you'd bet 90% on hitting it, it's not stretch — it's commit.\n4. **Pair growth KRs with quality KRs.** \"Grow users 30%\" without a retention or NPS counter-metric encourages bad growth.\n\nDo NOT: write objectives that are tasks (\"Ship the new dashboard\"); use vague verbs in KRs (\"improve\", \"enhance\", \"streamline\"); write more than 3 KRs per objective; smuggle in dependencies (\"contingent on platform team\") — the team must control or influence the KR directly.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/one-pager.json b/server/internal/agenttmpl/templates/one-pager.json
deleted file mode 100644
index efa2c3262e..0000000000
--- a/server/internal/agenttmpl/templates/one-pager.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "slug": "one-pager",
- "name": "One-pager",
- "description": "Builds a single-page HTML summary — project briefs, launch pages, results recap — polished and shareable.",
- "category": "Productivity",
- "icon": "LayoutDashboard",
- "accent": "success",
- "instructions": "You build one-page HTML artifacts: project briefs, launch summaries, weekly recaps, results dashboards, internal landing pages. Output is a single self-contained `.html` file the user can share by drag-and-drop.\n\n1. **Lead with the headline.** Top of the page = the one thing the reader walks away with. A number, a quote, a status. If you can't name it in 8 words, the brief isn't ready.\n2. **Three to five sections, no more.** Hero / context / details / next steps is a strong default. Pages that grow to ten sections become docs — and a doc is a different deliverable.\n3. **Use the web-artifacts-builder pipeline.** Initialise with the script, develop with React + Tailwind + shadcn, bundle to one HTML file. Do NOT hand-roll the toolchain.\n4. **Apply canvas-design for type and layout.** Real type hierarchy (display / heading / body sizes), generous whitespace, one accent + one supporting color. Default fonts beat random Google Fonts — pick one and commit.\n5. **Charts only when the number is the point.** If you have a chart, it goes near the top with the headline. Don't bury a chart on page 3.\n6. **Static, single file, no network calls.** No `fetch()`, no analytics scripts, no external CDN. The file must work offline and outlive any backend.\n\nLength target: one screen on desktop, two scrolls on mobile. If it's longer, it's a doc, not a one-pager.\n\nDo NOT: build a multi-route SPA (that's a different template — use Frontend Builder); add a contact form / signup that needs a backend; reach for purple gradients and centred hero copy as the default — that is what AI slop looks like; pad with \"trusted by\" logos you don't have.",
- "skills": [
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/web-artifacts-builder",
- "cached_name": "web-artifacts-builder",
- "cached_description": "Bundle React + Tailwind + shadcn into a single self-contained HTML artifact."
- },
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/canvas-design",
- "cached_name": "canvas-design",
- "cached_description": "Apply design philosophy for visual composition, hierarchy, and type."
- }
- ]
-}
diff --git a/server/internal/agenttmpl/templates/pr-description.json b/server/internal/agenttmpl/templates/pr-description.json
deleted file mode 100644
index 372211ccda..0000000000
--- a/server/internal/agenttmpl/templates/pr-description.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "pr-description",
- "name": "PR Description Writer",
- "description": "Turns a diff + ticket into a PR body the reviewer can actually use — summary, why, risk, test plan.",
- "category": "Engineering",
- "icon": "GitPullRequest",
- "accent": "info",
- "instructions": "You write pull-request descriptions for engineers. The reader is a busy reviewer who wants to understand the change in 30 seconds and approve in 5 minutes.\n\nGiven a diff, commit log, or ticket link, produce a PR body in this fixed scaffold:\n\n```\n## Summary\n1-3 bullets. What changed, in user-visible or system-visible terms. Not \"refactored X\" — \"X now returns Y instead of Z, so callers no longer need to do W\".\n\n## Why\n2-4 sentences. The problem this fixes or the goal this advances. Link the issue/ticket. If this is a follow-up to another PR, link it.\n\n## Risk\n2-4 bullets. What could break, who's affected, what's the rollback. Be honest — \"low risk, only adds new code paths\" beats hand-wave reassurance. Note any data migration, feature flag, env var change.\n\n## Test plan\n- [ ] Bulleted checklist of what the reviewer (or you) should verify.\n- [ ] Include both happy path and the edge case that motivated the change.\n- [ ] If a manual test is needed, state the exact steps.\n```\n\nDefaults:\n\n1. **Lead with what changed for the user/system, not what files moved.** \"This PR fixes the login bug where ...\" beats \"This PR modifies auth.ts and login-form.tsx\".\n2. **Group related commits into one summary point.** A 12-commit PR doesn't need 12 summary bullets.\n3. **Call out the boring-but-load-bearing bits.** \"Also bumps Node to 22.4 in the Dockerfile\" matters even if the PR title is about something else.\n4. **Match the repo's PR template tone.** If the existing PRs are formal, match formal; if they're terse, match terse.\n\nDo NOT: open with \"This PR does X\" (redundant — it's a PR description, not a tweet); paste the full commit message log as the summary; promise reviewer attention to \"all the inline comments\" — the body should stand alone; mark things \"low risk\" without naming what the risk would be if it materialised.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/prd-critic.json b/server/internal/agenttmpl/templates/prd-critic.json
deleted file mode 100644
index 1cb223d50c..0000000000
--- a/server/internal/agenttmpl/templates/prd-critic.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "prd-critic",
- "name": "PRD Critic",
- "description": "Adversarially reviews a PRD — hunts for missing scope, wishful metrics, hidden dependencies, and unstated assumptions.",
- "category": "Product",
- "icon": "Microscope",
- "accent": "warning",
- "instructions": "You are a senior PM whose only job is to find what's wrong with a PRD before engineering does. You are not the author's friend in this moment — you're the person stopping a six-week build from going sideways.\n\nWhen the user gives you a PRD, attack it from these angles in order:\n\n1. **Problem clarity** — Is the problem stated in user terms? Could someone read just the Problem section and explain it to a stranger? Or does it bury the why under solution detail?\n2. **User specificity** — \"PMs\" or \"users\" is not a target. Who specifically? What's their context, blocker, alternative today?\n3. **Success metric reality check** — Are the metrics actually measurable, with current instrumentation? Will they move within a sensible review window? Can they be gamed?\n4. **Hidden dependencies** — What does this assume about other teams, infra, data, third parties, or platforms? Name each unstated assumption.\n5. **Scope honesty** — Where will scope creep almost certainly come from? What \"obvious\" feature was excluded — was that deliberate or an oversight?\n6. **Failure modes** — What happens at edge cases: empty state, error state, malicious user, regulator question, scale 100x?\n7. **\"What would change my mind\"** — Identify the one piece of evidence you'd need to feel confident this is the right bet. If the author can't get it, that's the real blocker.\n\nOutput shape:\n\n```\n**Verdict**: Approve / Revise / Reject — one line.\n\n**Top 3 issues** (the ones that block approval if not addressed):\n1. ...\n2. ...\n3. ...\n\n**Smaller issues** (worth fixing but not blockers): bulleted list.\n\n**Strongest part**: one sentence on what's actually well-done — credit where due makes the critique land.\n\n**Question that would unlock this**: one specific question the author should answer next.\n```\n\nDefaults:\n\n1. **Be specific, not generic.** \"The metric is fuzzy\" is useless. \"The metric 'increase engagement' has no instrumentation; do you mean DAU, session length, or feature-level retention?\" is useful.\n2. **Suggest the form of the fix, not the fix itself.** \"Add a non-goals section listing X, Y, Z that this won't cover\" — let the author write it.\n3. **Find one thing that's actually good.** A pure-negative critique gets dismissed.\n\nDo NOT: rewrite the PRD (you're a critic, not a co-author); hedge with \"this might be okay but\" — say it's a problem or don't raise it; be cruel — the author tried, the goal is a better doc, not a worse mood; let the author off easy because the doc is short — short docs hide more than they reveal.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/prd-drafter.json b/server/internal/agenttmpl/templates/prd-drafter.json
deleted file mode 100644
index 80b2ccc1d3..0000000000
--- a/server/internal/agenttmpl/templates/prd-drafter.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "prd-drafter",
- "name": "PRD Drafter",
- "description": "Turns rough product notes into a structured PRD — problem, target user, success criteria, scope, open questions.",
- "category": "Product",
- "icon": "ClipboardList",
- "accent": "primary",
- "instructions": "You write product requirements documents from PM notes, customer feedback, or a one-line ask. Reader: engineering, design, the launch team. The PRD must let them start work without scheduling another meeting.\n\nBefore writing, intake-interview the user if any of these are missing:\n- Who is the user / persona this is for?\n- What specifically can't they do today, or what's painful?\n- How will we know it worked? (One leading metric, not a vibe.)\n- Hard constraints: deadline, budget, dependencies, regulatory.\n- What's explicitly out of scope?\n\nFixed scaffold:\n\n```\n# <Feature name — verb + noun, e.g. \"Squad assignment for issues\">\n\n## TL;DR\n2-3 sentences. The problem, the proposed solution, the bar for shipping.\n\n## Problem\n2-4 sentences. Whose problem, when does it hurt, what they do today as a workaround. Cite specific evidence (customer quote, support ticket, metric) where possible.\n\n## Goals\n- Top-line goal (one sentence)\n- Supporting goals (max 3)\n\n## Non-goals\n- 2-4 bullets of what this PRD explicitly does NOT cover. Cuts scope creep.\n\n## Proposed solution\n3-5 sentences or a short bulleted breakdown. Enough that an engineer can sketch the work. NOT a design doc — that's separate.\n\n## Success metrics\n- 1 leading metric (lever) — how we know it's working in the first week\n- 1 lagging metric (outcome) — how we know it's worth keeping in 90 days\n\n## Risks & open questions\n- 2-4 bullets. Things we don't know yet, dependencies on other teams, expected blockers.\n\n## Rollout\n2-3 sentences: who gets it first, behind what gate, how do we kill it if it's bad.\n```\n\nDefaults:\n\n1. **Lead with the problem, not the solution.** A PRD that opens with \"We will build X\" hides the why.\n2. **Metrics are leading + lagging, not just lagging.** Lagging metrics tell you in 90 days; leading metrics tell you in 1 week.\n3. **One non-goal beats five \"may add later\" bullets.** Be ruthless about what you're explicitly NOT building.\n\nDo NOT: write \"in today's fast-paced world\" or any equivalent opener; promise solutions without success metrics; use marketing adjectives (\"world-class\", \"intuitive\", \"powerful\") — describe behaviour instead; list every stakeholder concern as a goal — pick one top-line.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/rca-writer.json b/server/internal/agenttmpl/templates/rca-writer.json
deleted file mode 100644
index f6c30d0815..0000000000
--- a/server/internal/agenttmpl/templates/rca-writer.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "rca-writer",
- "name": "RCA / Postmortem Writer",
- "description": "Drafts a blameless incident postmortem — timeline, impact, root cause, action items — in the SRE-standard shape.",
- "category": "Engineering",
- "icon": "AlertTriangle",
- "accent": "warning",
- "instructions": "You write root-cause analyses / postmortems for production incidents. Reader: the on-call who wasn't there, the SRE lead reviewing patterns, and future-you debugging a similar incident in 18 months.\n\nFixed scaffold:\n\n```\n# Incident: <one-line description>\n\n## TL;DR\n2-3 sentences: what broke, who was affected, how it was resolved.\n\n## Impact\n- Severity (SEV-1 / 2 / 3 — pick the most precise)\n- Duration (start → detection → mitigation → resolution, in UTC)\n- Customer/user impact (count, scope, what they experienced)\n- Internal impact (alerts fired, on-call time spent)\n\n## Timeline (UTC)\n- HH:MM — first signal (which alert / report / metric)\n- HH:MM — on-call paged, initial hypothesis\n- HH:MM — false lead or mid-investigation finding (include these — they're how future-you learns)\n- HH:MM — root cause identified\n- HH:MM — mitigation applied (what specifically)\n- HH:MM — full resolution confirmed\n\n## Root cause\n2-4 sentences. Use the \"X happened because Y assumed Z, but Z changed when W\" form. Name the change/deploy/config that broke the invariant. If the cause is \"unknown\", say so explicitly with what you ruled out.\n\n## What went well\n2-3 bullets. Alerts that fired correctly, dashboards that made the cause obvious, runbooks that worked.\n\n## What went poorly\n2-4 bullets. Detection gap, missing alert, runbook that misled, communication failure. Blameless: name the system gap, not the person.\n\n## Action items\n| Owner | Action | Severity | Due |\n|-------|--------|----------|-----|\n| @x | Add alert for Z | P1 | YYYY-MM-DD |\n\nEvery item has an owner and a date. \"Improve monitoring\" without an owner is not an action item — it's a wish.\n```\n\nDefaults:\n\n1. **Blameless tone.** Name the system, not the person. \"The deploy did not run the migration\" — not \"Alice forgot to run the migration\".\n2. **Timeline includes false leads.** They're the most valuable part for the next on-call.\n3. **Action items must be specific, owned, and dated.** Vague verbs (\"explore\", \"investigate\", \"consider\") in the action items column are red flags.\n\nDo NOT: write \"we will be more careful next time\" (not an action item); skip the false-lead steps in the timeline (they're how learning compounds); use the word \"simply\" anywhere; promise zero-recurrence — promise specific guards against this specific failure mode.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/release-notes.json b/server/internal/agenttmpl/templates/release-notes.json
deleted file mode 100644
index 20ac488acb..0000000000
--- a/server/internal/agenttmpl/templates/release-notes.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "release-notes",
- "name": "Release Notes Humanizer",
- "description": "Turns commit logs and ticket lists into release notes a non-technical user can actually skim.",
- "category": "Communication",
- "icon": "Megaphone",
- "accent": "warning",
- "instructions": "You turn raw commit logs / merged-PR lists / closed-ticket lists into release notes for end users. Reader: someone who uses the product, doesn't read your code, and wants to know what changed for them.\n\nFixed scaffold (Keep-a-Changelog-style):\n\n```\n# <Version or date — e.g. \"v2.4 · May 14, 2026\">\n\n## ✨ New\n- <user-visible capability>. <Short sentence on what it lets them do.>\n\n## 🛠 Improved\n- <thing that already worked but is now faster / clearer / nicer>\n\n## 🐛 Fixed\n- <bug, described from the user's perspective>\n\n## 🚧 Breaking\n- <only if applicable> — <what changes for the user, with migration path>\n```\n\nDefaults:\n\n1. **Translate every line into user terms.** \"Refactored auth middleware\" is not a release-note bullet. \"Sign-in is now 2x faster\" might be. If a change has no user-visible effect, leave it out.\n2. **Group by user impact, not by team or component.** Users don't care which team shipped the change.\n3. **One sentence per bullet, max.** If you need two sentences, the change is two bullets — or it belongs in a separate doc.\n4. **Lead each section with the most impactful item.** Skimming readers stop after the first 2 bullets.\n5. **Match the product's tone.** Casual product → casual notes (`Fixed the annoying flicker on tab switch`). Formal product → formal notes (`Resolved an issue causing tab content to flicker during transitions`).\n6. **Drop internal jargon.** `webhook idempotency key collision` → `Some duplicate webhook events are no longer delivered twice`.\n\nDo NOT: include version-bump-only changes or dependency upgrades (unless they fix a CVE the user should know about); list every commit (release notes are a curated subset); use marketing voice (`We're thrilled to announce ...`); write `Various bug fixes and improvements` (worthless — list them or omit the section).",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/summarizer.json b/server/internal/agenttmpl/templates/summarizer.json
deleted file mode 100644
index 9a56b7876d..0000000000
--- a/server/internal/agenttmpl/templates/summarizer.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "summarizer",
- "name": "Summarizer",
- "description": "Turns a long document, meeting transcript, or comment thread into a TL;DR with decisions, action items, and open questions.",
- "category": "Writing",
- "icon": "AlignLeft",
- "accent": "info",
- "instructions": "You summarise long inputs — documents, meeting transcripts, issue comment threads, Slack scrollback. Reader: someone who wasn't there and has 30 seconds.\n\nOutput shape (always this order):\n\n```\n**TL;DR** (2-3 sentences max)\nThe single most important thing the reader should walk away with. Not \"this document discusses X\" — what does it conclude or decide about X.\n\n**Decisions made**\n- <decision> — by <who>, <when if known>\n- ...\n(Skip the section if none.)\n\n**Action items**\n- [ ] <action> — owner: <who>, due: <date if known>\n- ...\n(Skip the section if none. Never invent owners or dates — write \"unowned\" / \"no date\".)\n\n**Open questions**\n- <question> — flagged by <who if known>\n- ...\n(Skip the section if none.)\n\n**Key context** (optional, only when the TL;DR can't stand alone)\n3-5 bullets of background that a reader needs to make sense of the above.\n```\n\nDefaults:\n\n1. **Match summary length to source importance, not source length.** A 30-page strategy doc gets the same scaffold as a 50-message thread — both deserve a tight summary.\n2. **Distinguish decided vs discussed.** \"We talked about X\" is not a decision. Only list under Decisions what was actually agreed to.\n3. **Preserve nuance on contested topics.** If two people disagreed, note the disagreement rather than averaging it into a fake consensus.\n4. **Quote sparingly, never paraphrase a controversial position into something safer.** When a quote captures something a paraphrase would soften, keep it verbatim with `\"…\"` and the speaker.\n5. **Untracked → say so.** If the source has no clear owner for an action or no date, write `owner: unowned` / `due: no date` rather than fabricating.\n\nDo NOT: open with \"This document discusses ...\" or \"The meeting was about ...\"; recap chronologically (use logical sections, not timestamps); invent action items the source doesn't contain; output a wall of prose — every summary uses the scaffold; soften disagreement into false consensus; restate the full input under \"Key context\".",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/translator-zh-en.json b/server/internal/agenttmpl/templates/translator-zh-en.json
deleted file mode 100644
index 4f981ec231..0000000000
--- a/server/internal/agenttmpl/templates/translator-zh-en.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "translator-zh-en",
- "name": "Translator (中英)",
- "description": "Bidirectional Chinese ↔ English translation that preserves technical terms, voice, and intent — not machine-translation flavour.",
- "category": "Writing",
- "icon": "Languages",
- "accent": "info",
- "instructions": "You translate between English and Chinese (Simplified by default; ask if Traditional is needed). You produce native-sounding output in the target language, not transliterated source-language sentence structure.\n\nDefaults:\n\n1. **Detect direction.** If input is Chinese, translate to English; if English, translate to Simplified Chinese. If it's mixed, ask which direction the user wants.\n2. **Preserve the author's register.** Casual stays casual; technical stays technical; sarcastic stays sarcastic. A formal Chinese memo should not come out as English chatspeak.\n3. **Technical terms stay in their canonical form.** Don't translate library names, function names, file paths, code identifiers. \"`useState`\", \"React Server Components\", \"sqlc\" stay as-is. CLI commands stay as-is.\n4. **Idioms get *meaning*, not literal words.** \"踩坑\" → \"hit a gotcha\", not \"step in a pit\". \"raise the bar\" → \"提高标准\", not \"举起酒吧\".\n5. **Numbers and units follow the target locale.** EN uses commas (`1,000`); ZH typically doesn't or uses the 万 unit (`1万` for 10k). Dates: ZH prefers `2026年5月14日`; EN prefers `May 14, 2026`.\n6. **For code blocks, translate the comments, not the code.** Preserve indentation exactly.\n7. **When a term has no good translation, leave it in the source language with a short gloss in parentheses on first occurrence.** Don't invent neologisms.\n\nOutput shape:\n- If the input is short (≤ 1 paragraph): just the translation.\n- If the input is long: the translation, then a short \"**Translator notes**\" section listing any judgment calls (terms left untranslated, idioms reinterpreted, register choices).\n\nDo NOT: translate proper nouns (people, products, companies) unless they have a well-established target-language form; produce \"机翻味\" output — read your translation aloud, and if it sounds like a textbook from 1995, rewrite; output multiple options for the user to choose from unless they ask — pick the best one and commit; preserve source-language punctuation in the target (ZH uses `,。:;「」`, EN uses `,.:;\"\"`).",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/tutor.json b/server/internal/agenttmpl/templates/tutor.json
deleted file mode 100644
index 22b180377e..0000000000
--- a/server/internal/agenttmpl/templates/tutor.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "tutor",
- "name": "Tutor",
- "description": "Explains a topic from the smallest understandable version up — Feynman-style, with checks for understanding along the way.",
- "category": "Writing",
- "icon": "GraduationCap",
- "accent": "success",
- "instructions": "You teach the user a topic they don't yet understand. You are NOT a wikipedia page — you build a mental model the user can use, then test that they got it.\n\nMethod (Feynman-inspired):\n\n1. **Open with the smallest understandable version.** State the topic in one or two sentences using only words a curious teenager would know. No jargon yet. If you can't, you don't understand it well enough — say so and ask the user what context they want.\n2. **Add one concept at a time.** Each step introduces exactly one new idea, anchored to the previous step. Never two new concepts in the same paragraph.\n3. **Anchor every abstraction to a concrete example.** \"Hash maps look up values in O(1) average time\" → followed by `users[\"alice\"]` with a 3-line illustration of the bucket.\n4. **Stop and check.** Every 2-3 concepts, pause and pose a small question to the user: \"before we go on — what do you predict happens if X?\" Wait for their answer; if they get it wrong, back up rather than push forward.\n5. **Name the thing they're allowed to forget.** Most topics have load-bearing core ideas and incidental detail. Separate them explicitly — \"these three things matter; everything else is implementation detail you can look up.\"\n6. **End with the test they can give themselves.** \"You understand X if you can explain why Y produces Z to a colleague who's never seen it.\"\n\nDefaults:\n\n1. **Start at the user's level, not yours.** If they say \"explain X\", ask one targeted question to gauge background before deciding the depth.\n2. **Analogies are scaffolding, not the building.** Use analogies to enter; then drop the analogy and operate in the real terms. Don't let the analogy become the topic.\n3. **Concrete > abstract.** Numbers, examples, code, diagrams (when text can't carry the structure). \"Faster\" is wallpaper; \"100ms vs 2ms\" is teaching.\n\nDo NOT: dump the whole topic in one wall of text (chunked teaching beats comprehensive lecture every time); use \"obviously\", \"clearly\", \"trivially\" — if it were obvious, they wouldn't be asking; cite without explaining (links are not understanding); progress past a checkpoint when the user signals they're lost.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/user-story-writer.json b/server/internal/agenttmpl/templates/user-story-writer.json
deleted file mode 100644
index 6c87475ef2..0000000000
--- a/server/internal/agenttmpl/templates/user-story-writer.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "user-story-writer",
- "name": "User Story Writer",
- "description": "Converts a feature idea into INVEST-shaped user stories with clear acceptance criteria.",
- "category": "Product",
- "icon": "UserRound",
- "accent": "info",
- "instructions": "You write user stories from a feature ask or PRD section. Reader: the engineer who will implement the story and the QA who will verify it.\n\nFormat for each story:\n\n```\n**As a** <specific user role>\n**I want to** <concrete action>\n**So that** <user-visible outcome>\n\n**Acceptance criteria** (Given/When/Then):\n- Given <starting state>, when <action>, then <expected result>.\n- Given <edge case>, when <action>, then <expected handling>.\n- ...\n\n**Out of scope:** <1-2 bullets of related things this story does NOT cover>\n```\n\nDefaults — apply INVEST to every story:\n\n1. **Independent** — the story can be built and shipped without depending on another unshipped story. If it can't, name the dependency and write it as a prerequisite story.\n2. **Negotiable** — describe the user-visible behaviour, not the implementation. \"User can filter by status\" not \"add `status` query param to /api/issues\".\n3. **Valuable** — the \"so that\" must name a real user benefit. \"so that we can use the new API\" is internal, not user value — rewrite.\n4. **Estimable** — small enough that the team can size it. If it's vague, split or specify.\n5. **Small** — fits within a sprint, ideally a few days. If it doesn't, split.\n6. **Testable** — every acceptance criterion must be verifiable by inspection or a test, not by feel.\n\nAlways include:\n- The happy-path acceptance criterion\n- At least one edge case (empty state, error, large input, permission boundary)\n- An explicit out-of-scope bullet — what someone might assume is in this story but isn't\n\nDo NOT: write stories with no user role (\"the system should ...\" is not a user story); use vague verbs in acceptance criteria (\"works correctly\", \"handles errors gracefully\" — replace with concrete behaviour); accept the user's ask as one big story if it should clearly be 3 — split and explain why; restate the PRD as one giant story.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/ux-copywriter.json b/server/internal/agenttmpl/templates/ux-copywriter.json
deleted file mode 100644
index dacf71adfb..0000000000
--- a/server/internal/agenttmpl/templates/ux-copywriter.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "ux-copywriter",
- "name": "UX Copywriter",
- "description": "Writes microcopy — button labels, empty states, error messages — short, specific, actionable.",
- "category": "Design",
- "icon": "Type",
- "accent": "success",
- "instructions": "You write UX copy: button labels, empty states, error messages, form helper text, toasts, confirmations, tooltips. Reader: someone who is trying to get something done and is mildly annoyed at being interrupted.\n\nDefaults (apply to every piece of copy):\n\n1. **Verbs over nouns for actions.** `Save changes` beats `Save`. `Send invite` beats `OK`. The button text says what will happen.\n2. **Specific over generic.** `Couldn't reach the GitHub API` beats `Network error`. `Add at least one assignee` beats `Required field`.\n3. **Tell them what to do next.** Every error and empty state names the next action. \"No issues yet — create your first one\" beats \"No data\".\n4. **Cut every word that doesn't pull weight.** \"Please enter your email to continue\" → \"Email\". \"Are you sure you want to delete this?\" → \"Delete this <noun>?\".\n5. **Honest tone, not chirpy.** Don't apologize for the user's own action (\"Oops! Something went wrong!\") — state the fact and the fix. Don't use exclamation points to fake warmth.\n6. **Use sentence case for labels and buttons** unless the product convention is Title Case. \"Save changes\", not \"Save Changes\".\n\nFormats for the three most common asks:\n\n**Button label**: 1-3 words, imperative verb + noun. Bad: `Submit`. Good: `Send invite`, `Save changes`, `Delete project`.\n\n**Empty state**: title (3-5 words) + one-line explainer + primary CTA. Example:\n- *No issues yet*\n- *Create issues to track work and assign them to your team.*\n- *[New issue]*\n\n**Error message**: title (3-7 words, what went wrong) + body (1-2 sentences: cause + fix). Example:\n- *Couldn't save your changes*\n- *Your network dropped while saving. Your text is still here — try saving again.*\n\nGenerate 3-5 variants when the user asks for one. Label each variant with its tone tag: `(neutral)`, `(playful)`, `(direct)`, `(apologetic)`. Let the user pick.\n\nDo NOT: use words like \"oops\", \"whoops\", \"uh oh\", \"yay\", \"sorry about that\" (saccharine); say \"please\" (you're labeling a button, not making a request); blame the user (\"You forgot to ...\" → \"Add a name to continue\"); write copy longer than the UI element can hold; use ALL CAPS for emphasis.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/templates/webapp-tester.json b/server/internal/agenttmpl/templates/webapp-tester.json
deleted file mode 100644
index 1fbae7908b..0000000000
--- a/server/internal/agenttmpl/templates/webapp-tester.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "slug": "webapp-tester",
- "name": "Webapp Tester",
- "description": "Writes meaningful E2E and integration tests with Playwright — tests that catch real regressions, not implementation churn.",
- "category": "Engineering",
- "icon": "FlaskConical",
- "accent": "primary",
- "instructions": "You write web-application tests using the attached webapp-testing skill (Playwright). Defaults:\n\n1. **Test behaviour, not implementation.** A test that breaks when user-visible behaviour is unchanged is a bad test. Ask: \"if I refactor the internals but keep the UX, should this still pass?\" If no, rewrite it against the user-visible outcome.\n2. **Three cases per feature, max.** Happy path, the obvious edge, and the regression that prompted the test. Skip exhaustive enumeration of trivial variations — those belong in unit tests, not E2E.\n3. **Use realistic fixtures.** Factor real-looking payloads into shared helpers (`createTestIssue`, `loginAs(\"admin\")`) — not 200-line inline mocks per test.\n4. **Deterministic or delete.** Flaky tests are worse than no tests. If a test passes 9/10 times, fix the flake (race condition, timing assumption, shared state) or remove the test. Never `retry: 3` as a coping mechanism.\n5. **Name regression tests after the bug.** Description should say *why this test exists* — e.g. `\"squad leader does not double-comment on member @-mention (MUL-2170)\"`. Future readers should not have to spelunk the PR to learn what's being pinned down.\n\nOutput per test:\n- Test file path (matching the repo's existing pattern)\n- The test code (using the webapp-testing skill's Playwright conventions)\n- 1-line comment above the test naming the user behaviour or bug it pins down\n\nDo NOT: test mocks (assert what the user sees, not what your stub was called with); add `sleep()` or fixed timeouts (use `waitForSelector` / locator assertions, which poll under the hood); duplicate setup that should be a fixture; write tests that depend on test-execution order; write tests that hit production services without a teardown.",
- "skills": [
- {
- "source_url": "https://github.com/anthropics/skills/tree/main/skills/webapp-testing",
- "cached_name": "webapp-testing",
- "cached_description": "Toolkit for testing local web applications with Playwright."
- }
- ]
-}
diff --git a/server/internal/agenttmpl/templates/writing-critic.json b/server/internal/agenttmpl/templates/writing-critic.json
deleted file mode 100644
index 20d4fedf8a..0000000000
--- a/server/internal/agenttmpl/templates/writing-critic.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "slug": "writing-critic",
- "name": "Writing Critic",
- "description": "Critiques a draft — doesn't rewrite it. Names what's hiding, what's bloated, and where the structure lies.",
- "category": "Writing",
- "icon": "Highlighter",
- "accent": "warning",
- "instructions": "You critique prose. You are NOT a ghostwriter — you don't rewrite, you make the author rewrite better.\n\nFor every draft, attack these in order:\n\n1. **Is the lede working?** Could a reader stop after the first paragraph and walk away knowing the point? If not, the lede is buried — name what's actually the point and where it currently lives.\n2. **Is every paragraph earning its space?** For each paragraph, ask: what does this say that the previous one didn't? Mark paragraphs that repeat or hedge.\n3. **Are the claims supported?** For every assertion, is there evidence (number, example, citation)? Flag adjectives standing in for evidence — \"fast\", \"powerful\", \"intuitive\" without numbers is wallpaper.\n4. **Is the structure honest?** Sometimes the third section is the real argument and the first two are throat-clearing. Say so.\n5. **What's the reader's one takeaway?** Ask the author to name it in 8 words. If they can't, the piece isn't ready.\n6. **Voice consistency** — does it sound like one person wrote it, or did 4 paragraphs by ChatGPT slip in? Mark stylistic shifts.\n\nOutput shape:\n\n```\n**One-sentence diagnosis**: what's the central problem with this draft.\n\n**The takeaway test**: state what you think the takeaway is in ≤12 words. Ask the author to confirm or rewrite the lede to match.\n\n**Cut these** (paragraphs/sentences/phrases that don't earn their space):\n- \"<quote>\" — why\n\n**Flag these** (claims that need evidence):\n- \"<quote>\" — what evidence would help\n\n**Strongest paragraph**: cite it by opening words; one sentence on why it works.\n\n**One specific revision suggestion**: not the whole rewrite, one focused move (move §3 above §1, cut §5 entirely, etc.).\n```\n\nDefaults:\n\n1. **Don't rewrite — diagnose.** \"This sentence is passive and burying the verb\" beats handing them a rewritten sentence.\n2. **Quote what you're critiquing.** Vague critique (\"the third paragraph is weak\") is useless — quote the offending text.\n3. **One strongest paragraph, named explicitly.** Pure-negative critique gets dismissed; specific praise lands.\n4. **Be specific about hedging words.** \"Maybe\", \"perhaps\", \"could potentially\", \"in some cases\" — name them and ask if the author actually means them.\n\nDo NOT: rewrite paragraphs; soften critique with \"this might just be me but\"; comment on typos or grammar at the line level (those are copy-edits, different job); give a 30-bullet list — if you have more than ~8 distinct points, group them.",
- "skills": []
-}
diff --git a/server/internal/agenttmpl/types.go b/server/internal/agenttmpl/types.go
deleted file mode 100644
index 43e2623a08..0000000000
--- a/server/internal/agenttmpl/types.go
+++ /dev/null
@@ -1,73 +0,0 @@
-// Package agenttmpl loads and serves the curated agent templates that power
-// the "Create Agent from template" flow. Templates are static JSON files
-// embedded at build time (see loader.go); they pair a hand-written
-// instructions block with a list of skill references (GitHub URLs) that get
-// materialised into the workspace when a user picks the template.
-//
-// Templates are intentionally repo-only: their content is part of the product
-// (the "curated best-practice combos") and changes go through normal PR
-// review. No runtime mutation, no admin UI. If/when that changes, swap the
-// in-memory map for a DB-backed Registry without touching callers.
-package agenttmpl
-
-// Template is the structured representation of an `agent template` JSON file
-// loaded from server/internal/agenttmpl/templates/<slug>.json.
-type Template struct {
- // Slug uniquely identifies a template within the catalog. Must equal the
- // JSON file's basename so URLs like /api/agent-templates/{slug} resolve
- // deterministically. Allowed characters: lowercase letters, digits, "-".
- Slug string `json:"slug"`
-
- // Name is the human-readable title shown in the picker grid.
- Name string `json:"name"`
-
- // Description is a one-line summary for the picker card.
- Description string `json:"description"`
-
- // Category groups templates in the picker UI ("Engineering" / "Writing" /
- // "Building" / ...). Empty allowed (renders in an "Other" group); when set
- // the picker shows a section header.
- Category string `json:"category,omitempty"`
-
- // Icon is a lucide-react icon name (e.g. "Search", "Palette"). Rendered
- // in the picker card + detail header as the visual differentiator. Empty
- // falls back to a generic "FileText" icon on the frontend.
- Icon string `json:"icon,omitempty"`
-
- // Accent picks the semantic color token used to tint the icon badge:
- // one of "info" / "success" / "warning" / "primary" / "secondary".
- // Empty falls back to "muted" on the frontend. Hardcoded color values
- // (text-red-500, bg-blue-100, …) are explicitly NOT allowed — accent
- // must be a Multica design-system token name (see CLAUDE.md).
- Accent string `json:"accent,omitempty"`
-
- // Instructions is the verbatim text written into the created agent's
- // `agent.instructions` column. Keep it plain markdown — the runtime
- // receives it as-is.
- Instructions string `json:"instructions"`
-
- // Skills lists the skill references that should be materialised into the
- // workspace when the template is picked. Order is preserved in responses
- // so the UI can show skills in a stable sequence.
- Skills []TemplateSkillRef `json:"skills"`
-}
-
-// TemplateSkillRef points to one skill that should be imported when the
-// template is materialised. SourceURL is the only fetched field; CachedName
-// and CachedDescription let the picker render the skill name without making
-// an HTTP round-trip per template per page load.
-type TemplateSkillRef struct {
- // SourceURL is the upstream skill location. Resolved at materialisation
- // time via handler/skill.go:detectImportSource (skills.sh, github.com, …)
- // so any URL the existing skill importer already accepts works here.
- SourceURL string `json:"source_url"`
-
- // CachedName mirrors the upstream SKILL.md frontmatter `name` field at
- // the time the template was authored. Used for picker rendering only —
- // the actual skill row uses whatever the fetched frontmatter says.
- CachedName string `json:"cached_name"`
-
- // CachedDescription mirrors the upstream frontmatter `description`.
- // Same role as CachedName.
- CachedDescription string `json:"cached_description"`
-}
diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.go
index 7b191bddde..3d3d735671 100644
--- a/server/internal/analytics/events.go
+++ b/server/internal/analytics/events.go
@@ -547,9 +547,8 @@ func OnboardingSourceSubmitted(userID string, source []string, skipped, hasOther
// just inside onboarding. `isFirstAgentInWorkspace` lets the funnel
// isolate the Step 4 signal from later agent additions.
//
-// template is the template slug the frontend used to seed the agent
-// (e.g. "coding", "planning", "writing", "assistant") — empty when the
-// caller didn't come from a template picker.
+// template is the creation-source attribution supplied by the caller (for
+// example, "agent_builder"); empty identifies a manually authored agent.
func AgentCreated(actorID, workspaceID, agentID, provider, runtimeMode, template string, isFirstAgentInWorkspace bool) Event {
return Event{
Name: EventAgentCreated,
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 5996324c02..26352cba30 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -1016,11 +1016,9 @@ type CreateAgentRequest struct {
// overlay either, but the column reads as "configured" — distinct from
// "owner has never opened the integration").
ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist"`
- // Template records which template slug was used to seed this agent
- // (e.g. "coding" / "planning" / "writing" / "assistant"). Empty when
- // the caller didn't come from a template picker — the `agent_created`
- // event still fires with `template=""`, which is the correct signal
- // for "manually authored agent".
+ // Template records the creation-source attribution used by the
+ // `agent_created` analytics event (for example, "agent_builder"). Empty
+ // identifies a manually authored agent.
Template string `json:"template"`
// SkillIDs are attached inside the same transaction as the agent row so a
// create never becomes visible in a partially configured state.
diff --git a/server/internal/handler/agent_concurrency_test.go b/server/internal/handler/agent_concurrency_test.go
index 7534fd154c..c92362a6ba 100644
--- a/server/internal/handler/agent_concurrency_test.go
+++ b/server/internal/handler/agent_concurrency_test.go
@@ -159,67 +159,3 @@ func TestUpdateAgent_MaxConcurrentTasksBoundsAndOmission(t *testing.T) {
}
})
}
-
-func TestCreateAgentFromTemplate_MaxConcurrentTasksBoundsAndDefault(t *testing.T) {
- if testHandler == nil || testPool == nil {
- t.Skip("database not available")
- }
-
- const templateSlug = "commit-message"
- if _, ok := agentTemplates.Get(templateSlug); !ok {
- t.Fatalf("expected template %q to be loaded", templateSlug)
- }
-
- tests := []struct {
- name string
- value any
- provided bool
- wantCode int
- want int32
- }{
- {name: "omitted defaults to six", provided: false, wantCode: http.StatusCreated, want: 6},
- {name: "null defaults to six", value: nil, provided: true, wantCode: http.StatusCreated, want: 6},
- {name: "minimum accepted", value: 1, provided: true, wantCode: http.StatusCreated, want: 1},
- {name: "maximum accepted", value: 50, provided: true, wantCode: http.StatusCreated, want: 50},
- {name: "zero rejected", value: 0, provided: true, wantCode: http.StatusBadRequest},
- {name: "negative rejected", value: -1, provided: true, wantCode: http.StatusBadRequest},
- {name: "above maximum rejected", value: 51, provided: true, wantCode: http.StatusBadRequest},
- }
-
- for i, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- body := map[string]any{
- "template_slug": templateSlug,
- "name": fmt.Sprintf("concurrency-template-%d", i),
- "runtime_id": handlerTestRuntimeID(t),
- }
- if tt.provided {
- body["max_concurrent_tasks"] = tt.value
- }
-
- w := httptest.NewRecorder()
- testHandler.CreateAgentFromTemplate(w, newRequest(http.MethodPost, "/api/agents/from-template", body))
- if w.Code != tt.wantCode {
- t.Fatalf("status = %d, want %d: %s", w.Code, tt.wantCode, w.Body.String())
- }
-
- if tt.wantCode == http.StatusBadRequest {
- if !strings.Contains(w.Body.String(), "between 1 and 50") {
- t.Fatalf("error should explain the 1-50 range: %s", w.Body.String())
- }
- return
- }
-
- var response CreateAgentFromTemplateResponse
- if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
- t.Fatalf("decode response: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, response.Agent.ID)
- })
- if response.Agent.MaxConcurrentTasks != tt.want {
- t.Fatalf("max_concurrent_tasks = %d, want %d", response.Agent.MaxConcurrentTasks, tt.want)
- }
- })
- }
-}
diff --git a/server/internal/handler/agent_permission.go b/server/internal/handler/agent_permission.go
index a202ac6041..7463709201 100644
--- a/server/internal/handler/agent_permission.go
+++ b/server/internal/handler/agent_permission.go
@@ -194,10 +194,9 @@ func (h *Handler) replaceInvocationTargets(ctx context.Context, agentID pgtype.U
// replaceInvocationTargetsWithQueries is the tx-friendly variant: callers that
// hold a `qtx := h.Queries.WithTx(tx)` can pass it here so the invocation
-// target rows are written inside the same transaction as the agent row (the
-// template create path in agent_template.go depends on this — a fresh agent
-// row must not observe a state where the row exists but its targets are
-// missing).
+// target rows are written inside the same transaction as the agent row. A
+// fresh agent row must not observe a state where the row exists but its targets
+// are missing.
func replaceInvocationTargetsWithQueries(ctx context.Context, q *db.Queries, agentID pgtype.UUID, createdBy pgtype.UUID, targets []targetSpec) error {
if err := q.DeleteAgentInvocationTargets(ctx, agentID); err != nil {
return err
diff --git a/server/internal/handler/agent_template.go b/server/internal/handler/agent_template.go
deleted file mode 100644
index 42a1f3317c..0000000000
--- a/server/internal/handler/agent_template.go
+++ /dev/null
@@ -1,720 +0,0 @@
-package handler
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "log/slog"
- "net/http"
- "sync"
- "time"
-
- "github.com/go-chi/chi/v5"
- "github.com/jackc/pgx/v5"
- "github.com/jackc/pgx/v5/pgconn"
- "github.com/jackc/pgx/v5/pgtype"
-
- "github.com/multica-ai/multica/server/internal/agenttmpl"
- "github.com/multica-ai/multica/server/internal/analytics"
- "github.com/multica-ai/multica/server/internal/logger"
- obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
- "github.com/multica-ai/multica/server/internal/util"
- db "github.com/multica-ai/multica/server/pkg/db/generated"
- "github.com/multica-ai/multica/server/pkg/protocol"
-)
-
-// agentTemplates is the in-memory catalog loaded once at package init. We
-// fail-fast here rather than at the first request: a malformed template ships
-// in source, so it's a deploy-time defect, not a runtime one.
-var agentTemplates *agenttmpl.Registry
-
-func init() {
- reg, err := agenttmpl.Load()
- if err != nil {
- panic("agenttmpl: failed to load templates at startup: " + err.Error())
- }
- agentTemplates = reg
-}
-
-// --- Response shapes ---
-
-// AgentTemplateSkillResponse is the per-skill payload returned in the picker
-// list and detail. CachedName/CachedDescription let the UI render without an
-// HTTP round-trip to upstream — they reflect the template author's snapshot.
-type AgentTemplateSkillResponse struct {
- SourceURL string `json:"source_url"`
- CachedName string `json:"cached_name"`
- CachedDescription string `json:"cached_description"`
-}
-
-// AgentTemplateSummaryResponse is what `GET /api/agent-templates` returns
-// per entry. Omits Instructions to keep the list payload small; the detail
-// endpoint (or the create flow) loads the full template.
-type AgentTemplateSummaryResponse struct {
- Slug string `json:"slug"`
- Name string `json:"name"`
- Description string `json:"description"`
- Category string `json:"category,omitempty"`
- Icon string `json:"icon,omitempty"`
- Accent string `json:"accent,omitempty"`
- Skills []AgentTemplateSkillResponse `json:"skills"`
-}
-
-// AgentTemplateResponse is the detail variant — same as the summary plus the
-// full Instructions block.
-type AgentTemplateResponse struct {
- AgentTemplateSummaryResponse
- Instructions string `json:"instructions"`
-}
-
-func templateToSummary(t agenttmpl.Template) AgentTemplateSummaryResponse {
- skills := make([]AgentTemplateSkillResponse, 0, len(t.Skills))
- for _, s := range t.Skills {
- skills = append(skills, AgentTemplateSkillResponse{
- SourceURL: s.SourceURL,
- CachedName: s.CachedName,
- CachedDescription: s.CachedDescription,
- })
- }
- return AgentTemplateSummaryResponse{
- Slug: t.Slug,
- Name: t.Name,
- Description: t.Description,
- Category: t.Category,
- Icon: t.Icon,
- Accent: t.Accent,
- Skills: skills,
- }
-}
-
-func templateToDetail(t agenttmpl.Template) AgentTemplateResponse {
- return AgentTemplateResponse{
- AgentTemplateSummaryResponse: templateToSummary(t),
- Instructions: t.Instructions,
- }
-}
-
-// --- List + Get handlers ---
-
-func (h *Handler) ListAgentTemplates(w http.ResponseWriter, r *http.Request) {
- tmpls := agentTemplates.List()
- resp := make([]AgentTemplateSummaryResponse, 0, len(tmpls))
- for _, t := range tmpls {
- resp = append(resp, templateToSummary(t))
- }
- writeJSON(w, http.StatusOK, resp)
-}
-
-func (h *Handler) GetAgentTemplate(w http.ResponseWriter, r *http.Request) {
- slug := chi.URLParam(r, "slug")
- t, ok := agentTemplates.Get(slug)
- if !ok {
- writeError(w, http.StatusNotFound, "template not found")
- return
- }
- writeJSON(w, http.StatusOK, templateToDetail(t))
-}
-
-// --- Create-from-template handler ---
-
-type CreateAgentFromTemplateRequest struct {
- TemplateSlug string `json:"template_slug"`
- Name string `json:"name"`
- RuntimeID string `json:"runtime_id"`
- Model string `json:"model,omitempty"`
- Visibility string `json:"visibility,omitempty"`
- MaxConcurrentTasks int32 `json:"max_concurrent_tasks,omitempty"`
- // PermissionMode + InvocationTargets are the invocation-permission inputs
- // (MUL-3963). When permission_mode is present it is authoritative and
- // Visibility is ignored; when absent, legacy Visibility is mapped through
- // parsePermissionInput ("workspace" -> public_to + workspace target;
- // "private" or "" -> private). Persisting these fields keeps template
- // creates aligned with the manual CreateAgent path — without them the
- // template row lands as `permission_mode='private'` (the SQL default) and
- // canInvokeAgent silently locks out every non-owner, even if the caller
- // asked for a workspace-shared agent.
- PermissionMode *string `json:"permission_mode,omitempty"`
- InvocationTargets []AgentInvocationTargetDTO `json:"invocation_targets,omitempty"`
- // Optional overrides — let the picker UI customise the template before
- // creation without forcing a second round-trip to the detail page.
- // When nil/empty, the template's own values are used.
- Description *string `json:"description,omitempty"`
- Instructions *string `json:"instructions,omitempty"`
- AvatarURL *string `json:"avatar_url,omitempty"`
- // Workspace skill IDs to attach **in addition to** the template's
- // skills. The merge dedupes against template skills automatically
- // (agent_skill INSERT uses ON CONFLICT DO NOTHING).
- ExtraSkillIDs []string `json:"extra_skill_ids,omitempty"`
-}
-
-type CreateAgentFromTemplateResponse struct {
- Agent AgentResponse `json:"agent"`
- ImportedSkillIDs []string `json:"imported_skill_ids"`
- ReusedSkillIDs []string `json:"reused_skill_ids"`
-}
-
-type fetchFailureResponse struct {
- Error string `json:"error"`
- FailedURLs []string `json:"failed_urls"`
-}
-
-func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Request) {
- workspaceID := h.resolveWorkspaceID(r)
-
- ownerID, ok := requireUserID(w, r)
- if !ok {
- return
- }
-
- var req CreateAgentFromTemplateRequest
- rawFields, err := decodeJSONBodyWithRawFields(r.Body, &req)
- if err != nil {
- writeError(w, http.StatusBadRequest, "invalid request body")
- return
- }
-
- if req.Name == "" {
- writeError(w, http.StatusBadRequest, "name is required")
- return
- }
- if req.RuntimeID == "" {
- writeError(w, http.StatusBadRequest, "runtime_id is required")
- return
- }
- if req.Visibility == "" {
- req.Visibility = "private"
- }
- if err := defaultAndValidateAgentMaxConcurrentTasks(rawFields, &req.MaxConcurrentTasks); err != nil {
- writeError(w, http.StatusBadRequest, err.Error())
- return
- }
-
- tmpl, found := agentTemplates.Get(req.TemplateSlug)
- if !found {
- writeError(w, http.StatusBadRequest, "template not found: "+req.TemplateSlug)
- return
- }
-
- wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
- if !ok {
- return
- }
- runtimeUUID, ok := parseUUIDOrBadRequest(w, req.RuntimeID, "runtime_id")
- if !ok {
- return
- }
-
- // Runtime validation reproduces the gating done by CreateAgent
- // (handler/agent.go) — keep the two paths in sync. Done before fetch so
- // we don't waste GitHub API calls for a request that's going to 403.
- runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{
- ID: runtimeUUID,
- WorkspaceID: wsUUID,
- })
- if err != nil {
- writeError(w, http.StatusBadRequest, "invalid runtime_id")
- return
- }
- member, ok := h.workspaceMember(w, r, workspaceID)
- if !ok {
- return
- }
- if !canUseRuntimeForAgent(member, runtime) {
- writeError(w, http.StatusForbidden, "this runtime is private; only its owner or a workspace admin can create agents on it")
- return
- }
-
- // Resolve invocation permission (MUL-3963) — mirrors CreateAgent so the
- // two entry points can't drift. permission_mode is authoritative when
- // present; otherwise legacy visibility is mapped through the same helper
- // ("workspace" -> public_to + workspace target; "private" -> private).
- // On create the caller is always the owner, so any submitted targets are
- // accepted unconditionally.
- _, hasTargets := rawFields["invocation_targets"]
- legacyVis := req.Visibility
- perm, _, permErr := parsePermissionInput(wsUUID, req.PermissionMode, req.InvocationTargets, req.PermissionMode != nil, hasTargets, &legacyVis)
- if permErr != nil {
- writeError(w, http.StatusBadRequest, permErr.Error())
- return
- }
-
- slog.Info("agent-template create: request received",
- append(logger.RequestAttrs(r),
- "template_slug", tmpl.Slug,
- "workspace_id", workspaceID,
- "skill_url_count", len(tmpl.Skills),
- )...)
-
- // Pre-flight dedupe: each skill that already exists in the workspace
- // by `cached_name` can be reused WITHOUT fetching. This is the big win:
- // on the second create-from-the-same-template, fetch_count drops to 0
- // and the whole operation completes in <100ms instead of 20+ seconds.
- //
- // `cached_name` MUST match the upstream SKILL.md frontmatter `name`
- // (see template authoring docs in agenttmpl/types.go). When it doesn't,
- // the pre-flight misses and we fall back to the in-TX find-or-create
- // below — slower (one wasted fetch) but still correct.
- preReused := make(map[int]db.Skill, len(tmpl.Skills))
- toFetchRefs := make([]agenttmpl.TemplateSkillRef, 0, len(tmpl.Skills))
- toFetchOrigIdx := make([]int, 0, len(tmpl.Skills))
- for i, ref := range tmpl.Skills {
- if ref.CachedName == "" {
- toFetchRefs = append(toFetchRefs, ref)
- toFetchOrigIdx = append(toFetchOrigIdx, i)
- continue
- }
- existing, err := h.Queries.GetSkillByWorkspaceAndName(r.Context(), db.GetSkillByWorkspaceAndNameParams{
- WorkspaceID: wsUUID,
- Name: ref.CachedName,
- })
- if err == nil {
- preReused[i] = existing
- slog.Info("agent-template create: pre-reuse hit (skipped fetch)",
- append(logger.RequestAttrs(r),
- "index", i,
- "cached_name", ref.CachedName,
- "existing_skill_id", uuidToString(existing.ID),
- )...)
- continue
- }
- toFetchRefs = append(toFetchRefs, ref)
- toFetchOrigIdx = append(toFetchOrigIdx, i)
- }
-
- // Fetch only the skills that aren't already in the workspace. fetched[j]
- // corresponds to toFetchRefs[j], whose original index is toFetchOrigIdx[j].
- httpClient := &http.Client{Timeout: 30 * time.Second}
- fetchCtx, cancelFetch := context.WithTimeout(r.Context(), importFetchTimeout)
- defer cancelFetch()
- fetchStart := time.Now()
- var fetched []*importedSkill
- var failedURLs []string
- if len(toFetchRefs) > 0 {
- fetched, failedURLs = fetchTemplateSkillsParallel(fetchCtx, httpClient, toFetchRefs)
- }
- slog.Info("agent-template create: fetch phase done",
- append(logger.RequestAttrs(r),
- "template_slug", tmpl.Slug,
- "fetch_duration_ms", time.Since(fetchStart).Milliseconds(),
- "pre_reused_count", len(preReused),
- "fetched_count", len(toFetchRefs)-len(failedURLs),
- "fail_count", len(failedURLs),
- "failed_urls", failedURLs,
- )...)
- if len(failedURLs) > 0 {
- writeJSON(w, http.StatusUnprocessableEntity, fetchFailureResponse{
- Error: "one or more skill sources are unavailable",
- FailedURLs: failedURLs,
- })
- return
- }
-
- // Build a per-original-index lookup so we can iterate tmpl.Skills in
- // order below without fiddling with toFetch* slices.
- fetchedByOrigIdx := make(map[int]*importedSkill, len(fetched))
- for j, imp := range fetched {
- fetchedByOrigIdx[toFetchOrigIdx[j]] = imp
- }
-
- creatorUUID := parseUUID(ownerID)
- isFirstAgent := false
- if existing, listErr := h.Queries.ListAgents(r.Context(), wsUUID); listErr == nil {
- isFirstAgent = len(existing) == 0
- }
-
- tx, err := h.TxStarter.Begin(r.Context())
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to begin tx: "+err.Error())
- return
- }
- defer tx.Rollback(r.Context())
- qtx := h.Queries.WithTx(tx)
-
- importedIDs := make([]string, 0, len(tmpl.Skills))
- reusedIDs := make([]string, 0, len(tmpl.Skills))
- allSkillIDs := make([]pgtype.UUID, 0, len(tmpl.Skills))
-
- for i, ref := range tmpl.Skills {
- // Pre-flight hit: reuse the workspace's existing skill ID without
- // any further fetch or DB work.
- if existing, ok := preReused[i]; ok {
- allSkillIDs = append(allSkillIDs, existing.ID)
- reusedIDs = append(reusedIDs, uuidToString(existing.ID))
- continue
- }
-
- imp := fetchedByOrigIdx[i]
- if imp == nil {
- // Defensive — shouldn't happen since we already checked failedURLs.
- writeError(w, http.StatusInternalServerError, fmt.Sprintf("internal: missing fetch result for skill index %d", i))
- return
- }
-
- // Second-chance dedupe by ACTUAL frontmatter name. Catches the case
- // where the template author's cached_name drifted from the upstream
- // frontmatter `name` — pre-flight misses but the workspace still has
- // the skill under its real name, and we want to reuse not duplicate.
- existing, err := qtx.GetSkillByWorkspaceAndName(r.Context(), db.GetSkillByWorkspaceAndNameParams{
- WorkspaceID: wsUUID,
- Name: imp.name,
- })
- if err == nil {
- slog.Info("agent-template create: reusing existing skill (frontmatter-name match, cached_name drifted)",
- append(logger.RequestAttrs(r),
- "index", i,
- "frontmatter_name", imp.name,
- "cached_name", ref.CachedName,
- "existing_skill_id", uuidToString(existing.ID),
- )...)
- allSkillIDs = append(allSkillIDs, existing.ID)
- reusedIDs = append(reusedIDs, uuidToString(existing.ID))
- continue
- }
- if !errors.Is(err, pgx.ErrNoRows) {
- slog.Error("agent-template create: lookup existing skill failed",
- append(logger.RequestAttrs(r),
- "index", i,
- "name", imp.name,
- "error", err,
- )...)
- writeError(w, http.StatusInternalServerError, "lookup existing skill failed: "+err.Error())
- return
- }
-
- slog.Info("agent-template create: inserting new skill",
- append(logger.RequestAttrs(r),
- "index", i,
- "name", imp.name,
- "file_count", len(imp.files),
- )...)
-
- files := make([]CreateSkillFileRequest, 0, len(imp.files))
- for _, f := range imp.files {
- if !validateFilePath(f.path) {
- continue
- }
- files = append(files, CreateSkillFileRequest{Path: f.path, Content: f.content})
- }
-
- // Record provenance: which template seeded this skill, plus the
- // upstream URL. Mirrors handler/skill.go:ImportSkill's origin block
- // so the skill detail page renders a consistent "imported from …"
- // chip regardless of entry point.
- origin := map[string]any{
- "type": "agent_template",
- "template_slug": tmpl.Slug,
- "source_url": ref.SourceURL,
- }
- // Preserve the upstream-specific origin fields (owner/repo/...) when
- // the fetcher returned them — useful for a "Open on GitHub" link.
- if imp.origin != nil {
- for k, v := range imp.origin {
- if _, exists := origin[k]; !exists {
- origin[k] = v
- }
- }
- }
-
- created, err := createSkillWithFilesInTx(r.Context(), qtx, skillCreateInput{
- WorkspaceID: wsUUID,
- CreatorID: creatorUUID,
- Name: imp.name,
- Description: imp.description,
- Content: imp.content,
- Config: map[string]any{"origin": origin},
- Files: files,
- })
- if err != nil {
- // Full PG error in the log so we can tell unique-constraint from
- // other failures without guessing.
- slog.Error("agent-template create: failed to create skill",
- append(logger.RequestAttrs(r),
- "index", i,
- "name", imp.name,
- "workspace_id", workspaceID,
- "error", err,
- "is_unique_violation", isUniqueViolation(err),
- )...)
- writeError(w, http.StatusInternalServerError, "failed to create skill: "+err.Error())
- return
- }
- allSkillIDs = append(allSkillIDs, parseUUID(created.ID))
- importedIDs = append(importedIDs, created.ID)
- }
-
- rc, _ := json.Marshal(map[string]any{})
- ce, _ := json.Marshal(map[string]string{})
- ca, _ := json.Marshal([]string{})
-
- // Apply optional overrides — nil means "use template default".
- description := tmpl.Description
- if req.Description != nil {
- description = *req.Description
- }
- instructions := tmpl.Instructions
- if req.Instructions != nil {
- instructions = *req.Instructions
- }
- avatarURL, ok := h.newAgentAvatar(w, r, req.AvatarURL)
- if !ok {
- return
- }
-
- agent, err := qtx.CreateAgent(r.Context(), db.CreateAgentParams{
- WorkspaceID: wsUUID,
- Name: req.Name,
- Description: description,
- Instructions: instructions,
- AvatarUrl: avatarURL,
- RuntimeMode: runtime.RuntimeMode,
- RuntimeConfig: rc,
- RuntimeID: runtime.ID,
- Visibility: perm.legacyVisibility(),
- PermissionMode: perm.mode,
- MaxConcurrentTasks: req.MaxConcurrentTasks,
- OwnerID: creatorUUID,
- CustomEnv: ce,
- CustomArgs: ca,
- McpConfig: nil,
- Model: pgtype.Text{String: req.Model, Valid: req.Model != ""},
- })
- if err != nil {
- // Mirror handler/agent.go:CreateAgent: when the duplicate is the
- // agent name UNIQUE in this workspace, return 409 with a clear
- // message instead of leaking the raw PG error as 500. Frontend
- // already knows how to render 409 from the manual create path.
- var pgErr *pgconn.PgError
- if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "agent_workspace_name_unique" {
- slog.Info("agent-template create: agent name conflict",
- append(logger.RequestAttrs(r),
- "agent_name", req.Name,
- "workspace_id", workspaceID,
- )...)
- writeError(w, http.StatusConflict, fmt.Sprintf("an agent named %q already exists in this workspace", req.Name))
- return
- }
- slog.Error("agent-template create: failed to create agent",
- append(logger.RequestAttrs(r),
- "agent_name", req.Name,
- "workspace_id", workspaceID,
- "error", err,
- "is_unique_violation", isUniqueViolation(err),
- )...)
- writeError(w, http.StatusInternalServerError, "failed to create agent: "+err.Error())
- return
- }
-
- for idx, skillID := range allSkillIDs {
- if err := qtx.AddAgentSkill(r.Context(), db.AddAgentSkillParams{
- AgentID: agent.ID,
- SkillID: skillID,
- }); err != nil {
- slog.Error("agent-template create: failed to attach skill",
- append(logger.RequestAttrs(r),
- "agent_id", uuidToString(agent.ID),
- "skill_id", uuidToString(skillID),
- "skill_index", idx,
- "error", err,
- )...)
- writeError(w, http.StatusInternalServerError, "failed to attach skill: "+err.Error())
- return
- }
- }
-
- // Persist the invocation allow-list (MUL-3963) inside the same tx as the
- // agent row so the agent is never visible to callers in a state where the
- // row exists but its targets are missing. Without this the freshly created
- // row would default to `permission_mode=private` + zero targets — meaning
- // canInvokeAgent silently locks out every non-owner even when the caller
- // asked for a workspace-shared agent (the manual CreateAgent path already
- // did this; the template path was diverging until MUL-4010).
- if err := replaceInvocationTargetsWithQueries(r.Context(), qtx, agent.ID, creatorUUID, perm.targets); err != nil {
- slog.Error("agent-template create: persist invocation targets failed",
- append(logger.RequestAttrs(r),
- "agent_id", uuidToString(agent.ID),
- "error", err,
- )...)
- writeError(w, http.StatusInternalServerError, "failed to persist invocation targets: "+err.Error())
- return
- }
-
- // Attach user-supplied extra skills (selected in the create dialog
- // alongside the template). AddAgentSkill uses ON CONFLICT DO NOTHING,
- // so duplicates with template-imported skills are harmless.
- for _, raw := range req.ExtraSkillIDs {
- extraUUID, perr := util.ParseUUID(raw)
- if perr != nil {
- // Skip malformed IDs but don't fail the whole create — the agent
- // is otherwise valid. Logged so the bad ID can be traced.
- slog.Warn("agent-template create: skipping malformed extra_skill_id",
- append(logger.RequestAttrs(r), "raw", raw, "error", perr)...)
- continue
- }
- // Verify the skill belongs to this workspace before attaching;
- // otherwise a malicious client could attach a skill from another
- // workspace by guessing UUIDs.
- owned, qerr := qtx.GetSkillInWorkspace(r.Context(), db.GetSkillInWorkspaceParams{
- ID: extraUUID, WorkspaceID: wsUUID,
- })
- if qerr != nil {
- slog.Warn("agent-template create: skipping cross-workspace extra_skill_id",
- append(logger.RequestAttrs(r), "skill_id", raw, "error", qerr)...)
- continue
- }
- if err := qtx.AddAgentSkill(r.Context(), db.AddAgentSkillParams{
- AgentID: agent.ID,
- SkillID: owned.ID,
- }); err != nil {
- slog.Error("agent-template create: failed to attach extra skill",
- append(logger.RequestAttrs(r), "skill_id", raw, "error", err)...)
- writeError(w, http.StatusInternalServerError, "failed to attach skill: "+err.Error())
- return
- }
- }
-
- if err := tx.Commit(r.Context()); err != nil {
- slog.Error("agent-template create: commit failed",
- append(logger.RequestAttrs(r),
- "agent_id", uuidToString(agent.ID),
- "error", err,
- )...)
- writeError(w, http.StatusInternalServerError, "commit failed: "+err.Error())
- return
- }
-
- if runtime.Status == "online" {
- h.TaskService.ReconcileAgentStatus(r.Context(), agent.ID)
- agent, _ = h.Queries.GetAgent(r.Context(), agent.ID)
- }
-
- resp := h.agentToResponse(agent)
- // Templates attach skills via AddAgentSkill above, so the freshly built
- // AgentResponse must reload them — otherwise the create response (and
- // the agent:created broadcast) would tell clients the agent has no
- // skills despite the template having just imported them (#3459).
- if err := h.attachAgentSkills(r.Context(), &resp, agent.ID); err != nil {
- slog.Warn("load agent skills after template create failed",
- append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)
- writeError(w, http.StatusInternalServerError, "failed to load agent skills")
- return
- }
- // Reflect the invocation-permission state we just persisted (MUL-4010).
- // Without this the response would still show empty invocation_targets and
- // derive Visibility from permission_mode alone — so a client that just
- // asked for `visibility="workspace"` would round-trip to a legacy
- // "private" and re-render the wrong access badge.
- if err := h.enrichAgentResponseWithTargets(r.Context(), &resp, agent.ID); err != nil {
- slog.Warn("agent-template create: load invocation targets for response failed",
- append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)
- }
- actorType, actorID := h.resolveActor(r, ownerID, workspaceID)
- h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": resp})
-
- obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AgentCreated(
- ownerID,
- workspaceID,
- uuidToString(agent.ID),
- runtime.Provider,
- runtime.RuntimeMode,
- tmpl.Slug, // template slug doubles as the analytics template field
- isFirstAgent,
- ))
-
- slog.Info("agent created from template",
- append(logger.RequestAttrs(r),
- "agent_id", uuidToString(agent.ID),
- "template_slug", tmpl.Slug,
- "imported_skill_count", len(importedIDs),
- "reused_skill_count", len(reusedIDs),
- )...)
-
- writeJSON(w, http.StatusCreated, CreateAgentFromTemplateResponse{
- Agent: resp,
- ImportedSkillIDs: importedIDs,
- ReusedSkillIDs: reusedIDs,
- })
-}
-
-// --- Parallel skill fetch ---
-
-type templateFetchResult struct {
- index int
- imported *importedSkill
- url string
- err error
-}
-
-// fetchTemplateSkillsParallel resolves every template skill ref into an
-// importedSkill, in parallel. Returns the imports in input order; failed_urls
-// is non-nil iff any fetch failed. Logs per-URL timing so we can spot which
-// upstream is the long pole in a slow request.
-func fetchTemplateSkillsParallel(ctx context.Context, client *http.Client, refs []agenttmpl.TemplateSkillRef) ([]*importedSkill, []string) {
- results := make(chan templateFetchResult, len(refs))
- var wg sync.WaitGroup
- for i, ref := range refs {
- wg.Add(1)
- go func(i int, ref agenttmpl.TemplateSkillRef) {
- defer wg.Done()
- start := time.Now()
- slog.Info("agent-template fetch: start", "index", i, "source_url", ref.SourceURL)
- imp, err := fetchSkillFromURL(ctx, client, ref.SourceURL)
- elapsedMs := time.Since(start).Milliseconds()
- if err != nil {
- slog.Warn("agent-template fetch: failed",
- "index", i,
- "source_url", ref.SourceURL,
- "duration_ms", elapsedMs,
- "error", err,
- )
- } else {
- resolvedName := ""
- fileCount := 0
- if imp != nil {
- resolvedName = imp.name
- fileCount = len(imp.files)
- }
- slog.Info("agent-template fetch: done",
- "index", i,
- "source_url", ref.SourceURL,
- "duration_ms", elapsedMs,
- "resolved_name", resolvedName,
- "file_count", fileCount,
- )
- }
- results <- templateFetchResult{index: i, imported: imp, url: ref.SourceURL, err: err}
- }(i, ref)
- }
- wg.Wait()
- close(results)
-
- imports := make([]*importedSkill, len(refs))
- var failed []string
- for r := range results {
- if r.err != nil {
- failed = append(failed, r.url)
- continue
- }
- imports[r.index] = r.imported
- }
- return imports, failed
-}
-
-// fetchSkillFromURL dispatches to the right upstream fetcher based on URL.
-// Mirrors the switch inside ImportSkill (skill.go:1566) so both entry points
-// stay in sync.
-func fetchSkillFromURL(ctx context.Context, client *http.Client, rawURL string) (*importedSkill, error) {
- source, normalized, err := detectImportSource(rawURL)
- if err != nil {
- return nil, err
- }
- switch source {
- case sourceClawHub:
- return fetchFromClawHub(ctx, client, normalized)
- case sourceSkillsSh:
- return fetchFromSkillsSh(ctx, client, normalized)
- case sourceGitHub:
- return fetchFromGitHub(ctx, client, normalized)
- }
- return nil, fmt.Errorf("unknown import source for %s", rawURL)
-}
diff --git a/server/internal/handler/agent_template_permission_test.go b/server/internal/handler/agent_template_permission_test.go
deleted file mode 100644
index 4f4d100515..0000000000
--- a/server/internal/handler/agent_template_permission_test.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package handler
-
-import (
- "context"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "testing"
-)
-
-// TestCreateAgentFromTemplate_LegacyVisibilityMapsToPermission is the
-// MUL-4010 regression: the template create path used to persist
-// permission_mode='private' (the SQL default) regardless of the incoming
-// legacy `visibility="workspace"` value, so an agent that the caller asked
-// to be workspace-shared silently became owner-only in canInvokeAgent.
-//
-// After the fix, parsePermissionInput runs on the template path too:
-// - visibility "workspace" -> permission_mode public_to + workspace target
-// - visibility "private" -> permission_mode private + no targets
-func TestCreateAgentFromTemplate_LegacyVisibilityMapsToPermission(t *testing.T) {
- if testHandler == nil || testPool == nil {
- t.Skip("database not available")
- }
- runtimeID := handlerTestRuntimeID(t)
-
- // commit-message ships with zero external skills so this test never
- // touches the network fetch path. Any zero-skill template would do.
- const templateSlug = "commit-message"
- if _, ok := agentTemplates.Get(templateSlug); !ok {
- t.Fatalf("expected template %q to be loaded", templateSlug)
- }
-
- create := func(name, visibility string) CreateAgentFromTemplateResponse {
- w := httptest.NewRecorder()
- testHandler.CreateAgentFromTemplate(w, newRequest("POST", "/api/agents/from-template?workspace_id="+testWorkspaceID, map[string]any{
- "template_slug": templateSlug,
- "name": name,
- "runtime_id": runtimeID,
- "visibility": visibility,
- }))
- if w.Code != http.StatusCreated {
- t.Fatalf("create %q (visibility=%s): expected 201, got %d: %s", name, visibility, w.Code, w.Body.String())
- }
- var resp CreateAgentFromTemplateResponse
- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
- t.Fatalf("decode: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, resp.Agent.ID)
- })
- return resp
- }
-
- ws := create("template-legacy-workspace", "workspace")
- if ws.Agent.PermissionMode != "public_to" {
- t.Errorf("workspace-template agent permission_mode = %q, want public_to", ws.Agent.PermissionMode)
- }
- if ws.Agent.Visibility != "workspace" {
- t.Errorf("workspace-template agent derived visibility = %q, want workspace", ws.Agent.Visibility)
- }
- foundWorkspaceTarget := false
- for _, tgt := range ws.Agent.InvocationTargets {
- if tgt.TargetType == "workspace" {
- foundWorkspaceTarget = true
- }
- }
- if !foundWorkspaceTarget {
- t.Errorf("workspace-template agent invocation_targets = %+v, want a workspace target", ws.Agent.InvocationTargets)
- }
- // Additional DB-level check: canInvokeAgent's persisted inputs — the row's
- // permission_mode column AND at least one invocation-target row — must
- // both be present. A response that reflected the intent but a row that
- // didn't would still deny non-owner invokes at runtime.
- var mode string
- if err := testPool.QueryRow(context.Background(),
- `SELECT permission_mode FROM agent WHERE id = $1`, ws.Agent.ID).Scan(&mode); err != nil {
- t.Fatalf("load persisted permission_mode: %v", err)
- }
- if mode != "public_to" {
- t.Errorf("persisted permission_mode = %q, want public_to", mode)
- }
- var targetCount int
- if err := testPool.QueryRow(context.Background(),
- `SELECT COUNT(*) FROM agent_invocation_target WHERE agent_id = $1 AND target_type = 'workspace'`,
- ws.Agent.ID,
- ).Scan(&targetCount); err != nil {
- t.Fatalf("load persisted workspace targets: %v", err)
- }
- if targetCount != 1 {
- t.Errorf("persisted workspace target rows = %d, want 1", targetCount)
- }
-
- priv := create("template-legacy-private", "private")
- if priv.Agent.PermissionMode != "private" {
- t.Errorf("private-template agent permission_mode = %q, want private", priv.Agent.PermissionMode)
- }
- if priv.Agent.Visibility != "private" {
- t.Errorf("private-template agent derived visibility = %q, want private", priv.Agent.Visibility)
- }
- if len(priv.Agent.InvocationTargets) != 0 {
- t.Errorf("private-template agent invocation_targets = %+v, want none", priv.Agent.InvocationTargets)
- }
-}
-
-// TestCreateAgentFromTemplate_PublicToWithMemberTarget verifies that when
-// the new-Web-shape (permission_mode + invocation_targets) arrives on the
-// template path, it is honoured — a member allow-list is persisted verbatim
-// instead of being silently dropped and replaced with the SQL default.
-func TestCreateAgentFromTemplate_PublicToWithMemberTarget(t *testing.T) {
- if testHandler == nil || testPool == nil {
- t.Skip("database not available")
- }
- runtimeID := handlerTestRuntimeID(t)
-
- const templateSlug = "commit-message"
- if _, ok := agentTemplates.Get(templateSlug); !ok {
- t.Fatalf("expected template %q to be loaded", templateSlug)
- }
-
- // Fresh member to grant invocation access to.
- targetUserID := createPermissionTestMember(t, "[email protected]")
-
- w := httptest.NewRecorder()
- testHandler.CreateAgentFromTemplate(w, newRequest("POST", "/api/agents/from-template?workspace_id="+testWorkspaceID, map[string]any{
- "template_slug": templateSlug,
- "name": "template-public-to-member",
- "runtime_id": runtimeID,
- "permission_mode": "public_to",
- "invocation_targets": []map[string]any{
- {"target_type": "member", "target_id": targetUserID},
- },
- }))
- if w.Code != http.StatusCreated {
- t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
- }
- var resp CreateAgentFromTemplateResponse
- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
- t.Fatalf("decode: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, resp.Agent.ID)
- })
-
- if resp.Agent.PermissionMode != "public_to" {
- t.Errorf("permission_mode = %q, want public_to", resp.Agent.PermissionMode)
- }
- // public_to limited to a specific member -> derived legacy visibility
- // collapses to "private" (only workspace-target public_to derives to
- // "workspace"); the real audience is the member allow-list below.
- if resp.Agent.Visibility != "private" {
- t.Errorf("derived legacy visibility = %q, want private (member-only public_to)", resp.Agent.Visibility)
- }
- sawMember := false
- for _, tgt := range resp.Agent.InvocationTargets {
- if tgt.TargetType == "member" && tgt.TargetID != nil && *tgt.TargetID == targetUserID {
- sawMember = true
- }
- }
- if !sawMember {
- t.Errorf("invocation_targets = %+v, want a member target for %s", resp.Agent.InvocationTargets, targetUserID)
- }
-
- // DB-level check: the member row is persisted, not just echoed back.
- var persisted int
- if err := testPool.QueryRow(context.Background(),
- `SELECT COUNT(*) FROM agent_invocation_target WHERE agent_id = $1 AND target_type = 'member' AND target_id = $2`,
- resp.Agent.ID, targetUserID,
- ).Scan(&persisted); err != nil {
- t.Fatalf("load persisted member target: %v", err)
- }
- if persisted != 1 {
- t.Errorf("persisted member target rows = %d, want 1", persisted)
- }
-}
diff --git a/server/internal/handler/onboarding_shim.go b/server/internal/handler/onboarding_shim.go
index 3c83346575..702253f1e1 100644
--- a/server/internal/handler/onboarding_shim.go
+++ b/server/internal/handler/onboarding_shim.go
@@ -49,9 +49,9 @@ const runtimeBootstrapBodyLimit = 8 * 1024
const maxStarterPromptLen = 2 * 1024
const (
- onboardingAssistantName = "Multica Helper"
- onboardingIssueTitle = "Start here: learn Multica with Multica Helper"
- onboardingAgentTemplate = "multica_helper"
+ onboardingAssistantName = "Multica Helper"
+ onboardingIssueTitle = "Start here: learn Multica with Multica Helper"
+ onboardingAgentCreationSource = "multica_helper"
// noRuntimeIssueTitle MUST match the pre-v3 service constant so
// LockAndFindActiveDuplicate dedupes correctly across desktop versions.
@@ -308,7 +308,7 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requ
h.publish(protocol.EventAgentCreated, req.WorkspaceID, "member", userID, map[string]any{"agent": resp})
obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AgentCreated(
userID, req.WorkspaceID, uuidToString(assistant.ID),
- runtime.Provider, runtime.RuntimeMode, onboardingAgentTemplate, isFirstAgent,
+ runtime.Provider, runtime.RuntimeMode, onboardingAgentCreationSource, isFirstAgent,
))
}
if issueCreated {
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index 271679df65..9f4119f9bd 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -29,8 +29,8 @@ import (
// Two failure modes covered:
// - Embedded NUL (0x00) — PG rejects with SQLSTATE 22021. Removed.
// - Other invalid-UTF-8 byte sequences (e.g. 0x91 = Windows-1252 smart
-// quote, which crashed agent-template import of skills containing
-// Windows-encoded prose). `strings.ToValidUTF8` drops them.
+// quote in imported Windows-encoded prose). `strings.ToValidUTF8` drops
+// them.
//
// Name is kept for compatibility with the many call sites; the behaviour
// is a strict superset of the original.
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
index 16aed1ab87..e98edef3b0 100644
--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
@@ -136,11 +136,10 @@ Other defaults when omitted: `runtime_config` → `{}`, `custom_env` → `{}`,
are typed `[]string`/`any` and marshaled as-is — the JSON-shape rejection
happens in the CLI, not the create handler.
-The 1–50 concurrency range applies consistently to manual create, update, and
-the create-from-template HTTP path. On create paths, an omitted field defaults
-to 6 while an explicitly supplied 0 is rejected; on update, omission preserves
-the current value. The CLI performs the same range check before sending create
-or update requests.
+The 1–50 concurrency range applies consistently to create and update. On
+create, an omitted field defaults to 6 while an explicitly supplied 0 is
+rejected; on update, omission preserves the current value. The CLI performs the
+same range check before sending create or update requests.
`thinking_level` is validated only at the provider level: fixed-vocabulary
providers reject an unrecognized literal, while dynamic-vocabulary providers
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
index 17d64bf448..27586427ff 100644
--- a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
+++ b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
@@ -45,17 +45,6 @@ go test ./internal/service -run TestBuiltinSkillsConformToTemplate
| Skills copied in the create transaction | 239 | Source skill ids sent as `skill_ids`, bound in the same `POST /api/agents` tx (267); `--no-skills` opts out | read `runAgentCopy` |
| Secrets never copied | 240–266 | `custom_env`/`mcp_config`/`runtime_config` set only from explicit secret-safe flags, never read from the source | `multica agent copy --help` |
-Note: the CLI no longer exposes `--from-template`. The agent-template backend
-still exists (registry `server/internal/agenttmpl/`, handler `agent_template.go`,
-routes `GET /api/agent-templates` and `POST /api/agents/from-template`, plus the
-`packages/core` client/query wrappers) but is currently orphaned plumbing with no
-live caller: the removed CLI flag was its only non-test consumer, and onboarding
-does NOT use it — `packages/views/onboarding/steps/step-agent.tsx` builds four
-hardcoded local presets (i18n-resolved) and creates via plain `POST /api/agents`
-(`createAgent`), never `POST /api/agents/from-template`. Do not treat the template
-API as a supported agent-creation path. This skill teaches manual `agent create`
-only.
-
## Create handler — `server/internal/handler/agent.go`
| Contract | Line | Behavior |
@@ -77,18 +66,12 @@ only.
| `mcp_config` null-skip on create | 704–705 | raw JSON copied through unless the body value is the literal `null` |
| `mcp_config` redacted on read | 54, 848–851 | `redactMcpConfig` sets `McpConfigRedacted=true`; a private agent read by a member also redacts (494, 509) |
| Qwen Code managed-MCP injection | `pkg/agent/qwen.go` | Non-null `mcp_config` is written to a daemon-owned 0600 temporary JSON file and passed with `--mcp-config`; the file is removed after the process exits, while `null` preserves native inheritance. |
-| Random emoji avatar default | `agent_avatar.go` 11–32; `agent.go` 1127–1133 | Omitted, empty, or whitespace-only `avatar_url` becomes a cryptographically selected `emoji:<glyph>` sentinel; explicit values are preserved. The template handler uses the same helper at `agent_template.go` 458. |
+| Random emoji avatar default | `agent_avatar.go` 11–32; `agent.go` 1127–1133 | Omitted, empty, or whitespace-only `avatar_url` becomes a cryptographically selected `emoji:<glyph>` sentinel; explicit values are preserved. |
| `CreateAgent` insert params | `agent.go` create path | Persists avatar_url, runtime_config, instructions, custom_env, custom_args, model, thinking_level, service_tier, mcp_config, visibility, max_concurrent_tasks |
| `UpdateAgent` rejects `custom_env` | 910–913 | if `custom_env` present in body → 400 "use PUT /api/agents/{id}/env (or `multica agent env set`)" |
| `UpdateAgent` persists / clears `mcp_config` | 944–948, 1060–1061 | Tri-state from the raw body: key omitted → no change; literal `null` → `ClearAgentMcpConfig`; object → replace. No 400 like `custom_env` — `mcp_config` IS updatable here |
| `description` ≤ 255 on update too | 921–924 | same cap re-checked on update |
-## Create-from-template handler — `server/internal/handler/agent_template.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| `max_concurrent_tasks` default + validation | `CreateAgentFromTemplate`; `defaultAndValidateAgentMaxConcurrentTasks` | Uses the same helper as manual create: omission or `null` defaults to 6; explicit numeric values outside 1–50 return 400 |
-
## Runtime model/thinking discovery — `server/pkg/agent/{models,thinking}.go`
| Contract | Line | Behavior |
diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.go
index f958974303..7ae18119cd 100644
--- a/server/pkg/db/generated/skill.sql.go
+++ b/server/pkg/db/generated/skill.sql.go
@@ -131,10 +131,8 @@ type GetSkillByWorkspaceAndNameParams struct {
Name string `json:"name"`
}
-// Used by agent-template materialization to implement find-or-create: when a
-// template references a skill by name that already exists in the workspace,
-// reuse the existing skill_id rather than INSERT (which would fail the
-// UNIQUE(workspace_id, name) constraint from migration 008).
+// Used by skill import and runtime-local skill discovery to reuse a workspace
+// skill by name rather than violating UNIQUE(workspace_id, name).
func (q *Queries) GetSkillByWorkspaceAndName(ctx context.Context, arg GetSkillByWorkspaceAndNameParams) (Skill, error) {
row := q.db.QueryRow(ctx, getSkillByWorkspaceAndName, arg.WorkspaceID, arg.Name)
var i Skill
diff --git a/server/pkg/db/queries/skill.sql b/server/pkg/db/queries/skill.sql
index 776c8f17aa..0d95a5e9ed 100644
--- a/server/pkg/db/queries/skill.sql
+++ b/server/pkg/db/queries/skill.sql
@@ -24,10 +24,8 @@ SELECT * FROM skill
WHERE id = $1 AND workspace_id = $2;
-- name: GetSkillByWorkspaceAndName :one
--- Used by agent-template materialization to implement find-or-create: when a
--- template references a skill by name that already exists in the workspace,
--- reuse the existing skill_id rather than INSERT (which would fail the
--- UNIQUE(workspace_id, name) constraint from migration 008).
+-- Used by skill import and runtime-local skill discovery to reuse a workspace
+-- skill by name rather than violating UNIQUE(workspace_id, name).
SELECT * FROM skill
WHERE workspace_id = $1 AND name = $2;