Skip to main content

agentmux_srv/server/app_api/bundle/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `bundle.*` MuxAPI handlers — the Armory Bundle Format (ABF) surface.
5//!
6//! Module layout (split 2026-09-22): this file holds registration, the plain
7//! CRUD/validate/self_get handlers, and the helpers every family shares;
8//! each `bundle.*` family lives in its own child module. The children are
9//! glob-imported back here so that, exactly as when this was one file, any
10//! function can call any other without an import.
11
12use super::*;
13use crate::server::api_error::ApiError;
14
15/// Raw `[{path, content}]` entry shape, shared by `bundle.import`'s `files`
16/// input and the Phase 3 `bundle.import.preview`/`.commit` handlers. Now one
17/// definition in rpc_types rather than a private copy here, so the generated
18/// bindings and this file cannot disagree about it.
19use crate::backend::rpc_types::BundleImportFileEntry as FileEntry;
20
21// `PreviewReq`/`CommitReq`/`SkillSelection` moved to
22// backend::rpc_types::bundle_import so the bindings generator can see them --
23// they were private to this file, which is why the frontend's copies were
24// hand-written and, in preview's case, wrong (it declared only `file_path`).
25use crate::backend::rpc_types::{
26    BundleImportSkillSelection as SkillSelection,
27    CommandBundleImportCommitData as CommitReq,
28    CommandBundleImportPreviewData as PreviewReq,
29};
30
31mod components;
32mod export;
33mod export_for_agent;
34mod import;
35mod import_for_agent;
36
37#[cfg(test)]
38mod tests;
39
40use components::*;
41use export::*;
42use export_for_agent::*;
43use import::*;
44use import_for_agent::*;
45
46// Referenced from outside `bundle` under these paths and visibilities.
47pub(crate) use components::purge_bundle_component_refs;
48pub(super) use components::resolve_bundle_components;
49pub(crate) use components::MEMORY_NOT_EXPORTED_WARNING;
50
51/// Per-agent async lock serializing `bundle.import_for_agent`'s "check
52/// zero existing memory rows, then write" sequence — ABF v0.2 §2.3,
53/// reagent P2 on PR #2527. Mirrors `agent_open.rs`'s `AGENT_OPEN_LOCKS`
54/// precedent exactly, including its scope note: this only serializes
55/// calls handled by THIS process, not a genuinely different AgentMux
56/// instance/channel racing the same agent_id.
57static BUNDLE_IMPORT_FOR_AGENT_LOCKS: std::sync::LazyLock<
58    std::sync::Mutex<std::collections::HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
59> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
60
61fn bundle_import_for_agent_lock(agent_id: &str) -> Arc<tokio::sync::Mutex<()>> {
62    let mut locks = BUNDLE_IMPORT_FOR_AGENT_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
63    locks
64        .entry(agent_id.to_string())
65        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
66        .clone()
67}
68
69pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
70    register_bundle_list(engine, state);
71    register_bundle_get(engine, state);
72    register_bundle_upsert(engine, state);
73    register_bundle_delete(engine, state);
74    register_bundle_self_get(engine, state);
75    register_bundle_export(engine, state);
76    register_bundle_import(engine, state);
77    register_bundle_import_preview(engine, state);
78    register_bundle_import_commit(engine, state);
79    register_bundle_export_for_agent(engine, state);
80    register_bundle_export_for_agent_with_history(engine, state);
81    register_bundle_import_for_agent(engine, state);
82    register_bundle_validate(engine, state);
83    register_agent_project_instructions(engine, state);
84}
85
86/// Normalize a `bundle.upsert` request body into the shape the `Bundle` struct
87/// deserializes from, so MuxAPI accepts the request exactly as documented
88/// in the spec:
89///   - `id` may be omitted to create (the struct has no serde default), so an
90///     absent or null `id` is filled with an empty string (the handler then
91///     mints a UUID).
92///   - `context_files` / `mcp_servers` / `skills` are JSON-encoded array strings
93///     on the struct, but the spec shows them as JSON arrays. Array values are
94///     re-encoded to their JSON string form; values already given as strings
95///     pass through untouched.
96pub(super) fn normalize_bundle_upsert_input(mut data: serde_json::Value) -> serde_json::Value {
97    if let serde_json::Value::Object(ref mut map) = data {
98        match map.get("id") {
99            Some(serde_json::Value::String(_)) => {}
100            _ => {
101                map.insert("id".to_string(), serde_json::Value::String(String::new()));
102            }
103        }
104        for key in ["context_files", "mcp_servers", "skills"] {
105            if let Some(v) = map.get(key) {
106                if v.is_array() {
107                    let encoded =
108                        serde_json::to_string(v).unwrap_or_else(|_| "[]".to_string());
109                    map.insert(key.to_string(), serde_json::Value::String(encoded));
110                }
111            }
112        }
113    }
114    data
115}
116
117// The deprecated `preset.*` aliases (Phase 2's one-release compat window)
118// were retired as part of the ABF UI-alignment pass —
119// `bundle.*` is the only surface now; see the ABF branding sweep this
120// change shipped alongside.
121
122/// One `bundle.list` row: a bundle's summary fields, not the whole bundle.
123#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
124#[ts(export, export_to = "../../../frontend/types/rpc/")]
125pub(crate) struct BundleListItem {
126    pub(crate) id: String,
127    pub(crate) name: String,
128    pub(crate) description: String,
129    pub(crate) provider: String,
130    pub(crate) model: String,
131    pub(crate) is_blank: bool,
132    #[ts(type = "number")]
133    pub(crate) updated_at: i64,
134}
135
136/// Response for `bundle.list`: the same rows under both keys (see
137/// `bundle_list_impl`).
138#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
139#[ts(export, export_to = "../../../frontend/types/rpc/")]
140pub(crate) struct BundleListResponse {
141    pub(crate) bundles: Vec<BundleListItem>,
142    pub(crate) presets: Vec<BundleListItem>,
143}
144
145fn register_bundle_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
146    let state = state.clone();
147    engine.register_typed(COMMAND_BUNDLE_LIST, move |_req: Option<NoArgsReq>, _ctx| {
148        let state = state.clone();
149        async move { bundle_list_impl(&state).await.map_err(|e| e.to_string()) }
150    });
151}
152
153#[derive(serde::Deserialize, Default, ts_rs::TS)]
154#[ts(export, export_to = "../../../frontend/types/rpc/")]
155pub(super) struct BundleGetReq {
156    #[serde(default)]
157    #[ts(as = "Option<String>", optional)]
158    id: String,
159    #[serde(default)]
160    #[ts(as = "Option<String>", optional)]
161    name: String,
162}
163
164fn register_bundle_get(engine: &Arc<WshRpcEngine>, state: &AppState) {
165    let state = state.clone();
166    engine.register_typed(COMMAND_BUNDLE_GET, move |req: BundleGetReq, _ctx| {
167        let state = state.clone();
168        async move { bundle_get_impl(&state, &req.id, &req.name).await.map_err(|e| e.to_string()) }
169    });
170}
171
172// NOT migrated to `register_typed`, deliberately, unlike the rest of the
173// bundle surface. `bundle_validate_impl` runs its payload through
174// `normalize_bundle_upsert_input` BEFORE deserializing it -- that is what
175// fills a missing `id` with "" so an unsaved draft can be validated, and what
176// coerces array-valued `context_files`/`mcp_servers`/`skills` into the
177// JSON-encoded strings `Bundle` expects.
178//
179// `register_typed` deserializes the payload into `Req` first and hands the
180// handler a typed value, so there is no point at which that normalize step
181// could run. Typing this command would mean re-implementing normalize as
182// custom serde deserializers -- duplicating security-relevant coercion logic
183// to satisfy the generator, which is the wrong trade. The RESPONSE is typed
184// (`ValidationReport`, ts-rs-generated) and that is where the drift risk
185// actually was; the request stays a `Value` on purpose.
186fn register_bundle_validate(engine: &Arc<WshRpcEngine>, _state: &AppState) {
187    // `Value` request: bundle_validate_impl normalizes the loose bundle input
188    // itself, as bundle.upsert does.
189    engine.register_typed(COMMAND_BUNDLE_VALIDATE, |data: serde_json::Value, _ctx| async move {
190        bundle_validate_impl(data)
191    });
192}
193
194fn register_bundle_upsert(engine: &Arc<WshRpcEngine>, state: &AppState) {
195    let make = |state: &AppState| {
196        let id_store = state.id_store.clone();
197        let broker = state.broker.clone();
198        // `Value` request, as bundle.validate's: the payload goes through
199        // `normalize_bundle_upsert_input` before it is a `Bundle`.
200        move |data: serde_json::Value, _ctx: RpcContext| {
201            let id_store = id_store.clone();
202            let broker = broker.clone();
203            async move {
204                let mut memory: Bundle =
205                    serde_json::from_value(normalize_bundle_upsert_input(data))
206                        .map_err(|e| format!("bundle.upsert: {e}"))?;
207
208                // S4: guard on the target id, not the caller-supplied is_blank flag
209                // (which defaults false and can be omitted to bypass is_blank check).
210                if memory.id == "blank" || memory.id.starts_with("seed-") || memory.is_blank {
211                    return Err("FORBIDDEN: cannot mutate a protected bundle".to_string());
212                }
213                // Guard existing global bundles: an agent must not be able to demote or
214                // corrupt a shared global bundle it doesn't own by supplying its id.
215                if !memory.id.is_empty() {
216                    if let Some(existing) = id_store.bundle_get(&memory.id)
217                        .map_err(|e| format!("bundle.upsert: {e}"))?
218                    {
219                        if existing.is_global {
220                            return Err("FORBIDDEN: cannot mutate a global bundle".to_string());
221                        }
222                        // provider/model are a "suggested for" hint and may
223                        // change: the agent owns its harness, and its lock
224                        // moved there (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1).
225                    }
226                }
227                if memory.id.is_empty() {
228                    memory.id = uuid::Uuid::new_v4().to_string();
229                }
230                // S4a: strip caller-supplied escalation fields.
231                memory.is_global = false;
232                memory.sort_order = 0;
233
234                let now = agentmux_common::time::now_ms();
235                if memory.created_at == 0 { memory.created_at = now; }
236                memory.updated_at = now;
237
238                id_store.bundle_upsert(&memory)
239                    .map_err(|e| format!("bundle.upsert: {e}"))?;
240                broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
241                Ok(memory)
242            }
243        }
244    };
245    engine.register_typed(COMMAND_BUNDLE_UPSERT, make(state));
246}
247
248fn register_bundle_delete(engine: &Arc<WshRpcEngine>, state: &AppState) {
249    let make = |state: &AppState| {
250        let id_store = state.id_store.clone();
251        let mstore = state.mstore.clone();
252        let broker = state.broker.clone();
253        // `{ id }`, the same request `deletememory` takes.
254        move |req: CommandDeleteBundleData, _ctx: RpcContext| {
255            let id_store = id_store.clone();
256            let mstore = mstore.clone();
257            let broker = broker.clone();
258            async move {
259                if req.id == "blank" {
260                    return Err("FORBIDDEN: cannot delete a seeded bundle".to_string());
261                }
262
263                match id_store.bundle_delete(&req.id) {
264                    Ok(deleted) => {
265                        if deleted {
266                            purge_bundle_component_refs(&mstore, &req.id);
267                            broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
268                        }
269                        Ok(DeleteBundleResult { deleted })
270                    }
271                    Err(crate::backend::storage::error::StoreError::Other(msg))
272                        if msg.contains("seed") || msg.contains("seeded") =>
273                    {
274                        Err(format!("FORBIDDEN: cannot delete a seeded bundle"))
275                    }
276                    Err(e) => Err(format!("bundle.delete: {e}")),
277                }
278            }
279        }
280    };
281    engine.register_typed(COMMAND_BUNDLE_DELETE, make(state));
282}
283
284#[derive(serde::Deserialize, ts_rs::TS)]
285#[ts(export, export_to = "../../../frontend/types/rpc/")]
286pub(super) struct BundleSelfGetReq { agent_id: String }
287
288fn register_bundle_self_get(engine: &Arc<WshRpcEngine>, state: &AppState) {
289    let state = state.clone();
290    engine.register_typed(COMMAND_BUNDLE_SELF_GET, move |req: BundleSelfGetReq, ctx| {
291        let state = state.clone();
292        async move {
293            check_s1(&state.mstore, &ctx, &req.agent_id)?;
294            bundle_self_get_impl(&state, &req.agent_id).await.map_err(|e| e.to_string())
295        }
296    });
297}
298
299/// Resolve the agent definition behind an S1-authenticated `agent_id`.
300///
301/// **`check_s1` authenticates a SLUG, not a UUID.** `RpcContext.agent_id` is
302/// "slug of the authenticated agent from bus:register"
303/// (its doc in `rpc_types/misc.rs`), while `agent_def_get` queries `db_agents`
304/// by its UUID primary key — so calling it with the authenticated value
305/// returns `None` for every real caller (#3156).
306///
307/// Delegates to `resolve_agent_definition_id`, the existing resolver for
308/// exactly this, rather than hand-rolling the lookup: it already carries the
309/// registry-only fallback a previous review round forced in, for a live agent
310/// that never created a local `db_agents` row. A fresh two-tier lookup here
311/// would have that hole again.
312fn resolve_agent_for_s1(
313    state: &AppState,
314    agent_id: &str,
315) -> Result<crate::backend::storage::AgentDefinition, String> {
316    let def_id = resolve_agent_definition_id(state, agent_id)?;
317    state
318        .mstore
319        .agent_def_get(&def_id)
320        .map_err(|e| e.to_string())?
321        .ok_or_else(|| format!("no agent with slug or id {agent_id}"))
322}
323
324#[derive(serde::Deserialize, ts_rs::TS)]
325#[ts(export, export_to = "../../../frontend/types/rpc/")]
326pub(super) struct AgentProjectInstructionsReq {
327    agent_id: String,
328}
329
330/// One file in `agent.project_instructions`: a resolved
331/// `ProjectInstructionFile`, plus how it compares to the last launch's
332/// observation of it.
333#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
334#[ts(export, export_to = "../../../frontend/types/rpc/")]
335pub(super) struct AgentProjectInstructionFile {
336    path: String,
337    exists: bool,
338    #[ts(type = "number")]
339    size_bytes: u64,
340    content_hash: String,
341    /// `"agentmux"` or `"foreign"`.
342    owner: String,
343    content: String,
344    truncated: bool,
345    error: Option<String>,
346    change: crate::backend::storage::project_instructions::InstructionChange,
347    /// Null when the file was never observed.
348    #[ts(type = "number | null")]
349    last_observed_at: Option<i64>,
350}
351
352/// Response for `agent.project_instructions`.
353#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
354#[ts(export, export_to = "../../../frontend/types/rpc/")]
355pub(super) struct AgentProjectInstructionsResponse {
356    provider: String,
357    working_directory: String,
358    files: Vec<AgentProjectInstructionFile>,
359}
360
361/// `agent.project_instructions` — what this agent will actually read.
362///
363/// Phase 3 of `SPEC_INSTRUCTION_AND_MEMORY_PORTABILITY_2026_09_09.md`. Until
364/// now nothing could answer this: AgentMux knew what it wrote and recorded a
365/// single boolean about anything it found already there (§2.4).
366///
367/// Agent-scoped, so `check_s1` applies — an agent's working directory contents
368/// are not window-scoped data the way a bundle is.
369///
370/// **Read-only, and there is no write counterpart on purpose.** A foreign
371/// instruction file belongs to the repository;
372/// `SPEC_CLAUDE_MD_OWNERSHIP_PROTECTION_2026_08_22.md` exists to keep AgentMux
373/// out of it, and this must not become a way around that.
374fn register_agent_project_instructions(engine: &Arc<WshRpcEngine>, state: &AppState) {
375    let make = |state: AppState| {
376        move |req: AgentProjectInstructionsReq, ctx: RpcContext| {
377            let state = state.clone();
378            async move {
379                check_s1(&state.mstore, &ctx, &req.agent_id)?;
380
381                let agent = resolve_agent_for_s1(&state, &req.agent_id)
382                    .map_err(|e| format!("agent.project_instructions: {e}"))?;
383
384                // The directory the agent will actually run in: a blank
385                // working_directory means the per-agent default and a `~`
386                // path is expanded at launch, so the stored value alone
387                // describes a directory the agent never uses (Codex, #3156).
388                let work_dir = crate::backend::project_instructions::effective_working_dir(
389                    &agent.working_directory,
390                    &agent.name,
391                );
392                let files = crate::backend::project_instructions::resolve_project_instructions(
393                    &agent.provider,
394                    &work_dir,
395                );
396
397                // Compare against what was recorded at the last launch, so a
398                // repository file that changed underneath is visible rather
399                // than merely present. Observations are written at
400                // `agent.open` (`observe_project_instructions`) — this RPC
401                // stays a pure read, which is why a file edited since the last
402                // launch reports `modified` every time it is called until the
403                // agent is next opened.
404                let previous = state
405                    .mstore
406                    .project_instructions_list(&agent.id)
407                    .unwrap_or_default();
408                let mut enriched: Vec<AgentProjectInstructionFile> = files
409                    .iter()
410                    .map(|f| {
411                        let prev = previous.iter().find(|p| p.path == f.path);
412                        let change = crate::backend::storage::project_instructions::classify_change(
413                            prev,
414                            f.exists,
415                            &f.content_hash,
416                        );
417                        AgentProjectInstructionFile {
418                            path: f.path.clone(),
419                            exists: f.exists,
420                            size_bytes: f.size_bytes,
421                            content_hash: f.content_hash.clone(),
422                            owner: match f.owner {
423                                crate::backend::project_instructions::InstructionOwner::Agentmux => "agentmux",
424                                crate::backend::project_instructions::InstructionOwner::Foreign => "foreign",
425                            }
426                            .to_string(),
427                            content: f.content.clone(),
428                            truncated: f.truncated,
429                            error: f.error.clone(),
430                            change,
431                            last_observed_at: prev.map(|p| p.observed_at),
432                        }
433                    })
434                    .collect();
435
436                // A path the resolver no longer returns at all — a scanned
437                // `.github/instructions/*.instructions.md` deleted since the
438                // last launch — would otherwise just vanish from the response,
439                // never reported as `removed`, and recreating it later would
440                // read as `unchanged` against the stale row (Codex, PR #3162).
441                // The declared paths always come back (absent ones included),
442                // so this only ever fires for dynamically scanned files.
443                for prev in previous.iter().filter(|p| !files.iter().any(|f| f.path == p.path)) {
444                    let change = crate::backend::storage::project_instructions::classify_change(
445                        Some(prev),
446                        false,
447                        "",
448                    );
449                    enriched.push(AgentProjectInstructionFile {
450                        path: prev.path.clone(),
451                        exists: false,
452                        size_bytes: 0,
453                        content_hash: String::new(),
454                        owner: prev.owner.clone(),
455                        content: String::new(),
456                        truncated: false,
457                        error: None,
458                        change,
459                        last_observed_at: Some(prev.observed_at),
460                    });
461                }
462
463                Ok(AgentProjectInstructionsResponse {
464                    provider: agent.provider,
465                    working_directory: work_dir,
466                    files: enriched,
467                })
468            }
469        }
470    };
471    engine.register_typed(COMMAND_AGENT_PROJECT_INSTRUCTIONS, make(state.clone()));
472}
473
474/// Read-only account-requirement resolution (spec §4.5) — one identity
475/// lookup per DISTINCT provider, not per requirement row (codex P1, PR
476/// #2379 round 4: `bundle_import.rs` bounds the requirements array length,
477/// but even at that bound many rows commonly share a handful of
478/// providers). Extracted here (Phase 3 spec §3.1's account-resolution
479/// implementation note) so the existing `bundle.import` route and the new
480/// `bundle.import.preview`/`.commit` handlers share the exact same
481/// resolution logic rather than duplicating it in a second place where it
482/// could drift.
483/// Full, untruncated values — callers apply the shared bounded-display
484/// projection ([`bounded_display`]) to `id`/`provider`/`env` before ever
485/// serializing these into an RPC response (Phase 3 spec §3.1, round 11).
486struct RequirementResolution {
487    id: String,
488    provider: String,
489    env: String,
490    match_count: usize,
491}
492
493impl RequirementResolution {
494    fn resolved(&self) -> bool {
495        self.match_count == 1
496    }
497}
498
499fn resolve_account_requirements(
500    id_store: &crate::backend::storage::store::Store,
501    requirements: &[crate::backend::bundle_import::AccountRequirement],
502) -> Result<Vec<RequirementResolution>, String> {
503    let mut results: Vec<RequirementResolution> = Vec::new();
504    let mut match_count_by_provider: std::collections::HashMap<&str, usize> =
505        std::collections::HashMap::new();
506    for requirement in requirements {
507        let match_count = match match_count_by_provider.get(requirement.provider.as_str()) {
508            Some(&n) => n,
509            None => {
510                // Codex P2, PR #2379 round 2: account CRUD routes through
511                // id_store (shared/store.db when available), not mstore
512                // (the per-channel database).
513                let n = id_store
514                    .identity_list(Some(&requirement.provider))
515                    .map_err(|e| format!("account lookup failed: {e}"))?
516                    .len();
517                match_count_by_provider.insert(requirement.provider.as_str(), n);
518                n
519            }
520        };
521        results.push(RequirementResolution {
522            id: requirement.id.clone(),
523            provider: requirement.provider.clone(),
524            env: requirement.env.clone(),
525            match_count,
526        });
527    }
528    Ok(results)
529}
530
531/// Shared bounded-display projection (Phase 3 spec, round 12's governing
532/// rule) for every "meant to be short" field both `preview` and `commit`
533/// echo back: skill slug/description, requirement `id`/`provider`/`env`,
534/// context-file `display_path`, bundle `description`, and commit's
535/// `skipped_skills`/`resolved_requirement_ids` entries. `bundle.name` is
536/// NOT projected through this — it's bounded at parse time instead
537/// (round 13), since it's re-submitted verbatim as `bundle_name`.
538fn bounded_display(s: &str) -> String {
539    crate::backend::bundle_import::truncate_display(s, crate::backend::bundle_import::MAX_DISPLAY_FIELD_CHARS)
540}
541
542pub(crate) async fn bundle_list_impl(state: &AppState) -> Result<BundleListResponse, ApiError> {
543    let memories = state.id_store.bundle_list().map_err(|e| format!("bundle.list: {e}"))?;
544    let bundles: Vec<BundleListItem> = memories.into_iter().map(|m| BundleListItem {
545        id: m.id, name: m.name, description: m.description,
546        provider: m.provider, model: m.model, is_blank: m.is_blank, updated_at: m.updated_at,
547    }).collect();
548    // Emit both keys: `bundle.list` callers read `bundles`; the separate
549    // REST route `/api/v1/agent/preset/list` (`PresetList` MCP tool,
550    // server/mod.rs) still reads `presets` and is unrelated to the internal
551    // WS `preset.*` aliases retired in this pass — do not drop `presets`
552    // here without first retiring that REST route too.
553    Ok(BundleListResponse { presets: bundles.clone(), bundles })
554}
555
556pub(crate) async fn bundle_get_impl(
557    state: &AppState,
558    id: &str,
559    name: &str,
560) -> Result<Bundle, ApiError> {
561    let memory = if !id.is_empty() {
562        state.id_store.bundle_get(id).map_err(|e| format!("bundle.get: {e}"))?
563            .ok_or_else(|| ApiError::not_found(format!("bundle.get: not found id={id}")))?
564    } else if !name.is_empty() {
565        let all = state.id_store.bundle_list().map_err(|e| format!("bundle.get: {e}"))?;
566        all.into_iter().filter(|m| m.name == name).max_by_key(|m| m.updated_at)
567            .ok_or_else(|| ApiError::not_found(format!("bundle.get: not found name={name}")))?
568    } else {
569        return Err(ApiError::bad_request("bundle.get: provide id or name"));
570    };
571    Ok(memory)
572}
573
574/// Structurally validate a bundle draft — ABF
575/// UI-alignment pass. Takes the SAME payload shape `bundle.upsert` accepts
576/// (reuses its `normalize_bundle_upsert_input`), not just an id, so the
577/// Memory → Bundles editor's "Validate" button can check an unsaved draft (including a
578/// brand-new bundle with no id yet) rather than only whatever was last
579/// persisted.
580///
581/// Store-free: what it checks is all in the draft. (It read the bundle's
582/// bound MCP servers while bundles carried them;
583/// `SPEC_BUNDLE_CONTENTS_MEMORY_NOT_MCP_2026_10_07.md` §3.1.)
584pub(crate) fn bundle_validate_impl(
585    data: serde_json::Value,
586) -> Result<crate::backend::bundle_validate::ValidationReport, String> {
587    let memory: Bundle = serde_json::from_value(bundle::normalize_bundle_upsert_input(data))
588        .map_err(|e| format!("bundle.validate: {e}"))?;
589    Ok(crate::backend::bundle_validate::validate_bundle(&memory))
590}
591
592pub(crate) async fn bundle_self_get_impl<'o>(
593    state: &AppState,
594    owner: impl Into<SelfOwner<'o>>,
595) -> Result<Bundle, ApiError> {
596    let agent_id = match owner.into() {
597        SelfOwner::Slug(slug) => slug,
598        // Identity M4c-2c: an attributed caller's own row, and its registry
599        // record only by that row's slug AND id — never a same-named
600        // agent's.
601        SelfOwner::Uid(uid) => {
602            let row = SelfOwner::caller_row(uid, &state.mstore).map_err(|e| e.under("bundle.self.get"))?;
603            // The launch's bundle (`AgentInstance.memory_id`), as on the slug
604            // path — not `AgentDefinition.memory_id`, the default a launch
605            // inherits (`db_agents.default_memory_id`).
606            let launch = state.mstore.instance_get(uid)
607                .map_err(|e| format!("bundle.self.get: {e}"))?;
608            let memory_id = launch
609                .map(|i| i.memory_id)
610                .filter(|m| !m.is_empty())
611                .or_else(|| {
612                    crate::backend::agent_registry_lookup::find_active_record_by_slug_and_definition(
613                        &row.slug, &row.id,
614                    )
615                    .and_then(|rec| rec.data.memory_id)
616                });
617            return bundle_self_get_by_memory_id(state, memory_id);
618        }
619    };
620    let instance = state.mstore.instance_get_by_slug(agent_id)
621        .map_err(|e| format!("bundle.self.get: {e}"))?;
622    // `instance_get_by_slug` only ever hits the local `db_agents` table — a
623    // live agent that only exists in the global named-agent registry (never
624    // created a `db_agents` instance row) falls through with `instance:
625    // None` here. Without this fallback that silently read as "no bundle
626    // bound" and returned the blank/vanilla preset regardless of what's
627    // actually bound, with nothing to distinguish it from a genuinely
628    // unbound agent. Mirrors the two-tier lookup
629    // `native_memory_handlers::memory_dir_for_agent` already does for the
630    // same reason (see that function's own doc comment, issue #1836).
631    let memory_id = instance.as_ref()
632        .and_then(|i| if i.memory_id.is_empty() { None } else { Some(i.memory_id.clone()) })
633        .or_else(|| {
634            crate::server::native_memory_handlers::find_active_registry_record_by_slug(agent_id)
635                .and_then(|rec| rec.data.memory_id)
636        });
637    bundle_self_get_by_memory_id(state, memory_id)
638}
639
640/// The bundle `memory_id` names, or the blank singleton when none is bound.
641fn bundle_self_get_by_memory_id(
642    state: &AppState,
643    memory_id: Option<String>,
644) -> Result<Bundle, ApiError> {
645    let memory = if let Some(mid) = memory_id {
646        state.id_store.bundle_get(&mid).map_err(|e| format!("bundle.self.get: {e}"))?
647            .ok_or_else(|| ApiError::not_found(format!("bundle.self.get: memory_id {mid} not found")))?
648    } else {
649        // No bundle bound: return the blank singleton (two-step — list to find
650        // the blank id, then fetch the full object).
651        let all = state.id_store.bundle_list().map_err(|e| format!("bundle.self.get: {e}"))?;
652        let blank_id = all.into_iter().find(|m| m.is_blank).map(|m| m.id)
653            .ok_or_else(|| ApiError::internal("bundle.self.get: blank singleton not found"))?;
654        state.id_store.bundle_get(&blank_id).map_err(|e| format!("bundle.self.get: {e}"))?
655            .ok_or_else(|| ApiError::internal("bundle.self.get: blank singleton row missing"))?
656    };
657    Ok(memory)
658}
659
660/// The agent a self-scoped MuxAPI call is about — whose personal memory
661/// (`memory.*`, M4c-2b), linked accounts (`identity.self.accounts`,
662/// `identity.account.validate`), bound preset (`preset.get` self) and
663/// history (`history.search`, M4c-2c) — identity spec §6.5.9.
664#[derive(Debug, Clone, Copy)]
665pub(crate) enum SelfOwner<'a> {
666    /// The calling agent's own row, by its token's UID. Versions are keyed by
667    /// it as they are; the files are found by id
668    /// (`memory_dir_for_agent_by_id`), and a UID with no row or no directory
669    /// is an error — never another agent's directory (the #2901 class). A
670    /// directory that resolves but does not exist still lists as empty, as
671    /// on the slug path.
672    Uid(&'a str),
673    /// A slug, resolved as before M4c-2 (`memory_dir_for_agent`,
674    /// `resolve_agent_id`, the registry by slug): an Unattributed HTTP
675    /// caller, and the WS RPC.
676    Slug(&'a str),
677}
678
679impl<'a> From<&'a str> for SelfOwner<'a> {
680    fn from(slug: &'a str) -> Self {
681        Self::Slug(slug)
682    }
683}
684
685impl<'a> From<&'a String> for SelfOwner<'a> {
686    fn from(slug: &'a String) -> Self {
687        Self::Slug(slug)
688    }
689}
690
691impl<'a> SelfOwner<'a> {
692    /// The owner of an HTTP request: the caller's own row when attributed,
693    /// whatever `agent_id` names — a name that is not the caller's is counted
694    /// by M4a-2 — so a name two agents share no longer selects the other's
695    /// memory, accounts or history. The HTTP handlers refuse an Unattributed request
696    /// before this (`actor::require_token`); one that gets here anyway keeps the slug,
697    /// counted as `by_name_counter`.
698    pub(crate) fn of(
699        caller: Option<&'a crate::server::caller::Caller>,
700        slug: &'a str,
701        by_name_counter: &'static str,
702    ) -> Self {
703        match caller.and_then(crate::server::caller::Caller::uid) {
704            Some(uid) => Self::Uid(uid),
705            None => {
706                crate::backend::agent_resolve::record_uid_fallback(by_name_counter);
707                Self::Slug(slug)
708            }
709        }
710    }
711
712    /// The UID or the slug, for messages and logs.
713    pub(super) fn label(self) -> &'a str {
714        match self {
715            Self::Uid(v) | Self::Slug(v) => v,
716        }
717    }
718
719    /// The calling agent's row — a UID whose row is gone (a token that
720    /// outlived its agent) is an error on every path, never an empty history
721    /// or listing (ReAgent P1 on #3602).
722    pub(crate) fn caller_row(
723        uid: &str,
724        mstore: &crate::backend::storage::store::Store,
725    ) -> Result<crate::backend::storage::AgentDefinition, ApiError> {
726        mstore
727            .agent_def_get(uid)
728            .map_err(|e| format!("store: {e}"))?
729            .ok_or_else(|| ApiError::not_found(format!("calling agent {uid} not found")))
730    }
731
732    /// The owner's live memory directory.
733    pub(super) fn dir(self, mstore: &crate::backend::storage::store::Store) -> Result<std::path::PathBuf, ApiError> {
734        match self {
735            Self::Uid(uid) => {
736                let agent = Self::caller_row(uid, mstore).map_err(|e| e.under("memory"))?;
737                crate::server::native_memory_handlers::memory_dir_for_agent_by_id(mstore, &agent)
738                    .ok_or_else(|| ApiError::not_found(format!("memory: memory directory for agent {uid} not found")))
739            }
740            Self::Slug(slug) => Ok(crate::server::native_memory_handlers::memory_dir_for_agent(mstore, slug)?),
741        }
742    }
743
744    /// The owner's memory directory for a write: never an unverified guess
745    /// (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.2).
746    pub(super) fn dir_for_write(self, mstore: &crate::backend::storage::store::Store) -> Result<std::path::PathBuf, ApiError> {
747        let id = self.owner_id(mstore).map_err(|e| e.under("memory"))?;
748        match mstore.agent_def_get(&id).map_err(|e| format!("memory: store: {e}"))? {
749            Some(agent) => Ok(crate::server::native_memory_handlers::memory_dir_for_write_by_id(mstore, &agent)
750                .map_err(|e| format!("memory: {e}"))?),
751            // No local row (a slug caller naming a registry-only agent): its
752            // own spawn record still proves its directory.
753            None => crate::server::native_memory_handlers::memory_dir_from_spawn(&id).ok_or_else(|| {
754                ApiError::conflict(format!(
755                    "memory: agent {} has no local row and no spawn on record, so its memory directory \
756                     can't be verified for a write",
757                    self.label()
758                ))
759            }),
760        }
761    }
762
763    /// The owner's definition id (`db_agents.id`) — what its memory versions,
764    /// mirror rows and identity links are keyed by.
765    pub(super) fn owner_id(self, mstore: &crate::backend::storage::store::Store) -> Result<String, ApiError> {
766        match self {
767            Self::Uid(uid) => Self::caller_row(uid, mstore).map(|row| row.id),
768            Self::Slug(slug) => Ok(crate::server::native_memory_handlers::resolve_agent_uuid(mstore, slug)?),
769        }
770    }
771}