Skip to main content

agentmux_srv/server/app_api/
agent_open.rs

1use super::*;
2use super::agent_open_steps as steps;
3
4/// Per-agent-definition async lock serializing `agent.open`'s "check for a
5/// live block / seed resume session / create block / register controller"
6/// sequence.
7///
8/// Without this, two concurrent `agent.open` calls for the same agent (a
9/// double-invocation, or two tabs opened for the same agent close together)
10/// can both observe "not live yet" before either controller actually
11/// registers — `CreateBlock` dispatch, the layout-action enqueue, and
12/// `write_agent_config_files` all await in between — and both seed the same
13/// `resume_session_id`, spawning two controllers that `--resume` the
14/// identical provider session concurrently. That's the TOCTOU reagent
15/// flagged on PR #2059's first concurrency-guard attempt (the earlier
16/// single-point-in-time `agent_live_elsewhere` check closed the
17/// already-live case but not the still-racing-to-become-live case).
18///
19/// Scope note: this only serializes calls handled by THIS process — like
20/// the in-memory `CONTROLLER_REGISTRY` it guards, it can't see a genuinely
21/// different AgentMux instance/channel racing the same registry entry.
22/// Same boundary the live-elsewhere check already accepted.
23static AGENT_OPEN_LOCKS: std::sync::LazyLock<
24    std::sync::Mutex<std::collections::HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
25> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
26
27fn agent_open_lock(agent_id: &str) -> Arc<tokio::sync::Mutex<()>> {
28    let mut locks = AGENT_OPEN_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
29    locks
30        .entry(agent_id.to_string())
31        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
32        .clone()
33}
34
35/// How long `agent.open` waits for a missing pinned CLI to install before telling
36/// the caller to retry. The install is not cancelled when this elapses.
37pub(super) const AGENT_OPEN_INSTALL_WAIT_SECS: u64 = 150;
38
39/// Resolve the `(env_var, value)` pair to inject for this agent's model
40/// vendor override, if any — redirects the harness at a non-default
41/// backend (e.g. `ANTHROPIC_BASE_URL` for a `claude`-provider agent).
42/// Pure — no I/O — so it's directly unit-testable without the full
43/// async spawn-time harness this is called from.
44///
45/// `None` when there's nothing to override (empty `model_vendor_base_url`)
46/// OR the provider doesn't declare `base_url_env_var` — the latter should
47/// already be impossible by the time an agent reaches spawn (rejected at
48/// `agent.define`), but this stays defensive rather than trusting that
49/// write-time validation is the only thing that can ever set this field.
50/// Resolve the CLI argv for spawning `provider`'s process under `controller_type`
51/// (the string form: `"persistent"` / `"subprocess"` / `"acp"` / `"app-server"`).
52/// Pure — no I/O — so it's directly unit-testable without the full async
53/// spawn-time harness this is called from.
54///
55/// ReAgent P1 on PR #3215: this used to only branch on `"persistent"`, so an
56/// `"app-server"` controller silently fell back to `provider.launch_args` —
57/// Codex's one-shot `exec --json` args — instead of `provider.app_server`'s
58/// `--listen stdio://` args. The spawned child would never complete the App
59/// Server handshake once the provider registry flips a provider's controller
60/// type to `AppServer`.
61pub(super) fn resolve_cli_args(provider: &providers::ProviderConfig, controller_type: &str) -> Vec<String> {
62    let args: &[&str] = match controller_type {
63        "persistent" => provider.persistent_launch_args.unwrap_or(provider.launch_args),
64        "app-server" => provider
65            .app_server
66            .as_ref()
67            .map(|app_server| app_server.launch_args)
68            .unwrap_or(provider.launch_args),
69        _ => provider.launch_args,
70    };
71    args.iter().map(|s| s.to_string()).collect()
72}
73
74pub(super) fn resolve_vendor_env_override(
75    provider: &providers::ProviderConfig,
76    agent: &AgentDefinition,
77) -> Option<(&'static str, String)> {
78    if agent.model_vendor_base_url.is_empty() {
79        return None;
80    }
81    provider
82        .base_url_env_var
83        .map(|var| (var, agent.model_vendor_base_url.clone()))
84}
85
86// resolve_effective_provider_id (and its store-lookup helper) moved to
87// Store::resolve_effective_provider_id in backend/storage/agents/definition.rs
88// (2026-08-15) — the identical resolution logic was independently
89// duplicated in identity/resolver/inject.rs's layer-3 credential gate,
90// found reading agent.provider directly (the same mstore-vs-id_store
91// class of bug this file's own version was fixed for in round 3 of PR
92// #2587's review). Consolidated so both call sites share one
93// implementation and can't drift on it separately again — see that
94// method's own doc comment for the full history and the tests that
95// moved with it.
96
97#[cfg(test)]
98mod resolve_vendor_env_override_tests {
99    use super::*;
100
101    fn base_agent(model_vendor_base_url: &str) -> AgentDefinition {
102        crate::backend::storage::agents::test_agent_def("a1", "T", "claude", "host", 0, model_vendor_base_url)
103    }
104
105    #[test]
106    fn returns_none_when_override_is_unset() {
107        let provider = providers::get_provider("claude").unwrap();
108        let agent = base_agent("");
109        assert!(resolve_vendor_env_override(provider, &agent).is_none());
110    }
111
112    #[test]
113    fn returns_the_env_var_and_value_for_a_supporting_provider() {
114        let provider = providers::get_provider("claude").unwrap();
115        let agent = base_agent("https://my-proxy.example.com");
116        assert_eq!(
117            resolve_vendor_env_override(provider, &agent),
118            Some(("ANTHROPIC_BASE_URL", "https://my-proxy.example.com".to_string()))
119        );
120    }
121
122    #[test]
123    fn returns_none_for_a_non_supporting_provider_even_if_the_field_is_set() {
124        // Defensive: shouldn't be reachable in practice (agent.define
125        // rejects this combination), but a non-supporting provider must
126        // never get a spurious env var injected.
127        let provider = providers::get_provider("codex").unwrap();
128        let agent = base_agent("https://my-proxy.example.com");
129        assert!(resolve_vendor_env_override(provider, &agent).is_none());
130    }
131}
132
133#[cfg(test)]
134mod resolve_cli_args_tests {
135    use super::*;
136
137    #[test]
138    fn persistent_controller_uses_persistent_launch_args() {
139        let provider = providers::get_provider("claude").unwrap();
140        assert_eq!(
141            resolve_cli_args(provider, "persistent"),
142            provider.persistent_launch_args.unwrap().to_vec()
143        );
144    }
145
146    #[test]
147    fn subprocess_controller_uses_the_default_launch_args() {
148        let provider = providers::get_provider("codex").unwrap();
149        assert_eq!(resolve_cli_args(provider, "subprocess"), provider.launch_args.to_vec());
150    }
151
152    /// ReAgent P1 on PR #3215: this is the bug fix. Before it, an
153    /// `"app-server"` controller_type fell into the `else` branch and got
154    /// Codex's one-shot `exec --json` args — the App Server child would spawn
155    /// but never see `--listen stdio://`, so it never speaks the App Server
156    /// protocol and the handshake in `AppServerController::start` hangs until
157    /// `INITIALIZE_TIMEOUT`.
158    #[test]
159    fn app_server_controller_uses_the_app_server_launch_args_not_the_one_shot_ones() {
160        let provider = providers::get_provider("codex").unwrap();
161        let app_server_args = provider.app_server.as_ref().unwrap().launch_args.to_vec();
162
163        let resolved = resolve_cli_args(provider, "app-server");
164
165        assert_eq!(resolved, app_server_args);
166        assert_ne!(
167            resolved,
168            provider.launch_args.to_vec(),
169            "must not silently fall back to the one-shot exec args"
170        );
171    }
172
173    /// Defensive: a provider with no `app_server` config (everything except
174    /// Codex today) must not panic if `controller_type` is somehow
175    /// `"app-server"` for it — fall back to the ordinary launch args instead.
176    #[test]
177    fn app_server_controller_type_falls_back_gracefully_for_a_provider_without_one() {
178        let provider = providers::get_provider("claude").unwrap();
179        assert!(provider.app_server.is_none());
180        assert_eq!(resolve_cli_args(provider, "app-server"), provider.launch_args.to_vec());
181    }
182}
183
184/// The agent `agent.open` opens: a user agent (`is_seeded == 0`), named by
185/// definition id or by display name (ASCII case-insensitive) — its id first,
186/// then its name. Only when no user agent answers is a template consulted,
187/// and then only to refuse it with `TEMPLATE_NOT_OPENABLE`: opening one would
188/// launch a session that is no agent's (spec §6.5.8, template sessions); an
189/// agent is created from a template in the picker. A template's id is its
190/// lowercase name (`claude`), which a user agent created from it shares
191/// case-insensitively, so templates must never be matched first.
192pub(super) fn select_openable_agent<'a>(
193    agents: &'a [AgentDefinition],
194    wanted: &str,
195) -> Result<&'a AgentDefinition, String> {
196    let names = |a: &&AgentDefinition| a.id == wanted || a.name.eq_ignore_ascii_case(wanted);
197    let users = || agents.iter().filter(|a| a.is_seeded == 0);
198    let found = users()
199        .find(|a| a.id == wanted)
200        .or_else(|| users().find(|a| a.name.eq_ignore_ascii_case(wanted)))
201        .or_else(|| agents.iter().find(names))
202        .ok_or_else(|| format!("AGENT_NOT_FOUND: no agent definition with id '{wanted}'"))?;
203    if found.is_seeded != 0 {
204        return Err(format!(
205            "TEMPLATE_NOT_OPENABLE: '{}' is a template; agent.open opens an agent from My Agents — create an agent from this template in the agent picker first",
206            found.name
207        ));
208    }
209    Ok(found)
210}
211
212/// Identity M4b-4 (spec §6.5.8): a user agent's local row, backfilled from
213/// the shared registry if it is another channel's — and **confirmed**, or the
214/// open fails: without a local row the spawn would resolve to nothing, with
215/// no UID/token and no credential gate, exactly the process M4b closes (Codex
216/// P1 on #3584). `agent_def_list` listed the agent, so a missing row here is a
217/// failed backfill, not a missing agent.
218pub(super) fn require_local_agent_row(mstore: &Store, agent_id: &str) -> Result<(), String> {
219    match mstore.agent_row_ensure_local(agent_id) {
220        Ok(true) => Ok(()),
221        Ok(false) => Err(format!(
222            "AGENT_ROW_UNAVAILABLE: could not create a local row for agent '{agent_id}' — not started"
223        )),
224        Err(e) => Err(format!(
225            "AGENT_ROW_UNAVAILABLE: local row for agent '{agent_id}' could not be read or created ({e}) — not started"
226        )),
227    }
228}
229
230/// Identity M4b-4 (spec §6.5.8): record `agent.open`'s launch of user agent
231/// `agent_id` on `block_id` — a lifecycle-only update, never
232/// `instance_create` with a fresh record (whose fold would blank the agent's
233/// account, bundle and workspace) — and stamp the block with the row id.
234/// A row that is gone (the agent deleted mid-open — the delete handlers do
235/// not take `AGENT_OPEN_LOCKS`) or a failed write **fails the open**: the
236/// spawn would otherwise resolve to nothing, tokenless and past the
237/// credential gate (Codex P1 on #3584). A failed stamp is only logged — for a
238/// user agent the block's `agentId` already names its row.
239pub(super) fn record_agent_open_launch(mstore: &Store, agent_id: &str, block_id: &str) -> Result<(), String> {
240    let now = agentmux_common::time::now_ms();
241    match mstore.instance_record_launch(agent_id, block_id, now) {
242        Ok(true) => {
243            let mut stamp = obj::MetaMapType::new();
244            stamp.insert("agentInstanceId".to_string(), json!(agent_id));
245            if let Err(e) = crate::server::service::update_object_meta(
246                mstore,
247                &format!("block:{block_id}"),
248                &stamp,
249            ) {
250                tracing::warn!(agent_id, block_id, error = %e, "agent.open: stamping the block failed");
251            }
252        }
253        Ok(false) => {
254            return Err(format!(
255                "AGENT_ROW_UNAVAILABLE: agent '{agent_id}' has no local row to record the launch on (deleted?) — not started"
256            ));
257        }
258        Err(e) => {
259            return Err(format!(
260                "AGENT_ROW_UNAVAILABLE: recording the launch of agent '{agent_id}' failed ({e}) — not started"
261            ));
262        }
263    }
264    Ok(())
265}
266
267pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
268    register_agent_open(engine, state);
269}
270
271fn register_agent_open(engine: &Arc<WshRpcEngine>, state: &AppState) {
272    let app_state = state.clone();
273
274    engine.register_typed(COMMAND_AGENT_OPEN, move |cmd: CommandAgentOpenData, _ctx| {
275        let app_state = app_state.clone();
276        async move { open_agent_impl(&app_state, cmd).await }
277    });
278}
279
280/// The `agent.open` implementation — load the definition, resolve the
281/// provider/CLI, create the block, enqueue the layout insert, and register
282/// the controller. Extracted from the RPC closure so the HTTP surface
283/// (`POST /api/v1/agent/open`, backing the `OpenAgent` MCP tool) shares this
284/// exact code path instead of re-deriving it: the TOCTOU serialization via
285/// `AGENT_OPEN_LOCKS` (reagent P1 on PR #2059), the ABF provider shadowing,
286/// the resume-session seeding guard, and the CLI path resolution all live
287/// here once. Same extraction shape as `open_pane` / `handle_pane_open`.
288/// See docs/reports/REPORT_AGENT_OPEN_API_GAP_2026_09_06.md.
289pub(crate) async fn open_agent_impl(
290    state: &AppState,
291    cmd: CommandAgentOpenData,
292) -> Result<AgentOpenResult, String> {
293    let into_block = cmd.into_block_id.clone();
294    let cmd = CommandAgentOpenData { tab_id: tab_for_open(state, &cmd), ..cmd };
295    open_agent_inner(state, cmd, into_block.as_deref(), MetaMapType::new()).await
296}
297
298/// What a restore or an import calls an agent in a note: the name its pane carries, else its definition's name, else
299/// what the layout named it.
300pub(crate) fn agent_label(store: &Store, named_in_pane: &str, wanted: &str) -> String {
301    if !named_in_pane.is_empty() {
302        return named_in_pane.to_string();
303    }
304    store.agent_def_get(wanted).ok().flatten().map(|def| def.name).filter(|name| !name.is_empty()).unwrap_or_else(|| wanted.to_string())
305}
306
307/// What a restore or an import says of an agent that did not start. One held for a shared folder is not an error: its
308/// pane asks the person.
309pub(crate) fn not_started_note(who: &str, error: &str) -> String {
310    if error.starts_with(crate::backend::folder_overlap::OPEN_REFUSAL_CODE) {
311        return format!("{who} works in a folder a container agent can write, so its pane asks you before it opens.");
312    }
313    format!("An agent ({who}) didn't start, so its pane shows the agent picker: {error}")
314}
315
316/// The tab an open is for: the one it names, else the tab of the pane it opens into (where the window asks the person is
317/// not always the tab srv has as active), else none.
318pub(super) fn tab_for_open(state: &AppState, cmd: &CommandAgentOpenData) -> Option<String> {
319    cmd.tab_id.clone().or_else(|| cmd.into_block_id.as_deref().and_then(|block| resolve_tab_id_for_block(&state.mstore, block).ok()))
320}
321
322/// `agent.open`, but launching into an existing, empty agent pane
323/// (`{view:"agent"}`, the picker) instead of creating a new one and
324/// inserting it into the layout. Used by `layout.open` and Workspaces → Import…
325/// (`SPEC_LAYOUT_FILES_2026_09_25.md` §3.5), which rebuilds the saved split
326/// tree first and then launches each agent into its placeholder — so every
327/// check `agent.open` makes (admission, one live instance, provider, CLI,
328/// resume, config files) applies unchanged. If the agent is already open in
329/// this tab, that pane is returned and the placeholder is left as a picker.
330pub(crate) async fn open_agent_into_block(
331    state: &AppState,
332    agent_id: &str,
333    tab_id: &str,
334    block_id: &str,
335) -> Result<AgentOpenResult, String> {
336    open_agent_inner(
337        state,
338        CommandAgentOpenData {
339            agent_id: agent_id.to_string(),
340            tab_id: Some(tab_id.to_string()),
341            split_direction: None,
342            split_reference_block_id: None,
343            focus: Some(false),
344            into_block_id: None,
345        },
346        Some(block_id),
347        MetaMapType::new(),
348    )
349    .await
350}
351
352/// `extra_meta` goes on a new block as it's created (srv-only keys: `agent_spawn.rs`).
353pub(super) async fn open_agent_inner(
354    state: &AppState,
355    cmd: CommandAgentOpenData,
356    into_block: Option<&str>,
357    extra_meta: MetaMapType,
358) -> Result<AgentOpenResult, String> {
359    let mut extra_meta = extra_meta;
360    let headless = steps::take_start_marker(&mut extra_meta); // a start: no pane
361    let mstore = state.mstore.clone();
362
363    tracing::info!(agent_id = %cmd.agent_id, "agent.open");
364
365    // 1. Load the agent definition (by id or name)
366    let agent = steps::pick_openable_agent(state, &cmd.agent_id)?;
367
368    // Serialize the rest of this handler per agent definition —
369    // held until the function returns (guard drops at every exit
370    // path, success or error). See AGENT_OPEN_LOCKS' doc comment.
371    let open_lock = agent_open_lock(&agent.id);
372    let _open_guard = open_lock.lock().await;
373
374    steps::admit_open(state, &agent).await?;
375
376    // 2. Resolve provider
377    // A harness AgentMux no longer offers: the agent stays, with its history, and says why it does not start.
378    let provider = providers::get_provider(&agent.provider).ok_or_else(|| {
379        let why = providers::harness_unusable_reason(&agent.provider).unwrap_or_else(|| format!("unknown provider '{}'", agent.provider));
380        format!("INVALID_PROVIDER: {why}")
381    })?;
382
383    // 3-4. The tab, and the agent's own block when it has one: its pane in this tab, a
384    //      parked block attached here, or the pane that shows it elsewhere (`agent_attach`).
385    let tab_id = match super::agent_attach::tab_or_reuse(state, &agent, provider, &cmd, headless, into_block).await? {
386        Ok(tab_id) => tab_id,
387        Err(done) => return Ok(done),
388    };
389
390    // 5. Resolve the CLI path (see `resolve_cli_path`).
391    let resolved_cli_path = steps::resolve_cli_path(provider).await?;
392
393    // 6. Build metadata
394    let controller_type = steps::open_controller_type(&agent, provider)?;
395    let (seeded, pane_flags) = steps::seed_runtime_args(&mstore, &agent, provider, controller_type);
396
397    let work_dir = steps::agent_work_dir(&agent);
398    let routing_id = steps::routing_id(&agent);
399    let auth_dir = steps::prepare_auth_dir(provider)?;
400    let env_vars = steps::launch_env(&mstore, &agent, provider, &auth_dir, &routing_id, controller_type)?;
401
402    let resume_session_id = steps::resume_session_for(&mstore, &agent).await;
403    let mut meta = steps::pane_identity_meta(&mstore, &agent, provider);
404    let launch = steps::LaunchMeta { controller_type, cli_path: &resolved_cli_path, seeded, pane_flags: &pane_flags, work_dir: &work_dir, env_vars, resume_session_id: resume_session_id.as_deref(), extra_meta };
405    steps::add_launch_meta(&mut meta, provider, launch);
406
407    // 7. Create the block (see `create_agent_block`).
408    let meta_val = serde_json::to_value(&meta)
409        .map_err(|e| format!("agent.open: meta serialize: {e}"))?;
410    let block_id = match into_block {
411        Some(target) => steps::fill_existing_pane(state, target, meta_val).await?,
412        None => steps::create_agent_block(state, &tab_id, meta_val, headless, &cmd).await?,
413    };
414
415    tracing::info!(
416        block_id = %block_id,
417        agent_id = %cmd.agent_id,
418        provider = %agent.provider,
419        controller_type = %controller_type,
420        "agent.open: block created + layout updated"
421    );
422
423    // 8. Write the config files and record the launch (see `write_files_and_record_launch`).
424    steps::write_files_and_record_launch(state, &agent, &routing_id, &work_dir, &block_id)?;
425
426    steps::start_controller(state, provider, &tab_id, &block_id, headless)?;
427
428    // 10. Broadcast block + tab + layout updates to frontend
429    super::open_updates::broadcast_block_in_tab(state, &block_id, &tab_id);
430
431    let status = steps::launch_status(&block_id);
432    Ok(AgentOpenResult {
433        block_id,
434        tab_id,
435        agent_id: cmd.agent_id,
436        provider: agent.provider,
437        controller_type: controller_type.to_string(),
438        status,
439        created: true,
440    })
441}
442
443/// Write agent config files (CLAUDE.md, .mcp.json, etc.) to the working directory.
444pub(super) fn write_agent_config_files(
445    mstore: &Store,
446    id_store: &Store,
447    identity_store: &Store,
448    agent: &crate::backend::storage::AgentDefinition,
449    agent_slug: &str,
450    work_dir: &str,
451) -> Result<(), String> {
452    // An empty working_directory field means the caller chose the fallback `~/.agentmux/agents/<slug>`,
453    // shared by every same-name launch.
454    let workdir_is_shared = agent.working_directory.is_empty();
455    let config_files = super::agent_config_render::render_agent_config_files(
456        mstore,
457        id_store,
458        identity_store,
459        agent,
460        &agent.name,
461        agent_slug,
462        work_dir,
463        workdir_is_shared,
464    );
465    write_rendered_config_files(mstore, agent, config_files, work_dir)
466}
467
468/// Write `config_files` into `work_dir` and record what the agent will read as project instructions.
469fn write_rendered_config_files(
470    mstore: &Store,
471    agent: &crate::backend::storage::AgentDefinition,
472    config_files: Vec<crate::backend::agent_config::AgentConfigFile>,
473    work_dir: &str,
474) -> Result<(), String> {
475    // Expand ~ in work_dir
476    let expanded_dir = if let Some(under_override) = crate::backend::base::expand_under_home_override(work_dir) {
477        under_override.to_string_lossy().to_string()
478    } else if let (true, Ok(home)) = (work_dir.starts_with("~/") || work_dir == "~", std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE"))) {
479        format!("{}/{}", home, work_dir.trim_start_matches("~/"))
480    } else {
481        work_dir.to_string()
482    };
483
484    let base_path = std::path::Path::new(&expanded_dir);
485    if !base_path.exists() {
486        std::fs::create_dir_all(base_path) // workdir-fs: creates the workdir itself
487            .map_err(|e| format!("failed to create working dir: {e}"))?;
488    }
489    let on_host = !agent.runtime().is_container();
490    // A host agent in a folder a container agent can write is given its files from outside the folder
491    // (`host_agent_files`): nothing is written into the folder, and nothing of it is the agent's instructions.
492    if on_host && crate::backend::host_agent_files::write(&expanded_dir, config_files.iter().map(|f| (f.filename.as_str(), f.content.as_str())))? {
493        tracing::info!(agent_id = %agent.id, work_dir = %expanded_dir, file_count = config_files.len(), "agent.open: wrote config files outside the folder");
494        return Ok(());
495    }
496    let wd = crate::backend::workdir_fs::Workdir::open(base_path)
497        .map_err(|e| format!("failed to open working dir {}: {e}", base_path.display()))?;
498
499    // Remove skill-derived files (.claude/commands/*.md, .claude/skills/*/SKILL.md)
500    // that WE wrote on a previous launch but aren't part of this run's output --
501    // e.g. a skill's format switched between "prompt" and "agent-skill", or a
502    // skill was renamed/removed. Shared with `writeagentconfig` (editor_handlers.rs)
503    // so the two RPC paths that materialize config files never drift out of sync
504    // on this (reagent P1 + Codex P1/P2, PR #2322).
505    let new_managed_skill_paths = crate::backend::agent_config::managed_skill_file_paths(
506        config_files.iter().map(|f| f.filename.as_str()),
507    );
508    crate::backend::agent_config::cleanup_stale_managed_skill_files(base_path, &new_managed_skill_paths);
509
510    for file in &config_files {
511        super::agent_config_render::write_config_file(&wd, base_path, &expanded_dir, file, on_host)?;
512    }
513
514    crate::backend::agent_config::write_managed_skill_file_manifest(base_path, &new_managed_skill_paths);
515
516    // Record what this agent will read as project instructions, now that
517    // AgentMux's own files are in their final state for this launch — observed
518    // before the write, this would record the previous launch's content.
519    //
520    // Phase 3 of SPEC_INSTRUCTION_AND_MEMORY_PORTABILITY_2026_09_09.md.
521    // Observing at open is the spec's §8 decision 2: it costs nothing, catches
522    // the case that matters (the repository changed since last launch), and
523    // avoids a watcher. Drift *during* a session is deliberately not covered
524    // yet — revisit only if it shows up in practice.
525    //
526    // Best-effort: an agent must never fail to launch because a tracking row
527    // could not be written.
528    observe_project_instructions(mstore, agent, &expanded_dir);
529
530    tracing::info!(
531        agent_id = %agent.id,
532        work_dir = %expanded_dir,
533        file_count = config_files.len(),
534        "agent.open: wrote config files"
535    );
536
537    Ok(())
538}
539
540/// Resolve and record this agent's project instructions.
541///
542/// Split out so the launch path reads as one line and this can be tested on
543/// its own. Never returns an error: see the call site.
544pub(super) fn observe_project_instructions(
545    mstore: &crate::backend::storage::store::Store,
546    agent: &crate::backend::storage::AgentDefinition,
547    working_dir: &str,
548) {
549    use crate::backend::storage::project_instructions::ProjectInstructionObservation;
550
551    let files = crate::backend::project_instructions::resolve_project_instructions(
552        &agent.provider,
553        working_dir,
554    );
555    if files.is_empty() {
556        return;
557    }
558    let now = agentmux_common::time::now_ms();
559    let observations: Vec<ProjectInstructionObservation> = files
560        .iter()
561        .map(|f| ProjectInstructionObservation {
562            path: f.path.clone(),
563            content_hash: f.content_hash.clone(),
564            size_bytes: f.size_bytes as i64,
565            owner: match f.owner {
566                crate::backend::project_instructions::InstructionOwner::Agentmux => "agentmux",
567                crate::backend::project_instructions::InstructionOwner::Foreign => "foreign",
568            }
569            .to_string(),
570            existed: f.exists,
571            observed_at: now,
572        })
573        .collect();
574
575    if let Err(e) = mstore.project_instructions_record(&agent.id, &observations) {
576        tracing::warn!(
577            agent_id = %agent.id, error = %e,
578            "agent.open: could not record project-instruction observations"
579        );
580    }
581}
582
583#[cfg(test)]
584mod write_agent_config_files_tests {
585    use super::*;
586    use crate::backend::storage::Skill;
587
588    fn make_store() -> Store {
589        Store::open_in_memory().unwrap()
590    }
591
592    /// Write a launch's files with the relocated MCP config under a temp data home, so a test's
593    /// project folder is never written and nothing lands in the real AgentMux data root.
594    fn write_test_configs(mstore: &Store, id_store: &Store, agent: &AgentDefinition, work_dir: &str) {
595        let data = tempfile::tempdir().unwrap();
596        crate::backend::mcp_config_file::with_data_home(data.path(), || {
597            write_agent_config_files(mstore, id_store, mstore, agent, "test-agent", work_dir)
598        })
599        .unwrap();
600    }
601
602    fn make_agent(id: &str, working_directory: &str) -> AgentDefinition {
603        AgentDefinition {
604            slug: String::new(),
605            working_directory: working_directory.to_string(),
606            ..crate::backend::storage::agents::test_agent_def(id, "Test Agent", "claude", "host", 1_700_000_000_000, "")
607        }
608    }
609
610    fn make_skill(skill_type: &str) -> Skill {
611        Skill {
612            id: "skill-1".to_string(),
613            name: "Deploy".to_string(),
614            trigger: "deploy".to_string(),
615            skill_type: skill_type.to_string(),
616            description: "Deploy the app".to_string(),
617            content: "1. Test\n2. Deploy".to_string(),
618            is_global: false,
619            created_at: 1_700_000_000_000,
620            updated_at: 1_700_000_000_000,
621        }
622    }
623
624    /// reagent P1 + Codex P1/P2, PR #2322: switching a skill's `skill_type`
625    /// between "prompt" and "agent-skill" must remove the artifact from the
626    /// PREVIOUS format, not just write the new one -- otherwise the stale
627    /// file stays active alongside the newly selected format.
628    #[test]
629    fn switching_skill_format_removes_the_stale_artifact() {
630        let mstore = make_store();
631        let id_store = make_store();
632        let work_dir = tempfile::tempdir().unwrap();
633        let work_dir_str = work_dir.path().to_str().unwrap();
634
635        let mut agent = make_agent("agent-1", work_dir_str);
636        mstore.agent_def_insert(&mut agent).unwrap();
637        mstore.skill_upsert_unique(&mstore, "agent-1", &make_skill("agent-skill"), true).unwrap();
638
639        write_test_configs(&mstore, &id_store, &agent, work_dir_str);
640        let skill_md = work_dir.path().join(".claude/skills/deploy/SKILL.md");
641        assert!(skill_md.exists(), "expected .claude/skills/deploy/SKILL.md to be written");
642
643        // Flip the same skill to "prompt" format and relaunch.
644        let mut prompt_skill = make_skill("prompt");
645        prompt_skill.updated_at = 1_700_000_000_001;
646        mstore.skill_upsert_unique(&mstore, "agent-1", &prompt_skill, true).unwrap();
647        write_test_configs(&mstore, &id_store, &agent, work_dir_str);
648
649        let command_md = work_dir.path().join(".claude/commands/deploy.md");
650        assert!(command_md.exists(), "expected .claude/commands/deploy.md to be written");
651        assert!(
652            !skill_md.exists(),
653            "stale .claude/skills/deploy/SKILL.md must be removed when the skill switches to prompt format"
654        );
655        assert!(
656            !skill_md.parent().unwrap().exists(),
657            "the now-empty .claude/skills/deploy/ directory should be cleaned up too"
658        );
659    }
660
661    /// A file the user hand-authored under .claude/commands or .claude/skills
662    /// (never part of any AgentMux-written manifest) must never be deleted by
663    /// the stale-cleanup pass.
664    #[test]
665    fn user_authored_files_outside_the_manifest_are_never_touched() {
666        let mstore = make_store();
667        let id_store = make_store();
668        let work_dir = tempfile::tempdir().unwrap();
669        let work_dir_str = work_dir.path().to_str().unwrap();
670
671        let mut agent = make_agent("agent-1", work_dir_str);
672        mstore.agent_def_insert(&mut agent).unwrap();
673
674        let user_file = work_dir.path().join(".claude/commands/my-own-command.md");
675        std::fs::create_dir_all(user_file.parent().unwrap()).unwrap();
676        std::fs::write(&user_file, "# hand-authored, not from AgentMux").unwrap();
677
678        mstore.skill_upsert_unique(&mstore, "agent-1", &make_skill("agent-skill"), true).unwrap();
679        write_test_configs(&mstore, &id_store, &agent, work_dir_str);
680        write_test_configs(&mstore, &id_store, &agent, work_dir_str);
681
682        assert!(user_file.exists(), "hand-authored file outside AgentMux's manifest must survive");
683    }
684
685    /// Defense-in-depth: even if a manifest somehow contains a path-traversal
686    /// entry (e.g. from a bypass of the trigger sanitization added upstream
687    /// in agent_config.rs, or manual tampering with the manifest file
688    /// itself), the cleanup pass must never delete anything outside the
689    /// agent's working directory (reagent P1, PR #2322).
690    #[test]
691    fn cleanup_refuses_to_delete_a_manifest_path_that_escapes_the_working_dir() {
692        let mstore = make_store();
693        let id_store = make_store();
694        let work_dir = tempfile::tempdir().unwrap();
695        let work_dir_str = work_dir.path().to_str().unwrap();
696
697        let mut agent = make_agent("agent-1", work_dir_str);
698        mstore.agent_def_insert(&mut agent).unwrap();
699
700        // A sentinel file OUTSIDE the working directory that a traversal
701        // attempt would target.
702        let sentinel_dir = tempfile::tempdir().unwrap();
703        let sentinel = sentinel_dir.path().join("outside-file.txt");
704        std::fs::write(&sentinel, "must survive").unwrap();
705
706        // Simulate a manifest that (however it got there) records an escape.
707        std::fs::create_dir_all(work_dir.path().join(".claude")).unwrap();
708        let traversal_rel = format!(
709            "../{}/outside-file.txt",
710            sentinel_dir.path().file_name().unwrap().to_str().unwrap()
711        );
712        let malicious_manifest = serde_json::to_string(&vec![traversal_rel]).unwrap();
713        std::fs::write(
714            work_dir.path().join(crate::backend::agent_config::MANAGED_SKILL_FILES_MANIFEST),
715            malicious_manifest,
716        )
717        .unwrap();
718
719        // No skills at all this run, so the manifest's one entry is "stale"
720        // and would normally be deleted.
721        write_test_configs(&mstore, &id_store, &agent, work_dir_str);
722
723        assert!(sentinel.exists(), "file outside the working directory must never be deleted");
724    }
725
726    /// A `.claude` that links outside the workdir: the generic file loop
727    /// (skill files, settings) used to write straight through it, with only
728    /// a lexical check (SPEC_WORKDIR_SAFE_WRITES_2026_10_01 §1). Now refused
729    /// and skipped, and the launch still succeeds.
730    #[test]
731    fn config_files_are_never_written_through_a_claude_folder_linking_outside() {
732        let mstore = make_store();
733        let id_store = make_store();
734        let work_dir = tempfile::tempdir().unwrap();
735        let work_dir_str = work_dir.path().to_str().unwrap();
736        let outside = tempfile::tempdir().unwrap();
737        #[cfg(unix)]
738        let linked = std::os::unix::fs::symlink(outside.path(), work_dir.path().join(".claude")).is_ok();
739        #[cfg(windows)]
740        let linked = std::os::windows::fs::symlink_dir(outside.path(), work_dir.path().join(".claude")).is_ok();
741        if !linked {
742            return; // this OS user can't create links
743        }
744
745        let mut agent = make_agent("agent-1", work_dir_str);
746        mstore.agent_def_insert(&mut agent).unwrap();
747        mstore.skill_upsert_unique(&mstore, "agent-1", &make_skill("agent-skill"), true).unwrap();
748        write_test_configs(&mstore, &id_store, &agent, work_dir_str);
749
750        let leaked: Vec<_> = walkdir_files(outside.path());
751        assert!(leaked.is_empty(), "nothing may be written outside the workdir, found {leaked:?}");
752    }
753
754    fn walkdir_files(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
755        let mut out = Vec::new();
756        for entry in std::fs::read_dir(dir).unwrap().flatten() {
757            let p = entry.path();
758            if p.is_dir() {
759                out.extend(walkdir_files(&p));
760            } else {
761                out.push(p);
762            }
763        }
764        out
765    }
766
767    /// A bundle carries no MCP servers
768    /// (SPEC_BUNDLE_CONTENTS_MEMORY_NOT_MCP_2026_10_07.md §3.1): a bundle ref
769    /// an older build left behind neither reaches `.mcp.json` nor counts as
770    /// the agent's own, so the agent's legacy blob is still merged.
771    #[test]
772    fn a_leftover_bundle_mcp_ref_neither_launches_nor_drops_the_agents_legacy_mcp_blob() {
773        let mstore = make_store();
774        let id_store = make_store();
775        let work_dir = tempfile::tempdir().unwrap();
776        let work_dir_str = work_dir.path().to_str().unwrap();
777
778        let mut agent = make_agent("agent-1", work_dir_str);
779        mstore.agent_def_insert(&mut agent).unwrap();
780        mstore.agent_bundles_set("agent-1", &["bundle-1".to_string()]).unwrap();
781
782        mstore
783            .bundle_upsert(&crate::backend::storage::bundles::Bundle {
784                id: "bundle-1".to_string(),
785                name: "Bundle 1".to_string(),
786                description: String::new(),
787                is_blank: false,
788                is_global: false,
789                provider: "claude".to_string(),
790                model: "anthropic".to_string(),
791                instructions: String::new(),
792                instructions_by_provider: "{}".to_string(),
793                context_files: "[]".to_string(),
794                mcp_servers: "[]".to_string(),
795                skills: "[]".to_string(),
796                sort_order: 0,
797                created_at: 1_700_000_000_000,
798                updated_at: 1_700_000_000_000,
799                is_system: false,
800            })
801            .unwrap();
802        leftover_bundle_mcp_ref(&mstore, "bundle-1", "bundle-private-server", "bundle-server", "bundle-tool");
803        // agent-1 itself has NO own db_mcp_servers ref — only its bundle does.
804
805        mstore
806            .agent_content_set(&crate::backend::storage::content::AgentContent {
807                agent_id: "agent-1".to_string(),
808                content_type: "mcp".to_string(),
809                content: r#"{"mcpServers":{"legacy-server":{"command":"legacy-tool"}}}"#.to_string(),
810                updated_at: 1_700_000_000_000,
811            })
812            .unwrap();
813
814        // A user's project gets the config outside it (#3680), under the data root.
815        let data = tempfile::tempdir().unwrap();
816        let mcp_json = crate::backend::mcp_config_file::with_data_home(data.path(), || {
817            write_agent_config_files(&mstore, &id_store, &mstore, &agent, "test-agent", work_dir_str).unwrap();
818            std::fs::read_to_string(crate::backend::mcp_config_file::config_path(work_dir_str)).unwrap()
819        });
820        let parsed: serde_json::Value = serde_json::from_str(&mcp_json).unwrap();
821        assert!(
822            parsed["mcpServers"].get("legacy-server").is_some(),
823            "a leftover bundle ref must not drop the agent's legacy .mcp.json blob: {mcp_json}"
824        );
825        assert!(
826            parsed["mcpServers"].get("bundle-server").is_none(),
827            "a bundle's server must not launch: {mcp_json}"
828        );
829    }
830
831    /// A bundle MCP ref of the kind an older build wrote; nothing writes one now.
832    fn leftover_bundle_mcp_ref(store: &Store, bundle_id: &str, id: &str, name: &str, command: &str) {
833        store
834            .mcp_server_insert_raw(&crate::backend::storage::McpServer {
835                id: id.to_string(),
836                name: name.to_string(),
837                transport: "stdio".to_string(),
838                config: format!(r#"{{"command":"{command}"}}"#),
839                is_global: false,
840                created_at: 1_700_000_000_000,
841                updated_at: 1_700_000_000_000,
842            })
843            .unwrap();
844        store
845            .conn()
846            .lock()
847            .unwrap()
848            .execute(
849                "INSERT INTO db_bundle_mcp_ref (bundle_id, mcp_id) VALUES (?1, ?2)",
850                rusqlite::params![bundle_id, id],
851            )
852            .unwrap();
853    }
854
855    fn make_bundle(id: &str, name: &str, instructions: &str, is_global: bool) -> crate::backend::storage::bundles::Bundle {
856        crate::backend::storage::bundles::Bundle {
857            id: id.to_string(),
858            name: name.to_string(),
859            description: String::new(),
860            is_blank: false,
861            is_global,
862            provider: String::new(),
863            model: String::new(),
864            instructions: instructions.to_string(),
865            instructions_by_provider: "{}".to_string(),
866            context_files: "[]".to_string(),
867            mcp_servers: "[]".to_string(),
868            skills: "[]".to_string(),
869            sort_order: 0,
870            created_at: 1_700_000_000_000,
871            updated_at: 1_700_000_000_000,
872            is_system: false,
873        }
874    }
875
876    /// The bundles picked for an agent reach its launch
877    /// (SPEC_RENAME_KNOWLEDGE_TO_MEMORY_2026_10_06.md §3.6): their
878    /// instructions as `# [Bundle]` sections after Global Memory, in list
879    /// order; a listed bundle that no longer exists is skipped. Not MCP
880    /// servers: a bundle carries none.
881    #[test]
882    fn picked_bundles_reach_the_startup_file_but_not_the_mcp_config() {
883        let mstore = make_store();
884        let id_store = make_store();
885        let work_dir = tempfile::tempdir().unwrap();
886        let work_dir_str = work_dir.path().to_str().unwrap();
887
888        let mut agent = make_agent("agent-1", work_dir_str);
889        mstore.agent_def_insert(&mut agent).unwrap();
890        id_store.bundle_upsert(&make_bundle("global-1", "Rules", "global rule", true)).unwrap();
891        id_store.bundle_upsert(&make_bundle("b1", "Reviewer", "review carefully", false)).unwrap();
892        id_store.bundle_upsert(&make_bundle("b2", "Writer", "write plainly", false)).unwrap();
893        leftover_bundle_mcp_ref(&mstore, "b2", "b2-server", "writer-tools", "writer-tool");
894        mstore
895            .agent_bundles_set("agent-1", &["b2".to_string(), "gone".to_string(), "b1".to_string()])
896            .unwrap();
897
898        let data = tempfile::tempdir().unwrap();
899        let mcp_json = crate::backend::mcp_config_file::with_data_home(data.path(), || {
900            write_agent_config_files(&mstore, &id_store, &mstore, &agent, "test-agent", work_dir_str).unwrap();
901            std::fs::read_to_string(crate::backend::mcp_config_file::config_path(work_dir_str)).unwrap_or_default()
902        });
903
904        let claude_md = std::fs::read_to_string(work_dir.path().join("CLAUDE.md")).unwrap();
905        let global = claude_md.find("# [Workspace] Rules").expect("Global Memory section");
906        let writer = claude_md.find("# [Bundle] Writer\n\nwrite plainly").expect("first pick's section");
907        let reviewer = claude_md.find("# [Bundle] Reviewer\n\nreview carefully").expect("second pick's section");
908        assert!(global < writer && writer < reviewer, "Global Memory, then the picks in order: {claude_md}");
909
910        assert!(!mcp_json.contains("writer-tools"), "a picked bundle's server must not launch: {mcp_json}");
911    }
912
913    /// `memory:launchcost` counts what a launch writes: its parts sum to the
914    /// estimate of the written startup file (SPEC_MEMORY_PANE_TOKENS_2026_10_15.md §8).
915    #[test]
916    fn launch_cost_is_the_estimate_of_the_startup_file_a_launch_writes() {
917        let (mstore, id_store) = (make_store(), make_store());
918        let work_dir = tempfile::tempdir().unwrap();
919        let mut agent = make_agent("agent-1", work_dir.path().to_str().unwrap());
920        agent.provider = "codex".to_string();
921        mstore.agent_def_insert(&mut agent).unwrap();
922        id_store.bundle_upsert(&make_bundle("global-1", "Rules", "global rule", true)).unwrap();
923        id_store.bundle_upsert(&make_bundle("b1", "Reviewer", "review carefully", false)).unwrap();
924        mstore.agent_bundles_set("agent-1", &["b1".to_string()]).unwrap();
925        let (agent_id, content_type) = ("agent-1".to_string(), "soul".to_string());
926        let content = "You are {{AGENT}}, a careful reviewer.".to_string();
927        let soul = crate::backend::storage::content::AgentContent { agent_id, content_type, content, updated_at: 1 };
928        mstore.agent_content_set(&soul).unwrap();
929
930        write_test_configs(&mstore, &id_store, &agent, work_dir.path().to_str().unwrap());
931        let written = std::fs::read_to_string(work_dir.path().join("AGENTS.md")).unwrap();
932        let cost = crate::server::memory_launch_cost::launch_cost(&mstore, &id_store, &mstore, &agent, Some(&written), &[]);
933        let (_marker, body) = written.split_once("\n\n").unwrap();
934        assert_eq!(cost.total_tokens_est, agentmux_common::tokens::estimate_tokens(body));
935        let kinds: Vec<&str> = cost.parts.iter().map(|p| p.kind.as_str()).collect();
936        assert_eq!(kinds, ["workspace_global", "bundle", "soul", "formatting"]);
937        assert!(cost.delivered_by_file && cost.startup_file.as_deref() == Some("AGENTS.md"));
938    }
939}
940
941#[cfg(test)]
942mod record_agent_open_launch_tests {
943    use super::*;
944    use crate::backend::storage::agents::test_agent_def;
945
946    /// Identity M4b-4 (spec §6.5.8): an `agent.open` of a user agent records
947    /// the launch on its row (lifecycle only) and stamps the block, so the
948    /// block resolves to that row — the row's UID and token at its spawn.
949    /// Codex P1 on #3584: an open whose local row cannot be confirmed
950    /// (here: an agent that exists neither locally nor in a registry) fails
951    /// instead of spawning row-less; a local agent passes.
952    #[test]
953    fn an_open_without_a_confirmed_local_row_is_refused() {
954        let store = Store::open_in_memory().unwrap();
955        let err = require_local_agent_row(&store, "agent-nowhere").unwrap_err();
956        assert!(err.starts_with("AGENT_ROW_UNAVAILABLE"), "{err}");
957        let mut def = test_agent_def("agent-here", "Here", "claude", "agent", 1, "");
958        store.agent_def_insert(&mut def).unwrap();
959        assert!(require_local_agent_row(&store, "agent-here").is_ok());
960    }
961
962    /// Codex P1 on #3584: an agent deleted between the row check and the
963    /// record (the delete handlers do not take the open lock) fails the open
964    /// rather than spawning a block that names a missing row.
965    #[test]
966    fn an_open_whose_agent_was_deleted_mid_open_is_refused() {
967        let store = Store::open_in_memory().unwrap();
968        let mut def = test_agent_def("agent-gone-mid", "GoneMid", "claude", "agent", 1, "");
969        store.agent_def_insert(&mut def).unwrap();
970        assert!(require_local_agent_row(&store, "agent-gone-mid").is_ok());
971        assert!(store.agent_def_delete("agent-gone-mid").unwrap());
972        let err =
973            record_agent_open_launch(&store, "agent-gone-mid", &uuid::Uuid::new_v4().to_string())
974                .unwrap_err();
975        assert!(err.starts_with("AGENT_ROW_UNAVAILABLE"), "{err}");
976    }
977
978    #[test]
979    fn an_agent_open_launch_is_recorded_stamped_and_resolves() {
980        let store = Store::open_in_memory().unwrap();
981        let mut def = test_agent_def("agent-open-x", "OpenX", "claude", "agent", 1, "");
982        store.agent_def_insert(&mut def).unwrap();
983        // ORef::parse, behind update_object_meta, needs a UUID-shaped oid.
984        let block_id = uuid::Uuid::new_v4().to_string();
985        let mut block = Block {
986            oid: block_id.clone(),
987            parentoref: String::new(),
988            version: 0,
989            runtimeopts: None,
990            stickers: None,
991            meta: {
992                let mut m = obj::MetaMapType::new();
993                m.insert("agentId".to_string(), json!("agent-open-x"));
994                m
995            },
996            subblockids: None,
997        };
998        store.insert(&mut block).unwrap();
999
1000        record_agent_open_launch(&store, "agent-open-x", &block_id).unwrap();
1001
1002        let stamped: Block = store.must_get(&block_id).unwrap();
1003        assert_eq!(
1004            stamped.meta.get("agentInstanceId"),
1005            Some(&json!("agent-open-x"))
1006        );
1007        let row = store.instance_get("agent-open-x").unwrap().unwrap();
1008        assert_eq!(row.block_id, block_id);
1009        assert_eq!(row.status, "running");
1010        let resolved = store
1011            .instance_get_active_for_block(&block_id)
1012            .unwrap()
1013            .map(|r| r.id);
1014        assert_eq!(resolved.as_deref(), Some("agent-open-x"));
1015    }
1016
1017    fn def(id: &str, name: &str, is_seeded: i64) -> AgentDefinition {
1018        let mut d = test_agent_def(id, name, "claude", "agent", 1, "");
1019        d.is_seeded = is_seeded;
1020        d
1021    }
1022
1023    /// `agent.open` opens user agents only: a template is refused by id or by
1024    /// name, and a user agent is preferred over a template it shares a name
1025    /// with — including the template's id, which is its lowercase name
1026    /// (adversarial review of #3600) — whatever the list order.
1027    #[test]
1028    fn agent_open_selects_my_agents_and_refuses_templates() {
1029        let agents = vec![
1030            def("claude", "Claude", 1),
1031            def("agent-mine", "Claude", 0),
1032            def("codex", "Codex", 1),
1033            def("agent-other", "agent-mine", 0),
1034        ];
1035        let pick = |wanted| select_openable_agent(&agents, wanted).map(|a| a.id.as_str());
1036
1037        assert_eq!(pick("agent-mine"), Ok("agent-mine"), "an id wins over a name");
1038        assert_eq!(pick("claude"), Ok("agent-mine"), "not the template's id");
1039        assert_eq!(pick("CLAUDE"), Ok("agent-mine"));
1040        for wanted in ["codex", "Codex"] {
1041            let err = pick(wanted).unwrap_err();
1042            assert!(err.starts_with("TEMPLATE_NOT_OPENABLE"), "{wanted}: {err}");
1043        }
1044        let err = pick("nobody").unwrap_err();
1045        assert!(err.starts_with("AGENT_NOT_FOUND"), "{err}");
1046    }
1047}
1048
1049#[cfg(test)]
1050#[path = "agent_open_single_live_instance_tests.rs"]
1051mod single_live_instance_tests;