Skip to main content

agentmux_srv_core/backend/storage/agents/
definition.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agent_def_*`: the agent-definition catalog's CRUD on `db_agents`.
5
6use super::*;
7
8impl Store {
9    /// Fetch a single agent definition by primary key. Reads `db_agents`
10    /// directly (the same source `agent_def_list` reads, via the shared
11    /// private `agent_row_get`) — as of the definition flip this is no longer
12    /// scoped to definitions/templates only: any `db_agents` row, including
13    /// a bare template launch with no `db_agent_definitions` counterpart,
14    /// resolves here, matching what `agent_def_list` already returns for
15    /// it. Falls back to the global cross-channel registry when the row
16    /// doesn't exist locally at all.
17    ///
18    /// Used by the `template_promote` migration's deterministic-id
19    /// idempotency check (see
20    /// `migrate_promote_template_sessions_v1`): every retry asks
21    /// "does the promote-target clone for this template already
22    /// exist?" and either reuses it or inserts it.
23    ///
24    /// A local row's slug is the canonical one ([`canonical_slug`]), as in
25    /// `agent_def_list`: the spawn env and the registry mirror read it here.
26    pub fn agent_def_get(&self, id: &str) -> Result<Option<AgentDefinition>, StoreError> {
27        if let Some(local) = self.agent_row_get(id)? {
28            return Ok(Some(self.with_canonical_slug(local)));
29        }
30        // Not in local SQLite — check the global cross-channel registry.
31        // agent_def_list() already overlays this; keep agent_def_get consistent.
32        match self.shared_def_get(id) {
33            Ok(def) => Ok(def),
34            Err(e) => {
35                tracing::warn!(agent_id = %id, error = %e, "agent_def_get: global registry lookup failed; returning not-found");
36                Ok(None)
37            }
38        }
39    }
40
41    /// `agent_def_get`, but a failed read of the global definition registry
42    /// is an error rather than "not found". For callers that must refuse
43    /// instead of acting on a partial answer — the name resolver treats "no
44    /// such UID" as "send the bare name", which a hidden fault must not
45    /// trigger (Codex P2 on #3568).
46    pub(crate) fn agent_def_get_strict(&self, id: &str) -> Result<Option<AgentDefinition>, String> {
47        if let Some(local) = self.agent_row_get(id).map_err(|e| e.to_string())? {
48            return Ok(Some(self.with_canonical_slug(local)));
49        }
50        self.shared_def_get(id)
51            .map_err(|e| format!("global definition registry: {e}"))
52    }
53
54    fn with_canonical_slug(&self, mut def: AgentDefinition) -> AgentDefinition {
55        def.slug = canonical_slug(&def.id, &def.slug, self.shared_slug_of(&def.id).as_deref());
56        def
57    }
58
59    /// The global cross-channel definition for `id`, errors preserved.
60    fn shared_def_get(&self, id: &str) -> Result<Option<AgentDefinition>, crate::registry::DefStoreError> {
61        let Some(reg) = self.shared_def_registry() else {
62            return Ok(None);
63        };
64        Ok(reg
65            .get(id)?
66            .map(|record| super::super::def_registry_mirror::record_to_agent_definition(&record)))
67    }
68
69    /// List all agent definitions, **most-recently-used first**.
70    ///
71    /// Reads from the consolidated `db_agents` table, ordered by
72    /// `updated_at DESC` then `created_at ASC`. Every definition mutation
73    /// AND every instance lifecycle touch bumps `db_agents.updated_at`, so
74    /// recency on a row tracks the last time the agent was either edited or
75    /// launched.
76    ///
77    /// Result-set shape: every `db_agents` row is returned — templates
78    /// (`is_template = 1`) and user-clone projections (`is_template = 0`)
79    /// each appear once. `parent_id` is sourced from
80    /// `db_agents.parent_template_id`.
81    pub fn agent_def_list(&self) -> Result<Vec<AgentDefinition>, StoreError> {
82        // Local SQLite: this channel's templates (seeded) + its own user agents.
83        let local: Vec<AgentDefinition> = {
84            let conn = self.conn.lock().unwrap();
85            let mut stmt = conn.prepare(&format!("{AGENT_DEFINITION_SELECT} ORDER BY updated_at DESC, created_at ASC"))?;
86            let rows = stmt.query_map([], map_agent_definition_row)?;
87            let mut agents = Vec::new();
88            for row in rows {
89                agents.push(row?);
90            }
91            agents
92        };
93        // conn dropped. Overlay the GLOBAL cross-channel user-agent roster so
94        // an agent created in another channel appears here too. The global
95        // store wins for user rows (it's authoritative and holds cross-channel
96        // agents); templates (seeded — never in the global store) come from
97        // local SQLite. Falls back to SQLite-only when the global store is
98        // absent or unreadable. (P0.2c.)
99        let Some(reg) = self.shared_def_registry() else {
100            return Ok(local);
101        };
102        let global = match reg.list_active() {
103            Ok(recs) => recs,
104            Err(e) => {
105                tracing::warn!(error = %e, "def registry: global list failed, using SQLite only");
106                return Ok(local);
107            }
108        };
109        let mut by_id: std::collections::HashMap<String, AgentDefinition> =
110            local.into_iter().map(|d| (d.id.clone(), d)).collect();
111        for rec in &global {
112            let mut def = super::super::def_registry_mirror::record_to_agent_definition(rec);
113            // model_vendor_base_url is deliberately channel-local only —
114            // DefinitionRecordV1 doesn't carry it, so record_to_agent_definition
115            // always returns "" for it. Without this, the global overlay
116            // silently wiped a same-channel agent's override on every read
117            // (including agent.open's spawn-time resolution), making the
118            // whole feature a no-op in default single-instance operation —
119            // not just the genuinely-cross-channel case this limitation is
120            // documented for. Preserve the local row's value when one
121            // exists; only a truly cross-channel agent (no local row) sees
122            // the empty default. (reagent P0 on PR #2505.)
123            //
124            // memory_id needs the IDENTICAL treatment, for the identical
125            // reason (P0 fix, ReAgent review on PR #2587 round 6):
126            // DefinitionRecordV1 doesn't carry memory_id either (same
127            // documented gap, def_registry_mirror.rs), so
128            // record_to_agent_definition always returns "" for it too.
129            // Every local write auto-mirrors into the global registry
130            // (agent_def_insert -> registry_def_upsert), so this overlay
131            // fires for virtually every agent whenever a shared store is
132            // configured — the "normal case," not an edge case. Without
133            // this fix, agent_def_list() would silently zero memory_id on
134            // every read, defeating the bundle lookups that read it
135            // (bundle-scoped skills, the empty-provider
136            // fallback in resolve_effective_provider_id) and m0021's own
137            // memory_id-empty backfill filter (which would re-process
138            // every already-bound agent on every migration run, since it
139            // reads through this same function).
140            if let Some(existing) = by_id.get(&def.id) {
141                def.model_vendor_base_url = existing.model_vendor_base_url.clone();
142                def.memory_id = existing.memory_id.clone();
143                // conversation_visibility is the identical channel-local-only
144                // case (SPEC_MUXSPECT_CROSS_TIER_CONVERSATION_VISIBILITY_2026_08_21.md
145                // Phase B/C, jekt rules SPEC_JEKT_TRANSCRIPT_REQUEST_TIER_RULES_2026_08_22.md)
146                // — DefinitionRecordV1 doesn't carry it, so without this the
147                // global overlay would silently reset every agent's
148                // disclosure policy back to "private" on every list read,
149                // even though "private" is a safe fail-closed default (this
150                // preserves the ADMINISTRATOR'S actual configured choice,
151                // not just avoiding a crash).
152                def.conversation_visibility = existing.conversation_visibility.clone();
153                // The slug the other readers give too (an empty shared slug
154                // keeps the local one).
155                def.slug = canonical_slug(&def.id, &existing.slug, Some(&def.slug));
156            }
157            by_id.insert(def.id.clone(), def);
158        }
159        let mut result: Vec<AgentDefinition> = by_id.into_values().collect();
160        // Match the SQL ORDER BY: updated_at DESC, then created_at ASC.
161        result.sort_by(|a, b| {
162            b.updated_at
163                .cmp(&a.updated_at)
164                .then(a.created_at.cmp(&b.created_at))
165        });
166        Ok(result)
167    }
168
169    /// The shared definitions this build cannot read (a newer AgentMux wrote them, or the file is damaged), as stopped stand-ins
170    /// named as their record names them, with why in `description`. For lists that must show every agent a person has
171    /// (My Agents), never for anything that starts, edits or counts agents: a stand-in is not saved anywhere, and the record
172    /// it stands for is never rewritten (`DefinitionStore` refuses to save over a format it does not read).
173    pub fn agent_def_unreadable_stand_ins(&self) -> Vec<AgentDefinition> {
174        let Some(reg) = self.shared_def_registry() else { return Vec::new() };
175        let listed = reg.list_unreadable().unwrap_or_else(|e| {
176            tracing::warn!(error = %e, "def registry: the unreadable definitions could not be listed");
177            Vec::new()
178        });
179        listed
180            .into_iter()
181            .map(|u| {
182                let rec = crate::registry::DefinitionRecord {
183                    schema_version: 1,
184                    data: crate::registry::DefinitionRecordV1 { id: u.id.clone(), slug: u.id, name: u.name, provider: u.provider, description: u.reason, ..Default::default() },
185                };
186                super::super::def_registry_mirror::record_to_agent_definition(&rec)
187            })
188            .collect()
189    }
190
191    /// Why the shared definition `id` cannot be used by this build, or `None` when it is absent or reads fine.
192    pub fn agent_def_unreadable_reason(&self, id: &str) -> Option<String> {
193        self.shared_def_registry()?.unreadable_reason(id)
194    }
195
196    /// Count agent rows (used by seed engine to check if seeding is needed).
197    /// Reads from the consolidated `db_agents` table. The seed engine only
198    /// cares about `== 0` to decide "fresh database, seed templates".
199    pub fn agent_def_count(&self) -> Result<i64, StoreError> {
200        let conn = self.conn.lock().unwrap();
201        let count: i64 = conn.query_row(
202            "SELECT COUNT(*) FROM db_agents",
203            [],
204            |row| row.get(0),
205        )?;
206        Ok(count)
207    }
208
209    /// Whether a definition with `id` exists in the LOCAL channel's SQLite
210    /// (`db_agents`). Gates the cross-channel content/skills fallback: a
211    /// locally-known agent with genuinely empty content/skills must NOT
212    /// resurrect them from the global record. (reagent P1 on #1385.)
213    pub(in crate::backend::storage) fn agent_def_exists_local(&self, id: &str) -> Result<bool, StoreError> {
214        let conn = self.conn.lock().unwrap();
215        let exists: bool = conn.query_row(
216            "SELECT EXISTS(SELECT 1 FROM db_agents WHERE id = ?1)",
217            params![id],
218            |row| row.get(0),
219        )?;
220        Ok(exists)
221    }
222
223    /// Delete all seeded agents (is_seeded=1). Used by reseed to clear built-in agents.
224    ///
225    /// No project-instruction cleanup here, unlike `agent_def_delete`: this
226    /// removes template rows, and a template is never launched — observations
227    /// are recorded by `agent.open`, so a template has none to forget (Codex,
228    /// PR #3162).
229    pub fn agent_def_delete_seeded(&self) -> Result<usize, StoreError> {
230        // Consolidation Phase 3b (PR 2): only the template rows go. Every
231        // `is_template = 0` row — a user clone OR an agent launched from a
232        // template — is an agent in its own right and persists across a
233        // reseed, keeping its `parent_template_id` (templates have stable
234        // ids, so the lineage survives the re-insert).
235        let conn = self.conn.lock().unwrap();
236        Ok(conn.execute("DELETE FROM db_agents WHERE is_template=1", [])?)
237    }
238
239    /// Insert a new agent definition. Auto-derives slug from name if empty,
240    /// resolves collisions by appending `-2`, `-3`, etc., and mutates
241    /// `agent.slug` so the caller sees the resolved value (important
242    /// for handlers that serialize the struct back to the frontend
243    /// after insert).
244    ///
245    /// The collision check + insert run under a single mutex lock,
246    /// so this is race-safe against concurrent inserts on the same
247    /// connection.
248    pub fn agent_def_insert(&self, agent: &mut AgentDefinition) -> Result<(), StoreError> {
249        // Held from the slug pick (inside the local insert) to its publication
250        // by the mirror below.
251        let _allocating = self.slug_allocation_lock(agent)?;
252        let shared = self.shared_slugs_to_allocate(agent)?;
253        let host = self.host_slugs_to_allocate(agent)?;
254        self.agent_def_insert_with(agent, None, &shared, host.as_ref())?;
255        self.former_slugs.invalidate();
256        // Mirror into the global cross-channel definition store. Content +
257        // skills are inserted after the definition (separate calls), so this
258        // initial record is content-less; agent_content_set / agent_skill_*
259        // re-mirror with the full payload. (P0.2b.) Publishing the slug is
260        // part of the insert: undone if it fails.
261        self.publish_new_or_undo(&agent.id)
262    }
263
264    /// Mirror a just-inserted agent, which publishes its slug; on failure,
265    /// delete the row again and return the error (`registry_def_publish`).
266    /// The caller still holds the slug allocation lock.
267    fn publish_new_or_undo(&self, id: &str) -> Result<(), StoreError> {
268        let Err(e) = self.registry_def_publish(id) else {
269            return Ok(());
270        };
271        let conn = self.conn.lock().unwrap();
272        if let Err(undo) = conn.execute("DELETE FROM db_agents WHERE id = ?1", params![id]) {
273            tracing::warn!(agent_id = id, error = %undo, "agent insert: could not undo the local row after a failed publish");
274        }
275        Err(e)
276    }
277
278    /// The host-wide slug allocation lock for inserting `agent`
279    /// (`DefinitionStore::lock_slug_allocation`), so a concurrent insert in
280    /// another channel or instance picks its slug knowing this one's. `None`
281    /// for a template, which is never mirrored, or with no shared store. A
282    /// lock that can't be had in time fails the insert before anything is
283    /// written.
284    fn slug_allocation_lock(&self, agent: &AgentDefinition) -> Result<Option<crate::registry::SlugAllocationLock>, StoreError> {
285        let Some(reg) = self.shared_def_registry().filter(|_| agent.is_seeded == 0) else {
286            return Ok(None);
287        };
288        reg.lock_slug_allocation().map(Some).map_err(|e| {
289            StoreError::Other(format!("could not pick a slug for agent {}: {e}", agent.name))
290        })
291    }
292
293    /// Insert into `db_agents` only — does NOT mirror to the global
294    /// registry. Used directly by `agent_def_insert` (which mirrors right
295    /// after) and by `agent_def_backfill_local_from_registry` (which must
296    /// NOT mirror — see that function's doc comment for why re-mirroring
297    /// immediately after this call would wipe the registry's real
298    /// content/skills).
299    ///
300    /// `updated_at_override`: `None` stamps `updated_at = created_at`
301    /// (the original, unchanged behavior for genuinely new definitions).
302    /// `Some(ts)` stamps `updated_at = ts` instead — used by the backfill
303    /// path to preserve the registry record's real `updated_at` rather
304    /// than resetting it.
305    ///
306    /// `is_seeded = 1` rows become `is_template = 1` (a template; bindings
307    /// stay empty). `is_seeded = 0` rows become `is_template = 0` with
308    /// `parent_template_id = parent_id` — same is_template/parent_template_id
309    /// derivation the old dual-write mirror used (frozen intent, no longer
310    /// a second write).
311    pub(in crate::backend::storage) fn agent_def_insert_local_only(
312        &self,
313        agent: &mut AgentDefinition,
314        updated_at_override: Option<i64>,
315    ) -> Result<(), StoreError> {
316        self.agent_def_insert_with(agent, updated_at_override, &self.shared_slugs(), None)
317    }
318
319    /// Every other holder on this host a user agent's new slug is picked
320    /// against ([`Self::host_slugs_for_allocation`]). A template's is not: it
321    /// is seeded with the same slug in every channel, so another channel's
322    /// copy is not another holder.
323    fn host_slugs_to_allocate(
324        &self,
325        agent: &AgentDefinition,
326    ) -> Result<Option<crate::backend::slug_migration::HostSlugs>, StoreError> {
327        if agent.is_seeded == 0 {
328            self.host_slugs_for_allocation()
329        } else {
330            Ok(None)
331        }
332    }
333
334    /// The shared slugs a new agent's slug is picked against: all of them,
335    /// read strictly, for a user agent (`shared_slugs_for_allocation`); for a
336    /// template, which is never mirrored and is seeded at boot, the lenient
337    /// index, so a bad shared file can't stop seeding.
338    fn shared_slugs_to_allocate(&self, agent: &AgentDefinition) -> Result<SharedSlugs, StoreError> {
339        if agent.is_seeded == 0 {
340            self.shared_slugs_for_allocation()
341        } else {
342            Ok(self.shared_slugs())
343        }
344    }
345
346    /// [`Self::agent_def_insert_local_only`] against the given shared slugs
347    /// and, for a new agent, the host's other holders.
348    fn agent_def_insert_with(
349        &self,
350        agent: &mut AgentDefinition,
351        updated_at_override: Option<i64>,
352        shared: &SharedSlugs,
353        host: Option<&crate::backend::slug_migration::HostSlugs>,
354    ) -> Result<(), StoreError> {
355        let conn = self.conn.lock().unwrap();
356        let base = if agent.slug.is_empty() {
357            derive_slug(&agent.name)
358        } else {
359            agent.slug.clone()
360        };
361        // Collision-resolve against every `db_agents` slug — the consolidated
362        // table surfaces definition slugs and template-instance projections
363        // alike, so a collision against an instance-derived row is caught here
364        // too. Shared with `instance_create` so the two cannot drift.
365        agent.slug = resolve_slug_collision(&conn, &base, &agent.id, shared, host)?;
366        let stamped_updated_at = updated_at_override.unwrap_or(agent.created_at);
367        // A new definition is updated when it was created, unless the caller supplied an override (the backfill
368        // path, preserving the registry record's real updated_at).
369        insert_definition_row(&conn, agent, stamped_updated_at)?;
370        // Reagent P1 on #1013 round 2: do NOT mutate the caller's
371        // `&mut AgentDefinition` here. The PR is supposed to be
372        // zero-behaviour-change; the previous version reflected
373        // `stamped_updated_at` back onto the caller, which is an
374        // observable mutation downstream callers may rely on remaining
375        // untouched. Callers that need the freshly-stamped value can
376        // re-fetch the row via the normal read path.
377        Ok(())
378    }
379
380    /// Materialize a local shadow of a registry-only definition — this
381    /// channel's `db_agents` row plus a best-effort local copy of
382    /// content/skills — so `instance_create`'s FK can succeed for an agent
383    /// whose definition exists cross-channel but was never created in THIS
384    /// channel's SQLite.
385    ///
386    /// Deliberately does NOT call `registry_def_upsert` (unlike
387    /// `agent_def_insert`, which does): the registry is already
388    /// authoritative for this record. `registry_def_upsert` rebuilds
389    /// the registry record from `agent_content_get_all_local`/
390    /// `agent_skill_list_local` — LOCAL-only reads, by design (see that
391    /// function's own comment) — so calling it immediately after this
392    /// insert-with-no-content-yet would overwrite the registry's real
393    /// content/skills with empty arrays. Content/skill rows are instead
394    /// copied here via direct INSERTs (bypassing `agent_content_set`/
395    /// `agent_skill_insert`, which each call `registry_def_refresh_if_mirrored`
396    /// themselves) so nothing re-mirrors mid-backfill.
397    ///
398    /// Copy failures for content/skills are logged and otherwise
399    /// ignored — the definition row alone satisfies the FK, and reads
400    /// still resolve content/skills correctly via the existing
401    /// cross-channel fallback even if this best-effort local copy is
402    /// incomplete. A slug collision against an unrelated local agent
403    /// will rename the local slug (existing `agent_def_insert_local_only`
404    /// behavior) — low-probability and non-fatal, since slug isn't the
405    /// FK target.
406    pub(in crate::backend::storage) fn agent_def_backfill_local_from_registry(
407        &self,
408        record: &crate::registry::DefinitionRecord,
409    ) -> Result<(), StoreError> {
410        let mut def = super::super::def_registry_mirror::record_to_agent_definition(record);
411        self.agent_def_insert_local_only(&mut def, Some(record.data.updated_at))?;
412
413        let conn = self.conn.lock().unwrap();
414        if let Err(e) = record_former_slugs(&conn, &def.id, &record.data.former_slugs) {
415            tracing::warn!(def_id = %def.id, error = %e, "instance_create backfill: former slugs not copied (non-fatal)");
416        }
417        self.former_slugs.invalidate();
418        for c in &record.data.content {
419            if let Err(e) = conn.execute(
420                "INSERT INTO db_agent_content (agent_id, content_type, content, updated_at)
421                 VALUES (?1, ?2, ?3, ?4)
422                 ON CONFLICT(agent_id, content_type) DO UPDATE SET content=?3, updated_at=?4",
423                params![def.id, c.content_type, c.content, record.data.updated_at],
424            ) {
425                tracing::warn!(
426                    def_id = %def.id,
427                    content_type = %c.content_type,
428                    error = %e,
429                    "instance_create backfill: local content copy failed (non-fatal)"
430                );
431            }
432        }
433        for s in &record.data.skills {
434            if let Err(e) = conn.execute(
435                "INSERT INTO db_agent_skills (id, agent_id, name, trigger, skill_type, description, content, created_at)
436                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
437                params![
438                    s.id,
439                    def.id,
440                    s.name,
441                    s.trigger,
442                    s.skill_type,
443                    s.description,
444                    s.content,
445                    record.data.updated_at,
446                ],
447            ) {
448                tracing::warn!(
449                    def_id = %def.id,
450                    skill = %s.name,
451                    error = %e,
452                    "instance_create backfill: local skill copy failed (non-fatal)"
453                );
454            }
455        }
456        Ok(())
457    }
458
459    /// Atomic check-then-insert for `agent.define`.
460    ///
461    /// Looks up an existing user-owned definition by name (case-insensitive)
462    /// or derived slug under the SAME mutex guard that protects the INSERT —
463    /// preventing TOCTOU when two concurrent `agent.define` calls arrive for
464    /// the same name.
465    ///
466    /// Returns:
467    /// - `Ok(Some(def))` — an existing row matched; `agent` was NOT inserted.
468    /// - `Ok(None)` — no match; `agent` was inserted and `agent.slug` now
469    ///   holds the collision-resolved slug.
470    pub fn agent_def_find_or_insert(
471        &self,
472        agent: &mut AgentDefinition,
473    ) -> Result<Option<AgentDefinition>, StoreError> {
474        let name_lower = agent.name.trim().to_lowercase();
475        let derived_slug = derive_slug(agent.name.trim());
476        // Held through the mirror at the end, as in `agent_def_insert`.
477        let _allocating = self.slug_allocation_lock(agent)?;
478        // Strict for the insert below; a failure doesn't stop finding an
479        // existing agent, which only reads names.
480        let allocation = self.shared_slugs_to_allocate(agent);
481        let shared = allocation.as_ref().map_or_else(|_| self.shared_slugs(), SharedSlugs::clone);
482        // Strict for the insert the same way.
483        let host = self.host_slugs_to_allocate(agent);
484        // A slug an agent was renamed from is still that agent's: matched
485        // like its current slug, after a name or slug match (fork slug
486        // migration Phase 1). Read before the connection lock.
487        let former_owner = self.former_slug_owner(&derived_slug)?.map(|o| o.uid);
488
489        {
490            let conn = self.conn.lock().unwrap();
491
492            // Check under the same lock to close the TOCTOU window.
493            // `is_seeded = 0` already excludes templates; it does NOT
494            // exclude a template-launch row (also `is_seeded = 0`, no
495            // `db_agent_definitions` counterpart) — same as before this
496            // read moved to `db_agents`, since the legacy table never held
497            // launch rows to exclude in the first place.
498            // A name match first, then a slug match, where the slug is the
499            // canonical one every other reader gives ([`canonical_slug`]).
500            // Names compare as SQLite's `lower(trim(name))` did: ASCII only.
501            let mut stmt = conn.prepare(&format!(
502                "{AGENT_DEFINITION_SELECT} WHERE is_seeded = 0 ORDER BY created_at ASC, id ASC"
503            ))?;
504            let rows = stmt.query_map([], map_agent_definition_row)?.collect::<Result<Vec<_>, _>>()?;
505            // Drop borrows on `conn` before proceeding to the insert.
506            drop(stmt);
507            let canonical = |d: &AgentDefinition| canonical_slug(&d.id, &d.slug, shared.slug(&d.id));
508            let found = rows
509                .iter()
510                .find(|d| d.name.trim_matches(' ').to_ascii_lowercase() == name_lower)
511                .or_else(|| rows.iter().find(|d| canonical(d).eq_ignore_ascii_case(&derived_slug)))
512                .or_else(|| former_owner.as_deref().and_then(|uid| rows.iter().find(|d| d.id == uid)));
513            if let Some(def) = found {
514                let mut def = def.clone();
515                def.slug = canonical(&def);
516                return Ok(Some(def));
517            }
518
519            // Not found — insert under the same lock.
520            let base = if agent.slug.is_empty() {
521                derive_slug(&agent.name)
522            } else {
523                agent.slug.clone()
524            };
525            // The shared resolver: case-insensitive, like the key tables.
526            agent.slug = super::name_keys::resolve_slug_collision(&conn, &base, &agent.id, &allocation?, host?.as_ref())?;
527            // A new row: updated when it was created.
528            insert_definition_row(&conn, agent, agent.created_at)?;
529        }
530        // Do NOT mutate `agent.updated_at` here — matches
531        // `agent_def_insert_local_only`'s own "zero-behaviour-change"
532        // posture (reagent P1 on #1013 round 2): callers that need the
533        // freshly-stamped value re-fetch the row via the normal read path.
534        // Mirror the freshly-defined agent into the global store (agent.define
535        // path). Without this a define-created agent stays channel-local until
536        // a later edit. (codex P2 on #1385.)
537        // Undone if it fails, as on insert.
538        self.publish_new_or_undo(&agent.id)?;
539
540        Ok(None)
541    }
542
543    /// Set the `user_hidden` flag on a single agent definition. Phase 2
544    /// of the two-tier picker (Q2 Decision Y). Returns:
545    ///   `Ok(true)`  — row updated.
546    ///   `Ok(false)` — no row with that id exists.
547    ///   `Err(...)`  — the row exists but is NOT a seeded template
548    ///                 (`is_seeded != 1`). User-owned definitions go
549    ///                 through `agent_def_delete`, not hide.
550    ///
551    /// Does NOT bump `updated_at`: hide is a per-user view-state flag,
552    /// not a definition-content edit. Keeps `updated_at` faithful to the
553    /// agent's payload (the manifest re-sync compares `description` etc.
554    /// against the canonical row).
555    pub fn agent_def_set_hidden(&self, id: &str, hidden: bool) -> Result<bool, StoreError> {
556        let conn = self.conn.lock().unwrap();
557        // Only seeded templates (`is_template = 1`) may flip the hide flag.
558        // Templates carry `is_template = 1` and are the only rows allowed
559        // to flip the hide flag; folded user-clone-def projections and
560        // template-instance projections (both `is_template = 0`) reject.
561        let is_template: i64 = match conn.query_row(
562            "SELECT is_template FROM db_agents WHERE id = ?1",
563            params![id],
564            |row| row.get(0),
565        ) {
566            Ok(v) => v,
567            Err(rusqlite::Error::QueryReturnedNoRows) => return Ok(false),
568            Err(e) => return Err(StoreError::Sqlite(e)),
569        };
570        if is_template != 1 {
571            return Err(StoreError::Other(format!(
572                "agent_def_set_hidden: {id} is not a seeded template (is_template={is_template}); \
573                 user-owned definitions must use delete/archive paths, not hide"
574            )));
575        }
576        // Templates are seeded; they do NOT go to the global cross-channel
577        // def store, so no registry mirror here.
578        let rows = conn.execute(
579            "UPDATE db_agents SET user_hidden = ?1 WHERE id = ?2 AND is_template = 1",
580            params![if hidden { 1_i64 } else { 0_i64 }, id],
581        )?;
582        Ok(rows > 0)
583    }
584
585    /// Whether this channel's store has its own row for definition `id`, as
586    /// opposed to the definition only resolving through the global registry
587    /// overlay. Only a local row can have its `default_memory_id` set.
588    pub fn agent_def_has_local_row(&self, id: &str) -> Result<bool, StoreError> {
589        let conn = self.conn.lock().unwrap();
590        let found: bool = conn.query_row(
591            "SELECT EXISTS(SELECT 1 FROM db_agents WHERE id = ?1)",
592            params![id],
593            |r| r.get(0),
594        )?;
595        Ok(found)
596    }
597
598    /// Set `db_agents.default_memory_id` on a LOCAL agent — but only if
599    /// it's currently empty. Exists because `agent_def_update`'s SET clause
600    /// deliberately never touches this column (readonly-after-creation, see
601    /// its own field doc comment) — this is the one narrow, explicit path
602    /// allowed to set it, and only the FIRST time, for `m0021`'s backfill
603    /// and definition-time provisioning to use. Returns `Ok(true)` if the
604    /// row existed and had an empty `default_memory_id` (write applied),
605    /// `Ok(false)` if the row doesn't exist locally OR already has a
606    /// non-empty value (no-op, not an error — matches the "set once"
607    /// semantic silently rather than requiring every caller to pre-check).
608    ///
609    /// LOCAL ONLY, deliberately — a cross-channel (global-registry-only)
610    /// definition can't be reached this way today because
611    /// `DefinitionRecordV1` doesn't carry `memory_id` yet (same accepted gap
612    /// as `model_vendor_base_url`, see `def_registry_mirror.rs`). Callers
613    /// backfilling across the whole agent population must check
614    /// `agent_def_get` first and skip (with a log) anything that only
615    /// resolves via the global registry.
616    pub fn agent_def_set_memory_id_if_empty(
617        &self,
618        id: &str,
619        memory_id: &str,
620    ) -> Result<bool, StoreError> {
621        let conn = self.conn.lock().unwrap();
622        let rows = conn.execute(
623            "UPDATE db_agents SET default_memory_id = ?1 WHERE id = ?2 AND default_memory_id = ''",
624            params![memory_id, id],
625        )?;
626        Ok(rows > 0)
627    }
628
629    /// Empty `db_agents.default_memory_id` on a LOCAL agent: it no longer has a
630    /// bundle of its own (`m0047`). Returns whether a binding was cleared.
631    pub fn agent_def_clear_memory_id(&self, id: &str) -> Result<bool, StoreError> {
632        let conn = self.conn.lock().unwrap();
633        let rows = conn.execute("UPDATE db_agents SET default_memory_id = '' WHERE id = ?1 AND default_memory_id != ''", params![id])?;
634        Ok(rows > 0)
635    }
636
637    /// The provider's default vendor, or `"custom"` when the agent has a
638    /// non-empty `model_vendor_base_url` override — same rule the
639    /// frontend's `resolveEffectiveVendor`
640    /// (`frontend/app/view/agent/providers/catalog.ts`) already uses for
641    /// the dual-icon vendor badge. Falls back to the provider id itself
642    /// if the provider isn't in the registry (e.g. a stale/custom
643    /// provider string), same fallback the frontend uses.
644    ///
645    /// Derived wherever it's needed rather than stored: a Claude agent
646    /// pointed at a custom endpoint is `"custom"`, not `"anthropic"`
647    /// (#2587).
648    pub fn resolve_effective_vendor(provider: &str, model_vendor_base_url: &str) -> String {
649        if !model_vendor_base_url.trim().is_empty() {
650            return "custom".to_string();
651        }
652        crate::backend::providers::get_provider(provider)
653            .and_then(|p| p.supported_vendors.first().copied())
654            .unwrap_or(provider)
655            .to_string()
656    }
657
658    /// The harness/provider id `agent` runs: its own `provider`. A bundle
659    /// carries no harness (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1);
660    /// the agent owns it, read-only after creation (`updateagent` and
661    /// `agent.define` refuse a change). The bound bundle's `provider` is a
662    /// hint and is consulted only when the agent has none at all, a
663    /// definition the §3.3 migration couldn't reach; there it is the value
664    /// the agent has always run with.
665    ///
666    /// **Call this on the EFFECTIVE identity/memory store
667    /// (`AppState.id_store`), never on the per-channel `mstore`** — that
668    /// fallback reads the bundle, which lives in the shared store when one is
669    /// configured. One shared implementation for spawn (`agent_open.rs`),
670    /// the credential gate (`identity/resolver/inject.rs`), clone, fork and
671    /// export, so they can't disagree.
672    pub fn resolve_effective_provider_id(&self, agent: &AgentDefinition) -> String {
673        if !agent.provider.is_empty() || agent.memory_id.is_empty() {
674            return agent.provider.clone();
675        }
676        match self.bundle_get(&agent.memory_id) {
677            Ok(Some(b)) => b.provider,
678            _ => String::new(),
679        }
680    }
681
682    /// Resolve a `db_bundles.name` guaranteed not to collide with an
683    /// existing row — that column is `TEXT NOT NULL UNIQUE`, but only
684    /// `AgentDefinition.slug` is guaranteed unique, not the display
685    /// `name`, so a naive `"{agent.name} — ABF"` collides whenever two
686    /// agents share a display name. Appends a numeric suffix on
687    /// collision, same shape `agent_def_insert_local_only` already uses
688    /// for slug collisions.
689    ///
690    /// P1 fix (2026-08-15, ReAgent review on PR #2587 round 4): before
691    /// this, a collision here silently left a runtime-provisioned agent
692    /// unbound (the caller's best-effort error handling swallowed it) and
693    /// — worse — unconditionally ABORTED `m0021`'s entire backfill loop
694    /// via `?` on the very first collision, permanently stalling backfill
695    /// for every agent processed after it, on every subsequent boot,
696    /// until the underlying name collision was manually resolved.
697    pub(crate) fn resolve_unique_bundle_name(&self, base_name: &str) -> Result<String, StoreError> {
698        let existing_names: std::collections::HashSet<String> =
699            self.bundle_list()?.into_iter().map(|b| b.name).collect();
700        if !existing_names.contains(base_name) {
701            return Ok(base_name.to_string());
702        }
703        let mut n: u32 = 2;
704        loop {
705            let candidate = format!("{base_name} ({n})");
706            if !existing_names.contains(&candidate) {
707                return Ok(candidate);
708            }
709            n += 1;
710        }
711    }
712
713    /// Update an existing agent definition (all fields except id, created_at, is_seeded, `parent_id`).
714    /// `parent_id` is NOT updatable post-insert — it describes the agent's
715    /// lineage; re-parenting is done by creating a new fork, not mutating the
716    /// original.
717    ///
718    /// `branch_label` IS written here (unlike `parent_id`) — this storage-
719    /// layer function persists whatever is on `agent`. Immutability for most
720    /// callers is enforced one layer up, at the RPC handler: `updateagent`
721    /// always passes back `old.branch_label.clone()` unchanged, so it's a
722    /// no-op for that caller. `renameagentdefinitiontitle` is the one
723    /// deliberate exception that supplies a real change — see
724    /// `crates/srv/src/server/agent_handlers/template.rs` and
725    /// docs/specs/SPEC_PANE_TAB_STRIP_COMPACT_SIZING_AND_RENAME_2026_07_22.md §4.
726    ///
727    /// Self-stamps `updated_at` with the current time and writes it back into
728    /// `agent.updated_at`, so the caller's struct (e.g. an RPC response body)
729    /// reflects exactly what landed in the database.
730    pub fn agent_def_update(&self, agent: &mut AgentDefinition) -> Result<bool, StoreError> {
731        let now = agentmux_common::time::now_ms();
732        let rows = {
733            let conn = self.conn.lock().unwrap();
734            conn.execute(
735                "UPDATE db_agents SET name=?1, icon=?2, provider=?3, description=?4,
736                 working_directory=?5, shell=?6, provider_flags=?7, auto_start=?8,
737                 restart_on_crash=?9, idle_timeout_minutes=?10,
738                 agent_type=?11, environment=?12, agent_bus_id=?13, accounts=?14, updated_at=?15,
739                 container_image=?17, container_volumes=?18, container_name=?19,
740                 use_ambient_login=?20, branch_label=?21, model_vendor_base_url=?22,
741                 conversation_visibility=?23
742                 WHERE id=?16",
743                params![
744                    agent.name,
745                    agent.icon,
746                    agent.provider,
747                    agent.description,
748                    agent.working_directory,
749                    agent.shell,
750                    agent.provider_flags,
751                    agent.auto_start,
752                    agent.restart_on_crash,
753                    agent.idle_timeout_minutes,
754                    agent.agent_type,
755                    agent.environment,
756                    agent.agent_bus_id,
757                    agent.accounts,
758                    now,
759                    agent.id,
760                    agent.container_image,
761                    agent.container_volumes,
762                    agent.container_name,
763                    agent.use_ambient_login,
764                    agent.branch_label,
765                    agent.model_vendor_base_url,
766                    agent.conversation_visibility,
767                ],
768            )?
769        };
770        // Reflect the persisted timestamp back to the caller's struct so an
771        // RPC response carries the fresh value, not the pre-update one.
772        agent.updated_at = now;
773        // A renamed agent's old display name is a former name from now on.
774        self.former_names_changed();
775        if rows > 0 {
776            // Mirror the updated definition into the global store. (P0.2b.)
777            self.registry_def_upsert(&agent.id);
778        }
779        // Cross-channel edit: an agent surfaced only via the global overlay has
780        // no local SQLite row, so the UPDATE affected 0 rows. Apply the edit to
781        // the global record directly (preserving its content/skills) so editing
782        // a cross-channel agent isn't silently dropped with a "not found" error
783        // — symmetric with the unconditional cross-channel delete. (reagent P1
784        // on #1385.)
785        let updated_global = if rows == 0 {
786            self.registry_def_update_definition_fields(agent)
787        } else {
788            false
789        };
790        Ok(rows > 0 || updated_global)
791    }
792
793    /// Delete a agent definition by id. Returns true if a row was deleted.
794    pub fn agent_def_delete(&self, id: &str) -> Result<bool, StoreError> {
795        // Consolidation Phase 3b (PR 2): a user agent launched from this
796        // template keeps its own `db_agents` row (it is an agent, not a
797        // launch of the template), the same way user clones always survived
798        // deleting their template — deleting `id` here removes only its own
799        // row. The JSON registry mirror for the deleted row is covered by
800        // `registry_def_retire` below.
801        // Its shared slug and former slugs, read before the record is retired.
802        // A record that exists but can't be read refuses the delete.
803        let shared = self.shared_slugs_for_delete(id)?;
804        let (rows, scope) = {
805            let conn = self.conn.lock().unwrap();
806            // Read BEFORE the DELETE — afterwards there is no row to ask.
807            // See `scope_for_row` for what this decides and why.
808            let scope = Self::scope_for_row(&conn, id);
809            // Identity M4a: also read before the DELETE.
810            tombstone_key_names(&conn, id, &shared)?;
811            purge_name_keyed_keys(&conn, id, self.wan_identity().as_deref(), self.host_lan_keys().as_deref(), &shared)?;
812            let rows = conn.execute("DELETE FROM db_agents WHERE id=?1", params![id])?;
813            // Unconditional, same convergence rule as the registry sweep
814            // below (codex P2 on PR #3262): if a previous attempt committed
815            // the `db_agents` DELETE and then failed partway through the
816            // dependent purge, the retry sees `rows == 0` — gating here
817            // would strand that agent's credentials and signing keys
818            // permanently, with no UI path left to try again. Every
819            // statement in the purge is an idempotent DELETE, so running it
820            // for an id with no rows costs a few no-op statements.
821            purge_agent_dependents(&conn, id, self.token_index().as_deref())?;
822            (rows, scope)
823        };
824        // Tombstone the global definition record so another channel's stale
825        // SQLite can't resurrect this deleted user agent — AND so an agent
826        // that exists in THIS channel only via the global overlay (no local
827        // SQLite row, rows == 0) is actually deletable instead of reappearing
828        // on the next agent_def_list. (P0.2b + codex P1 on #1385.)
829        let global_retired = self.registry_def_retire(id);
830        self.former_slugs.invalidate();
831        // Unconditional, deliberately.
832        //
833        // Gating this on `rows > 0` was the original bug's second half: the
834        // instance registry is host-global while `db_agents` is
835        // per-channel, so a cross-channel agent — one this channel only ever
836        // saw through the global overlay — deletes with `rows == 0` and
837        // still has a registry record another channel wrote. That record
838        // stayed active with its definition now tombstoned, which
839        // `listrecentsessions` still renders as a row (no provider, so no
840        // icon, and "(missing definition)") — the delete looked like it
841        // half-worked.
842        //
843        // `rows > 0 || global_retired` isn't enough either (codex P2 on
844        // PR #3262): if an earlier attempt retired the definition but failed
845        // to remove a registry file — or another channel wrote a stale
846        // record after this process's startup reconcile — a RETRY sees
847        // `rows == 0` AND `global_retired == false` (the tombstone already
848        // exists), so it would skip the sweep and the ghost row would
849        // survive every further Delete until restart. Sweeping
850        // unconditionally makes Delete converge: the sweep is a no-op for an
851        // id with no records, so there is nothing to gate on in the first
852        // place.
853        self.purge_agent_side_effects(id, "agent_def_delete", scope);
854        Ok(rows > 0 || global_retired)
855    }
856
857    /// The [`RecordScope`] every registry operation on `id` must use.
858    ///
859    /// **Read this before adding another registry call.** The wide scope
860    /// matches records by `definition_id`, and a TEMPLATE's id is the
861    /// `definition_id` of every legacy, never-re-keyed launch record
862    /// belonging to a REAL agent launched from it — so a wide match on a
863    /// template deletes / retires / renames those agents' records along
864    /// with the template, making them vanish from the picker. ReAgent found
865    /// exactly that omission at four separate call sites on PR #3262
866    /// (`agent_def_delete`, `instance_delete`, `instance_set_hidden`,
867    /// `instance_rename`), which is why the rule lives here rather than as
868    /// a fourth hand-written `if`.
869    ///
870    /// An id with no row at all is NOT a template: the global definition
871    /// store only holds `is_seeded == 0` user agents, so a cross-channel id
872    /// is always an agent — which is what lets the delete paths still sweep
873    /// on a retry after the local row is already gone.
874    ///
875    /// Takes the connection rather than `&self` because every caller needs
876    /// this read in the SAME critical section as its own UPDATE/DELETE —
877    /// otherwise the row could change kind in between. A `&self` wrapper
878    /// existed briefly and was dead on arrival for exactly that reason
879    /// (ReAgent P2 on PR #3262).
880    pub(in crate::backend::storage) fn scope_for_row(conn: &rusqlite::Connection, id: &str) -> RecordScope {
881        let is_template = conn
882            .query_row(
883                "SELECT is_template FROM db_agents WHERE id = ?1",
884                params![id],
885                |r| r.get::<_, i64>(0),
886            )
887            .map(|v| v != 0)
888            .unwrap_or(false);
889        if is_template {
890            RecordScope::FileKeyOnly
891        } else {
892            RecordScope::Agent
893        }
894    }
895
896    /// Purge this store's rows keyed to a deleted agent, without touching
897    /// `db_agents` itself. For the OTHER physical database an agent has
898    /// rows in: `agent_def_delete` covers the object store it runs against,
899    /// and the `deleteagent` handler calls this on `state.identity_store`,
900    /// which is where the live `db_agent_identity_links` /
901    /// `db_agent_credentials` / native-memory rows actually are
902    /// (`SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md`). See
903    /// [`purge_agent_dependents`] for the table list and why one list
904    /// serves both stores. Returns rows removed.
905    pub fn agent_dependents_purge(&self, id: &str) -> Result<usize, StoreError> {
906        let conn = self.conn.lock().unwrap();
907        purge_agent_dependents(&conn, id, self.token_index().as_deref())
908    }
909
910    /// The non-SQLite half of deleting an agent row: observations keyed to
911    /// it, and its records in the host-global instance registry. Shared by
912    /// [`Self::agent_def_delete`] and [`Self::instance_delete`] — the two
913    /// names one deletion is reached by since the definition flip (see
914    /// `instance_delete`'s own doc comment). Best-effort throughout:
915    /// SQLite has already committed, and neither side failing is a reason
916    /// to report the delete as failed. `caller` only labels the logs.
917    ///
918    /// `scope` must come from `scope_for_row`, read
919    /// BEFORE the row was deleted — afterwards there is nothing left to ask.
920    pub(in crate::backend::storage) fn purge_agent_side_effects(&self, id: &str, caller: &'static str, scope: RecordScope) {
921        // Project-instruction observations are keyed by agent id with no
922        // foreign key (they record files this agent READS, which is not a
923        // relationship SQLite can enforce), so nothing else would remove
924        // them and a future agent reusing this id would inherit somebody
925        // else's baseline — every file reporting `unchanged` against
926        // observations that were never made about it. Cleaned up here,
927        // beside the row it belongs to, rather than left to each caller
928        // (ReAgent, PR #3162).
929        if let Err(e) = self.project_instructions_forget(id) {
930            tracing::warn!(
931                agent_def_id = %id, caller, error = %e,
932                "agent delete: project-instruction observations left behind"
933            );
934        }
935        if let Some(reg) = self.registry() {
936            // An AGENT's records are matched by either key — see
937            // `Registry::hard_delete_for_agent` for why the file key and the
938            // record's own `definition_id` can disagree, and what a missed
939            // record looks like in the picker.
940            //
941            // A TEMPLATE's are matched by file key only. A template's id can
942            // legitimately be the `definition_id` of a legacy,
943            // never-re-keyed launch record belonging to a real agent
944            // launched from it, and the wide match would delete that agent's
945            // record along with the template — making agents disappear from
946            // the picker instead of the one thing the user asked to delete
947            // (ReAgent P1 round 3 on PR #3262;
948            // `agent_def_delete_removes_only_its_own_registry_file` is the
949            // protection, and
950            // `deleting_a_template_spares_a_legacy_launch_record_pointing_at_it`
951            // pins the legacy shape that test doesn't construct).
952            match reg.hard_delete_for_agent(id, scope) {
953                Ok(0) => {}
954                Ok(removed) => tracing::debug!(
955                    agent_def_id = %id, caller, removed,
956                    "registry: purged instance records for deleted agent"
957                ),
958                Err(e) => tracing::warn!(
959                    agent_def_id = %id, caller, error = %e,
960                    "registry: failed to mirror agent delete"
961                ),
962            }
963        }
964    }
965
966    // AgentContent / AgentSkill / AgentHistory CRUD live in
967    // `super::content` / `super::skills` / `super::history` —
968    // each adds an `impl Store {}` block to this type.
969}
970
971/// The one statement that inserts a definition's `db_agents` row, for every way one is inserted:
972/// on the caller's connection, under the lock it resolved `agent.slug` with. `updated_at` is the
973/// caller's: when the definition was created for a new one, the registry record's own time for a
974/// backfill.
975///
976/// `is_seeded = 1` rows become `is_template = 1` with no parent; `is_seeded = 0` rows become
977/// `is_template = 0` with `parent_template_id = parent_id`.
978fn insert_definition_row(conn: &rusqlite::Connection, agent: &AgentDefinition, updated_at: i64) -> rusqlite::Result<usize> {
979    let is_template = if agent.is_seeded == 1 { 1_i64 } else { 0_i64 };
980    let parent_template_id = if agent.is_seeded == 1 { String::new() } else { agent.parent_id.clone() };
981    conn.execute(
982        "INSERT INTO db_agents (
983            id, name, icon, description,
984            is_template, parent_template_id,
985            provider, provider_flags, shell, environment,
986            agent_type, agent_bus_id, accounts,
987            auto_start, restart_on_crash, idle_timeout_minutes,
988            slug, branch_label, working_directory,
989            created_at, updated_at, is_seeded, user_hidden,
990            container_image, container_volumes, container_name,
991            use_ambient_login, model_vendor_base_url,
992            default_memory_id, conversation_visibility
993         ) VALUES (
994            ?1, ?2, ?3, ?4,
995            ?5, ?6,
996            ?7, ?8, ?9, ?10,
997            ?11, ?12, ?13,
998            ?14, ?15, ?16,
999            ?17, ?18, ?19,
1000            ?20, ?21, ?22, ?23,
1001            ?24, ?25, ?26,
1002            ?27, ?28,
1003            ?29, ?30
1004         )",
1005        params![
1006            agent.id,
1007            agent.name,
1008            agent.icon,
1009            agent.description,
1010            is_template,
1011            parent_template_id,
1012            agent.provider,
1013            agent.provider_flags,
1014            agent.shell,
1015            agent.environment,
1016            agent.agent_type,
1017            agent.agent_bus_id,
1018            agent.accounts,
1019            agent.auto_start,
1020            agent.restart_on_crash,
1021            agent.idle_timeout_minutes,
1022            agent.slug,
1023            agent.branch_label,
1024            agent.working_directory,
1025            agent.created_at,
1026            updated_at,
1027            agent.is_seeded,
1028            // Phase 2 (hide templates): new rows start visible. The
1029            // user only hides via the explicit `agentdefhide` RPC,
1030            // and the agent-seed re-sync forces user_hidden = 0 on
1031            // any newly-added template id anyway, so honouring the
1032            // caller-supplied value here is safe even when a stray
1033            // 1 sneaks through.
1034            agent.user_hidden,
1035            agent.container_image,
1036            agent.container_volumes,
1037            agent.container_name,
1038            agent.use_ambient_login,
1039            agent.model_vendor_base_url,
1040            agent.memory_id,
1041            agent.conversation_visibility,
1042        ],
1043    )
1044}
1045
1046#[cfg(test)]
1047#[path = "definition_insert_tests.rs"]
1048mod insert_tests;