agentmux_srv_core/backend/storage/agents/mod.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent subsystem — definitions, instances, and their lifecycle CRUD.
5//!
6//! Covers `agent_def_*` methods (template + user-clone definitions),
7//! `instance_*` methods (per-launch instance rows, named-agent
8//! continuation, identity-bound active-for-block resolution), the
9//! `AgentDefinition` / `AgentInstance` structs, and the `InstanceStatus` enum.
10//!
11//! This file holds the types and defaults; the methods are in `definition`
12//! (`agent_def_*`) and `instance` (`instance_*`), the shared column lists and
13//! row mappers in `row`, slugs and name-keyed rows in `name_keys`, which of
14//! an agent's two stored slugs is its slug in `canonical_slug`, the slugs it
15//! answered to before a rename in `former_slugs`, the display names it was
16//! renamed from (and the one resolver for both kinds) in `former_names`, and
17//! the delete cascade in `purge`.
18//!
19//! Every method in both groups reads and writes `db_agents` only, as of the
20//! agent-concept consolidation's definition flip
21//! (`docs/specs/SPEC_AGENT_ARCHITECTURE_2026_05_27.md` Phase 3d) — the
22//! instance side flipped first (Phase 3b, PR 2 of 4, #3080), the definition
23//! side followed once the six agent-child tables' FK re-pointed to
24//! `db_agents` (Phase 3c, PR 3 of 4, #3088) removed the reason
25//! `agent_def_get` had to stay scoped to `db_agent_definitions`. Neither
26//! legacy table has a live writer left in this file; the old `dual_write` module, which
27//! used to mirror definition writes into `db_agents`, is gone — there is no
28//! second table left to mirror into one from.
29//!
30//! `db_agent_definitions` and `db_agent_instances` are still physically
31//! present in the schema (dropped in a later PR) — do not read either as a
32//! live source anywhere in this file; every read here is `db_agents`.
33
34use rusqlite::params;
35use serde::{Deserialize, Serialize};
36
37use super::error::StoreError;
38use super::store::Store;
39use crate::registry::RecordScope;
40
41pub mod canonical_slug;
42pub mod definition;
43pub mod former_names;
44pub mod former_slugs;
45pub mod instance;
46pub mod name_keys;
47pub mod purge;
48pub mod row;
49
50pub(in crate::backend::storage) use canonical_slug::{canonical_slug, rows_with_canonical_slugs, SharedSlugs};
51pub use former_slugs::FormerSlugOwner;
52pub(super) use former_slugs::FormerSlugSet;
53pub(crate) use former_slugs::FORMER_SLUGS_SCHEMA;
54pub(super) use name_keys::FORMER_BRANCH_LABEL_TRIGGER;
55pub use name_keys::AgentNameMatch;
56#[cfg(test)]
57pub(super) use name_keys::key_tombstones_for_tests;
58#[cfg(test)]
59pub(super) use purge::purge_agent_dependents_for_tests;
60#[allow(unused_imports)]
61use self::{canonical_slug::*, former_names::*, former_slugs::*, name_keys::*, purge::*, row::*};
62
63/// A user-defined AI agent in the user's agent-definition catalog.
64#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
65#[ts(export, export_to = "../../../frontend/types/rpc/")]
66pub struct AgentDefinition {
67 pub id: String,
68 /// Stable, filesystem-safe identifier. Drives working directory,
69 /// env var keys (AGENTMUX_AGENT_ID), and cross-references.
70 /// NEVER changes after creation — distinct from `name` which is
71 /// the renameable display. See
72 /// docs/specs/SPEC_AGENT_IDENTITY_RESTRUCTURE_2026_04_14.md.
73 #[serde(default)]
74 pub slug: String,
75 pub name: String,
76 pub icon: String,
77 pub provider: String,
78 pub description: String,
79 #[serde(default)]
80 pub working_directory: String,
81 #[serde(default)]
82 pub shell: String,
83 #[serde(default)]
84 pub provider_flags: String,
85 #[serde(default)]
86 #[ts(type = "number")]
87 pub auto_start: i64,
88 #[serde(default)]
89 #[ts(type = "number")]
90 pub restart_on_crash: i64,
91 #[serde(default)]
92 #[ts(type = "number")]
93 pub idle_timeout_minutes: i64,
94 #[ts(type = "number")]
95 pub created_at: i64,
96 #[serde(default = "default_agent_type")]
97 pub agent_type: String,
98 #[serde(default)]
99 pub environment: String,
100 #[serde(default)]
101 pub agent_bus_id: String,
102 #[serde(default)]
103 #[ts(type = "number")]
104 pub is_seeded: i64,
105 /// JSON-encoded per-provider account assignments
106 /// (`{"github":"acct-id", …}`). Written by the Agent pane's Identity
107 /// tab (`AgentIdentityPanel`) via `updateagent`, read back by
108 /// `parseAgentAccounts` and consumed by startup credential
109 /// resolution. (An older v6 comment called this deprecated in favour
110 /// of `db_agent_identity_links`; that migration never completed — the
111 /// JSON blob is still the live store, so the schema flatten keeps the
112 /// column.)
113 #[serde(default)]
114 pub accounts: String,
115 /// Parent definition id (db_agent_definitions.id). Empty string = root
116 /// definition; non-empty = this agent was forked from another.
117 /// Added in v6. See spec §Phase 1.
118 #[serde(default)]
119 pub parent_id: String,
120 /// Label describing the branch (e.g. `"pr-422-review"`,
121 /// `"experiment-refactor"`). Empty for root definitions and for
122 /// branches that didn't set a label. Added in v6.
123 #[serde(default)]
124 pub branch_label: String,
125 /// Last-modified timestamp (epoch ms). Set to `created_at` on insert
126 /// and refreshed on every `agent_def_update`. Schema v2. `0` for
127 /// rows written before v2 (until next update).
128 #[serde(default)]
129 #[ts(type = "number")]
130 pub updated_at: i64,
131 /// Per-user hide flag for seeded templates. `1` = the user clicked
132 /// "Hide template" on the picker's `+ New from template` tier; the
133 /// row stays on disk (templates are manifest-managed; deletion would
134 /// fight re-seed) but the default `listagents` view filters it out.
135 /// Reset to `0` by the agent-seed re-sync flow for any NEW template
136 /// id newly added to the manifest, so a fresh template surfaces once
137 /// even if a same-named one was previously hidden. Schema v3 (Phase
138 /// 2 of `SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md` — Q2 Decision Y).
139 /// User-owned rows (`is_seeded = 0`) MUST stay at `0` here; their
140 /// removal path is `deleteagent`, not hide.
141 #[serde(default)]
142 #[ts(type = "number")]
143 pub user_hidden: i64,
144 /// Docker image to use when `agent_type == "container"`.
145 /// e.g. `"ghcr.io/agentmuxai/agent-base:latest"`.
146 /// Empty string for host agents. Schema v6.
147 #[serde(default)]
148 pub container_image: String,
149 /// JSON array of volume mount specs for container agents.
150 /// Each element is a string in Docker bind-mount format:
151 /// `"source:target"` or `"source:target:options"`.
152 /// Empty JSON array (`"[]"`) for host agents. Schema v6.
153 #[serde(default = "default_container_volumes")]
154 pub container_volumes: String,
155 /// Stable Docker container name managed by the server.
156 /// Set to `"agentmux-<slug>"` on first container spawn;
157 /// empty for host agents. Schema v6.
158 #[serde(default)]
159 pub container_name: String,
160 /// Inert. It was a per-agent opt-in to the CLI's global login when no
161 /// account resolved at spawn; the spawn gate no longer reads it (an
162 /// oauth-class agent with no bound account is always refused), no RPC
163 /// sets it and no UI shows it. The column and this field stay only so
164 /// the shared definition registry keeps the value older builds read
165 /// (linkless agents were grandfathered to `1` there by migrations since retired).
166 /// SPEC_MY_AGENTS_TILES_AUTH_AND_HISTORY_2026_10_03.md R10.
167 #[serde(default)]
168 #[ts(type = "number")]
169 pub use_ambient_login: i64,
170 /// Redirects this agent's harness (CLI) at a non-default model vendor
171 /// backend — e.g. `"https://my-proxy.example.com"` for a `claude`-provider
172 /// agent, injected into `ANTHROPIC_BASE_URL` at spawn time. Empty string
173 /// (default) = use the harness's default vendor endpoint. Only settable
174 /// when the resolved provider declares `ProviderConfig::base_url_env_var`
175 /// (validated in `agent_define_core`) — see docs/specs for the harness
176 /// vs. model-vendor concept this formalizes. Schema v15. Channel-local:
177 /// does not currently survive a cross-channel reopen of the same agent
178 /// (known limitation, not wired into the registry mirror).
179 #[serde(default)]
180 pub model_vendor_base_url: String,
181 /// Legacy: the agent's own dedicated ABF bundle (`db_bundles.id`). An agent
182 /// has no bundle of its own now: `m0047` moved any into the agent's picks
183 /// (`db_agent_bundles`) and emptied this. It stays set only for an agent
184 /// with no provider of its own, whose provider is read from the bundle
185 /// (`Store::resolve_effective_provider_id`). Distinct from
186 /// `AgentInstance.memory_id` (a specific *launch*'s bundle). Stored in `db_agents.default_memory_id`
187 /// — a separate column from `db_agents.memory_id`, which is the
188 /// instance-scoped field this doc paragraph opens by distinguishing it
189 /// from. Schema v19; the two-column split dates to
190 /// ARCHITECTURE_MANDATORY_ABF_RETHINK_2026_08_14.md §3.1.
191 #[serde(default)]
192 pub memory_id: String,
193 /// This agent's own disclosure policy for an incoming cross-tier
194 /// `transcript_request` jekt (`muxspect` Phase B/C — LAN/WAN
195 /// conversation visibility, `SPEC_MUXSPECT_CROSS_TIER_CONVERSATION_VISIBILITY_2026_08_21.md`,
196 /// jekt tier rules confirmed in `SPEC_JEKT_TRANSCRIPT_REQUEST_TIER_RULES_2026_08_22.md`).
197 /// One of `"private"` (default — auto-deny, fail-closed), `"trusted_peers"`
198 /// (auto-approve only a requester in `db_conversation_trust_grants`), or
199 /// `"ask"` (force human escalation, never auto-respond). Schema v26.
200 /// Channel-local only, like `model_vendor_base_url`/`memory_id` above —
201 /// deliberately NOT added to `DefinitionRecordV1`'s cross-channel wire
202 /// format yet; a cross-channel-reopened agent starts back at the safe
203 /// `"private"` default rather than carrying a stale value. Known
204 /// limitation, not a bug — same precedent as those two fields.
205 #[serde(default = "default_conversation_visibility")]
206 pub conversation_visibility: String,
207 /// The agent's seat: role, lead and area
208 /// (`SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md`). It lives on the shared
209 /// definition record, not in `db_agents`, so it's filled where the record
210 /// is read: `agent_def_list`'s overlay and a cross-channel agent's
211 /// `agent_def_get`. `agent_def_get` of a local row leaves it `None`; read
212 /// it with `Store::agent_seat_get`. Written only by `agent.setSeat`
213 /// (`Store::agent_seat_set`); every other definition write leaves the
214 /// stored seat alone. `listagents` gives a spawned worker with no seat its
215 /// effective one (`backend::agent_seat::effective_seat`).
216 #[serde(default, skip_serializing_if = "Option::is_none")]
217 #[ts(optional)]
218 pub seat: Option<crate::registry::AgentSeat>,
219}
220
221impl AgentDefinition {
222 /// Where this agent runs: the one place `agent_type` is read as host or container.
223 pub fn runtime(&self) -> crate::backend::runtime_adapter::RuntimeKind {
224 crate::backend::runtime_adapter::RuntimeKind::of_agent_type(&self.agent_type)
225 }
226}
227
228/// `AgentDefinition::conversation_visibility`'s serde default — the safe,
229/// fail-closed value for any row/context that doesn't specify one
230/// (including every pre-existing row before this column existed).
231pub fn default_conversation_visibility() -> String {
232 "private".to_string()
233}
234
235/// The working directory `agent.open` substitutes when an
236/// `AgentDefinition`'s own `working_directory` is blank —
237/// `~/.agentmux/agents/<name-derived-slug>`.
238///
239/// Blank is the DEFAULT for a newly defined agent, so this is the path most
240/// agents actually run in. Extracted so `agent.open` (which creates and uses
241/// it) and native-memory resolution (which must find the memories written
242/// inside it) share one definition and cannot drift — they previously
243/// disagreed, and the resolver simply gave up on a blank field, breaking
244/// Memory → Personal for the common case. See
245/// `docs/specs/SPEC_FIX_PERSONAL_MEMORY_EMPTY_WORKDIR_2026_09_01.md`.
246///
247/// NOTE: deliberately NOT `derive_slug` above. `agent.open`'s own inline
248/// derivation is `name.to_lowercase()` with a Unicode-aware
249/// `char::is_alphanumeric()` filter (keeping `-`/`_`), which differs from
250/// `derive_slug`'s ASCII-only rule, dash-collapsing, 64-char trim and
251/// `"agent"` fallback. Reusing `derive_slug` here would silently point at a
252/// DIFFERENT directory than the one the agent is really running in for any
253/// non-ASCII or dash-heavy name. This mirrors the real behaviour exactly.
254pub fn default_agent_working_dir(agent_name: &str) -> String {
255 format!("~/.agentmux/agents/{}", agentmux_common::slug::path_slug(agent_name))
256}
257
258/// Derive a filesystem-safe slug from a display name
259/// (`agentmux_common::slug::definition_slug`).
260pub fn derive_slug(name: &str) -> String {
261 agentmux_common::slug::definition_slug(name)
262}
263
264fn default_agent_type() -> String {
265 "standalone".to_string()
266}
267
268fn default_container_volumes() -> String {
269 "[]".to_string()
270}
271
272/// Instance lifecycle status. Serialised lowercase to match the DB text.
273#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
274#[serde(rename_all = "lowercase")]
275pub enum InstanceStatus {
276 Running,
277 Paused,
278 Stopped,
279 Crashed,
280 Detached,
281}
282
283impl InstanceStatus {
284 pub fn as_str(&self) -> &'static str {
285 match self {
286 Self::Running => "running",
287 Self::Paused => "paused",
288 Self::Stopped => "stopped",
289 Self::Crashed => "crashed",
290 Self::Detached => "detached",
291 }
292 }
293}
294
295/// Partial-update payload for [`Store::instance_update_partial`]. Each
296/// `Some` field is written; `None` leaves the column untouched. Mirrors
297/// the mutable subset of `CommandUpdateAgentInstanceData`
298/// (`block_id`/`session_id`/`status`/`github_context`/`ended_at`) — the
299/// only columns `instance_update` ever wrote. `Some("")` for a string
300/// field explicitly clears it.
301#[derive(Debug, Clone, Default)]
302pub struct InstanceUpdate {
303 pub block_id: Option<String>,
304 pub session_id: Option<String>,
305 pub status: Option<String>,
306 pub github_context: Option<String>,
307 pub ended_at: Option<i64>,
308}
309
310/// One row per running/historical execution of an agent definition.
311/// `block_id` / `session_id` / `github_context` are modelled as empty
312/// strings on the wire rather than `Option<String>` to match the
313/// existing schema conventions (`NOT NULL DEFAULT ''`). Callers
314/// that need structured absence can use `.is_empty()`.
315#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
316#[ts(export, export_to = "../../../frontend/types/rpc/")]
317pub struct AgentInstance {
318 pub id: String,
319 pub definition_id: String,
320 #[serde(default)]
321 pub parent_instance_id: String,
322 #[serde(default)]
323 pub block_id: String,
324 #[serde(default)]
325 pub session_id: String,
326 pub status: String,
327 /// JSON-encoded `GitHubContext`, or empty string.
328 #[serde(default)]
329 pub github_context: String,
330 #[ts(type = "number")]
331 pub started_at: i64,
332 #[serde(default)]
333 #[ts(type = "number")]
334 pub ended_at: i64,
335 #[ts(type = "number")]
336 pub created_at: i64,
337 /// Legacy Identity-bundle id column — `db_identity_bundles` was
338 /// dropped in Phase 4c of SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md.
339 /// A launch now writes an account_id here instead; credential
340 /// resolution and display names both go through
341 /// `db_agent_identity_links`/`db_accounts`. Empty string means no
342 /// account was picked at launch.
343 #[serde(default)]
344 pub identity_id: String,
345 /// FK to `db_bundles.id`. Empty string means "use the blank
346 /// singleton" (= vanilla CLI, no instructions). Set at
347 /// instantiation from the agent's first bundle.
348 #[serde(default)]
349 pub memory_id: String,
350 /// User-chosen instance name (becomes `AGENTMUX_AGENT_ID` in the
351 /// spawn env). Empty for pre-v8 rows and for un-named launches.
352 /// Drives `listnamedagents` (My Agents).
353 #[serde(default)]
354 pub instance_name: String,
355 /// Absolute path returned by `allocate_agent_workdir` at spawn.
356 /// Stored explicitly (rather than re-derived from the slug at
357 /// continue-time) so the continue flow is robust against
358 /// slug-rule changes and user-side renames.
359 #[serde(default)]
360 pub working_directory: String,
361 /// Soft-delete flag for the "Forget agent" affordance. Hidden
362 /// rows stay on disk for audit + recovery.
363 #[serde(default)]
364 pub display_hidden: bool,
365}
366
367/// Shared test fixture: an `AgentDefinition` with every field defaulted to
368/// an empty/zero value except the ones callers actually vary. Originally
369/// shared to avoid `tests::bare_agent_def` and
370/// `bundle_provisioning_store_separation_tests::base_agent` each hardcoding
371/// this 30-field struct literal independently (reagentx P2 on PR #2602);
372/// `bare_agent_def` is gone (its only caller pinned pre-flip behavior this
373/// module no longer has), leaving `base_agent` as the remaining caller —
374/// kept as one definition here regardless, so a future field addition only
375/// needs updating once.
376#[cfg(any(test, feature = "test-support"))]
377pub fn test_agent_def(
378 id: &str,
379 name: &str,
380 provider: &str,
381 agent_type: &str,
382 timestamp: i64,
383 model_vendor_base_url: &str,
384) -> AgentDefinition {
385 AgentDefinition {
386 id: id.to_string(),
387 slug: id.to_string(),
388 name: name.to_string(),
389 icon: String::new(),
390 provider: provider.to_string(),
391 description: String::new(),
392 working_directory: String::new(),
393 shell: String::new(),
394 provider_flags: String::new(),
395 auto_start: 0,
396 restart_on_crash: 0,
397 idle_timeout_minutes: 0,
398 created_at: timestamp,
399 agent_type: agent_type.to_string(),
400 environment: String::new(),
401 agent_bus_id: String::new(),
402 is_seeded: 0,
403 accounts: String::new(),
404 parent_id: String::new(),
405 branch_label: String::new(),
406 updated_at: timestamp,
407 user_hidden: 0,
408 container_image: String::new(),
409 container_volumes: "[]".to_string(),
410 container_name: String::new(),
411 use_ambient_login: 0,
412 model_vendor_base_url: model_vendor_base_url.to_string(),
413 memory_id: String::new(),
414 seat: None,
415 conversation_visibility: default_conversation_visibility(),
416 }
417}
418
419/// Shared test fixture: a running `AgentInstance` of `definition_id` on `block_id`, started and
420/// created at `started_at`, with every other field empty. A test names only the fields it is about:
421/// `AgentInstance { session_id: "s".to_string(), ..test_agent_instance("i", "def", "block", 1000) }`.
422#[cfg(any(test, feature = "test-support"))]
423pub fn test_agent_instance(id: &str, definition_id: &str, block_id: &str, started_at: i64) -> AgentInstance {
424 AgentInstance {
425 id: id.to_string(),
426 definition_id: definition_id.to_string(),
427 parent_instance_id: String::new(),
428 block_id: block_id.to_string(),
429 session_id: String::new(),
430 status: InstanceStatus::Running.as_str().to_string(),
431 github_context: String::new(),
432 started_at,
433 ended_at: 0,
434 created_at: started_at,
435 identity_id: String::new(),
436 memory_id: String::new(),
437 instance_name: String::new(),
438 working_directory: String::new(),
439 display_hidden: false,
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use crate::registry::{
447 DefContentBlob, DefSkillBlob, DefinitionRecord, DefinitionRecordV1, DefinitionStore,
448 DEF_MAX_SUPPORTED_SCHEMA,
449 };
450 use std::sync::Arc;
451
452 /// Mirrors `def_registry_mirror.rs`'s own test fixture — a user
453 /// agent that exists only in the global cross-channel registry,
454 /// with one content blob and one skill, so a backfill has
455 /// something real to preserve.
456 fn global_user_agent(id: &str, name: &str) -> DefinitionRecord {
457 DefinitionRecord {
458 schema_version: DEF_MAX_SUPPORTED_SCHEMA,
459 data: DefinitionRecordV1 {
460 id: id.to_string(),
461 name: name.to_string(),
462 provider: "claude".to_string(),
463 is_seeded: 0,
464 updated_at: 42,
465 content: vec![DefContentBlob {
466 content_type: "agentmd".to_string(),
467 content: "be helpful".to_string(),
468 }],
469 skills: vec![DefSkillBlob {
470 id: "sk1".to_string(),
471 name: "greet".to_string(),
472 ..Default::default()
473 }],
474 ..Default::default()
475 },
476 }
477 }
478
479 fn instance(id: &str, definition_id: &str) -> AgentInstance {
480 AgentInstance {
481 status: "init".to_string(),
482 instance_name: id.to_string(),
483 ..crate::backend::storage::agents::test_agent_instance(id, definition_id, "", 1)
484 }
485 }
486
487 #[test]
488 fn instance_create_backfills_local_definition_from_registry_only_record() {
489 let store = Store::open_in_memory().unwrap();
490 let tmp = tempfile::tempdir().unwrap();
491 let def_store = Arc::new(DefinitionStore::open(tmp.path().join("definitions")).unwrap());
492 def_store
493 .upsert(&global_user_agent("remote-1", "Remote"))
494 .unwrap();
495 store.set_def_registry(def_store.clone());
496
497 // Local db_agent_definitions has no row for "remote-1" — this
498 // is exactly the Moras/Oozp/Parko scenario. Without the
499 // backfill this INSERT fails with a FOREIGN KEY error.
500 let result = store.instance_create(&instance("inst-1", "remote-1"));
501 assert!(result.is_ok(), "instance_create failed: {result:?}");
502
503 // The backfilled local row must exist and satisfy the FK.
504 let local = store.agent_row_get("remote-1").unwrap();
505 assert!(local.is_some(), "backfill must create a local definition row");
506
507 // Critical regression guard: the registry's real content/skills
508 // must NOT have been wiped by the backfill (this is exactly
509 // what a naive `agent_def_insert`-based backfill would do —
510 // see agent_def_backfill_local_from_registry's doc comment).
511 let rec = def_store.get("remote-1").unwrap().unwrap();
512 assert_eq!(rec.data.content.len(), 1, "registry content must survive backfill");
513 assert_eq!(rec.data.skills.len(), 1, "registry skills must survive backfill");
514 }
515
516 #[test]
517 fn instance_create_still_errors_when_definition_missing_everywhere() {
518 let store = Store::open_in_memory().unwrap();
519 let tmp = tempfile::tempdir().unwrap();
520 let def_store = Arc::new(DefinitionStore::open(tmp.path().join("definitions")).unwrap());
521 store.set_def_registry(def_store);
522
523 // No local row, nothing in the registry either — genuinely
524 // orphaned definition_id. Must still fail loudly, not silently
525 // swallow a real error.
526 let result = store.instance_create(&instance("inst-2", "nowhere"));
527 assert!(result.is_err(), "instance_create must still fail for a truly orphaned definition_id");
528 }
529
530 // SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md follow-up: App-API
531 // self-lookup callers (MemoryList/Read/Write, IdentityAccounts,
532 // IdentityValidate, bundle.self.get) pass the AGENTMUX_AGENT_ID routing
533 // slug, not the literal display name. Confirmed live: a real agent
534 // named "AgentY" (slug "agenty") got "agent agenty not found" from
535 // every one of those endpoints before `instance_get_by_slug` existed.
536 #[test]
537 fn instance_get_by_slug_resolves_a_mixed_case_display_name_via_its_slug() {
538 let store = Store::open_in_memory().unwrap();
539 let tmp = tempfile::tempdir().unwrap();
540 let def_store = Arc::new(DefinitionStore::open(tmp.path().join("definitions")).unwrap());
541 def_store.upsert(&global_user_agent("def-agenty", "AgentY")).unwrap();
542 store.set_def_registry(def_store);
543
544 let mut inst = instance("inst-agenty", "def-agenty");
545 inst.instance_name = "AgentY".to_string();
546 store.instance_create(&inst).unwrap();
547
548 // The routing slug ("agenty", what every MCP-tool-backed App-API
549 // endpoint actually has) must resolve to the display-cased row.
550 let found = store.instance_get_by_slug("agenty").unwrap();
551 assert!(found.is_some(), "must resolve via the persisted slug column");
552 assert_eq!(found.unwrap().instance_name, "AgentY");
553 }
554
555 #[test]
556 fn instance_get_by_slug_returns_none_for_a_genuinely_unrelated_slug() {
557 let store = Store::open_in_memory().unwrap();
558 let tmp = tempfile::tempdir().unwrap();
559 let def_store = Arc::new(DefinitionStore::open(tmp.path().join("definitions")).unwrap());
560 def_store.upsert(&global_user_agent("def-agenty2", "AgentY")).unwrap();
561 store.set_def_registry(def_store);
562
563 let mut inst = instance("inst-agenty2", "def-agenty2");
564 inst.instance_name = "AgentY".to_string();
565 store.instance_create(&inst).unwrap();
566
567 let found = store.instance_get_by_slug("someone-else").unwrap();
568 assert!(found.is_none(), "an unrelated slug must not match by coincidence");
569 }
570
571 // reagentx P1 on PR #2428 (round 2): a slug-normalized re-derivation of
572 // the CURRENT display name (`derive_slug(instance_name)`) only equals
573 // the real routing slug when the display name has never changed and
574 // never collided with another agent's at creation. `slug` is stable
575 // and persisted once, `name`/`instance_name` are renameable — this
576 // test deliberately sets them to unrelated values (as if the agent
577 // were renamed, or its slug got a "-2" collision suffix at creation)
578 // to prove the fix resolves via the real persisted `slug` column, not
579 // a fresh re-derivation that a rename would silently invalidate.
580 #[test]
581 fn instance_get_by_slug_resolves_via_the_persisted_slug_even_after_a_rename() {
582 let store = Store::open_in_memory().unwrap();
583 let tmp = tempfile::tempdir().unwrap();
584 let def_store = Arc::new(DefinitionStore::open(tmp.path().join("definitions")).unwrap());
585 // The registry's own `name` is the CURRENT (post-rename) display
586 // name — deliberately unrelated to `slug`, which was fixed at
587 // creation and never changes.
588 def_store
589 .upsert(&DefinitionRecord {
590 schema_version: DEF_MAX_SUPPORTED_SCHEMA,
591 data: DefinitionRecordV1 {
592 id: "def-renamed".to_string(),
593 slug: "agenty".to_string(),
594 name: "Agent Y Renamed".to_string(),
595 provider: "claude".to_string(),
596 updated_at: 42,
597 ..Default::default()
598 },
599 })
600 .unwrap();
601 store.set_def_registry(def_store);
602
603 let mut inst = instance("inst-renamed", "def-renamed");
604 inst.instance_name = "Agent Y Renamed".to_string();
605 store.instance_create(&inst).unwrap();
606
607 // derive_slug("Agent Y Renamed") would be "agent-y-renamed" — NOT
608 // "agenty". Only a lookup against the real persisted slug column
609 // resolves this; a re-derivation from the current name would miss
610 // it, reproducing the exact bug this test guards against.
611 let found = store.instance_get_by_slug("agenty").unwrap();
612 assert!(found.is_some(), "must resolve via the persisted slug, not a re-derivation of the current name");
613 assert_eq!(found.unwrap().instance_name, "Agent Y Renamed");
614 }
615
616 // reagentx P1 on PR #2428 (round 3): a single query matching
617 // `(instance_name = ?1 OR slug = ?1)` let a coincidental cross-
618 // namespace collision (one agent's literal `instance_name` equaling a
619 // DIFFERENT agent's `slug`) match both rows simultaneously, silently
620 // disambiguated by recency — meaning an App-API self-lookup call could
621 // return an unrelated agent's memory, accounts or bundle. This test builds
622 // exactly that collision (agent A's `instance_name` == agent B's
623 // `slug` == "shared-name") and proves `instance_get_by_slug` stays
624 // within its own namespace: it finds ONLY the slug match (B), never
625 // A's row (its literal-name counterpart is gone — see below).
626 #[test]
627 fn instance_get_by_name_and_by_slug_never_cross_the_others_namespace() {
628 let store = Store::open_in_memory().unwrap();
629 let tmp = tempfile::tempdir().unwrap();
630 let def_store = Arc::new(DefinitionStore::open(tmp.path().join("definitions")).unwrap());
631
632 // Agent A: literal display name is exactly "shared-name"; its own
633 // slug is unrelated ("agent-a-slug").
634 def_store
635 .upsert(&DefinitionRecord {
636 schema_version: DEF_MAX_SUPPORTED_SCHEMA,
637 data: DefinitionRecordV1 {
638 id: "def-a".to_string(),
639 slug: "agent-a-slug".to_string(),
640 name: "shared-name".to_string(),
641 provider: "claude".to_string(),
642 updated_at: 1,
643 ..Default::default()
644 },
645 })
646 .unwrap();
647 // Agent B: slug is exactly "shared-name" (e.g. a rename left its
648 // slug pointing at a string that collides with A's literal name);
649 // its own display name is unrelated.
650 def_store
651 .upsert(&DefinitionRecord {
652 schema_version: DEF_MAX_SUPPORTED_SCHEMA,
653 data: DefinitionRecordV1 {
654 id: "def-b".to_string(),
655 slug: "shared-name".to_string(),
656 name: "Agent B Display".to_string(),
657 provider: "claude".to_string(),
658 updated_at: 2,
659 ..Default::default()
660 },
661 })
662 .unwrap();
663 store.set_def_registry(def_store);
664
665 let mut inst_a = instance("inst-a", "def-a");
666 inst_a.instance_name = "shared-name".to_string();
667 store.instance_create(&inst_a).unwrap();
668
669 let mut inst_b = instance("inst-b", "def-b");
670 inst_b.instance_name = "Agent B Display".to_string();
671 store.instance_create(&inst_b).unwrap();
672
673 // `instance_get_by_name` was deleted in consolidation Phase 3b (PR 2)
674 // — it had no production caller — so the slug side is the whole
675 // guarantee now: the slug lookup must never resolve to A's row just
676 // because A's literal instance_name equals B's slug.
677 let by_slug = store.instance_get_by_slug("shared-name").unwrap()
678 .expect("must find agent B by slug");
679 assert_eq!(by_slug.id, "def-b", "slug lookup must never resolve to A's row");
680 }
681
682 // The §4 safety net. `instance_create` used to bind `def.slug` verbatim,
683 // making it the one writer that could mint a duplicate — `agent_def_insert`
684 // has always suffix-resolved, and no UNIQUE constraint backs the column.
685 //
686 // Note this is a contract fix, not a fix for an observed fault: the launch
687 // flow names its agent and goes through `agent_def_insert`, so this branch
688 // is reached only by handing `instance_create` a seeded template id
689 // directly. A data check across 47 databases found 0 duplicate slugs and 18
690 // launches, none inheriting a template's slug (§2.5.2).
691 #[test]
692 fn two_launches_of_one_template_get_distinct_slugs() {
693 let store = Store::open_in_memory().unwrap();
694 let mut tmpl = test_agent_def("tmpl-1", "Shared Template", "claude", "agent", 1, "");
695 tmpl.slug = "shared-template".to_string();
696 tmpl.is_seeded = 1;
697 store.agent_def_insert_local_only(&mut tmpl, None).unwrap();
698
699 let mut first = instance("launch-a", "tmpl-1");
700 first.instance_name = "Launch A".to_string();
701 store.instance_create(&first).unwrap();
702 let mut second = instance("launch-b", "tmpl-1");
703 second.instance_name = "Launch B".to_string();
704 store.instance_create(&second).unwrap();
705
706 // Neither launch may leave a resolvable duplicate behind: whatever
707 // slugs they got, no slug may name two non-template rows.
708 let conn = store.conn.lock().unwrap();
709 let dupes: i64 = conn
710 .query_row(
711 "SELECT COUNT(*) FROM (SELECT slug FROM db_agents
712 WHERE is_template = 0 AND user_hidden = 0 AND slug <> ''
713 GROUP BY slug HAVING COUNT(*) > 1)",
714 [],
715 |r| r.get(0),
716 )
717 .unwrap();
718 assert_eq!(dupes, 0, "a template launch must not mint a duplicate slug");
719 }
720
721 // A slug does not identify an agent once two rows share one, so the honest
722 // answer is "unknown" — the same fail-closed rule
723 // `agent_registry_lookup::find_active_record_by_slug` adopted for the
724 // registry in #3480, here for `db_agents` (#3500).
725 //
726 // This test predates the §4 safety net above and used to build its
727 // duplicate by launching one template twice, on the reasoning that
728 // `instance_create` copied `def.slug` verbatim. That is no longer true —
729 // and was never true of the real launch flow either (§2.5.2) — so the
730 // duplicate is now forced deliberately. The state remains reachable in
731 // production: no UNIQUE constraint backs the column.
732 #[test]
733 fn instance_get_by_slug_fails_closed_when_two_rows_share_a_slug() {
734 let store = Store::open_in_memory().unwrap();
735
736 let mut tmpl = test_agent_def("tmpl-1", "Shared Template", "claude", "agent", 1, "");
737 tmpl.slug = "shared-template".to_string();
738 tmpl.is_seeded = 1;
739 store.agent_def_insert_local_only(&mut tmpl, None).unwrap();
740 assert_eq!(tmpl.slug, "shared-template", "fixture precondition");
741
742 let mut first = instance("launch-a", "tmpl-1");
743 first.instance_name = "Launch A".to_string();
744 store.instance_create(&first).unwrap();
745
746 let mut second = instance("launch-b", "tmpl-1");
747 second.instance_name = "Launch B".to_string();
748 store.instance_create(&second).unwrap();
749
750 // Both write paths suffix-resolve now (§4 safety net), so two launches
751 // no longer collide on their own — see
752 // `two_launches_of_one_template_get_distinct_slugs`. Force the duplicate
753 // this guard exists for.
754 //
755 // Done in two steps on purpose. Asserting only the final `None` cannot
756 // tell "refused an ambiguous slug" from "nothing matched that slug" —
757 // both are `None`, and after the safety net the second is what a naive
758 // fixture actually produces. Resolving ONE row first pins that the
759 // lookup is live and the fixture is real; the second row is then the
760 // only thing that changed.
761 store.test_force_slug("launch-a", "collide-me").unwrap();
762 let single = store.instance_get_by_slug("collide-me").unwrap();
763 assert_eq!(
764 single.map(|i| i.id).as_deref(),
765 Some("launch-a"),
766 "one row with the slug must resolve — otherwise the check below is vacuous"
767 );
768
769 store.test_force_slug("launch-b", "collide-me").unwrap();
770
771 // Before this guard, `ORDER BY updated_at DESC LIMIT 1` handed back
772 // whichever row was touched last — deterministically the same wrong
773 // agent every time — and `HistoryService::sessions_for_agent` then
774 // resolved one agent's conversation history into the other's request.
775 assert!(
776 store.instance_get_by_slug("collide-me").unwrap().is_none(),
777 "adding a second row with the same slug must flip resolve to refusal"
778 );
779 }
780
781 #[test]
782 fn instance_create_preserves_registry_updated_at_on_backfill() {
783 let store = Store::open_in_memory().unwrap();
784 let tmp = tempfile::tempdir().unwrap();
785 let def_store = Arc::new(DefinitionStore::open(tmp.path().join("definitions")).unwrap());
786 let record = global_user_agent("remote-2", "Remote2");
787 def_store.upsert(&record).unwrap();
788 store.set_def_registry(def_store);
789
790 // Call the backfill directly rather than through a full
791 // `instance_create`: "remote-2" is a user agent (is_seeded = 0), so
792 // `instance_create` immediately follows the backfill with its own
793 // launch-state fold, which legitimately bumps `updated_at` again —
794 // by design, every launch touch does (see `agent_def_list`'s doc
795 // comment). That second, later bump isn't what this test is
796 // pinning; the backfill INSERT preserving the registry's real
797 // `updated_at`, rather than resetting it to `created_at`, is.
798 store.agent_def_backfill_local_from_registry(&record).unwrap();
799
800 let local = store.agent_row_get("remote-2").unwrap().unwrap();
801 assert_eq!(
802 local.updated_at, 42,
803 "backfilled row must preserve the registry's real updated_at, not reset to created_at"
804 );
805 }
806
807 /// Pins the definition flip's actual point: `agent_def_list()` and
808 /// `agent_def_get()` now read the SAME table, so a row visible to one
809 /// is visible to the other. Before the flip these deliberately
810 /// disagreed (`agent_def_get` was scoped to `db_agent_definitions`
811 /// only) — that inconsistency meant an agent visible in "My Agents"
812 /// (`agent_def_list`) could 404 the moment something tried to open its
813 /// detail view (`agent_def_get`) if it existed only as a `db_agents`
814 /// row (a template launch). A row written directly into `db_agents`,
815 /// bypassing `agent_def_insert` entirely, now resolves through both.
816 #[test]
817 fn agent_def_list_and_agent_def_get_agree_on_the_same_row() {
818 let store = Store::open_in_memory().unwrap();
819
820 // A `db_agents` row with no `agent_def_insert` ever having run for
821 // it — stands in for a template-launch row, which never had one.
822 {
823 let conn = store.conn.lock().unwrap();
824 conn.execute(
825 "INSERT INTO db_agents (id, slug, name, provider, is_template, created_at, updated_at, is_seeded)
826 VALUES ('launch-only', 'launch-only', 'LaunchOnly', 'claude', 0, 1, 1, 0)",
827 [],
828 )
829 .unwrap();
830 }
831
832 let listed = store.agent_def_list().unwrap();
833 assert!(
834 listed.iter().any(|d| d.id == "launch-only"),
835 "agent_def_list() must read db_agents"
836 );
837 let got = store.agent_def_get("launch-only").unwrap();
838 assert!(
839 got.is_some(),
840 "agent_def_get() must resolve a row agent_def_list() already shows — no more disagreement between the two"
841 );
842 assert_eq!(got.unwrap().name, "LaunchOnly");
843 }
844}
845
846// P1/P2 fixes (Codex + ReAgent review on PR #2587):
847// - resolve_effective_vendor must respect model_vendor_base_url ("custom"),
848// not just the provider's bare default.
849#[cfg(test)]
850mod bundle_provisioning_store_separation_tests {
851 use super::*;
852
853 fn base_agent(id: &str, name: &str, provider: &str, model_vendor_base_url: &str) -> AgentDefinition {
854 super::test_agent_def(id, name, provider, "host", 0, model_vendor_base_url)
855 }
856
857 #[test]
858 fn resolve_effective_vendor_defaults_to_the_providers_first_supported_vendor() {
859 assert_eq!(Store::resolve_effective_vendor("claude", ""), "anthropic");
860 assert_eq!(Store::resolve_effective_vendor("codex", ""), "openai");
861 }
862
863 #[test]
864 fn resolve_effective_vendor_returns_custom_when_a_base_url_override_is_set() {
865 assert_eq!(
866 Store::resolve_effective_vendor("claude", "https://my-proxy.example.com"),
867 "custom",
868 "an agent with a vendor override must not claim the provider's default vendor"
869 );
870 }
871
872 #[test]
873 fn resolve_effective_vendor_ignores_a_whitespace_only_override() {
874 assert_eq!(Store::resolve_effective_vendor("claude", " "), "anthropic");
875 }
876
877 #[test]
878 fn resolve_effective_vendor_falls_back_to_the_provider_id_for_an_unknown_provider() {
879 assert_eq!(Store::resolve_effective_vendor("not-a-real-provider", ""), "not-a-real-provider");
880 }
881
882 // P1 regression tests (ReAgent review on PR #2587 round 4):
883 // db_bundles.name is UNIQUE but only AgentDefinition.slug is
884 // guaranteed unique, not the display name two agents can share — a
885 // naive "{name} — ABF" used to collide, silently leaving a
886 // runtime-provisioned agent unbound and unconditionally aborting
887 // m0021's entire backfill loop on the first collision.
888
889 /// A collision suffix keeps a slug a valid agent id: a 64-char slug plus
890 /// "-2" used to make a 66-char one that failed every registration
891 /// (REPORT_FORK_AGENT_ISOLATION_2026_10_12.md F4).
892 #[test]
893 fn a_collision_suffixed_slug_stays_within_64_chars() {
894 let store = Store::open_in_memory().unwrap();
895 let long = "a".repeat(64);
896 let mut first = test_agent_def("id-1", "First", "claude", "host", 1, "");
897 first.slug = long.clone();
898 store.agent_def_insert(&mut first).unwrap();
899 let mut second = test_agent_def("id-2", "Second", "claude", "host", 2, "");
900 second.slug = long.clone();
901 store.agent_def_insert(&mut second).unwrap();
902 assert_eq!(first.slug, long);
903 assert_ne!(second.slug, long);
904 assert!(agentmux_common::slug::is_agent_id(&second.slug), "{} is a valid id", second.slug);
905 assert!(second.slug.ends_with("-2"));
906 }
907
908 /// A bundle row with `name`, as a name collision needs.
909 fn named_bundle(store: &Store, name: &str) {
910 store
911 .bundle_upsert(&super::super::bundles::Bundle {
912 id: name.to_string(),
913 name: name.to_string(),
914 description: String::new(),
915 is_blank: false,
916 is_global: false,
917 provider: String::new(),
918 model: String::new(),
919 instructions: String::new(),
920 instructions_by_provider: "{}".to_string(),
921 context_files: "[]".to_string(),
922 mcp_servers: "[]".to_string(),
923 skills: "[]".to_string(),
924 sort_order: 0,
925 created_at: 0,
926 updated_at: 0,
927 is_system: false,
928 })
929 .unwrap();
930 }
931
932 #[test]
933 fn resolve_unique_bundle_name_returns_the_base_name_when_no_collision() {
934 let store = Store::open_in_memory().unwrap();
935 assert_eq!(store.resolve_unique_bundle_name("Agent One — ABF").unwrap(), "Agent One — ABF");
936 }
937
938 #[test]
939 fn resolve_unique_bundle_name_disambiguates_on_collision() {
940 let store = Store::open_in_memory().unwrap();
941 named_bundle(&store, "Same Name — ABF");
942
943 let unique = store.resolve_unique_bundle_name("Same Name — ABF").unwrap();
944 assert_eq!(unique, "Same Name — ABF (2)");
945 }
946
947 #[test]
948 fn resolve_unique_bundle_name_walks_past_multiple_collisions() {
949 let store = Store::open_in_memory().unwrap();
950 named_bundle(&store, "Dup — ABF");
951 // Directly seed the "(2)" slot too, so the resolver must walk to "(3)".
952 let taken = super::super::bundles::Bundle {
953 id: "taken-2".to_string(),
954 name: "Dup — ABF (2)".to_string(),
955 description: String::new(),
956 is_blank: false,
957 is_global: false,
958 provider: String::new(),
959 model: String::new(),
960 instructions: String::new(),
961 instructions_by_provider: "{}".to_string(),
962 context_files: "[]".to_string(),
963 mcp_servers: "[]".to_string(),
964 skills: "[]".to_string(),
965 sort_order: 0,
966 created_at: 0,
967 updated_at: 0,
968 is_system: false,
969 };
970 store.bundle_upsert(&taken).unwrap();
971
972 let unique = store.resolve_unique_bundle_name("Dup — ABF").unwrap();
973 assert_eq!(unique, "Dup — ABF (3)");
974 }
975
976 // resolve_effective_provider_id — consolidated shared implementation
977 // (was previously duplicated between agent_open.rs's spawn path and
978 // identity/resolver/inject.rs's layer-3 credential gate; the latter
979 // was found reading agent.provider directly during a follow-up
980 // scoping pass, the same class of bug agent_open.rs already had
981 // fixed for itself). These mirror agent_open.rs's own former
982 // `resolve_effective_provider_id_tests` module one-for-one, plus the
983 // store-separation case matching this file's other bundle-resolution
984 // tests.
985
986 // A bundle row from before the bundle stopped carrying a harness.
987 fn bundle_with_provider(store: &Store, id: &str, provider: &str) {
988 store
989 .bundle_upsert(&super::super::bundles::Bundle {
990 id: id.to_string(),
991 name: id.to_string(),
992 description: String::new(),
993 is_blank: false,
994 is_global: false,
995 provider: provider.to_string(),
996 model: String::new(),
997 instructions: String::new(),
998 instructions_by_provider: "{}".to_string(),
999 context_files: "[]".to_string(),
1000 mcp_servers: "[]".to_string(),
1001 skills: "[]".to_string(),
1002 sort_order: 0,
1003 created_at: 0,
1004 updated_at: 0,
1005 is_system: false,
1006 })
1007 .unwrap();
1008 }
1009
1010 #[test]
1011 fn resolve_effective_provider_id_is_the_agents_own_even_when_its_bundle_says_otherwise() {
1012 let store = Store::open_in_memory().unwrap();
1013 let mut agent = base_agent("a1", "Agent One", "codex", "");
1014 bundle_with_provider(&store, "b1", "claude");
1015 agent.memory_id = "b1".to_string();
1016 assert_eq!(store.resolve_effective_provider_id(&agent), "codex");
1017 }
1018
1019 #[test]
1020 fn resolve_effective_provider_id_reads_the_bundle_only_for_an_agent_with_no_provider() {
1021 let store = Store::open_in_memory().unwrap();
1022 let mut agent = base_agent("a1", "Agent One", "", "");
1023 bundle_with_provider(&store, "b1", "gemini");
1024 agent.memory_id = "b1".to_string();
1025 assert_eq!(store.resolve_effective_provider_id(&agent), "gemini");
1026 }
1027
1028 #[test]
1029 fn resolve_effective_provider_id_falls_back_to_agent_provider_when_unbound() {
1030 let store = Store::open_in_memory().unwrap();
1031 let agent = base_agent("a1", "Agent One", "claude", "");
1032 assert_eq!(store.resolve_effective_provider_id(&agent), "claude");
1033 }
1034
1035 #[test]
1036 fn resolve_effective_provider_id_falls_back_when_bundle_row_is_missing() {
1037 let store = Store::open_in_memory().unwrap();
1038 let mut agent = base_agent("a1", "Agent One", "claude", "");
1039 agent.memory_id = "no-such-bundle".to_string();
1040 assert_eq!(store.resolve_effective_provider_id(&agent), "claude");
1041 }
1042
1043 // The fallback reads the bundle through the store it's called on: a
1044 // caller that passes mstore instead of id_store gets nothing, not a
1045 // silently wrong answer.
1046 #[test]
1047 fn resolve_effective_provider_id_fallback_reads_only_the_store_it_is_called_on() {
1048 let id_store = Store::open_in_memory().unwrap();
1049 let mstore = Store::open_in_memory().unwrap();
1050 let mut agent = base_agent("a1", "Agent One", "", "");
1051 bundle_with_provider(&id_store, "b1", "codex");
1052 agent.memory_id = "b1".to_string();
1053 assert_eq!(id_store.resolve_effective_provider_id(&agent), "codex");
1054 assert_eq!(mstore.resolve_effective_provider_id(&agent), "");
1055 }
1056}
1057
1058#[cfg(test)]
1059mod fallback_id_tests {
1060 use super::*;
1061
1062 /// Byte-for-byte with `agent-slug.ts`'s `jsAsciiSlug`,
1063 /// `name.toLowerCase().replace(/[^a-z0-9-_]/g, "-")` (UTF-16 units).
1064 #[test]
1065 fn the_frontend_fallback_matches_javascript_utf16_semantics() {
1066 assert_eq!(frontend_fallback_id("Agent 🚀"), "agent---");
1067 assert_eq!(frontend_fallback_id("Agent (v2)"), "agent--v2-");
1068 assert_eq!(frontend_fallback_id("Café Bot"), "caf--bot");
1069 assert_eq!(agent_open_fallback_id("Café Bot"), "café-bot");
1070 }
1071}
1072
1073/// The only keys a remembered runtime may hold, and the longest value of each.
1074const LAST_RUNTIME_KEYS: &[(&str, usize)] = &[("permissionMode", 32), ("model", 128), ("effort", 32)];
1075
1076/// Validate and canonicalise a remembered runtime before it is stored:
1077/// `''` clears; otherwise a JSON object of non-empty strings under the known
1078/// keys only (`permissionMode`, `model`, `effort`), each bounded. Anything
1079/// else is rejected, so the column can only ever hold something the launch
1080/// path knows how to read.
1081pub fn normalize_last_runtime(raw: &str) -> Result<String, String> {
1082 if raw.trim().is_empty() {
1083 return Ok(String::new());
1084 }
1085 let value: serde_json::Value =
1086 serde_json::from_str(raw).map_err(|e| format!("last runtime is not JSON: {e}"))?;
1087 let obj = value.as_object().ok_or("last runtime must be a JSON object")?;
1088 let mut out = serde_json::Map::new();
1089 for (key, v) in obj {
1090 let Some(&(_, max)) = LAST_RUNTIME_KEYS.iter().find(|(k, _)| k == key) else {
1091 return Err(format!("unknown last-runtime key {key:?}"));
1092 };
1093 let s = v.as_str().ok_or_else(|| format!("{key} must be a string"))?;
1094 if s.is_empty() || s.len() > max || s.chars().any(char::is_control) {
1095 return Err(format!("{key} is empty, too long or has control characters"));
1096 }
1097 out.insert(key.clone(), serde_json::Value::String(s.to_owned()));
1098 }
1099 if out.is_empty() {
1100 return Ok(String::new());
1101 }
1102 Ok(serde_json::Value::Object(out).to_string())
1103}