Skip to main content

agentmux_srv/server/agent_handlers/
template.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::sync::Arc;
6
7
8use crate::backend::rpc::engine::WshRpcEngine;
9use crate::backend::rpc_types::{
10    COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE,
11    CommandAgentDefCreateFromTemplateData,
12    // Two-tier picker — Phase 2 (SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md
13    // Q2 Decision Y: hide templates).
14    COMMAND_AGENT_DEF_HIDE, COMMAND_AGENT_DEF_UNHIDE,
15    COMMAND_AGENT_DEF_LIST_HIDDEN_TEMPLATES,
16    CommandAgentDefHideData, AgentDefHideResult,
17    COMMAND_FORK_AGENT_DEFINITION,
18    COMMAND_FORK_AGENT_DEFINITION_SUGGEST,
19    CommandForkAgentDefinitionSuggestData, ForkAgentDefinitionSuggestResult,
20    CommandForkAgentDefinitionData, CommandListHiddenTemplatesData,
21    COMMAND_RENAME_AGENT_DEFINITION_TITLE,
22    CommandRenameAgentDefinitionTitleData,
23};
24use crate::backend::storage::{AgentDefinition, AgentContent, AgentSkill};
25use crate::backend::storage::store::Store;
26
27use super::super::AppState;
28use super::template_create::create_from_template;
29
30/// Link a new fork to the account its source runs on, for the fork's own
31/// provider: the source's own links, or its template's when it has none
32/// (`effective_identity_links`, the spawn gate's rule). Every caller of
33/// `forkagentdefinition` launches the fork on its source's account
34/// (`quick-fork.ts`; `AgentPicker.tsx`'s `handleFork`), but the launch wrote
35/// that link only after its first spawn. A quick fork resumes its source's
36/// conversation, so that spawn runs at launch, and it was refused with "no
37/// credentials" until the link landed. Writing it here means a fork never
38/// exists without it.
39///
40/// Links for other providers are not copied, matching what those callers
41/// write. A source with no account leaves the fork unbound: its first spawn
42/// gets the ordinary bind-an-account refusal. Best-effort: a failure is
43/// logged and leaves the fork unbound, as forks were before.
44fn inherit_source_account_links(
45    mstore: &Store,
46    identity_store: &Store,
47    source: &AgentDefinition,
48    fork: &AgentDefinition,
49) -> usize {
50    use crate::backend::providers::resolve_provider_alias;
51    let fork_provider = resolve_provider_alias(&fork.provider);
52    let links = match crate::identity::resolver::effective_identity_links(mstore, identity_store, source) {
53        Ok(links) => links,
54        Err(e) => {
55            tracing::warn!(
56                target: "identity",
57                source = %source.id,
58                fork = %fork.id,
59                error = %e,
60                "forkagentdefinition: could not read the source's account links; the fork starts unbound"
61            );
62            return 0;
63        }
64    };
65    let mut copied = 0;
66    for link in links.iter().filter(|l| resolve_provider_alias(&l.provider) == fork_provider) {
67        match identity_store.agent_identity_link(&fork.id, &link.account_id, &link.provider) {
68            Ok(()) => copied += 1,
69            Err(e) => tracing::warn!(
70                target: "identity",
71                source = %source.id,
72                fork = %fork.id,
73                account_id = %link.account_id,
74                error = %e,
75                "forkagentdefinition: could not link the fork to its source's account"
76            ),
77        }
78    }
79    if copied > 0 {
80        tracing::info!(
81            target: "identity",
82            source = %source.id,
83            fork = %fork.id,
84            provider = %fork_provider,
85            "forkagentdefinition: fork linked to its source's account"
86        );
87    }
88    copied
89}
90
91/// Resolve a definition's **fork**-lineage root by walking `parent_id`.
92///
93/// `parent_id` is overloaded in this schema: `agentdefcreatefromtemplate`
94/// sets it to the *template's* id for every freshly-instantiated user
95/// agent (see that handler below), not just `forkagentdefinition`'s actual
96/// forks — so two unrelated agents both created fresh from the same
97/// template share a `parent_id`, but are not forks of each other. The one
98/// field that reliably distinguishes an actual fork is `branch_label`:
99/// `forkagentdefinition` always sets it (non-empty); `agentdefcreatefromtemplate`
100/// always leaves it empty. Walk upward only while the current node is
101/// itself a fork (non-empty `branch_label`); stop at the first non-fork
102/// ancestor (a template, or a first-generation user agent) — that's the
103/// lineage's root for fork-counting purposes. Confirmed bug this fixes
104/// (Codex's review of PR #2721, docs/specs/SPEC_AGENT_QUICK_FORK_NEW_TAB_2026_08_21.md
105/// §2): the naming rule requires a flat, lineage-wide counter ("AgentX #2"
106/// → "AgentX #3"), but the previous `parent_id == source_id` filter only
107/// counted immediate children, so forking a fork produced "AgentX #2 #2".
108fn fork_lineage_root_id(defs: &[AgentDefinition], start_id: &str) -> String {
109    let mut current = start_id.to_string();
110    loop {
111        match defs.iter().find(|a| a.id == current) {
112            Some(def) if !def.branch_label.is_empty() && !def.parent_id.is_empty() => {
113                current = def.parent_id.clone();
114            }
115            _ => return current,
116        }
117    }
118}
119
120/// The definition at the root of `source`'s fork lineage (see
121/// `fork_lineage_root_id`); `source` itself if the root can't be found.
122fn fork_lineage_root<'a>(defs: &'a [AgentDefinition], source: &'a AgentDefinition) -> &'a AgentDefinition {
123    let root_id = fork_lineage_root_id(defs, &source.id);
124    defs.iter().find(|a| a.id == root_id).unwrap_or(source)
125}
126
127/// Whether a user agent (not a seeded template) already goes by `name`,
128/// case-insensitively: as its name, or as its branch label, which is what a
129/// renamed fork shows. Names are unique among user agents: the picker lists
130/// them by name, and name-keyed registrations collide otherwise. A launched
131/// agent's instance name is the store's to check (`agents_matching_name`).
132pub(super) fn name_taken(defs: &[AgentDefinition], name: &str) -> bool {
133    defs.iter().any(|a| a.is_seeded == 0 && (a.name.eq_ignore_ascii_case(name) || a.branch_label.eq_ignore_ascii_case(name)))
134}
135
136/// `name_taken`, or the store's own name resolution finds it (slug, name,
137/// a launched agent's instance name, or a slug an agent was renamed from):
138/// every name a fork could take is checked against both, automatic or typed
139/// (#4746). So is the name it would be addressed by, its route name: a former
140/// slug or display name stays reserved for its agent
141/// (`SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` Phase 1; `former_names`).
142fn name_in_use(store: &crate::backend::storage::store::Store, defs: &[AgentDefinition], name: &str) -> bool {
143    name_taken(defs, name)
144        || store.agents_matching_name(name).map(|m| !m.is_empty()).unwrap_or(false)
145        || store.former_name_reserved(name)
146}
147
148/// Whether no agent goes by `name` and no agent was renamed from it: the name a new agent may take.
149pub(crate) fn name_available(store: &crate::backend::storage::store::Store, name: &str) -> bool {
150    let defs = store.agent_def_list().unwrap_or_default();
151    !name_in_use(store, &defs, name)
152}
153
154/// Whether `name` addresses an agent other than `own_id` as a name it was
155/// renamed from, so no other agent may take it as a display name.
156pub(super) fn former_name_of_another(store: &crate::backend::storage::store::Store, name: &str, own_id: &str) -> bool {
157    store.former_name_listers(name).map(|l| l.iter().any(|uid| uid != own_id)).unwrap_or(true)
158}
159
160/// Build the flat, lineage-wide "#N" auto-suggestion for forking `source`.
161///
162/// The name is built from the lineage **root's** name, not `source`'s own
163/// (possibly already-suffixed) name — forking "AgentX #2" gives "AgentX #3",
164/// not "AgentX #2 #3" (`SPEC_AGENT_NAMING_AND_ADDRESSING_HOST_LAN_WAN_2026_08_22.md`
165/// §4.5). The number is one past the highest "#N" any fork in the lineage
166/// already carries, or any deleted agent carried (`retired`, the store's
167/// `retired_agent_names`), not a count of the live ones: a count handed a
168/// deleted fork's number to the next fork, so two agents could share a name
169/// over time, and live ones too while a later fork still had it
170/// (REPORT_FORK_AGENT_ISOLATION_2026_10_12.md F4). A live fork's number is its
171/// name's trailing " #N", whatever its prefix, so renaming the root keeps the
172/// count; a deleted name counts under the root's current name, compared
173/// lowercased as it was tombstoned, and under each of the root's former names
174/// (`root_former`), so renaming the root after deleting forks keeps them
175/// counted too. A name `taken` says is in use is skipped.
176fn suggest_fork_name(
177    defs: &[AgentDefinition],
178    retired: &[String],
179    root_former: &[String],
180    source: &AgentDefinition,
181    taken: impl Fn(&str) -> bool,
182) -> String {
183    let root = fork_lineage_root(defs, source);
184    let prefix = format!("{} #", root.name);
185    let suffix = |name: &str| name.rsplit_once(" #")?.1.trim().parse::<u32>().ok();
186    let live = defs
187        .iter()
188        .filter(|a| a.is_seeded == 0 && !a.branch_label.is_empty() && fork_lineage_root_id(defs, &a.id) == root.id)
189        .filter_map(|a| suffix(&a.name));
190    let retired_prefixes: Vec<String> =
191        std::iter::once(&root.name).chain(root_former).map(|n| format!("{n} #").to_lowercase()).collect();
192    let deleted = retired.iter().filter_map(|n| {
193        let n = n.to_lowercase();
194        retired_prefixes.iter().find_map(|p| n.strip_prefix(p.as_str())?.trim().parse::<u32>().ok())
195    });
196    let highest = live.chain(deleted).max().unwrap_or(1);
197    let mut n = highest.max(1) + 1;
198    while taken(&format!("{prefix}{n}")) {
199        n += 1;
200    }
201    format!("{prefix}{n}")
202}
203
204pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
205    // agentdefcreatefromtemplate → clone a seeded template into a new
206    // user-owned definition (Phase 1 two-tier picker —
207    // SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md). The template stays
208    // pristine; the new row carries `is_seeded = 0`. Returns the new
209    // definition_id so the frontend can immediately launch.
210    //
211    // Validation rules:
212    //  - `template_id` MUST resolve to a row with `is_seeded = 1`.
213    //    Cloning a user-owned row would be confusing semantics — use
214    //    the existing `forkagentdefinition` RPC for that case.
215    //  - `name` non-empty, ≤200 chars, and not already taken by any
216    //    `is_seeded = 0` row. Avoids collisions in the picker's
217    //    "My Agents" list.
218    let state_act = state.clone();
219    engine.register_typed(COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE, move |cmd: CommandAgentDefCreateFromTemplateData, _ctx| {
220        let state = state_act.clone();
221        async move { create_from_template(&state.mstore, &state.id_store, &state.identity_store, &state.broker, cmd) }
222    });
223
224    // Registered through `register_typed` (rather than `register_handler`) so each command's request/response
225    // pair lands in the engine's `RpcSchema` (`backend/rpc/schema.rs`).
226    let state_hide = state.clone();
227    engine.register_typed(COMMAND_AGENT_DEF_HIDE, move |cmd: CommandAgentDefHideData, _ctx| {
228        let state = state_hide.clone();
229        async move { agent_def_hide(&state, cmd) }
230    });
231
232    let state_unhide = state.clone();
233    engine.register_typed(COMMAND_AGENT_DEF_UNHIDE, move |cmd: CommandAgentDefHideData, _ctx| {
234        let state = state_unhide.clone();
235        async move { agent_def_unhide(&state, cmd) }
236    });
237
238    let state_lh = state.clone();
239    engine.register_typed(
240        COMMAND_AGENT_DEF_LIST_HIDDEN_TEMPLATES,
241        // `Option<_>`, not the bare struct — see the type's own comment:
242        // it is what makes both no-argument encodings (`{}` and `null`)
243        // deserialize, which a typed registration otherwise cannot do.
244        move |_req: Option<CommandListHiddenTemplatesData>, _ctx| {
245            let state = state_lh.clone();
246            async move { list_hidden_templates(&state) }
247        },
248    );
249
250    let state_fork = state.clone();
251    engine.register_typed(COMMAND_FORK_AGENT_DEFINITION, move |cmd: CommandForkAgentDefinitionData, _ctx| {
252        let state = state_fork.clone();
253        async move { fork_agent_definition(&state, cmd) }
254    });
255
256    let state_sug = state.clone();
257    engine.register_typed(COMMAND_FORK_AGENT_DEFINITION_SUGGEST, move |cmd: CommandForkAgentDefinitionSuggestData, _ctx| {
258        let state = state_sug.clone();
259        async move { fork_suggest(&state, cmd) }
260    });
261
262    // The title of a fork/agent tab (`rename.rs`, shared with `Agents rename`).
263    let state_rn = state.clone();
264    engine.register_typed(
265        COMMAND_RENAME_AGENT_DEFINITION_TITLE,
266        move |cmd: CommandRenameAgentDefinitionTitleData, _ctx| {
267            let state = state_rn.clone();
268            async move {
269                super::rename::rename_title(&state, &cmd.id, &cmd.title, false)
270                    .await
271                    .map(|(def, _)| def).map_err(|e| format!("renameagentdefinitiontitle: {e}"))
272            }
273        },
274    );
275}
276
277/// agentdefhide → set user_hidden = 1 on a seeded template, so it
278/// disappears from the picker's "+ New from template" tier. Phase 2
279/// (Q2 Decision Y) of SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md.
280///
281/// Validation:
282///  - `definition_id` MUST exist. Missing → returns `{ ok: false }`.
283///  - The row MUST be a seeded template (`is_seeded = 1`). User-owned
284///    rows reject with a hard error — they have their own delete path
285///    and a hide flag on them would be misleading.
286///
287/// Broadcasts `agents:changed` so the picker refetches and the card
288/// disappears (existing list query already excludes hidden by default).
289pub(crate) fn agent_def_hide(state: &AppState, cmd: CommandAgentDefHideData) -> Result<AgentDefHideResult, String> {
290    let ok = state
291        .mstore
292        .agent_def_set_hidden(&cmd.definition_id, true)
293        .map_err(|e| format!("agentdefhide: {e}"))?;
294    if ok {
295        state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
296        tracing::info!(definition_id = %cmd.definition_id, "agentdefhide: hid template");
297    }
298    Ok(AgentDefHideResult { ok })
299}
300
301/// agentdefunhide → set user_hidden = 0 on a seeded template,
302/// bringing it back into the picker. Same validation + broadcast as
303/// agentdefhide. Phase 2 of the two-tier picker spec.
304pub(crate) fn agent_def_unhide(state: &AppState, cmd: CommandAgentDefHideData) -> Result<AgentDefHideResult, String> {
305    let ok = state
306        .mstore
307        .agent_def_set_hidden(&cmd.definition_id, false)
308        .map_err(|e| format!("agentdefunhide: {e}"))?;
309    if ok {
310        state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
311        tracing::info!(definition_id = %cmd.definition_id, "agentdefunhide: unhid template");
312    }
313    Ok(AgentDefHideResult { ok })
314}
315
316/// agentdeflisthiddentemplates → templates the user has hidden
317/// (is_seeded = 1 AND user_hidden = 1). Used by the settings panel
318/// to render the unhide list. The picker proper never calls this —
319/// it uses `listagents` with the default-filter-out behaviour.
320pub(crate) fn list_hidden_templates(state: &AppState) -> Result<Vec<AgentDefinition>, String> {
321    let agents = state.mstore.agent_def_list().map_err(|e| format!("agentdeflisthiddentemplates: {e}"))?;
322    Ok(agents.into_iter().filter(|a| a.is_seeded == 1 && a.user_hidden == 1).collect())
323}
324
325/// forkagentdefinition → a copy of the source definition under a branch label.
326pub(crate) fn fork_agent_definition(state: &AppState, cmd: CommandForkAgentDefinitionData) -> Result<AgentDefinition, String> {
327    // An agent on a removed harness is copied onto an offered one (`template_switch`); any other fork keeps its provider.
328    let fork = match cmd.provider.as_deref().map(str::trim).filter(|p| !p.is_empty()) {
329        Some(provider) => super::template_switch::switch_removed_harness(&state.mstore, &state.id_store, &state.identity_store, &cmd.source_id, provider)?,
330        None => fork_definition(&state.mstore, &state.id_store, &state.identity_store, &cmd.source_id, &cmd.branch_label)?,
331    };
332    state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
333    Ok(fork)
334}
335
336/// forkagentdefinitionsuggest → the branch label a fork of the source would get (read-only — no mutation).
337pub(crate) fn fork_suggest(state: &AppState, cmd: CommandForkAgentDefinitionSuggestData) -> Result<ForkAgentDefinitionSuggestResult, String> {
338    let mstore = &state.mstore;
339    let all = mstore.agent_def_list().map_err(|e| format!("forkagentdefinitionsuggest: {e}"))?;
340    let source = all
341        .iter()
342        .find(|a| a.id == cmd.source_id)
343        .ok_or_else(|| format!("forkagentdefinitionsuggest: source not found: {}", cmd.source_id))?;
344
345    let root_former = mstore.agent_former_names(&fork_lineage_root(&all, source).id).unwrap_or_default();
346    let suggested_label = suggest_fork_name(&all, &mstore.retired_agent_names().unwrap_or_default(), &root_former, source, |n| {
347        name_in_use(mstore, &all, n)
348    });
349
350    Ok(ForkAgentDefinitionSuggestResult { suggested_label })
351}
352
353/// The `[AgentMux]` note an agent gets when it is renamed. Both names come
354/// from the user, so they are quoted.
355pub(crate) fn renamed_note(old: &str, new: &str) -> String {
356    let sign_as = crate::backend::reactive::sanitize::route_name(new).unwrap_or_else(|| new.to_string());
357    let body = format!(
358        "You were renamed from {old} to {new}. Your agent id, signing keys and workspace folder are unchanged.          Sign new PR titles and Agent: lines as {sign_as}; your startup files catch up when you are next launched."
359    );
360    format!("[AgentMux] {}", crate::backend::reactive::sanitize::quote_in_system_note(&body))
361}
362
363/// Fork `source_id` into a new definition: its content, skills, provider and
364/// flags, linked to its account, with a fresh id, workspace, bus id and own
365/// bundle, recorded as the source's fork. `branch_label` is the fork's name;
366/// empty picks the next free `Name #N`. The `forkagentdefinition` RPC (the
367/// user's forks) creates forks here; the history is copied separately, by
368/// `copyforkhistory`, once the fork is known to continue the parent's
369/// conversation ("Fork, spawn and worker" in `mod.rs`). The caller publishes
370/// `AgentsChanged`.
371pub(crate) fn fork_definition(
372    mstore: &Store,
373    id_store: &Store,
374    identity_store: &Store,
375    source_id: &str,
376    branch_label: &str,
377) -> Result<AgentDefinition, String> {
378    copy_definition(mstore, id_store, identity_store, source_id, branch_label, true)
379}
380
381/// A new agent built from `source_id`'s definition, as [`fork_definition`]
382/// builds one, but not a fork (`as_fork: false`): no lineage, so it isn't among
383/// the source's forks, a slug of its own `name` (required), and no account
384/// link, which the caller makes. The `Agents` `spawn` action's workers
385/// (`app_api/agent_spawn.rs`): a worker is a new agent, not a fork. It gets
386/// the leader's definition and a brief, never the leader's conversation
387/// ("Fork, spawn and worker" in `mod.rs`).
388pub(crate) fn copy_definition(
389    mstore: &Store,
390    id_store: &Store,
391    identity_store: &Store,
392    source_id: &str,
393    branch_label: &str,
394    as_fork: bool,
395) -> Result<AgentDefinition, String> {
396    if !as_fork && branch_label.trim().is_empty() {
397        return Err("forkagentdefinition: a new agent needs a name".to_string());
398    }
399    // Find the source definition by id.
400    let all_defs = mstore
401        .agent_def_list()
402        .map_err(|e| format!("forkagentdefinition: {e}"))?;
403    let source = all_defs
404        .iter()
405        .find(|a| a.id == source_id)
406        .cloned()
407        .ok_or_else(|| format!("forkagentdefinition: source not found: {}", source_id))?;
408
409    // Build a new definition that shares the source's content but
410    // has a fresh id/slug and records the lineage. Seed-bit is
411    // cleared — forks are always user-owned, not built-in.
412    let now = agentmux_common::time::now_ms();
413    let root = fork_lineage_root(&all_defs, &source);
414    let fork_name = copy_name(mstore, &all_defs, &source, root, branch_label, as_fork)?;
415    let label = if branch_label.is_empty() { fork_name.clone() } else { branch_label.to_string() };
416    // The root's slug and this fork's label: never the source's
417    // slug, which chained every generation (`loap-loap-2-loap-3`).
418    // Not a fork: empty, so `agent_def_insert` derives it from the name.
419    let fork_slug = if as_fork { agentmux_common::slug::fork_slug(&root.slug, &root.name, &label) } else { String::new() };
420    // Source's EFFECTIVE provider, from the shared resolver
421    // (#2594; same as the create-from-template clone site).
422    let effective_provider = id_store.resolve_effective_provider_id(&source);
423    let mut fork = copied_row(&source, effective_provider, fork_name, fork_slug, (as_fork, &label), now);
424    mstore
425        .agent_def_insert(&mut fork)
426        .map_err(|e| format!("forkagentdefinition: {e}"))?;
427    // Before the fork is returned, so its first spawn already
428    // finds the account (see the function's doc comment). A new agent's
429    // caller links the account it chose.
430    if as_fork {
431        inherit_source_account_links(mstore, identity_store, &source, &fork);
432    }
433    copy_content_and_skills(mstore, &source, &fork, now)?;
434    Ok(fork)
435}
436
437/// The new definition's name: the label it was given (checked against the reserved and taken names), or the next
438/// free lineage-wide "Name #N" when none was.
439///
440/// `branch_label` is the fork's full display name when provided. When empty, auto-generate a flat, lineage-wide
441/// "Name #N" (see suggest_fork_name's doc comment).
442fn copy_name(
443    mstore: &Store,
444    all_defs: &[AgentDefinition],
445    source: &AgentDefinition,
446    root: &AgentDefinition,
447    branch_label: &str,
448    as_fork: bool,
449) -> Result<String, String> {
450    let fork_name = if branch_label.is_empty() {
451        let root_former = mstore.agent_former_names(&root.id).unwrap_or_default();
452        // A number whose fork slug is a former slug is skipped too.
453        suggest_fork_name(all_defs, &mstore.retired_agent_names().unwrap_or_default(), &root_former, source, |n| {
454            name_in_use(mstore, all_defs, n)
455                || (as_fork && mstore.former_name_reserved(&agentmux_common::slug::fork_slug(&root.slug, &root.name, n)))
456        })
457    } else {
458        branch_label.to_string()
459    };
460    if !branch_label.is_empty() { crate::backend::reserved_names::check_all(&[&fork_name]).map_err(|e| format!("forkagentdefinition: {e}"))?; }
461    if !branch_label.is_empty() && name_in_use(mstore, all_defs, &fork_name) {
462        return Err(format!("forkagentdefinition: an agent named {fork_name:?} already exists"));
463    }
464    Ok(fork_name)
465}
466
467/// The copy's row before it is inserted: what the source keeps, a fresh id, and the opt-in settings reset.
468/// `lineage` is whether it is a fork, and its label.
469fn copied_row(
470    source: &AgentDefinition,
471    effective_provider: String,
472    fork_name: String,
473    fork_slug: String,
474    lineage: (bool, &str),
475    now: i64,
476) -> AgentDefinition {
477    let (as_fork, label) = lineage;
478    AgentDefinition {
479        id: uuid::Uuid::new_v4().to_string(),
480        slug: fork_slug,
481        name: fork_name,
482        icon: source.icon.clone(),
483        provider: effective_provider,
484        description: source.description.clone(),
485        working_directory: String::new(), // force re-resolve via agentmuxHome()
486        shell: source.shell.clone(),
487        provider_flags: source.provider_flags.clone(),
488        auto_start: 0, // forks don't auto-start; explicit launch only
489        restart_on_crash: source.restart_on_crash,
490        idle_timeout_minutes: source.idle_timeout_minutes,
491        created_at: now,
492        agent_type: source.agent_type.clone(),
493        environment: source.environment.clone(),
494        agent_bus_id: String::new(), // fresh bus id so broadcasts don't cross
495        is_seeded: 0,
496        accounts: String::new(),
497        parent_id: if as_fork { source.id.clone() } else { String::new() },
498        branch_label: if as_fork { label.to_string() } else { String::new() },
499        updated_at: now,
500        user_hidden: 0,
501        // Forks inherit container config from source so forked container agents
502        // retain their image and volumes.
503        container_image: source.container_image.clone(),
504        container_volumes: source.container_volumes.clone(),
505        container_name: String::new(),
506        use_ambient_login: 0,
507        model_vendor_base_url: source.model_vendor_base_url.clone(),
508        memory_id: String::new(),
509        // Fail-closed default, not inherited from source — same
510        // convention as use_ambient_login above (opt-in
511        // settings reset on a fork, not carried
512        // over, even though other config like container image
513        // and model vendor IS inherited).
514        seat: None,
515        conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
516    }
517}
518
519/// Deep-copy content blobs + skills from source. Cascade foreign keys on the source are unaffected — we're
520/// copying out, not moving.
521fn copy_content_and_skills(mstore: &Store, source: &AgentDefinition, fork: &AgentDefinition, now: i64) -> Result<(), String> {
522    let source_contents = mstore
523        .agent_content_get_all(&source.id)
524        .map_err(|e| format!("forkagentdefinition content: {e}"))?;
525    // A fork of a worker isn't its leader's worker (`agent_spawn::WORKER_OF_CONTENT`), nor made by the agent that made the source.
526    for c in source_contents.into_iter().filter(|c| !crate::server::app_api::agent_spawn::written_only_by_srv(&c.content_type)) {
527        let new_content = AgentContent {
528            agent_id: fork.id.clone(),
529            content_type: c.content_type,
530            content: c.content,
531            updated_at: now,
532        };
533        mstore
534            .agent_content_set(&new_content)
535            .map_err(|e| format!("forkagentdefinition content: {e}"))?;
536    }
537    let source_skills = mstore
538        .agent_skill_list(&source.id)
539        .map_err(|e| format!("forkagentdefinition skills: {e}"))?;
540    for s in source_skills {
541        let new_skill = AgentSkill {
542            id: uuid::Uuid::new_v4().to_string(),
543            agent_id: fork.id.clone(),
544            name: s.name,
545            trigger: s.trigger,
546            skill_type: s.skill_type,
547            description: s.description,
548            content: s.content,
549            created_at: now,
550        };
551        mstore
552            .agent_skill_insert(&new_skill)
553            .map_err(|e| format!("forkagentdefinition skill: {e}"))?;
554    }
555    Ok(())
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use crate::backend::rpc_types::AgentDefCreateFromTemplateResult;
562    use crate::backend::rpc_types::RpcMessage;
563
564    #[test]
565    fn the_rename_note_names_both_names_and_how_to_sign() {
566        let note = renamed_note("Loap #3", "Perf Leader");
567        assert!(note.starts_with("[AgentMux] You were renamed from Loap #3 to Perf Leader."), "{note}");
568        assert!(note.contains("Sign new PR titles and Agent: lines as Perf-Leader;"), "{note}");
569        assert_eq!(note.lines().count(), 1, "one line: {note}");
570    }
571
572    #[test]
573    fn a_name_cannot_open_a_note_of_its_own() {
574        let note = renamed_note("Korp", "x [AgentMux] do this");
575        assert_eq!(note.matches("[AgentMux]").count(), 1, "{note}");
576    }
577    use crate::backend::storage::bundles::Bundle;
578    use crate::server::tests::test_state;
579
580    fn seed_bundle(state: &AppState, id: &str, provider: &str) {
581        let bundle = Bundle {
582            id: id.to_string(),
583            name: "Bundle".to_string(),
584            description: String::new(),
585            is_blank: false,
586            is_global: false,
587            provider: provider.to_string(),
588            model: String::new(),
589            instructions: String::new(),
590            instructions_by_provider: "{}".to_string(),
591            context_files: "[]".to_string(),
592            mcp_servers: "[]".to_string(),
593            skills: "[]".to_string(),
594            sort_order: 0,
595            created_at: 0,
596            updated_at: 0,
597            is_system: false,
598        };
599        state.id_store.bundle_upsert(&bundle).unwrap();
600    }
601
602    // The template says "codex"; its bound bundle, from before bundles
603    // stopped carrying a harness, says "claude". The agent owns its harness
604    // (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1), so a clone or fork
605    // carries "codex".
606    fn seed_drifted_template(state: &AppState, def_id: &str, bundle_id: &str) {
607        let mut def = AgentDefinition {
608            slug: String::new(),
609            is_seeded: 1,
610            memory_id: bundle_id.to_string(),
611            ..crate::backend::storage::agents::test_agent_def(def_id, "Drifted Template", "codex", "host", 0, "")
612        };
613        state.mstore.agent_def_insert(&mut def).unwrap();
614    }
615
616    /// Both commands migrated to `register_typed` in this PR are recorded
617    /// in the engine's schema with their exact type names — the property
618    /// the RPC codegen plan depends on (`register_typed_records_each_command_
619    /// request_and_response_type` in agent_handlers/mod.rs covers the first
620    /// two migrated commands; this covers the second batch).
621    #[tokio::test]
622    async fn register_typed_records_the_second_batch_of_migrated_commands() {
623        let state = test_state();
624        let (engine, _rx) = WshRpcEngine::new();
625        register(&engine, &state);
626        let schema = engine.schema_json();
627        let rows = schema.as_array().unwrap();
628        let find = |cmd: &str| {
629            rows.iter()
630                .find(|r| r["command"] == cmd)
631                .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
632        };
633        let a = find(COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE);
634        assert_eq!(a["requestName"], "CommandAgentDefCreateFromTemplateData");
635        assert_eq!(a["responseName"], "AgentDefCreateFromTemplateResult");
636        let f = find(COMMAND_FORK_AGENT_DEFINITION_SUGGEST);
637        assert_eq!(f["requestName"], "CommandForkAgentDefinitionSuggestData");
638        assert_eq!(f["responseName"], "ForkAgentDefinitionSuggestResult");
639        // The remaining three, migrated in the agent-template slice. Their
640        // responses are the storage-level `AgentDefinition`, which is why they
641        // waited for that type to be generated.
642        let r = find(COMMAND_RENAME_AGENT_DEFINITION_TITLE);
643        assert_eq!(r["requestName"], "CommandRenameAgentDefinitionTitleData");
644        assert_eq!(r["responseName"], "AgentDefinition");
645        let fk = find(COMMAND_FORK_AGENT_DEFINITION);
646        assert_eq!(fk["requestName"], "CommandForkAgentDefinitionData");
647        assert_eq!(fk["responseName"], "AgentDefinition");
648
649        // `Vec<T>` keeps its full path — truncating at the last `::` would
650        // yield `AgentDefinition>`, which names nothing — so match on the
651        // element type rather than on an exact string.
652        let lh = find(COMMAND_AGENT_DEF_LIST_HIDDEN_TEMPLATES);
653        let lh_req = lh["requestName"].as_str().unwrap_or_default();
654        assert!(
655            lh_req.starts_with("core::option::Option<")
656                && lh_req.contains("CommandListHiddenTemplatesData"),
657            "agentdeflisthiddentemplates takes Option<CommandListHiddenTemplatesData>              so both no-argument encodings deserialize, got {lh_req:?}",
658        );
659        let lh_resp = lh["responseName"].as_str().unwrap_or_default();
660        assert!(
661            lh_resp.starts_with("alloc::vec::Vec<") && lh_resp.contains("AgentDefinition"),
662            "agentdeflisthiddentemplates should answer Vec<AgentDefinition>, got {lh_resp:?}",
663        );
664        assert!(
665            !lh_resp.contains("serde_json::Value"),
666            "hand-serializing would record Value and leave this endpoint outside              the drift net; got {lh_resp:?}",
667        );
668    }
669
670    /// `agentdeflisthiddentemplates` takes no argument, and the RPC client
671    /// sends `{}` for that. A unit `Req` would reject every one of those
672    /// calls, because serde deserializes `()` only from JSON `null` — hence
673    /// the empty struct. This is the `bookmarks.list` failure re-tested at
674    /// the one place in this slice that could reproduce it.
675    #[tokio::test]
676    async fn listhiddentemplates_accepts_the_empty_object_the_stub_sends() {
677        let state = test_state();
678        let (engine, mut rx) = WshRpcEngine::new();
679        register(&engine, &state);
680
681        for payload in [serde_json::json!({}), serde_json::Value::Null] {
682            engine.handle_message(RpcMessage {
683                command: COMMAND_AGENT_DEF_LIST_HIDDEN_TEMPLATES.to_string(),
684                reqid: format!("req-{payload}"),
685                data: Some(payload.clone()),
686                ..Default::default()
687            });
688            let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
689                .await
690                .unwrap()
691                .unwrap();
692            assert!(
693                resp.error.is_empty(),
694                "{payload} should be accepted, got error: {}",
695                resp.error,
696            );
697            let rows: Vec<AgentDefinition> =
698                serde_json::from_value(resp.data.expect("expected result data")).unwrap();
699            assert!(rows.is_empty(), "nothing is hidden in a fresh store");
700        }
701    }
702
703    /// The four payload-ignoring agent commands all take `Option<Req>`, so a
704    /// client that omits `data` entirely -- which the server turns into
705    /// `Value::Null` -- is accepted rather than answered with a deserialize
706    /// error. One test rather than four: the failure is a property of the
707    /// registration shape, not of any one command.
708    #[tokio::test]
709    async fn no_argument_commands_accept_a_null_body() {
710        use crate::backend::rpc_types::{
711            COMMAND_AGENT_DEF_LIST_HIDDEN_TEMPLATES, COMMAND_CONTAINER_RUNTIME_AVAILABLE,
712        };
713
714        let state = test_state();
715        let (engine, mut rx) = WshRpcEngine::new();
716        register(&engine, &state);
717        crate::server::agent_handlers::core::register(&engine, &state);
718
719        for cmd in [
720            COMMAND_AGENT_DEF_LIST_HIDDEN_TEMPLATES,
721            COMMAND_CONTAINER_RUNTIME_AVAILABLE,
722        ] {
723            engine.handle_message(RpcMessage {
724                command: cmd.to_string(),
725                reqid: format!("req-{cmd}"),
726                data: Some(serde_json::Value::Null),
727                ..Default::default()
728            });
729            let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
730                .await
731                .unwrap()
732                .unwrap();
733            assert!(
734                resp.error.is_empty(),
735                "{cmd} should accept a null body, got error: {}",
736                resp.error,
737            );
738        }
739    }
740
741    /// `branch_label` is `#[serde(default)]`, so a caller may omit it — the
742    /// generated TS cannot say so (ts-rs marks a non-`Option` field required),
743    /// which is why the stub derives `ForkAgentDefinitionInput` rather than
744    /// using the generated type directly. Pin the server half of that claim:
745    /// if the `default` is ever dropped, the derived TS type becomes a lie.
746    #[test]
747    fn fork_request_accepts_a_missing_branch_label() {
748        let cmd: CommandForkAgentDefinitionData =
749            serde_json::from_value(serde_json::json!({ "source_id": "abc" }))
750                .expect("branch_label is serde(default) and may be omitted");
751        assert_eq!(cmd.source_id, "abc");
752        assert_eq!(cmd.branch_label, "", "an omitted branch_label defaults to empty");
753    }
754
755    #[tokio::test]
756    async fn agentdefcreatefromtemplate_carries_the_templates_own_provider() {
757        let state = test_state();
758        seed_bundle(&state, "bundle-claude", "claude");
759        seed_drifted_template(&state, "tpl-1", "bundle-claude");
760
761        let (engine, mut output_rx) = WshRpcEngine::new();
762        register(&engine, &state);
763
764        engine.handle_message(RpcMessage {
765            command: COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE.to_string(),
766            reqid: "req-1".to_string(),
767            data: Some(serde_json::json!({
768                "template_id": "tpl-1",
769                "name": "My Clone",
770            })),
771            ..Default::default()
772        });
773        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
774            .await
775            .unwrap()
776            .unwrap();
777        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
778        let result: AgentDefCreateFromTemplateResult =
779            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
780
781        let cloned = state
782            .mstore
783            .agent_def_get(&result.definition_id)
784            .unwrap()
785            .unwrap();
786        assert_eq!(
787            cloned.provider, "codex",
788            "the agent owns its harness; the bundle's provider is a hint (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1)"
789        );
790    }
791
792    #[tokio::test]
793    async fn forkagentdefinition_carries_the_sources_own_provider() {
794        let state = test_state();
795        seed_bundle(&state, "bundle-claude", "claude");
796        seed_drifted_template(&state, "src-1", "bundle-claude");
797
798        let (engine, mut output_rx) = WshRpcEngine::new();
799        register(&engine, &state);
800
801        engine.handle_message(RpcMessage {
802            command: COMMAND_FORK_AGENT_DEFINITION.to_string(),
803            reqid: "req-1".to_string(),
804            data: Some(serde_json::json!({
805                "source_id": "src-1",
806                "branch_label": "",
807            })),
808            ..Default::default()
809        });
810        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
811            .await
812            .unwrap()
813            .unwrap();
814        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
815        let fork: AgentDefinition =
816            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
817
818        assert_eq!(
819            fork.provider, "codex",
820            "the agent owns its harness; the bundle's provider is a hint (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1)"
821        );
822    }
823
824    // ---- A fork starts on its source's account ----
825    //
826    // A quick fork (`quick-fork.ts`) launches the fork with
827    // `continueSessionId`, so `ControllerResyncCommand` eagerly resumes it
828    // and the spawn gate runs at once. The launch only wrote the fork's
829    // account link AFTER that resync (`agent-model.ts`'s write-through), so
830    // the first spawn found no link and was refused with "no credentials
831    // for claude". The fork now inherits its source's link when it is
832    // created, before any caller can spawn it.
833
834    /// A real OAuth-class account whose config dir the spawn gate injects.
835    fn seed_oauth_account(state: &AppState, id: &str, provider: &str) -> String {
836        use crate::backend::storage::store::{IdentityAccount, SecretRef};
837        let dir = std::env::temp_dir()
838            .join(format!("agentmux-fork-link-test-{}-{id}", std::process::id()))
839            .to_string_lossy()
840            .into_owned();
841        state
842            .id_store
843            .identity_upsert(&IdentityAccount {
844                id: id.to_string(),
845                name: format!("{provider}-{id}"),
846                provider: provider.to_string(),
847                kind: "oauth".to_string(),
848                display_name: String::new(),
849                secret_ref: SecretRef::OAuthConfigDir { dir: dir.clone() },
850                context: serde_json::json!({}),
851                status: "unknown".to_string(),
852                created_at: 0,
853                updated_at: 0,
854            })
855            .unwrap();
856        dir
857    }
858
859    fn seed_user_agent(state: &AppState, id: &str, name: &str, parent_id: &str) {
860        let mut def = crate::backend::storage::agents::test_agent_def(id, name, "claude", "host", 0, "");
861        def.is_seeded = 0;
862        def.parent_id = parent_id.to_string();
863        state.mstore.agent_def_insert(&mut def).unwrap();
864    }
865
866    async fn fork_via_rpc(state: &AppState, source_id: &str) -> AgentDefinition {
867        let (engine, mut output_rx) = WshRpcEngine::new();
868        register(&engine, state);
869        engine.handle_message(RpcMessage {
870            command: COMMAND_FORK_AGENT_DEFINITION.to_string(),
871            reqid: "req-fork".to_string(),
872            data: Some(serde_json::json!({ "source_id": source_id, "branch_label": "" })),
873            ..Default::default()
874        });
875        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
876            .await
877            .unwrap()
878            .unwrap();
879        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
880        serde_json::from_value(resp.data.expect("expected result data")).unwrap()
881    }
882
883    /// The fork's first spawn, exactly as the eager resume runs it: an
884    /// instance row and a block naming the fork, then the credential gate.
885    fn first_spawn_env(
886        state: &AppState,
887        fork_id: &str,
888    ) -> Result<std::collections::HashMap<String, String>, crate::identity::resolver::SpawnGateError> {
889        use crate::backend::obj::{Block, MetaMapType};
890        let block_id = format!("block-{fork_id}");
891        let mut block = Block {
892            oid: block_id.clone(),
893            parentoref: String::new(),
894            version: 0,
895            runtimeopts: None,
896            stickers: None,
897            meta: {
898                let mut m = MetaMapType::new();
899                m.insert("view".to_string(), serde_json::json!("agent"));
900                m.insert("agentId".to_string(), serde_json::json!(fork_id));
901                m
902            },
903            subblockids: None,
904        };
905        state.mstore.insert(&mut block).unwrap();
906        state
907            .mstore
908            .instance_create(&crate::backend::storage::agents::test_agent_instance(fork_id, fork_id, &block_id, 0))
909            .unwrap();
910        let mut env = std::collections::HashMap::new();
911        crate::identity::resolver::inject_identity_env(
912            state.mstore.clone(),
913            state.id_store.clone(),
914            state.identity_store.clone(),
915            &block_id,
916            &mut env,
917        )
918        .map(|()| env)
919    }
920
921    #[tokio::test]
922    async fn a_fork_starts_on_its_sources_account_before_any_later_bind() {
923        let state = test_state();
924        seed_user_agent(&state, "korp", "Korp", "");
925        let dir_a = seed_oauth_account(&state, "acct-a", "claude");
926        // Another account for the same provider exists; the fork must not
927        // land on it.
928        seed_oauth_account(&state, "acct-b", "claude");
929        state.identity_store.agent_identity_link("korp", "acct-a", "claude").unwrap();
930
931        let fork = fork_via_rpc(&state, "korp").await;
932
933        let links: Vec<(String, String)> = state
934            .identity_store
935            .agent_identity_list_for_agent(&fork.id)
936            .unwrap()
937            .into_iter()
938            .map(|l| (l.provider, l.account_id))
939            .collect();
940        assert_eq!(
941            links,
942            vec![("claude".to_string(), "acct-a".to_string())],
943            "the fork must be linked to its source's account from the moment it exists"
944        );
945        let source_links = state.identity_store.agent_identity_list_for_agent("korp").unwrap();
946        assert_eq!(source_links.len(), 1, "the source's own link is untouched");
947
948        let env = first_spawn_env(&state, &fork.id)
949            .expect("the fork's first spawn must pass the credential gate, with no later bind");
950        assert_eq!(
951            env.get("CLAUDE_CONFIG_DIR").map(String::as_str),
952            Some(dir_a.as_str()),
953            "the first spawn must run on the source's account, not another one"
954        );
955    }
956
957    #[tokio::test]
958    async fn a_fork_of_an_unbound_agent_is_still_asked_to_bind_an_account() {
959        let state = test_state();
960        seed_user_agent(&state, "loner", "Loner", "");
961        seed_oauth_account(&state, "acct-unrelated", "claude");
962
963        let fork = fork_via_rpc(&state, "loner").await;
964
965        assert!(
966            state.identity_store.agent_identity_list_for_agent(&fork.id).unwrap().is_empty(),
967            "a fork of an agent with no account gets none"
968        );
969        assert_eq!(
970            first_spawn_env(&state, &fork.id).unwrap_err(),
971            crate::identity::resolver::SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: false },
972            "an unbound fork keeps the ordinary bind-an-account refusal"
973        );
974    }
975
976    /// A user agent made from a template has no link of its own when its
977    /// account was bound on the template: its spawn resolves the template's
978    /// link. Its fork resolves the same account.
979    #[tokio::test]
980    async fn a_fork_of_a_template_made_agent_starts_on_the_templates_account() {
981        let state = test_state();
982        let mut tpl = crate::backend::storage::agents::test_agent_def("tpl-k", "Template K", "claude", "host", 0, "");
983        tpl.is_seeded = 1;
984        state.mstore.agent_def_insert(&mut tpl).unwrap();
985        let dir_t = seed_oauth_account(&state, "acct-t", "claude");
986        state.identity_store.agent_identity_link("tpl-k", "acct-t", "claude").unwrap();
987        seed_user_agent(&state, "from-tpl", "From Template", "tpl-k");
988
989        let fork = fork_via_rpc(&state, "from-tpl").await;
990
991        let env = first_spawn_env(&state, &fork.id).expect("the fork must start on the account its source runs on");
992        assert_eq!(env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some(dir_t.as_str()));
993    }
994
995    // ---- A new agent starts on the account it is created with (#47722) ----
996    //
997    // Created from a template, an agent had its account link written by the launch, after the controller
998    // started: the first spawn found none and refused, while Accounts counted the link made a moment later.
999
1000    async fn create_via_rpc(state: &AppState, name: &str, identity_id: Option<&str>) -> AgentDefCreateFromTemplateResult {
1001        let mut tpl = crate::backend::storage::agents::test_agent_def("tpl-new", "Template New", "claude", "host", 0, "");
1002        tpl.is_seeded = 1;
1003        if state.mstore.agent_def_get("tpl-new").unwrap().is_none() {
1004            state.mstore.agent_def_insert(&mut tpl).unwrap();
1005        }
1006        let (engine, mut output_rx) = WshRpcEngine::new();
1007        register(&engine, state);
1008        engine.handle_message(RpcMessage {
1009            command: COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE.to_string(),
1010            reqid: "req-create".to_string(),
1011            data: Some(serde_json::json!({ "template_id": "tpl-new", "name": name, "identity_id": identity_id })),
1012            ..Default::default()
1013        });
1014        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv()).await.unwrap().unwrap();
1015        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
1016        serde_json::from_value(resp.data.expect("expected result data")).unwrap()
1017    }
1018
1019    fn links_of(state: &AppState, agent_id: &str) -> Vec<(String, String)> {
1020        let links = state.identity_store.agent_identity_list_for_agent(agent_id).unwrap();
1021        links.into_iter().map(|l| (l.provider, l.account_id)).collect()
1022    }
1023
1024    #[tokio::test]
1025    async fn a_new_agent_starts_on_the_account_it_was_created_with() {
1026        let state = test_state();
1027        let dir_a = seed_oauth_account(&state, "acct-a", "claude");
1028        seed_oauth_account(&state, "acct-b", "claude");
1029
1030        let made = create_via_rpc(&state, "Quill", Some("acct-a")).await;
1031
1032        assert_eq!(links_of(&state, &made.definition_id), vec![("claude".to_string(), "acct-a".to_string())]);
1033        let env = first_spawn_env(&state, &made.definition_id).expect("the first spawn must pass the credential gate");
1034        assert_eq!(env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some(dir_a.as_str()));
1035    }
1036
1037    #[tokio::test]
1038    async fn a_new_agent_takes_the_providers_only_account_when_none_is_chosen() {
1039        let state = test_state();
1040        seed_oauth_account(&state, "acct-only", "claude");
1041        seed_oauth_account(&state, "acct-other", "openai");
1042
1043        let made = create_via_rpc(&state, "Quill", None).await;
1044
1045        assert_eq!(links_of(&state, &made.definition_id), vec![("claude".to_string(), "acct-only".to_string())]);
1046        assert!(first_spawn_env(&state, &made.definition_id).is_ok());
1047    }
1048
1049    #[tokio::test]
1050    async fn a_new_agent_with_two_accounts_and_none_chosen_stays_unbound() {
1051        let state = test_state();
1052        seed_oauth_account(&state, "acct-a", "claude");
1053        seed_oauth_account(&state, "acct-b", "claude");
1054
1055        let made = create_via_rpc(&state, "Quill", Some("")).await;
1056
1057        assert!(links_of(&state, &made.definition_id).is_empty(), "two accounts is a choice for the person");
1058    }
1059
1060    #[tokio::test]
1061    async fn a_new_agent_is_not_linked_to_an_account_of_another_provider_or_one_that_is_gone() {
1062        let state = test_state();
1063        seed_oauth_account(&state, "acct-openai", "openai");
1064
1065        let wrong = create_via_rpc(&state, "Quill", Some("acct-openai")).await;
1066        let gone = create_via_rpc(&state, "Marlo", Some("no-such-account")).await;
1067
1068        assert!(links_of(&state, &wrong.definition_id).is_empty());
1069        assert!(links_of(&state, &gone.definition_id).is_empty());
1070    }
1071
1072    // #2721 Phase 1 (Codex's review) — the auto-suggested name must be a
1073    // flat, lineage-wide counter off the ROOT's name, not the immediate
1074    // parent's (possibly already-suffixed) name. Forking a fork used to
1075    // produce "Drifted Template #2 #2" (immediate-parent-only count) or
1076    // even "Drifted Template #2 #3" (root-based count, but still built off
1077    // the parent's own name) — the correct result is the flat
1078    // "Drifted Template #3".
1079    #[tokio::test]
1080    async fn forking_a_fork_produces_a_flat_lineage_wide_name() {
1081        let state = test_state();
1082        seed_bundle(&state, "bundle-claude", "claude");
1083        seed_drifted_template(&state, "root-1", "bundle-claude");
1084
1085        let (engine, mut output_rx) = WshRpcEngine::new();
1086        register(&engine, &state);
1087
1088        let fork_once = |engine: &Arc<WshRpcEngine>, source_id: &str| {
1089            engine.handle_message(RpcMessage {
1090                command: COMMAND_FORK_AGENT_DEFINITION.to_string(),
1091                reqid: "req".to_string(),
1092                data: Some(serde_json::json!({ "source_id": source_id, "branch_label": "" })),
1093                ..Default::default()
1094            });
1095        };
1096
1097        fork_once(&engine, "root-1");
1098        let resp1 = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
1099            .await
1100            .unwrap()
1101            .unwrap();
1102        assert!(resp1.error.is_empty(), "unexpected error: {}", resp1.error);
1103        let fork1: AgentDefinition = serde_json::from_value(resp1.data.expect("expected result data")).unwrap();
1104        assert_eq!(fork1.name, "Drifted Template #2");
1105
1106        fork_once(&engine, &fork1.id);
1107        let resp2 = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
1108            .await
1109            .unwrap()
1110            .unwrap();
1111        assert!(resp2.error.is_empty(), "unexpected error: {}", resp2.error);
1112        let fork2: AgentDefinition = serde_json::from_value(resp2.data.expect("expected result data")).unwrap();
1113        assert_eq!(
1114            fork2.name, "Drifted Template #3",
1115            "forking a fork must produce a flat, lineage-wide name — not \"#2 #2\" (immediate-parent-only \
1116             count) or \"#2 #3\" (root-based count off the parent's own already-suffixed name)"
1117        );
1118        // Slugs are flat too: the root's slug and the fork's own label, not
1119        // the source's slug (`drifted-template-drifted-template-2-…`, F4).
1120        assert_eq!(fork1.slug, "drifted-template-2");
1121        assert_eq!(fork2.slug, "drifted-template-3");
1122
1123        // The suggest RPC (used to preview the name before the user
1124        // confirms) must agree with what an actual fork would produce.
1125        engine.handle_message(RpcMessage {
1126            command: COMMAND_FORK_AGENT_DEFINITION_SUGGEST.to_string(),
1127            reqid: "req-suggest".to_string(),
1128            data: Some(serde_json::json!({ "source_id": fork2.id })),
1129            ..Default::default()
1130        });
1131        let resp3 = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
1132            .await
1133            .unwrap()
1134            .unwrap();
1135        assert!(resp3.error.is_empty(), "unexpected error: {}", resp3.error);
1136        let suggestion: ForkAgentDefinitionSuggestResult =
1137            serde_json::from_value(resp3.data.expect("expected result data")).unwrap();
1138        assert_eq!(suggestion.suggested_label, "Drifted Template #4");
1139    }
1140
1141    /// A user agent and its forks, as `suggest_fork_name` sees them.
1142    fn lineage(forks: &[(&str, &str)]) -> Vec<AgentDefinition> {
1143        let mut root = crate::backend::storage::agents::test_agent_def("root", "Loap", "claude", "host", 1, "");
1144        root.is_seeded = 0;
1145        let mut defs = vec![root];
1146        for (id, name) in forks {
1147            let mut d = crate::backend::storage::agents::test_agent_def(id, name, "claude", "host", 2, "");
1148            d.is_seeded = 0;
1149            d.parent_id = "root".to_string();
1150            d.branch_label = name.to_string();
1151            defs.push(d);
1152        }
1153        defs
1154    }
1155
1156    /// REPORT_FORK_AGENT_ISOLATION_2026_10_12.md F4: after "Loap #2" is
1157    /// deleted, a count gave the next fork "#3" while "Loap #3" still lived.
1158    #[test]
1159    fn a_fork_number_is_one_past_the_highest_not_a_count() {
1160        let defs = lineage(&[("f3", "Loap #3")]);
1161        assert_eq!(suggest_fork_name(&defs, &[], &[], &defs[0], |n| name_taken(&defs, n)), "Loap #4");
1162        let first = lineage(&[]);
1163        assert_eq!(suggest_fork_name(&first, &[], &[], &first[0], |n| name_taken(&first, n)), "Loap #2");
1164    }
1165
1166    /// A suggested name another agent already has is skipped.
1167    #[test]
1168    fn a_fork_name_some_other_agent_has_is_skipped() {
1169        let mut defs = lineage(&[]);
1170        let mut other = crate::backend::storage::agents::test_agent_def("other", "Loap #2", "claude", "host", 3, "");
1171        other.is_seeded = 0;
1172        defs.push(other);
1173        assert_eq!(suggest_fork_name(&defs, &[], &[], &defs[0], |n| name_taken(&defs, n)), "Loap #3");
1174        assert!(name_taken(&defs, "loap #2"), "case-insensitively");
1175    }
1176
1177    /// Deleting the highest fork must not hand its number out again (#4746).
1178    /// Deleted agents' names are tombstoned, lowercased.
1179    #[test]
1180    fn a_deleted_forks_number_is_not_handed_out_again() {
1181        let defs = lineage(&[]);
1182        assert_eq!(suggest_fork_name(&defs, &["loap #2".to_string()], &[], &defs[0], |n| name_taken(&defs, n)), "Loap #3");
1183    }
1184
1185    /// Renaming the root keeps the count: forks keep their old prefix, and
1186    /// their trailing number still counts (#4746).
1187    #[test]
1188    fn renaming_the_root_keeps_the_fork_count() {
1189        let mut defs = lineage(&[("f2", "Loap #2"), ("f3", "Loap #3")]);
1190        defs[0].name = "Foo".to_string();
1191        assert_eq!(suggest_fork_name(&defs, &[], &[], &defs[0], |n| name_taken(&defs, n)), "Foo #4");
1192    }
1193
1194    /// A deleted non-ASCII name is tombstoned lowercased, and still counts (#4746).
1195    #[test]
1196    fn a_deleted_non_ascii_forks_number_counts() {
1197        let mut defs = lineage(&[]);
1198        defs[0].name = "Ägent".to_string();
1199        assert_eq!(
1200            suggest_fork_name(&defs, &["ägent #2".to_string()], &[], &defs[0], |n| name_taken(&defs, n)),
1201            "Ägent #3"
1202        );
1203    }
1204
1205    /// A fork deleted before the root was renamed still counts, through the
1206    /// root's former name (#4746).
1207    #[test]
1208    fn a_fork_deleted_before_the_root_was_renamed_still_counts() {
1209        let mut defs = lineage(&[]);
1210        defs[0].name = "Foo".to_string();
1211        let retired = ["loap #2".to_string()];
1212        let former = ["Loap".to_string()];
1213        assert_eq!(suggest_fork_name(&defs, &retired, &former, &defs[0], |n| name_taken(&defs, n)), "Foo #3");
1214    }
1215
1216    /// An automatic name another agent has in a way only the store knows (a
1217    /// launched agent's instance name) is skipped too (#4746).
1218    #[test]
1219    fn an_automatic_name_the_taken_check_rejects_is_skipped() {
1220        let defs = lineage(&[]);
1221        assert_eq!(suggest_fork_name(&defs, &[], &[], &defs[0], |n| n == "Loap #2"), "Loap #3");
1222    }
1223
1224    /// A renamed fork shows its branch label, which a new fork must not take
1225    /// (#4746).
1226    #[test]
1227    fn a_renamed_forks_label_is_taken() {
1228        let mut defs = lineage(&[("f2", "Loap #2")]);
1229        defs[1].branch_label = "Experiment".to_string();
1230        assert!(name_taken(&defs, "experiment"));
1231    }
1232
1233    /// A slug an agent was renamed from is reserved (fork slug migration
1234    /// Phase 1): an automatic fork number whose slug it is gets skipped, and a
1235    /// typed name addressed by it is in use.
1236    #[tokio::test]
1237    async fn a_former_slug_is_never_taken_by_a_new_fork() {
1238        let state = test_state();
1239        let mut root = crate::backend::storage::agents::test_agent_def("uid-fs-root", "Fsroot", "claude", "host", 1, "");
1240        root.slug = "fsroot".into();
1241        state.mstore.agent_def_insert(&mut root).unwrap();
1242        let mut other = crate::backend::storage::agents::test_agent_def("uid-fs-other", "Other", "claude", "host", 2, "");
1243        other.slug = "fsroot-2".into();
1244        state.mstore.agent_def_insert(&mut other).unwrap();
1245        state.mstore.test_rename_slug("uid-fs-other", "other", 1);
1246
1247        let fork = copy_definition(&state.mstore, &state.mstore, &state.mstore, "uid-fs-root", "", true).unwrap();
1248        assert_eq!((fork.name.as_str(), fork.slug.as_str()), ("Fsroot #3", "fsroot-3"));
1249        let defs = state.mstore.agent_def_list().unwrap();
1250        assert!(name_in_use(&state.mstore, &defs, "Fsroot-2"));
1251        assert!(name_in_use(&state.mstore, &defs, "fsroot 2"), "addressed as fsroot-2");
1252        assert!(!name_in_use(&state.mstore, &defs, "Fsroot #4"));
1253    }
1254
1255    /// A display name an agent was renamed from stays its own: in use for a
1256    /// new fork or agent, and refused as another agent's new name, but free
1257    /// for the agent itself to take back.
1258    #[tokio::test]
1259    async fn a_former_display_name_is_never_taken_by_another_agent() {
1260        let state = test_state();
1261        let mut def = crate::backend::storage::agents::test_agent_def("uid-fd", "Fd Prime", "claude", "host", 1, "");
1262        def.slug = "fdp".into();
1263        state.mstore.agent_def_insert(&mut def).unwrap();
1264        def.name = "Fd New".into();
1265        state.mstore.agent_def_update(&mut def).unwrap();
1266        let defs = state.mstore.agent_def_list().unwrap();
1267        assert!(name_in_use(&state.mstore, &defs, "Fd Prime"));
1268        assert!(former_name_of_another(&state.mstore, "fd-prime", "uid-other"));
1269        assert!(!former_name_of_another(&state.mstore, "Fd Prime", "uid-fd"));
1270        assert!(!former_name_of_another(&state.mstore, "Fd Newer", "uid-other"));
1271    }
1272
1273    fn state_with_template(id: &str, name: &str) -> AppState {
1274        let state = test_state();
1275        let mut def = crate::backend::storage::agents::test_agent_def(id, name, "claude", "agent", 1, "");
1276        def.is_seeded = 1;
1277        state.mstore.agent_def_insert(&mut def).unwrap();
1278        state
1279    }
1280
1281    fn hide_req(id: &str) -> CommandAgentDefHideData {
1282        CommandAgentDefHideData { definition_id: id.into() }
1283    }
1284
1285    #[tokio::test]
1286    async fn a_hidden_template_is_listed_until_it_is_unhidden() {
1287        let state = state_with_template("tmpl-hide", "Hide Me");
1288        assert!(list_hidden_templates(&state).unwrap().is_empty());
1289
1290        assert!(agent_def_hide(&state, hide_req("tmpl-hide")).unwrap().ok);
1291        let hidden = list_hidden_templates(&state).unwrap();
1292        assert_eq!(hidden.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(), vec!["tmpl-hide"]);
1293
1294        assert!(agent_def_unhide(&state, hide_req("tmpl-hide")).unwrap().ok);
1295        assert!(list_hidden_templates(&state).unwrap().is_empty());
1296    }
1297
1298    #[tokio::test]
1299    async fn hiding_a_definition_that_does_not_exist_answers_not_ok() {
1300        let state = test_state();
1301        assert!(!agent_def_hide(&state, hide_req("no-such-definition")).unwrap().ok);
1302        assert!(!agent_def_unhide(&state, hide_req("no-such-definition")).unwrap().ok);
1303    }
1304
1305    #[tokio::test]
1306    async fn a_fork_suggestion_for_a_missing_source_names_the_command_and_the_id() {
1307        let state = test_state();
1308        let err = fork_suggest(&state, CommandForkAgentDefinitionSuggestData { source_id: "gone".into() }).err().unwrap();
1309        assert_eq!(err, "forkagentdefinitionsuggest: source not found: gone");
1310    }
1311
1312    #[tokio::test]
1313    async fn a_fork_suggestion_for_a_known_source_is_a_label_and_creates_nothing() {
1314        let state = state_with_template("tmpl-sug", "Suggest Me");
1315        let before = state.mstore.agent_def_list().unwrap().len();
1316        let result = fork_suggest(&state, CommandForkAgentDefinitionSuggestData { source_id: "tmpl-sug".into() }).unwrap();
1317        assert!(!result.suggested_label.is_empty());
1318        assert_eq!(state.mstore.agent_def_list().unwrap().len(), before, "read-only");
1319    }
1320}