Skip to main content

agentmux_srv/server/app_api/bundle/
import_for_agent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `bundle.import_for_agent`: apply an ABF to an existing agent definition,
5//! serialised per agent by `bundle_import_for_agent_lock`.
6
7use super::*;
8
9#[derive(serde::Deserialize, Default, ts_rs::TS)]
10#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "BundleImportForAgentReq")]
11pub(super) struct ImportForAgentReq {
12    pub(crate) agent_id: String,
13    #[serde(default)]
14    #[ts(optional)]
15    pub(crate) file_path: Option<String>,
16    #[serde(default)]
17    #[ts(optional)]
18    pub(crate) zip_base64: Option<String>,
19    #[serde(default)]
20    #[ts(optional)]
21    pub(crate) files: Option<Vec<FileEntry>>,
22}
23
24/// Response for `bundle.import_for_agent`.
25#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
26#[ts(export, export_to = "../../../frontend/types/rpc/")]
27pub(crate) struct BundleImportForAgentResponse {
28    pub(crate) bundle_id: String,
29    #[ts(type = "number")]
30    pub(crate) memory_files_written: usize,
31    pub(crate) skipped_skills: Vec<String>,
32    pub(crate) warnings: Vec<String>,
33}
34
35/// `bundle.import_for_agent` — ABF v0.2 §2.3. The only import path that
36/// processes a `components.memory` key; the generic `bundle.import`
37/// explicitly skips it (see `parse_bundle_import_with_budget`'s own
38/// components.memory guard). Unlike `bundle.import`/`bundle.import.commit`,
39/// this is a single-step import — no preview phase — since a
40/// memory-bearing import has its own unconditional safety net instead:
41/// the target agent must have ZERO existing `db_agent_native_memory` rows,
42/// or the whole import is rejected before any write happens. Simpler than
43/// skip/rename/replace conflict resolution, and sufficient for v0.2 (see
44/// the spec's revision note for why merge semantics are an explicit
45/// follow-up, not designed here). Extracted from the RPC closure into a
46/// directly-callable, directly-testable function, matching
47/// `bundle_import_preview_impl`'s pattern.
48pub(super) async fn bundle_import_for_agent_impl(
49    id_store: &crate::backend::storage::store::Store,
50    identity_store: &crate::backend::storage::store::Store,
51    mstore: &crate::backend::storage::store::Store,
52    req: ImportForAgentReq,
53) -> Result<BundleImportForAgentResponse, String> {
54    use crate::backend::bundle_import as bi;
55
56    let agent = mstore
57        .agent_def_get(&req.agent_id)
58        .map_err(|e| format!("bundle.import_for_agent: {e}"))?
59        .ok_or_else(|| format!("bundle.import_for_agent: no agent with id {}", req.agent_id))?;
60
61    // reagent P2, PR #2527: serialize the whole "check zero rows, then
62    // write" sequence per agent — without this, two concurrent
63    // bundle.import_for_agent calls for the same agent can both pass the
64    // zero-rows check before either writes, both proceeding and defeating
65    // the "can't destroy existing memory" invariant. Held until the
66    // function returns (guard drops at every exit path), mirroring
67    // agent_open.rs's AGENT_OPEN_LOCKS precedent — same same-process-only
68    // scope note applies (can't see a genuinely different AgentMux
69    // instance/channel racing the same agent_id).
70    let import_lock = bundle_import_for_agent_lock(&agent.id);
71    let _import_guard = import_lock.lock().await;
72
73    let mut warnings: Vec<String> = Vec::new();
74    let memory_dir = refresh_memory_mirror_before_check(mstore, id_store, &agent, &mut warnings);
75
76    // Reject BEFORE any parsing/decoding work — a target with existing
77    // memory is a hard stop, not something worth spending
78    // decompression/parse cost on first.
79    let existing = id_store
80        .agent_native_memory_list_meta(&agent.id)
81        .map_err(|e| format!("bundle.import_for_agent: {e}"))?;
82    if !existing.is_empty() {
83        return Err(format!(
84            "bundle.import_for_agent: agent {} already has {} native memory file(s) — import into an agent with no existing memory, or clear it first",
85            req.agent_id,
86            existing.len()
87        ));
88    }
89
90    let resolved = resolve_import_input(req.file_path, req.zip_base64, req.files, bi::WarningBudget::unbounded())
91        .map_err(|e| format!("bundle.import_for_agent: {e}"))?;
92    let parsed = bi::parse_bundle_import(&resolved.files)
93        .map_err(|e| format!("bundle.import_for_agent: {e}"))?;
94
95    warnings.extend(resolved.intake_warnings);
96    // reagent P1, PR #2527: parse_bundle_import unconditionally warns
97    // that components.memory is "present but ignored" (correct for
98    // bundle.import/.preview/.commit, which really do ignore it) — but
99    // THIS function handles memory itself, further down. Filtering the
100    // exact shared-constant string out here (rather than duplicating a
101    // literal that could drift) stops every successful memory-bearing
102    // import from falsely claiming its memory was ignored.
103    warnings.extend(parsed.warnings.iter().filter(|w| w.as_str() != bi::MEMORY_COMPONENT_IGNORED_WARNING).cloned());
104
105    let manifest_memory_paths = resolved_memory_paths(&resolved.files);
106    let memory_dir = memory_dir_for_import(mstore, &agent, memory_dir, &manifest_memory_paths)?;
107
108    // Normal bundle components, exactly as bundle.import creates them —
109    // a memory-bearing import still creates a reusable bundle row
110    // alongside the agent-scoped memory write below.
111    let bundle_id = uuid::Uuid::new_v4().to_string();
112    let now = now_ms();
113    let imported_skill_ids = import_global_skills(mstore, identity_store, &parsed.skills, now, &mut warnings)?;
114    create_bundle_row(mstore, id_store, identity_store, &parsed, &bundle_id, &imported_skill_ids, now)?;
115
116    // The bundle row now exists, so its skills can be bound. Ref tables are
117    // authoritative — without this the imported bundle would export empty.
118    warnings.extend(bind_imported_components(
119        mstore,
120        id_store,
121        identity_store,
122        &bundle_id,
123        &imported_skill_ids,
124    ));
125    warnings.extend(mcp_servers_not_imported_warning(&parsed.mcp_servers));
126
127    let memory_files_written =
128        write_memory_files(id_store, &agent.id, memory_dir, manifest_memory_paths, &resolved.files, &mut warnings);
129
130    Ok(BundleImportForAgentResponse {
131        bundle_id,
132        memory_files_written,
133        skipped_skills: parsed.skipped_skills,
134        warnings,
135    })
136}
137
138/// The agent's memory directory (None when it has no resolvable working directory), after
139/// refreshing the mirror from it when it is a verified one.
140///
141/// The "zero existing memory" guard only (#2527)
142/// consults db_agent_native_memory (the mirror) — a live file that was
143/// written autonomously but never viewed through the Stash Bundle tab
144/// is NOT in the mirror yet, so the check would pass and the write
145/// loop further down would silently overwrite it via fs::rename. Same
146/// class of bug bundle.export_for_agent already had to guard against
147/// (see refresh_memory_mirror_from_live_fs's own doc comment) — the
148/// fix is the same: refresh from the live FS before trusting the
149/// mirror's row count. A missing/unresolvable working directory is not
150/// an error here (nothing to refresh from); the emptiness check below
151/// still runs against whatever the mirror already has.
152/// Only a verified directory is refreshed from: an unverified guess can be
153/// another agent's folder, and refreshing from it would write that
154/// agent's files into this one's mirror (SPEC_MEMORY_FOLLOWS_THE_AGENT
155/// §2.1.2).
156fn refresh_memory_mirror_before_check(
157    mstore: &crate::backend::storage::store::Store,
158    id_store: &crate::backend::storage::store::Store,
159    agent: &crate::backend::storage::AgentDefinition,
160    warnings: &mut Vec<String>,
161) -> Option<std::path::PathBuf> {
162    let resolved = crate::server::native_memory_handlers::resolve_memory_dir_by_id(mstore, agent);
163    let verified = resolved.as_ref().is_some_and(|r| {
164        r.provenance != crate::server::native_memory_handlers::MemoryDirProvenance::Unverified
165    });
166    let memory_dir = resolved.map(|r| r.path);
167    if let Some(dir) = memory_dir.as_ref().filter(|_| verified) {
168        if let Err(e) = crate::server::native_memory_handlers::refresh_memory_mirror_from_live_fs(&agent.id, dir, id_store) {
169            warnings.push(format!("native memory refresh failed (checking mirror as-is): {e}"));
170        }
171    }
172    memory_dir
173}
174
175/// The directory the import writes memory into: the one resolved before, unless the manifest has
176/// memory files, in which case it must be a verified one.
177fn memory_dir_for_import(
178    mstore: &crate::backend::storage::store::Store,
179    agent: &crate::backend::storage::AgentDefinition,
180    memory_dir: Option<std::path::PathBuf>,
181    manifest_memory_paths: &[String],
182) -> Result<Option<std::path::PathBuf>, String> {
183    // reagent P2, PR #2527: this RPC exists specifically to transfer
184    // memory — if the manifest actually has a memory component but this
185    // agent has no resolvable working directory (and therefore no memory
186    // dir to write into), failing fast here (before any skill/bundle
187    // writes) is correct; silently succeeding with
188    // memory_files_written: 0 would drop the one thing the caller asked
189    // for. A bundle with NO memory component is unaffected — that's a
190    // normal bundle.import_for_agent call that just happens not to need
191    // a memory dir.
192    if !manifest_memory_paths.is_empty() && memory_dir.is_none() {
193        return Err(format!(
194            "bundle.import_for_agent: agent {} has no working directory configured; cannot import its memory",
195            agent.id
196        ));
197    }
198    // Importing memory writes files, so the directory must be verified, not
199    // a blank-working-dir guess (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.2).
200    if manifest_memory_paths.is_empty() {
201        Ok(memory_dir)
202    } else {
203        crate::server::native_memory_handlers::memory_dir_for_write_by_id(mstore, agent)
204            .map(Some)
205            .map_err(|e| format!("bundle.import_for_agent: {e}"))
206    }
207}
208
209/// Delete the global skills an import created, after a later step failed; the errors of any that
210/// could not be deleted.
211///
212/// reagent P2, PR #2527: mirrors bundle.import's own rollback_skills
213/// closure — without it, a later failure (the bundle upsert below)
214/// leaves already-created global skill rows orphaned with no way for
215/// the caller to know cleanup may be needed.
216fn rollback_skills(
217    mstore: &crate::backend::storage::store::Store,
218    identity_store: &crate::backend::storage::store::Store,
219    ids: &[String],
220) -> Vec<String> {
221    ids.iter()
222        .filter_map(|id| mstore.skill_delete(identity_store, id).err().map(|e| format!("{id}: {e}")))
223        .collect()
224}
225
226/// `msg`, plus a note naming the skills a rollback could not delete.
227pub(super) fn with_rollback_note(mut msg: String, rollback_errors: Vec<String>) -> String {
228    if !rollback_errors.is_empty() {
229        msg.push_str(&format!(
230            "; additionally, rollback of {} previously-created skill(s) failed and may have left orphaned global skill row(s): {}",
231            rollback_errors.len(),
232            rollback_errors.join("; ")
233        ));
234    }
235    msg
236}
237
238/// Create the bundle's skills as global skills, exactly as bundle.import does (global, not bound to
239/// any agent; skill_upsert_unique_global is the real API — a genuine name conflict is a per-skill
240/// warning, any other error aborts the whole RPC). Returns the ids of the skills created.
241fn import_global_skills(
242    mstore: &crate::backend::storage::store::Store,
243    identity_store: &crate::backend::storage::store::Store,
244    skills: &[crate::backend::bundle_import::ParsedSkill],
245    now: i64,
246    warnings: &mut Vec<String>,
247) -> Result<Vec<String>, String> {
248    let mut imported_skill_ids: Vec<String> = Vec::new();
249    for skill in skills {
250        let row = crate::backend::storage::Skill {
251            id: uuid::Uuid::new_v4().to_string(),
252            name: skill.slug.clone(),
253            trigger: skill.slug.clone(),
254            skill_type: crate::backend::agent_config::SKILL_TYPE_AGENT_SKILL.to_string(),
255            description: skill.description.clone(),
256            content: skill.content.clone(),
257            is_global: true,
258            created_at: now,
259            updated_at: now,
260        };
261        match identity_store.skill_upsert_unique_global(&row) {
262            Ok(()) => imported_skill_ids.push(row.id),
263            Err(e) if e.to_string().contains("already exists") => {
264                warnings.push(format!("skill \"{}\" already exists; skipped", skill.slug));
265            }
266            Err(e) => {
267                let rollback_errors = rollback_skills(mstore, identity_store, &imported_skill_ids);
268                let msg = format!("bundle.import_for_agent: failed to create skill \"{}\": {e}", skill.slug);
269                return Err(with_rollback_note(msg, rollback_errors));
270            }
271        }
272    }
273    Ok(imported_skill_ids)
274}
275
276/// Insert the reusable bundle row for an import; on failure the skills it created are rolled back.
277fn create_bundle_row(
278    mstore: &crate::backend::storage::store::Store,
279    id_store: &crate::backend::storage::store::Store,
280    identity_store: &crate::backend::storage::store::Store,
281    parsed: &crate::backend::bundle_import::ParsedBundleImport,
282    bundle_id: &str,
283    imported_skill_ids: &[String],
284    now: i64,
285) -> Result<(), String> {
286    let memory = crate::backend::storage::store::Bundle {
287        id: bundle_id.to_string(),
288        name: parsed.name.clone(),
289        description: parsed.description.clone(),
290        is_blank: false,
291        is_global: false,
292        provider: parsed.provider.clone(),
293        model: parsed.model.clone(),
294        instructions: parsed.instructions.clone(),
295        instructions_by_provider: serde_json::to_string(&parsed.instructions_by_provider)
296            .unwrap_or_else(|_| "{}".to_string()),
297        context_files: serde_json::to_string(
298            &parsed.context_files.iter().map(|cf| json!({"path": cf.path, "content": cf.content})).collect::<Vec<_>>(),
299        ).unwrap_or_else(|_| "[]".to_string()),
300        // A bundle carries no MCP servers (see the warning below).
301        mcp_servers: "[]".to_string(),
302        skills: serde_json::to_string(imported_skill_ids).unwrap_or_else(|_| "[]".to_string()),
303        sort_order: 0,
304        created_at: now,
305        updated_at: now,
306        is_system: false,
307    };
308    if let Err(e) = id_store.bundle_upsert(&memory) {
309        let rollback_errors = rollback_skills(mstore, identity_store, imported_skill_ids);
310        return Err(with_rollback_note(format!("bundle.import_for_agent: {e}"), rollback_errors));
311    }
312    Ok(())
313}
314
315/// Bundle files: write through the SAME dual-write path
316/// agent:memory:write_file uses (live FS via memory_dir_for_cwd, then
317/// the mirror) — writing only to db_agent_native_memory would leave
318/// this content visible in Stash while invisible to the actual
319/// running agent (see the spec's revision note). Returns how many files were written.
320fn write_memory_files(
321    id_store: &crate::backend::storage::store::Store,
322    agent_id: &str,
323    memory_dir: Option<std::path::PathBuf>,
324    manifest_memory_paths: Vec<String>,
325    files: &[crate::backend::bundle_import::BundleImportFile],
326    warnings: &mut Vec<String>,
327) -> usize {
328    let mut memory_files_written = 0usize;
329    if let Some(memory_dir) = &memory_dir {
330        if let Err(e) = std::fs::create_dir_all(memory_dir) {
331            warnings.push(format!("native memory: mkdir failed: {e}"));
332        }
333    }
334    let Some(memory_dir) = memory_dir else {
335        return memory_files_written;
336    };
337    for path in manifest_memory_paths {
338        // reagent P1, PR #2527 (third round): every skip in this loop
339        // must warn — this RPC's whole reason to exist is transferring
340        // memory, and a silent drop here (bundle_id/skills already
341        // created, memory_files_written silently undercounting)
342        // directly contradicts that. Matches the sibling
343        // invalid-filename branch just below, which already warned.
344        let Some(filename) = path.strip_prefix("memory/") else {
345            warnings.push(format!("{path}: components.memory path is not under memory/; skipped"));
346            continue;
347        };
348        if crate::server::native_memory_handlers::validate_memory_filename(filename).is_err() {
349            warnings.push(format!("memory/{filename}: not a valid memory filename; skipped"));
350            continue;
351        }
352        let Some(content) = files.iter().find(|f| f.path == path).map(|f| f.content.clone()) else {
353            warnings.push(format!("{path}: referenced in components.memory but not found among the bundle's files; skipped"));
354            continue;
355        };
356        if write_memory_file(id_store, agent_id, &memory_dir, filename, &content, warnings) {
357            memory_files_written += 1;
358        }
359    }
360    memory_files_written
361}
362
363/// Write one memory file to the live directory and the mirror; false when either write failed
364/// (the failure is a warning).
365fn write_memory_file(
366    id_store: &crate::backend::storage::store::Store,
367    agent_id: &str,
368    memory_dir: &std::path::Path,
369    filename: &str,
370    content: &str,
371    warnings: &mut Vec<String>,
372) -> bool {
373    // Into the agent's memory record first, as every AgentMux write
374    // (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.1).
375    crate::backend::memory::reconcile::record_agentmux_write(
376        agent_id,
377        memory_dir,
378        filename,
379        content.as_bytes(),
380        "bundle-import",
381        "",
382    );
383    let dest = memory_dir.join(filename);
384    let tmp = memory_dir.join(format!(".{filename}.{}.tmp", uuid::Uuid::new_v4()));
385    let write_result = std::fs::write(&tmp, content)
386        .and_then(|_| std::fs::rename(&tmp, &dest));
387    if let Err(e) = write_result {
388        let _ = std::fs::remove_file(&tmp);
389        warnings.push(format!("memory/{filename}: write failed: {e}"));
390        return false;
391    }
392    let dest_meta = std::fs::metadata(&dest).ok();
393    let size_bytes = dest_meta.as_ref().map(|m| m.len() as i64).unwrap_or(content.len() as i64);
394    let mtime_ms = dest_meta
395        .and_then(|m| m.modified().ok())
396        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
397        .map(|d| d.as_millis() as i64)
398        .unwrap_or(0);
399    let metadata_type = crate::server::native_memory_handlers::parse_memory_frontmatter_type(content);
400    if let Err(e) = id_store.agent_native_memory_upsert(
401        agent_id,
402        filename,
403        content,
404        metadata_type.as_deref(),
405        &dest.to_string_lossy(),
406        size_bytes,
407        mtime_ms,
408    ) {
409        warnings.push(format!("memory/{filename}: mirror upsert failed: {e}"));
410        return false;
411    }
412    true
413}
414
415pub(super) fn register_bundle_import_for_agent(engine: &Arc<WshRpcEngine>, state: &AppState) {
416    let id_store = state.id_store.clone();
417    let identity_store = state.identity_store.clone();
418    let mstore = state.mstore.clone();
419    engine.register_typed(
420        COMMAND_BUNDLE_IMPORT_FOR_AGENT,
421        move |req: ImportForAgentReq, _ctx| {
422            let id_store = id_store.clone();
423            let identity_store = identity_store.clone();
424            let mstore = mstore.clone();
425            async move {
426                crate::backend::bundle_use::note("import_for_agent");
427                bundle_import_for_agent_impl(&id_store, &identity_store, &mstore, req).await
428            }
429        },
430    );
431}
432
433/// Every `memory/*` path listed under `components.memory` in a parsed
434/// import's manifest (`bundle.json`, or `armory.json` before ABF v0.3) — mirrors how `components.instructions`/
435/// `components.skills` are read elsewhere in this file, kept local to
436/// `bundle.import_for_agent` since no other handler needs it.
437pub(super) fn resolved_memory_paths(files: &[crate::backend::bundle_import::BundleImportFile]) -> Vec<String> {
438    let Some(name) = crate::backend::bundle_import::manifest_file_name(|n| files.iter().any(|f| f.path == n)) else {
439        return Vec::new();
440    };
441    let Some(manifest_file) = files.iter().find(|f| f.path == name) else {
442        return Vec::new();
443    };
444    let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&manifest_file.content) else {
445        return Vec::new();
446    };
447    manifest["components"]["memory"]
448        .as_array()
449        .map(|arr| arr.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
450        .unwrap_or_default()
451}