Skip to main content

agentmux_srv/server/app_api/bundle/
import.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `bundle.import`, `bundle.import.preview`, `bundle.import.commit`: the ABF
5//! file/bytes intake path, its size and warning budgets, and the two-phase
6//! preview/commit flow.
7
8use super::*;
9
10#[derive(serde::Deserialize, Default, ts_rs::TS)]
11#[ts(export, export_to = "../../../frontend/types/rpc/")]
12pub(super) struct BundleImportReq {
13    #[serde(default)]
14    #[ts(optional)]
15    pub(super) zip_base64: Option<String>,
16    #[serde(default)]
17    #[ts(optional)]
18    pub(super) files: Option<Vec<FileEntry>>,
19}
20
21/// Response for `bundle.import`.
22#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
23#[ts(export, export_to = "../../../frontend/types/rpc/")]
24pub(crate) struct BundleImportResponse {
25    pub(crate) bundle_id: String,
26    pub(crate) imported_skill_ids: Vec<String>,
27    pub(crate) skipped_skills: Vec<String>,
28    pub(crate) resolved_requirement_ids: Vec<String>,
29    pub(crate) unresolved_requirements: Vec<crate::backend::rpc_types::BundleImportUnresolvedRequirement>,
30    pub(crate) warnings: Vec<String>,
31}
32
33/// Parses the two intake shapes of `bundle.import` -- `zip_base64` or a raw
34/// `files` list, exactly one -- into the file list plus the intake warnings.
35fn bundle_import_intake(
36    req: BundleImportReq,
37) -> Result<(Vec<crate::backend::bundle_import::BundleImportFile>, Vec<String>), String> {
38    match (req.zip_base64, req.files) {
39        (Some(_), Some(_)) => {
40            Err("bundle.import: exactly one of zip_base64/files must be present, got both".to_string())
41        }
42        (None, None) => {
43            Err("bundle.import: exactly one of zip_base64/files must be present, got neither".to_string())
44        }
45        (Some(b64), None) => {
46            use base64::Engine as _;
47            let zip_bytes = base64::engine::general_purpose::STANDARD
48                .decode(&b64)
49                .map_err(|e| format!("bundle.import: invalid zip_base64: {e}"))?;
50            crate::backend::bundle_import::unzip_bundle_import(&zip_bytes)
51                .map_err(|e| format!("bundle.import: {e}"))
52        }
53        (None, Some(files)) => {
54            // reagent P1, PR #2379 round 5: the raw `files`
55            // list previously skipped straight to
56            // parse_bundle_import with zero size/count
57            // enforcement, even though the spec treats it as
58            // an equally untrusted alternate ingestion path
59            // to zip_base64 — bypassing every zip-bomb/DoS
60            // defense the zip path enforces.
61            let raw_files: Vec<crate::backend::bundle_import::BundleImportFile> = files
62                .into_iter()
63                .map(|f| crate::backend::bundle_import::BundleImportFile {
64                    path: f.path,
65                    content: f.content,
66                })
67                .collect();
68            crate::backend::bundle_import::enforce_raw_files_caps(raw_files)
69                .map_err(|e| format!("bundle.import: {e}"))
70        }
71    }
72}
73
74/// Skills — global, not bound to any agent (mirrors
75/// skill.catalog.upsert's own is_global: true convention for
76/// a shared-resource creation path). A genuine name
77/// conflict (the ONLY intentional business error
78/// `skill_upsert_unique_global` returns —
79/// `StoreError::Other` containing "already exists") is a
80/// per-skill warning, not an aborted import. Codex P2, PR
81/// #2379: any OTHER error (locked/corrupt store, I/O
82/// failure) previously hit this same arm and was silently
83/// treated as a skip too — turning an infrastructure
84/// failure into an apparently-successful lossy import.
85/// Only the confirmed-conflict shape is swallowed; anything
86/// else aborts the whole RPC.
87///
88/// Returns `(imported_skill_ids, skipped_skills)`.
89fn create_global_skills(
90    state: &AppState,
91    parsed: &crate::backend::bundle_import::ParsedBundleImport,
92    warnings: &mut Vec<String>,
93    now: i64,
94) -> Result<(Vec<String>, Vec<String>), String> {
95    let mut imported_skill_ids: Vec<String> = Vec::new();
96    let mut skipped_skills = parsed.skipped_skills.clone();
97    for skill in &parsed.skills {
98        let row = crate::backend::storage::Skill {
99            id: uuid::Uuid::new_v4().to_string(),
100            name: skill.slug.clone(),
101            trigger: skill.slug.clone(),
102            skill_type: crate::backend::agent_config::SKILL_TYPE_AGENT_SKILL.to_string(),
103            description: skill.description.clone(),
104            content: skill.content.clone(),
105            is_global: true,
106            created_at: now,
107            updated_at: now,
108        };
109        match state.identity_store.skill_upsert_unique_global(&row) {
110            Ok(()) => imported_skill_ids.push(row.id),
111            Err(crate::backend::storage::error::StoreError::Other(msg))
112                if msg.contains("already exists") =>
113            {
114                warnings.push(format!("skill \"{}\": {msg}", skill.slug));
115                skipped_skills.push(skill.slug.clone());
116            }
117            Err(e) => {
118                // Codex P2, PR #2379: roll back every skill this
119                // loop already created before propagating —
120                // otherwise an infra failure partway through
121                // leaves orphaned global skill rows (bound to
122                // no bundle, but visible/bindable by any agent)
123                // behind a failed RPC.
124                let rollback_errors = rollback_skills(state, &imported_skill_ids);
125                let mut msg = format!(
126                    "bundle.import: failed to create skill \"{}\": {e}",
127                    skill.slug
128                );
129                if !rollback_errors.is_empty() {
130                    msg.push_str(&format!(
131                        "; additionally, rollback of {} previously-created skill(s) failed and may have left orphaned global skill row(s): {}",
132                        rollback_errors.len(),
133                        rollback_errors.join("; ")
134                    ));
135                }
136                return Err(msg);
137            }
138        }
139    }
140    Ok((imported_skill_ids, skipped_skills))
141}
142
143/// codex P2, PR #2379 round 4: rollback previously discarded
144/// every skill_delete error via `let _ = ...`, so if the SAME
145/// failing store also rejects the cleanup deletes, previously-
146/// inserted global skills could silently survive an RPC that
147/// reports failure. No transaction primitive exists on Store
148/// today, so full atomicity is out of scope here; surfacing
149/// the rollback failure instead of swallowing it is the fix
150/// that fits — the caller at least learns cleanup itself may
151/// not have fully succeeded.
152fn rollback_skills(state: &AppState, ids: &[String]) -> Vec<String> {
153    ids.iter()
154        .filter_map(|id| state.mstore.skill_delete(&state.identity_store, id).err().map(|e| format!("{id}: {e}")))
155        .collect()
156}
157
158/// The bundle row a parsed import becomes.
159fn imported_bundle_row(
160    parsed: &crate::backend::bundle_import::ParsedBundleImport,
161    imported_skill_ids: &[String],
162    now: i64,
163) -> Bundle {
164    Bundle {
165        id: uuid::Uuid::new_v4().to_string(),
166        name: parsed.name.clone(),
167        description: parsed.description.clone(),
168        is_blank: false,
169        // Never imported as global — an import must not
170        // silently start injecting into every agent's
171        // CLAUDE.md without explicit user action (spec §4.4).
172        is_global: false,
173        provider: parsed.provider.clone(),
174        model: parsed.model.clone(),
175        instructions: parsed.instructions.clone(),
176        // ABF v0.2 §2.2: every variant is stored verbatim, no
177        // merge decision made at import time.
178        instructions_by_provider: serde_json::to_string(&parsed.instructions_by_provider)
179            .unwrap_or_else(|_| "{}".to_string()),
180        // Phase 3 spec §3.0: ImportedContextFile gained a
181        // stable `id` selection key alongside `path`/`content`
182        // -- project it away before persisting, matching
183        // `Bundle.context_files`'s existing documented
184        // `[{path, content}]` shape.
185        context_files: serde_json::to_string(
186            &parsed.context_files.iter().map(|cf| json!({"path": cf.path, "content": cf.content})).collect::<Vec<_>>(),
187        )
188        .unwrap_or_else(|_| "[]".to_string()),
189        // A bundle carries no MCP servers (see the warning below).
190        mcp_servers: "[]".to_string(),
191        skills: serde_json::to_string(imported_skill_ids)
192            .unwrap_or_else(|_| "[]".to_string()),
193        sort_order: 0,
194        created_at: now,
195        updated_at: now,
196        is_system: false,
197    }
198}
199
200/// `bundle.import` — ABF importer, Phase 2 of
201/// docs/specs/SPEC_ABF_V0_1_SINGLE_FILE_AND_IMPORTER_2026_08_01.md. Window-
202/// scoped like `bundle.export` (bundles aren't agent-specific). Accepts
203/// EITHER `zip_base64` (a `.abf` archive, mirroring `bundle.export`'s own
204/// `zip_base64` response field) OR `files` (a raw `[{path, content}]`
205/// list) — exactly one must be present. Hands the bytes to the pure
206/// `bundle_import` module for parsing/validation, then owns every Store
207/// side-effect: creates the bundle row, creates one global Skill row per
208/// parsed skill, and performs READ-ONLY account-requirement lookups
209/// (never creates an account, never writes a secret anywhere — see the
210/// spec's §4.5 correction for why this stopped short of "resolving"
211/// placeholders in place).
212pub(super) fn bundle_import(state: &AppState, req: BundleImportReq) -> Result<BundleImportResponse, String> {
213    let (files, mut warnings) = bundle_import_intake(req)?;
214
215    let parsed = crate::backend::bundle_import::parse_bundle_import(&files)
216        .map_err(|e| format!("bundle.import: {e}"))?;
217    warnings.extend(parsed.warnings.clone());
218
219    // Account requirement resolution (§4.5) — read-only lookup
220    // by provider, purely informational. Never creates an
221    // account, never writes anything derived from a match.
222    // Phase 3 spec §3.1: extracted into resolve_account_requirements,
223    // shared with the new preview/commit RPC handlers.
224    // Today's existing route keeps its response shape exactly
225    // as before -- unbounded, matching its own already-shipped
226    // behavior. The bounded-display projection below is a
227    // Phase 3 preview/commit-only requirement.
228    let resolved = resolve_account_requirements(&state.id_store, &parsed.requirements)
229        .map_err(|e| format!("bundle.import: {e}"))?;
230    let resolved_requirement_ids: Vec<String> =
231        resolved.iter().filter(|r| r.resolved()).map(|r| r.id.clone()).collect();
232    let unresolved_requirements: Vec<crate::backend::rpc_types::BundleImportUnresolvedRequirement> = resolved
233        .iter()
234        .filter(|r| !r.resolved())
235        .map(|r| crate::backend::rpc_types::BundleImportUnresolvedRequirement {
236            id: r.id.clone(),
237            provider: r.provider.clone(),
238            env: r.env.clone(),
239            match_count: r.match_count,
240        })
241        .collect();
242
243    let now = now_ms();
244    let (imported_skill_ids, skipped_skills) = create_global_skills(state, &parsed, &mut warnings, now)?;
245
246    let memory = imported_bundle_row(&parsed, &imported_skill_ids, now);
247    if let Err(e) = state.id_store.bundle_upsert(&memory) {
248        // Codex P2, PR #2379: same rollback as above — the
249        // skills this RPC just created must not survive a
250        // failed bundle creation as orphaned global rows.
251        let rollback_errors = rollback_skills(state, &imported_skill_ids);
252        let mut msg = format!("bundle.import: {e}");
253        if !rollback_errors.is_empty() {
254            msg.push_str(&format!(
255                "; additionally, rollback of {} previously-created skill(s) failed and may have left orphaned global skill row(s): {}",
256                rollback_errors.len(),
257                rollback_errors.join("; ")
258            ));
259        }
260        return Err(msg);
261    }
262
263    // Ref tables are authoritative — bind after the bundle row
264    // exists, or this import exports empty.
265    warnings.extend(bind_imported_components(
266        &state.mstore,
267        &state.id_store,
268        &state.identity_store,
269        &memory.id,
270        &imported_skill_ids,
271    ));
272    warnings.extend(mcp_servers_not_imported_warning(&parsed.mcp_servers));
273
274    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
275    if !imported_skill_ids.is_empty() {
276        state.broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
277    }
278
279    Ok(BundleImportResponse {
280        bundle_id: memory.id,
281        imported_skill_ids,
282        skipped_skills,
283        resolved_requirement_ids,
284        unresolved_requirements,
285        warnings,
286    })
287}
288
289pub(super) fn register_bundle_import(engine: &Arc<WshRpcEngine>, state: &AppState) {
290    let s = state.clone();
291    engine.register_typed(COMMAND_BUNDLE_IMPORT, move |req: BundleImportReq, _ctx| {
292        let s = s.clone();
293        async move {
294            crate::backend::bundle_use::note("import");
295            bundle_import(&s, req)
296        }
297    });
298}
299
300/// On-disk size ceiling for `file_path` input (Phase 3 spec §3.0.5, rounds
301/// 4/5) — generous headroom above `MAX_TOTAL_UNCOMPRESSED_BYTES`'s 50 MiB
302/// for compression/container overhead and imperfectly-compressed content.
303pub(super) const MAX_ABF_FILE_SIZE_BYTES: u64 = 100 * 1024 * 1024;
304
305/// Reads a `file_path` input server-side (Phase 3 spec §3.0.5). Opens the
306/// path with a no-follow mechanism so a symlink fails to open at all
307/// rather than being silently resolved to its target (round 6) — one
308/// handle, one continuous read, no second path resolution for anything to
309/// race against (round 5's TOCTOU fix): metadata comes from that SAME open
310/// handle and is checked against `MAX_ABF_FILE_SIZE_BYTES` BEFORE any read
311/// (round 4); the actual read is still hard-bounded via `.take(...)`
312/// regardless of what the metadata claimed.
313pub(super) fn read_abf_file_path(path: &str) -> Result<Vec<u8>, String> {
314    use std::io::Read;
315
316    #[cfg(unix)]
317    let mut file = {
318        use std::os::unix::fs::OpenOptionsExt;
319        std::fs::OpenOptions::new()
320            .read(true)
321            .custom_flags(libc::O_NOFOLLOW)
322            .open(path)
323            .map_err(|e| format!("{path}: failed to open: {e}"))?
324    };
325    #[cfg(windows)]
326    let mut file = {
327        use std::os::windows::fs::OpenOptionsExt;
328        // FILE_FLAG_OPEN_REPARSE_POINT (0x0020_0000): opens a symlink/
329        // junction AS the reparse point itself, rather than transparently
330        // following it to its target — the Windows equivalent of Unix's
331        // O_NOFOLLOW, in a single atomic CreateFileW call (no separate
332        // path resolution for a TOCTOU window to open in). The metadata
333        // check immediately below then rejects the handle outright if it
334        // turns out to be a reparse point. Windows symlinks require
335        // elevated privileges to create by default, narrowing (not
336        // eliminating) the practical risk this guards against.
337        const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
338        std::fs::OpenOptions::new()
339            .read(true)
340            .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
341            .open(path)
342            .map_err(|e| format!("{path}: failed to open: {e}"))?
343    };
344    #[cfg(not(any(unix, windows)))]
345    let mut file = std::fs::File::open(path).map_err(|e| format!("{path}: failed to open: {e}"))?;
346
347    let metadata = file.metadata().map_err(|e| format!("{path}: failed to stat: {e}"))?;
348    #[cfg(windows)]
349    if metadata.file_type().is_symlink() {
350        return Err(format!("{path}: refusing to follow a symlink"));
351    }
352    if !metadata.is_file() {
353        return Err(format!("{path}: not a regular file"));
354    }
355    if metadata.len() > MAX_ABF_FILE_SIZE_BYTES {
356        return Err(format!(
357            "{path}: size ({} bytes) exceeds the limit ({MAX_ABF_FILE_SIZE_BYTES} bytes)",
358            metadata.len()
359        ));
360    }
361
362    let mut buf: Vec<u8> = Vec::new();
363    let mut limited = (&mut file).take(MAX_ABF_FILE_SIZE_BYTES + 1);
364    limited.read_to_end(&mut buf).map_err(|e| format!("{path}: failed to read: {e}"))?;
365    if buf.len() as u64 > MAX_ABF_FILE_SIZE_BYTES {
366        return Err(format!("{path}: exceeds the size limit while reading"));
367    }
368    Ok(buf)
369}
370
371/// Bounded warning budget shared by `bundle.import.preview`/`.commit`
372/// (Phase 3 spec §3.1, round 11) — unlike the existing `bundle.import`
373/// route's effectively-unbounded budget, preserved unchanged above.
374pub(super) fn preview_commit_warning_budget() -> crate::backend::bundle_import::WarningBudget {
375    crate::backend::bundle_import::WarningBudget::bounded(200, 300)
376}
377
378/// Final combined-list bound applied to a preview/commit response's
379/// `warnings` (Phase 3 spec §3.1 round 8 / round 9's commit-response
380/// generalization) — cheap defense-in-depth over an already
381/// per-source-bounded list (each of `resolve_import_input`'s intake
382/// warnings and `parse_bundle_import_with_budget`'s own warnings is
383/// already individually bounded; concatenating two independently-bounded
384/// lists can still exceed either bound alone, so one more pass caps the
385/// combined total before it's ever serialized).
386/// Per-entry content cap for `project_instructions` in an import preview.
387///
388/// Deliberately far below `MAX_INSTRUCTIONS_PREVIEW_CHARS` (50k): that cap
389/// applies to ONE field, whereas a preview can carry up to
390/// `MAX_IMPORTED_PROJECT_INSTRUCTIONS` (200) of these, so the same number
391/// would put a 10 MB ceiling on a single response. 4k is enough to recognize a
392/// file and see how it opens; the untruncated bytes are in the archive itself.
393pub(super) const MAX_PROJECT_INSTRUCTION_PREVIEW_CHARS: usize = 4_000;
394
395pub(super) fn bound_warnings_for_response(warnings: Vec<String>) -> (Vec<String>, bool) {
396    const MAX_COMBINED_WARNINGS: usize = 200;
397    if warnings.len() <= MAX_COMBINED_WARNINGS {
398        (warnings, false)
399    } else {
400        let mut kept: Vec<String> = warnings.into_iter().take(MAX_COMBINED_WARNINGS).collect();
401        kept.push("... additional warnings not shown".to_string());
402        (kept, true)
403    }
404}
405
406/// The outcome of resolving one of `file_path`/`zip_base64`/`files` into
407/// intake-ready files plus the Phase 3 content digest (§3.0.5) — shared by
408/// `bundle.import.preview` and `.commit` so both compute the digest
409/// identically. The mode tag baked into `content_digest` (round 7) means a
410/// plain digest-equality check at commit is sufficient to enforce "same
411/// input mode as preview" (round 6) — no separate mode field is needed.
412#[derive(Debug)]
413pub(super) struct ResolvedImportInput {
414    pub(crate) files: Vec<crate::backend::bundle_import::BundleImportFile>,
415    pub(crate) intake_warnings: Vec<String>,
416    pub(crate) content_digest: String,
417    /// The archive's widgets (`widgets/<id>/`, read as bytes), out of
418    /// `files` and its warnings (SPEC_WIDGET_SHARING_2026_10_10.md §3).
419    pub(crate) widgets: Vec<crate::backend::bundle_widgets::BundleWidget>,
420}
421
422/// Takes a zip's widget entries out of the text files and their warnings,
423/// and reads them as bytes instead.
424fn split_widgets(
425    raw: &[u8],
426    files: &mut Vec<crate::backend::bundle_import::BundleImportFile>,
427    warnings: &mut Vec<String>,
428) -> Result<Vec<crate::backend::bundle_widgets::BundleWidget>, String> {
429    use crate::backend::bundle_widgets as bw;
430    files.retain(|f| !bw::is_widget_path(&f.path));
431    warnings.retain(|w| !bw::is_widget_warning(w));
432    bw::read_from_zip(raw)
433}
434
435pub(super) fn resolve_import_input(
436    file_path: Option<String>,
437    zip_base64: Option<String>,
438    files: Option<Vec<FileEntry>>,
439    warning_budget: crate::backend::bundle_import::WarningBudget,
440) -> Result<ResolvedImportInput, String> {
441    use crate::backend::bundle_import as bi;
442    let provided = [file_path.is_some(), zip_base64.is_some(), files.is_some()]
443        .iter()
444        .filter(|p| **p)
445        .count();
446    if provided != 1 {
447        return Err(format!(
448            "exactly one of file_path/zip_base64/files must be present, got {provided}"
449        ));
450    }
451    if let Some(path) = file_path {
452        let raw = read_abf_file_path(&path)?;
453        let content_digest = bi::content_digest_raw_bytes(bi::ImportInputMode::FilePath, &raw);
454        let (mut files, mut intake_warnings) = bi::unzip_bundle_import_with_budget(&raw, warning_budget)?;
455        let widgets = split_widgets(&raw, &mut files, &mut intake_warnings)?;
456        return Ok(ResolvedImportInput { files, intake_warnings, content_digest, widgets });
457    }
458    if let Some(b64) = zip_base64 {
459        use base64::Engine as _;
460        let raw = base64::engine::general_purpose::STANDARD
461            .decode(&b64)
462            .map_err(|e| format!("invalid zip_base64: {e}"))?;
463        let content_digest = bi::content_digest_raw_bytes(bi::ImportInputMode::ZipBase64, &raw);
464        let (mut files, mut intake_warnings) = bi::unzip_bundle_import_with_budget(&raw, warning_budget)?;
465        let widgets = split_widgets(&raw, &mut files, &mut intake_warnings)?;
466        return Ok(ResolvedImportInput { files, intake_warnings, content_digest, widgets });
467    }
468    let files = files.expect("exactly one input already validated present");
469    let raw_files: Vec<bi::BundleImportFile> = files
470        .into_iter()
471        .map(|f| bi::BundleImportFile { path: f.path, content: f.content })
472        .collect();
473    let (capped_files, intake_warnings) = bi::enforce_raw_files_caps_with_budget(raw_files, warning_budget)?;
474    let content_digest = bi::content_digest_files(&capped_files);
475    // Text files can't carry a widget's bytes: widgets come only in a zip.
476    Ok(ResolvedImportInput { files: capped_files, intake_warnings, content_digest, widgets: vec![] })
477}
478
479/// `bundle.import.preview` — Phase 3 of
480/// docs/specs/SPEC_ABF_IMPORT_UI_PHASE3_2026_08_02.md §3.1. Pure parse plus
481/// read-only collision/name-collision lookups — zero Store writes. Window-
482/// scoped like the rest of `bundle.*`. Extracted from the RPC closure into
483/// a directly-callable, directly-testable function (the closure itself
484/// only deserializes the request and forwards).
485pub(super) async fn bundle_import_preview_impl(
486    id_store: &crate::backend::storage::store::Store,
487    identity_store: &crate::backend::storage::store::Store,
488    mstore: &crate::backend::storage::store::Store,
489    req: PreviewReq,
490) -> Result<crate::backend::rpc_types::BundleImportPreviewResponse, String> {
491    use crate::backend::bundle_import as bi;
492
493    let resolved = resolve_import_input(req.file_path, req.zip_base64, req.files, preview_commit_warning_budget())
494        .map_err(|e| format!("bundle.import.preview: {e}"))?;
495
496    let parsed = bi::parse_bundle_import_with_budget(&resolved.files, preview_commit_warning_budget())
497        .map_err(|e| format!("bundle.import.preview: {e}"))?;
498
499    let widgets = preview_widgets(&resolved);
500    let mut all_warnings = resolved.intake_warnings;
501    all_warnings.extend(parsed.warnings.clone());
502
503    let skills = skill_previews(&parsed, identity_store, mstore).map_err(|e| format!("bundle.import.preview: {e}"))?;
504    let (instructions_preview, instructions_truncated, instructions_total_chars) =
505        bi::bounded_instructions_preview(&parsed.instructions);
506    let requirements = requirement_previews(id_store, &parsed).map_err(|e| format!("bundle.import.preview: {e}"))?;
507
508    // Bundle name collision -- soft, informational (§2: bundle_upsert
509    // has no name uniqueness constraint, so this never blocks).
510    let name_collision = id_store
511        .bundle_list()
512        .map_err(|e| format!("bundle.import.preview: {e}"))?
513        .into_iter()
514        .any(|b| b.name == parsed.name);
515
516    let (warnings, warnings_truncated) = bound_warnings_for_response(all_warnings);
517
518    Ok(crate::backend::rpc_types::BundleImportPreviewResponse {
519        widgets,
520        project_instructions: project_instruction_previews(&parsed),
521        description: bounded_display(&parsed.description),
522        instructions_preview,
523        instructions_truncated,
524        instructions_total_chars,
525        context_files: context_file_previews(&parsed),
526        skills,
527        mcp_servers: mcp_server_previews(&parsed),
528        requirements,
529        warnings,
530        warnings_truncated,
531        name_collision,
532        content_digest: resolved.content_digest,
533        name: parsed.name,
534    })
535}
536
537/// Skill collision detection (§3.1, two-pass): against the skills already installed, and among the bundle's own.
538fn skill_previews(
539    parsed: &crate::backend::bundle_import::ParsedBundleImport,
540    identity_store: &crate::backend::storage::store::Store,
541    mstore: &crate::backend::storage::store::Store,
542) -> Result<Vec<crate::backend::rpc_types::BundleImportSkillPreview>, String> {
543    use crate::backend::bundle_import as bi;
544    let global_slugs: std::collections::HashSet<String> =
545        mstore.skill_list_global(identity_store).map_err(|e| e.to_string())?.into_iter().map(|item| item.skill.name).collect();
546    let in_bundle_dupes = bi::duplicate_in_bundle_slugs(&parsed.skills);
547    Ok(parsed
548        .skills
549        .iter()
550        .zip(crate::backend::bundle_import_skill_text::bounded_skill_previews(&parsed.skills))
551        .map(|(skill, text)| {
552            let collision = bi::classify_skill_collision(&skill.slug, &global_slugs, &in_bundle_dupes);
553            crate::backend::rpc_types::BundleImportSkillPreview {
554                source_dir: skill.source_dir.clone(),
555                slug: bounded_display(&skill.slug),
556                description: bounded_display(&skill.description),
557                collision: collision.to_string(),
558                content: text.text,
559                content_truncated: text.truncated,
560                content_total_chars: text.total_chars,
561            }
562        })
563        .collect())
564}
565
566fn mcp_server_previews(
567    parsed: &crate::backend::bundle_import::ParsedBundleImport,
568) -> Vec<crate::backend::rpc_types::BundleImportMcpServerPreview> {
569    use crate::backend::rpc_types::{BundleImportMcpServerDisplay, BundleImportMcpServerPreview};
570    parsed
571        .mcp_servers
572        .iter()
573        .map(|m| {
574            // `mcp_server_display` still returns a Value (it is also used
575            // elsewhere and has its own tests asserting it never leaks the full
576            // config); read its two known keys back into the typed shape rather
577            // than changing that function's contract here.
578            let display = crate::backend::bundle_import::mcp_server_display(&m.config);
579            BundleImportMcpServerPreview {
580                source_path: m.source_path.clone(),
581                display: BundleImportMcpServerDisplay {
582                    name: display.get("name").and_then(|v| v.as_str()).map(str::to_string),
583                    command: display.get("command").and_then(|v| v.as_str()).map(str::to_string),
584                },
585            }
586        })
587        .collect()
588}
589
590fn context_file_previews(
591    parsed: &crate::backend::bundle_import::ParsedBundleImport,
592) -> Vec<crate::backend::rpc_types::BundleImportContextFilePreview> {
593    parsed
594        .context_files
595        .iter()
596        .map(|cf| crate::backend::rpc_types::BundleImportContextFilePreview {
597            id: cf.id,
598            display_path: bounded_display(&cf.path),
599            size_bytes: cf.content.len(),
600        })
601        .collect()
602}
603
604fn requirement_previews(
605    id_store: &crate::backend::storage::store::Store,
606    parsed: &crate::backend::bundle_import::ParsedBundleImport,
607) -> Result<Vec<crate::backend::rpc_types::BundleImportRequirementPreview>, String> {
608    Ok(resolve_account_requirements(id_store, &parsed.requirements)?
609        .iter()
610        .map(|r| crate::backend::rpc_types::BundleImportRequirementPreview {
611            id: bounded_display(&r.id),
612            provider: bounded_display(&r.provider),
613            env: bounded_display(&r.env),
614            resolved: r.resolved(),
615            match_count: r.match_count,
616        })
617        .collect())
618}
619
620/// Phase 3, Codex P1 on PR #3163. Read-only: this is what the SOURCE agent
621/// was reading, and `bundle.import.commit` has no counterpart field — the
622/// entries exist to be looked at, never to be written into the importing
623/// repository (spec §5.2). Each content is bounded the same way
624/// `instructions_preview` is, since a snapshot can be an arbitrarily large
625/// repository file and the response carries up to
626/// MAX_IMPORTED_PROJECT_INSTRUCTIONS of them.
627fn project_instruction_previews(
628    parsed: &crate::backend::bundle_import::ParsedBundleImport,
629) -> Vec<crate::backend::rpc_types::BundleImportProjectInstructionPreview> {
630    parsed
631        .project_instructions
632        .iter()
633        .map(|pi| {
634            let total_chars = pi.content.chars().count();
635            let truncated = total_chars > MAX_PROJECT_INSTRUCTION_PREVIEW_CHARS;
636            let preview: String = if truncated {
637                pi.content.chars().take(MAX_PROJECT_INSTRUCTION_PREVIEW_CHARS).collect()
638            } else {
639                pi.content.clone()
640            };
641            crate::backend::rpc_types::BundleImportProjectInstructionPreview {
642                path: bounded_display(&pi.path),
643                file: bounded_display(&pi.file),
644                content_hash: bounded_display(&pi.content_hash),
645                owner: bounded_display(&pi.owner),
646                content_preview: preview,
647                content_truncated: truncated,
648                content_total_chars: total_chars,
649            }
650        })
651        .collect()
652}
653
654pub(super) fn register_bundle_import_preview(engine: &Arc<WshRpcEngine>, state: &AppState) {
655    let id_store = state.id_store.clone();
656    let identity_store = state.identity_store.clone();
657    let mstore = state.mstore.clone();
658    engine.register_typed(
659        COMMAND_BUNDLE_IMPORT_PREVIEW,
660        move |req: PreviewReq, _ctx| {
661            let id_store = id_store.clone();
662            let identity_store = identity_store.clone();
663            let mstore = mstore.clone();
664            async move {
665                bundle_import_preview_impl(&id_store, &identity_store, &mstore, req).await
666            }
667        },
668    );
669}
670
671
672
673
674/// `bundle.import.commit` — Phase 3 §3.2. Re-resolves and re-parses the
675/// same input fresh (never trusts client-supplied preview data for
676/// anything written), rejects on a content-digest mismatch, then writes
677/// only the selected items. Shares `bundle.import`'s existing skill-write/
678/// rollback logic; the differences are selection filtering, the
679/// `bundle_name`/`import_as` overrides, and the digest gate. Extracted
680/// from the RPC closure into a directly-callable, directly-testable
681/// function (the closure itself only deserializes the request and
682/// forwards).
683pub(super) async fn bundle_import_commit_impl(
684    id_store: &crate::backend::storage::store::Store,
685    identity_store: &crate::backend::storage::store::Store,
686    mstore: &crate::backend::storage::store::Store,
687    broker: &crate::backend::mps::Broker,
688    req: CommitReq,
689) -> Result<crate::backend::rpc_types::BundleImportCommitResponse, String> {
690    use crate::backend::bundle_import as bi;
691    use crate::backend::rpc_types::BundleImportCommitResponse;
692
693    let resolved = resolve_import_input(req.file_path, req.zip_base64, req.files, preview_commit_warning_budget())
694        .map_err(|e| format!("bundle.import.commit: {e}"))?;
695
696    // §3.0.5: reject BEFORE doing anything else on a mismatch -- never a partial import against
697    // whatever content was actually given. The mode tag baked into content_digest also enforces
698    // "same input mode as preview", so no separate mode field is needed.
699    if resolved.content_digest != req.expected_content_digest {
700        return Err(
701            "bundle.import.commit: content changed since preview (digest mismatch) — re-select and preview again"
702                .to_string(),
703        );
704    }
705
706    let parsed = bi::parse_bundle_import_with_budget(&resolved.files, preview_commit_warning_budget())
707        .map_err(|e| format!("bundle.import.commit: {e}"))?;
708
709    let mut warnings = resolved.intake_warnings;
710    warnings.extend(parsed.warnings.clone());
711
712    // The bundle_name override must be substituted for parsed.name, never silently ignored.
713    // Unlike parsed.name (bounded at parse time) a client-supplied override had no length cap, so
714    // bound_bundle_name applies the same cap to both paths (a no-op when it is already parsed.name).
715    let bundle_name = bi::bound_bundle_name(&req.bundle_name.unwrap_or_else(|| parsed.name.clone()));
716
717    let resolved_reqs = resolve_account_requirements(id_store, &parsed.requirements)
718        .map_err(|e| format!("bundle.import.commit: {e}"))?;
719    let (resolved_requirement_ids, unresolved_requirements) = split_requirements(&resolved_reqs);
720
721    let now = now_ms();
722    let mut skipped_skills: Vec<String> = Vec::new();
723    let imported_skill_ids = import_selected_skills(
724        mstore,
725        identity_store,
726        &parsed,
727        &req.include_skills,
728        now,
729        &mut warnings,
730        &mut skipped_skills,
731    )?;
732
733    let memory = commit_bundle_row(&parsed, bundle_name, req.include_instructions, &req.include_context_files, &imported_skill_ids, now);
734    if let Err(e) = id_store.bundle_upsert(&memory) {
735        let rollback_errors = rollback_skill_rows(mstore, identity_store, &imported_skill_ids);
736        return Err(with_rollback_note(format!("bundle.import.commit: {e}"), rollback_errors));
737    }
738
739    // Ref tables are authoritative — bind after the bundle row exists.
740    warnings.extend(bind_imported_components(mstore, id_store, identity_store, &memory.id, &imported_skill_ids));
741    warnings.extend(mcp_servers_not_imported_warning(&parsed.mcp_servers));
742
743    broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
744    if !imported_skill_ids.is_empty() {
745        broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
746    }
747
748    // Bounded the same as preview's response, not left unbounded like bundle.import.
749    let (bounded_warnings, warnings_truncated) = bound_warnings_for_response(warnings);
750
751    Ok(BundleImportCommitResponse {
752        widgets: vec![],
753        bundle_id: memory.id,
754        imported_skill_ids,
755        skipped_skills,
756        resolved_requirement_ids,
757        unresolved_requirements,
758        warnings: bounded_warnings,
759        warnings_truncated,
760    })
761}
762
763/// The commit response's requirement lists, using the same bounded-display projection as preview.
764fn split_requirements(
765    resolved_reqs: &[RequirementResolution],
766) -> (Vec<String>, Vec<crate::backend::rpc_types::BundleImportUnresolvedRequirement>) {
767    let resolved_ids = resolved_reqs.iter().filter(|r| r.resolved()).map(|r| bounded_display(&r.id)).collect();
768    let unresolved = resolved_reqs
769        .iter()
770        .filter(|r| !r.resolved())
771        .map(|r| crate::backend::rpc_types::BundleImportUnresolvedRequirement {
772            id: bounded_display(&r.id),
773            provider: bounded_display(&r.provider),
774            env: bounded_display(&r.env),
775            match_count: r.match_count,
776        })
777        .collect();
778    (resolved_ids, unresolved)
779}
780
781/// Delete the skill rows a failed commit already created; returns one message per row that would
782/// not delete.
783fn rollback_skill_rows(
784    mstore: &crate::backend::storage::store::Store,
785    identity_store: &crate::backend::storage::store::Store,
786    ids: &[String],
787) -> Vec<String> {
788    ids.iter()
789        .filter_map(|id| mstore.skill_delete(identity_store, id).err().map(|e| format!("{id}: {e}")))
790        .collect()
791}
792
793/// The selections to import: the client-supplied `include_skills` has no length cap and no dedup
794/// by source_dir, so an unbounded or repeated array could otherwise drive an unbounded number of
795/// skill_upsert_unique_global writes regardless of how many skills the archive itself parsed to
796/// (parsed.skills is already bounded by MAX_IMPORTED_SKILLS). First occurrence wins per source_dir,
797/// then the list is capped at the same MAX_IMPORTED_SKILLS the parser enforces.
798fn dedupe_skill_selections(include_skills: &[SkillSelection]) -> Vec<&SkillSelection> {
799    let mut seen_source_dirs: std::collections::HashSet<&str> = std::collections::HashSet::new();
800    include_skills
801        .iter()
802        .filter(|s| seen_source_dirs.insert(s.source_dir.as_str()))
803        .take(crate::backend::bundle_import::MAX_IMPORTED_SKILLS)
804        .collect()
805}
806
807/// Write the selected skills as global skills and return the ids created. A skill whose slug
808/// collides and has no non-empty rename is skipped; a name conflict at write time is a warning and
809/// a skip; any other write error rolls back the skills already created and fails the commit.
810///
811/// The collision is recomputed server-side so §4.1 point 4 ("an empty rename on a colliding skill =
812/// skip") is enforced here, not left to a client to honour: otherwise a "duplicate_in_bundle"
813/// collision (not yet in the global catalog) would let the FIRST of two same-slug skills write
814/// under its own slug even with an empty rename, since skill_upsert_unique_global alone would not
815/// reject it until the second attempt.
816fn import_selected_skills(
817    mstore: &crate::backend::storage::store::Store,
818    identity_store: &crate::backend::storage::store::Store,
819    parsed: &crate::backend::bundle_import::ParsedBundleImport,
820    include_skills: &[SkillSelection],
821    now: i64,
822    warnings: &mut Vec<String>,
823    skipped_skills: &mut Vec<String>,
824) -> Result<Vec<String>, String> {
825    use crate::backend::bundle_import as bi;
826    let global_slugs: std::collections::HashSet<String> = mstore
827        .skill_list_global(identity_store)
828        .map_err(|e| format!("bundle.import.commit: {e}"))?
829        .into_iter()
830        .map(|item| item.skill.name)
831        .collect();
832    let in_bundle_dupes = bi::duplicate_in_bundle_slugs(&parsed.skills);
833    let mut imported_skill_ids: Vec<String> = Vec::new();
834
835    for selection in dedupe_skill_selections(include_skills) {
836        let Some(skill) = parsed.skills.iter().find(|s| s.source_dir == selection.source_dir) else {
837            continue; // source_dir not present in this parse -- nothing to import
838        };
839        let collision = bi::classify_skill_collision(&skill.slug, &global_slugs, &in_bundle_dupes);
840        let non_empty_rename = selection.import_as.as_deref().filter(|s| !s.is_empty());
841
842        if collision != "none" && non_empty_rename.is_none() {
843            // §4.1 point 4: never silently sent through with its original, known-conflicting slug.
844            skipped_skills.push(bounded_display(&skill.slug));
845            continue;
846        }
847        let effective_slug = non_empty_rename.map(|s| s.to_string()).unwrap_or_else(|| skill.slug.clone());
848
849        let row = crate::backend::storage::Skill {
850            id: uuid::Uuid::new_v4().to_string(),
851            name: effective_slug.clone(),
852            trigger: effective_slug.clone(),
853            skill_type: crate::backend::agent_config::SKILL_TYPE_AGENT_SKILL.to_string(),
854            description: skill.description.clone(),
855            content: skill.content.clone(),
856            is_global: true,
857            created_at: now,
858            updated_at: now,
859        };
860        match identity_store.skill_upsert_unique_global(&row) {
861            Ok(()) => imported_skill_ids.push(row.id),
862            Err(crate::backend::storage::error::StoreError::Other(msg)) if msg.contains("already exists") => {
863                // effective_slug can be the caller-supplied import_as, which has no length bound
864                // before this point, and msg's own text embeds that same value a second time. Use a
865                // fixed message (its only informative content, "already exists", is implied by the
866                // branch guard) and the shared bounded_display projection, closing both unbounded
867                // paths at once rather than truncating msg in place.
868                warnings.push(format!("skill \"{}\": already exists", bounded_display(&effective_slug)));
869                skipped_skills.push(bounded_display(&effective_slug));
870            }
871            Err(e) => {
872                let rollback_errors = rollback_skill_rows(mstore, identity_store, &imported_skill_ids);
873                let msg = format!("bundle.import.commit: failed to create skill \"{effective_slug}\": {e}");
874                return Err(with_rollback_note(msg, rollback_errors));
875            }
876        }
877    }
878    Ok(imported_skill_ids)
879}
880
881/// The bundle row a commit writes: the parsed bundle with only the selected components.
882fn commit_bundle_row(
883    parsed: &crate::backend::bundle_import::ParsedBundleImport,
884    bundle_name: String,
885    include_instructions: bool,
886    include_context_files: &[usize],
887    imported_skill_ids: &[String],
888    now: i64,
889) -> Bundle {
890    let instructions = if include_instructions { parsed.instructions.clone() } else { String::new() };
891    // ABF v0.2 §2.2: provider-scoped variants are part of the same "instructions" component, gated
892    // by the same include_instructions flag; the preview/commit UI has no per-variant selection.
893    let instructions_by_provider =
894        if include_instructions { parsed.instructions_by_provider.clone() } else { std::collections::HashMap::new() };
895    // include_context_files selects by the stable `id`, never by (truncatable) display_path.
896    let selected_context_files: Vec<serde_json::Value> = parsed
897        .context_files
898        .iter()
899        .filter(|cf| include_context_files.contains(&cf.id))
900        .map(|cf| json!({ "path": cf.path, "content": cf.content }))
901        .collect();
902    Bundle {
903        id: uuid::Uuid::new_v4().to_string(),
904        name: bundle_name,
905        description: parsed.description.clone(),
906        is_blank: false,
907        is_global: false,
908        // Like `description` (and unlike instructions and context files), provider/model are
909        // structural identity fields, not opt-in components: there is no include_provider toggle in
910        // the preview/commit UI, so these always carry straight through when present.
911        provider: parsed.provider.clone(),
912        model: parsed.model.clone(),
913        instructions,
914        instructions_by_provider: serde_json::to_string(&instructions_by_provider).unwrap_or_else(|_| "{}".to_string()),
915        context_files: serde_json::to_string(&selected_context_files).unwrap_or_else(|_| "[]".to_string()),
916        mcp_servers: "[]".to_string(),
917        skills: serde_json::to_string(imported_skill_ids).unwrap_or_else(|_| "[]".to_string()),
918        sort_order: 0,
919        created_at: now,
920        updated_at: now,
921        is_system: false,
922    }
923}
924
925pub(super) fn register_bundle_import_commit(engine: &Arc<WshRpcEngine>, state: &AppState) {
926    let id_store = state.id_store.clone();
927    let identity_store = state.identity_store.clone();
928    let mstore = state.mstore.clone();
929    let broker = state.broker.clone();
930    let app = state.clone();
931    engine.register_typed(
932        COMMAND_BUNDLE_IMPORT_COMMIT,
933        move |req: CommitReq, _ctx| {
934            let id_store = id_store.clone();
935            let identity_store = identity_store.clone();
936            let mstore = mstore.clone();
937            let broker = broker.clone();
938            let app = app.clone();
939            async move {
940                crate::backend::bundle_use::note("import_commit");
941                let widgets_input = (!req.include_widgets.is_empty())
942                    .then(|| (req.file_path.clone(), req.zip_base64.clone(), req.expected_content_digest.clone(), req.include_widgets.clone()));
943                let mut resp = bundle_import_commit_impl(&id_store, &identity_store, &mstore, &broker, req).await?;
944                if let Some((file_path, zip_base64, digest, include)) = widgets_input {
945                    resp.widgets = install_bundle_widgets(&app, file_path, zip_base64, &digest, &include).await;
946                }
947                Ok(resp)
948            }
949        },
950    );
951}
952
953/// The import preview's line for each widget the bundle carries.
954fn preview_widgets(resolved: &ResolvedImportInput) -> Vec<crate::backend::bundle_widgets::BundleImportWidgetPreview> {
955    use crate::backend::bundle_widgets as bw;
956    if resolved.widgets.is_empty() {
957        return vec![];
958    }
959    let manifest = resolved.files.iter().find(|f| f.path == crate::backend::bundle_import::MANIFEST_FILE).map(|f| f.content.as_str());
960    let declared = bw::declared(manifest);
961    let svc = crate::backend::widget::packages::service();
962    let installed = svc.map(|s| s.list()).unwrap_or_default();
963    resolved
964        .widgets
965        .iter()
966        .map(|w| {
967            bw::preview(w, &declared, &installed, |id, signer| match svc {
968                Some(s) => s.describe_signature(id, signer),
969                None => crate::backend::widget::signature::describe(id, signer, &Default::default()),
970            })
971        })
972        .collect()
973}
974
975/// After a commit: copy in the chosen widgets and ask the user to approve
976/// each, the way an agent's `WidgetInstall` does. The archive is read again
977/// and held to the digest the user previewed, so what installs is what they
978/// saw (SPEC_WIDGET_SHARING_2026_10_10.md §3.3). A bundle never approves a
979/// widget.
980async fn install_bundle_widgets(
981    app: &AppState,
982    file_path: Option<String>,
983    zip_base64: Option<String>,
984    digest: &str,
985    include: &[String],
986) -> Vec<crate::backend::rpc_types::BundleImportWidgetResult> {
987    use crate::backend::bundle_widgets as bw;
988    use crate::backend::rpc_types::BundleImportWidgetResult;
989    use crate::backend::widget::packages::{self as wp, WidgetState};
990    let failed = |id: &str, e: String| BundleImportWidgetResult { id: id.to_string(), status: "failed".into(), error: Some(e) };
991    let Some(svc) = wp::service() else {
992        return include.iter().map(|id| failed(id, "widget packages aren't available on this AgentMux".into())).collect();
993    };
994    let resolved = match tokio::task::spawn_blocking(move || resolve_import_input(file_path, zip_base64, None, preview_commit_warning_budget())).await {
995        Ok(Ok(r)) if r.content_digest == digest => r,
996        Ok(Ok(_)) => return include.iter().map(|id| failed(id, "the bundle changed since the preview".into())).collect(),
997        Ok(Err(e)) => return include.iter().map(|id| failed(id, e.clone())).collect(),
998        Err(e) => return include.iter().map(|id| failed(id, e.to_string())).collect(),
999    };
1000    let previews = preview_widgets(&resolved);
1001    let name = resolved
1002        .files
1003        .iter()
1004        .find(|f| f.path == crate::backend::bundle_import::MANIFEST_FILE)
1005        .and_then(|f| serde_json::from_str::<serde_json::Value>(&f.content).ok())
1006        .and_then(|v| v.get("name").and_then(|n| n.as_str()).map(str::to_string))
1007        .unwrap_or_else(|| "a bundle".into());
1008    let mut results = Vec::new();
1009    let mut asking = Vec::new();
1010    for id in include {
1011        let (Some(w), Some(p)) = (resolved.widgets.iter().find(|w| &w.id == id), previews.iter().find(|p| &p.id == id)) else {
1012            results.push(failed(id, "the bundle doesn't carry it".into()));
1013            continue;
1014        };
1015        if let Some(e) = &p.error {
1016            results.push(failed(id, e.clone()));
1017            continue;
1018        }
1019        if p.same_as_installed {
1020            results.push(BundleImportWidgetResult { id: id.clone(), status: "unchanged".into(), error: None });
1021            continue;
1022        }
1023        let (dir, widget) = (svc.widgets_dir.clone(), w.clone());
1024        match tokio::task::spawn_blocking(move || bw::install(&dir, &widget)).await {
1025            Ok(Ok(_)) => {
1026                asking.push(id.clone());
1027                results.push(BundleImportWidgetResult { id: id.clone(), status: "waiting".into(), error: None });
1028            }
1029            Ok(Err(e)) => results.push(failed(id, e)),
1030            Err(e) => results.push(failed(id, e.to_string())),
1031        }
1032    }
1033    if !asking.is_empty() {
1034        let packages = wp::refresh_off_thread(&app.config_watcher, &app.event_bus, &app.broker).await;
1035        let asker = format!("The bundle \u{201c}{name}\u{201d}");
1036        for pkg in packages.iter().filter(|p| asking.contains(&p.id) && p.state != WidgetState::Approved) {
1037            // Nobody waits on the answer: the prompt is the user's, and the
1038            // widget stays in Settings → Widgets until they answer.
1039            drop(crate::backend::widget::requests::requests().ask(crate::backend::widget::requests::WidgetInstallRequest::of(pkg, &asker, "")));
1040        }
1041        crate::server::widget_agent_handlers::publish_requests(app);
1042    }
1043    results
1044}