Skip to main content

agentmux_srv_core/backend/storage/
agent_tokens.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Per-agent local identity token, keyed by the agent's UID (`db_agents.id`).
5//!
6//! Identity M1 of `docs/specs/SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md`
7//! (§6, §9.1). See `db_agent_tokens` in migrations.rs (OBJECT_SCHEMA_VERSION
8//! v37).
9//!
10//! **What it is.** A secret the server generates for one agent and hands to
11//! that agent's process environment at spawn (`AGENTMUX_AGENT_TOKEN`, set by
12//! `build_persistent_spawn_env`). Only the server and the agent it spawned
13//! ever hold the value, which is what will let a later phase (M4) map
14//! token → UID on a request and treat *that* as the caller's identity,
15//! instead of trusting an `agent_id` the request body asserts. Spec §2
16//! rule 2: identity is proven, not asserted.
17//!
18//! **What it is not.** Not the cloud Cognito M2M credential in
19//! `muxbus/agent_credentials.rs` — that one needs a prior human login and
20//! falls back to a shared token by design, both of which disqualify it
21//! (spec §0.3). This is minted locally, with no network and no fallback.
22//!
23//! **Lifetime.** Long-lived for the agent's lifetime and revoked when the
24//! agent is deleted (`purge_agent_dependents`), replaced only on request
25//! (`agent_token_rotate`), never renewed on a timer:
26//! spec §6.3 — expiry mid-task turns a healthy agent silent, and renewal is a
27//! liveness dependency on the very path being secured. Persisted here, in
28//! the server's own store, so an srv restart does not strand every running
29//! agent with a token nothing can verify (same section). This is the
30//! server persisting its own secret where only the server reads it — not a
31//! name-keyed, agent-readable file in shared space, which §6.3 rules out.
32//!
33//! **Keyed by UID, not name.** `db_agent_jekt_keys` and the registry entry
34//! files are keyed by display name, so two agents sharing a name share one
35//! credential (spec §6.3). This table cannot have that defect: `db_agents.id`
36//! is a `PRIMARY KEY`, and every non-template row is a UUID.
37//!
38//! **Read since M4a** through [`TokenIndex`]: a request carrying
39//! `X-Agent-Token` is attributed to the UID the token was minted for
40//! (spec §6.5.3). Attribution only — an unknown token is treated as absent,
41//! never refused.
42
43use std::collections::HashMap;
44use std::sync::{Arc, RwLock};
45
46use rusqlite::params;
47
48use super::agent_lan_keys::random_seed_bytes;
49use super::error::StoreError;
50use super::store::Store;
51
52use agentmux_common::time::now_secs;
53
54/// 32 bytes of CSPRNG randomness from `random_seed_bytes`, hex-encoded
55/// (64 chars); hex rather than base64 so the value is safe in any
56/// environment-variable or shell context without quoting.
57fn random_token() -> String {
58    hex::encode(random_seed_bytes())
59}
60
61/// token → UID, in memory, so attributing a request never reads the store
62/// (spec §10.1). Attached to the channel's object store only
63/// ([`Store::attach_token_index`]) and kept in step with `db_agent_tokens`
64/// by the statements that change it — mint (`agent_token_ensure`), replace
65/// (`agent_token_rotate`) and revoke (`purge_agent_dependents`) — each under the store's connection
66/// lock, so the index never disagrees with a committed row (spec §6.5.3:
67/// purge is a sequence of autocommit statements, not a transaction, so
68/// the index follows the token statement itself, not the purge's result).
69#[derive(Default)]
70pub struct TokenIndex {
71    maps: RwLock<TokenMaps>,
72}
73
74#[derive(Default)]
75struct TokenMaps {
76    uid_by_token: HashMap<String, String>,
77    token_by_uid: HashMap<String, String>,
78}
79
80impl TokenIndex {
81    /// The UID `token` was minted for, if any.
82    pub fn uid_for(&self, token: &str) -> Option<String> {
83        let maps = self.maps.read().unwrap_or_else(|e| e.into_inner());
84        maps.uid_by_token.get(token).cloned()
85    }
86
87    fn insert(&self, uid: &str, token: &str) {
88        // A token is never written into a transcript.
89        crate::backend::transcript::withhold::register(token);
90        let mut maps = self.maps.write().unwrap_or_else(|e| e.into_inner());
91        if let Some(old) = maps.token_by_uid.insert(uid.to_string(), token.to_string()) {
92            if old != token {
93                maps.uid_by_token.remove(&old);
94            }
95        }
96        maps.uid_by_token.insert(token.to_string(), uid.to_string());
97    }
98
99    /// Drop `uid`'s token. Called by `purge_agent_dependents` right after
100    /// the row's delete, under the same connection lock.
101    pub(super) fn forget_uid(&self, uid: &str) {
102        let mut maps = self.maps.write().unwrap_or_else(|e| e.into_inner());
103        if let Some(token) = maps.token_by_uid.remove(uid) {
104            maps.uid_by_token.remove(&token);
105        }
106    }
107
108    #[cfg(any(test, feature = "test-support"))]
109    pub fn len(&self) -> usize {
110        self.maps
111            .read()
112            .unwrap_or_else(|e| e.into_inner())
113            .uid_by_token
114            .len()
115    }
116}
117
118impl Store {
119    /// Build this store's [`TokenIndex`] from `db_agent_tokens` and attach
120    /// it, so mint and revoke keep it current from here on. Called once, on
121    /// the channel's object store at boot — never on the shared, identity or
122    /// migration-time stores, which must not grow an index of their own.
123    pub fn attach_token_index(&self) -> Result<Arc<TokenIndex>, StoreError> {
124        let conn = self.conn.lock().unwrap();
125        let index = Arc::new(TokenIndex::default());
126        {
127            let mut stmt = conn.prepare("SELECT agent_id, token FROM db_agent_tokens")?;
128            let rows =
129                stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
130            for row in rows {
131                let (uid, token) = row?;
132                index.insert(&uid, &token);
133            }
134        }
135        *self.token_index.lock().unwrap_or_else(|e| e.into_inner()) = Some(index.clone());
136        Ok(index)
137    }
138
139    /// The attached [`TokenIndex`], if this store has one.
140    pub fn token_index(&self) -> Option<Arc<TokenIndex>> {
141        self.token_index
142            .lock()
143            .unwrap_or_else(|e| e.into_inner())
144            .clone()
145    }
146
147    /// This agent's token if one has been minted, without minting.
148    ///
149    /// The verification read (M4) is the production caller; until it lands
150    /// only tests read this, hence the `dead_code` allowance outside test
151    /// builds. Deletion does not go through here — `purge_agent_dependents`
152    /// covers `db_agent_tokens` directly.
153    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
154    pub fn agent_token_load(&self, uid: &str) -> Result<Option<String>, StoreError> {
155        let conn = self.conn.lock().unwrap();
156        let mut stmt = conn.prepare("SELECT token FROM db_agent_tokens WHERE agent_id = ?1")?;
157        match stmt.query_row(params![uid], |row| row.get::<_, String>(0)) {
158            Ok(v) => Ok(Some(v)),
159            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
160            Err(e) => Err(e.into()),
161        }
162    }
163
164    /// This agent's token, minting and persisting one on first use.
165    ///
166    /// Race-safe under concurrent first use, the same way
167    /// `agent_jekt_key_ensure` is: the insert is `OR IGNORE` and the row is
168    /// re-read regardless of whether this call's insert won, so two spawns
169    /// of a never-before-seen agent agree on one token instead of each
170    /// holding a different one. An empty `uid` is refused rather than given
171    /// a token: a token keyed by `""` would be shared by every caller that
172    /// failed to resolve an identity, which is the shared-credential defect
173    /// this table exists to remove.
174    pub fn agent_token_ensure(&self, uid: &str) -> Result<String, StoreError> {
175        if uid.trim().is_empty() {
176            return Err(StoreError::Other(
177                "agent_token_ensure: refusing to mint a token for an empty uid".to_string(),
178            ));
179        }
180        let conn = self.conn.lock().unwrap();
181        conn.execute(
182            "INSERT OR IGNORE INTO db_agent_tokens (agent_id, token, created_at) VALUES (?1, ?2, ?3)",
183            params![uid, random_token(), now_secs()],
184        )?;
185        let mut stmt = conn.prepare("SELECT token FROM db_agent_tokens WHERE agent_id = ?1")?;
186        let token: String = stmt.query_row(params![uid], |row| row.get(0))?;
187        crate::backend::transcript::withhold::register(&token);
188        // Still under the connection lock: the index follows the row.
189        if let Some(index) = self.token_index() {
190            index.insert(uid, &token);
191        }
192        Ok(token)
193    }
194
195    /// Replace this agent's token with a new one: the old value stops working at once, because the row and
196    /// the index change together under the connection lock, and the agent holds exactly one token afterwards.
197    /// An agent with no token yet is given one. The value is not returned: the agent reads it from its next
198    /// spawn environment (`agent_token_ensure`), and nothing else needs it. An empty `uid` is refused, as in
199    /// `agent_token_ensure`.
200    pub fn agent_token_rotate(&self, uid: &str) -> Result<(), StoreError> {
201        if uid.trim().is_empty() {
202            return Err(StoreError::Other("agent_token_rotate: refusing to rotate the token of an empty uid".to_string()));
203        }
204        let token = random_token();
205        let conn = self.conn.lock().unwrap();
206        conn.execute(
207            "INSERT OR REPLACE INTO db_agent_tokens (agent_id, token, created_at) VALUES (?1, ?2, ?3)",
208            params![uid, token, now_secs()],
209        )?;
210        // The new value is withheld from transcripts; the old one stays withheld, so a line that already
211        // holds it is still redacted when read.
212        crate::backend::transcript::withhold::register(&token);
213        if let Some(index) = self.token_index() {
214            index.insert(uid, &token);
215        }
216        Ok(())
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223
224    fn object_store() -> Store {
225        Store::open_in_memory().unwrap()
226    }
227
228    #[test]
229    fn load_is_none_until_minted_then_ensure_is_stable() {
230        let store = object_store();
231        assert_eq!(store.agent_token_load("uid-a").unwrap(), None);
232
233        let first = store.agent_token_ensure("uid-a").unwrap();
234        assert_eq!(first.len(), 64, "32 random bytes, hex-encoded");
235        assert!(first.chars().all(|c| c.is_ascii_hexdigit()));
236
237        // Second ensure returns the persisted value, not a fresh mint.
238        assert_eq!(store.agent_token_ensure("uid-a").unwrap(), first);
239        assert_eq!(
240            store.agent_token_load("uid-a").unwrap().as_deref(),
241            Some(first.as_str())
242        );
243    }
244
245    /// The property M4 will rely on: two agents never share a token, even
246    /// when everything a human can see about them (their names) collides.
247    /// The table is keyed by UID, so the names never enter into it.
248    #[test]
249    fn a_minted_or_loaded_token_is_withheld_from_transcripts() {
250        use crate::backend::transcript::withhold;
251        let store = object_store();
252        let minted = store.agent_token_ensure("uid-withhold-a").unwrap();
253        assert!(withhold::text(&format!("TOKEN={minted}")).contains(withhold::MARK), "a minted token");
254        // A token loaded at boot (a row a previous run minted) is registered when the index is built.
255        let conn = store.conn.lock().unwrap();
256        conn.execute(
257            "INSERT INTO db_agent_tokens (agent_id, token, created_at) VALUES ('uid-withhold-b', 'loaded-at-boot-0123456789abcdef', 1)",
258            [],
259        )
260        .unwrap();
261        drop(conn);
262        store.attach_token_index().unwrap();
263        assert_eq!(withhold::text("TOKEN=loaded-at-boot-0123456789abcdef"), format!("TOKEN={}", withhold::MARK));
264    }
265
266    #[test]
267    fn distinct_uids_get_distinct_tokens() {
268        let store = object_store();
269        let a = store.agent_token_ensure("4f3c-agenty").unwrap();
270        let b = store.agent_token_ensure("9b2e-agenty").unwrap();
271        assert_ne!(a, b);
272    }
273
274    #[test]
275    fn empty_uid_is_refused_not_given_a_shared_token() {
276        let store = object_store();
277        assert!(store.agent_token_ensure("").is_err());
278        assert!(store.agent_token_ensure("   ").is_err());
279        assert_eq!(store.agent_token_load("").unwrap(), None);
280    }
281
282    // ---- identity M4a: the index follows the token rows ----------------
283
284    /// Mint puts the token in the index, and attaching to a store that
285    /// already holds tokens loads them — an srv restart attributes a running
286    /// agent's requests without it respawning.
287    #[test]
288    fn the_index_follows_mint_and_is_rebuilt_on_attach() {
289        let store = object_store();
290        let before = store.agent_token_ensure("uid-a").unwrap();
291        let index = store.attach_token_index().unwrap();
292        assert_eq!(
293            index.uid_for(&before).as_deref(),
294            Some("uid-a"),
295            "loaded on attach"
296        );
297        let minted = store.agent_token_ensure("uid-b").unwrap();
298        assert_eq!(
299            index.uid_for(&minted).as_deref(),
300            Some("uid-b"),
301            "added on mint"
302        );
303        assert_eq!(index.len(), 2);
304    }
305
306    /// A rotate replaces the row and the index together: the old value is refused at once, the new one
307    /// works, the agent holds one token, and another agent's token is untouched.
308    #[test]
309    fn rotate_replaces_the_token_and_the_old_value_stops_working() {
310        use crate::backend::transcript::withhold;
311        let store = object_store();
312        let index = store.attach_token_index().unwrap();
313        let old = store.agent_token_ensure("uid-a").unwrap();
314        let other = store.agent_token_ensure("uid-b").unwrap();
315
316        store.agent_token_rotate("uid-a").unwrap();
317
318        let new = store.agent_token_load("uid-a").unwrap().unwrap();
319        assert_ne!(new, old);
320        assert_eq!(new.len(), 64);
321        assert_eq!(index.uid_for(&old), None, "the old value is refused");
322        assert_eq!(index.uid_for(&new).as_deref(), Some("uid-a"), "the new value works");
323        assert_eq!(index.uid_for(&other).as_deref(), Some("uid-b"), "another agent's token is untouched");
324        assert_eq!(index.len(), 2, "one token per agent");
325        assert_eq!(store.agent_token_ensure("uid-a").unwrap(), new, "a spawn after the rotate reads the new value");
326        assert!(withhold::text(&format!("T={new}")).contains(withhold::MARK), "the new value is withheld");
327        assert!(withhold::text(&format!("T={old}")).contains(withhold::MARK), "the old value stays withheld");
328    }
329
330    /// Each rotate leaves one token; a second rotate retires the first replacement too; an agent with no
331    /// token is given one; an empty uid is refused.
332    #[test]
333    fn rotate_twice_keeps_one_token_and_a_new_agent_is_given_one() {
334        let store = object_store();
335        let index = store.attach_token_index().unwrap();
336        store.agent_token_rotate("uid-new").unwrap();
337        let first = store.agent_token_load("uid-new").unwrap().unwrap();
338        assert_eq!(index.uid_for(&first).as_deref(), Some("uid-new"));
339
340        store.agent_token_rotate("uid-new").unwrap();
341        let second = store.agent_token_load("uid-new").unwrap().unwrap();
342        assert_ne!(first, second);
343        assert_eq!(index.uid_for(&first), None);
344        assert_eq!(index.uid_for(&second).as_deref(), Some("uid-new"));
345        assert_eq!(index.len(), 1);
346
347        assert!(store.agent_token_rotate("").is_err());
348        assert!(store.agent_token_rotate("  ").is_err());
349    }
350
351    /// The rows a restart reloads give the same answer: the replaced value is the one that is loaded.
352    #[test]
353    fn a_rotated_token_survives_an_index_rebuild() {
354        let store = object_store();
355        let old = store.agent_token_ensure("uid-a").unwrap();
356        store.agent_token_rotate("uid-a").unwrap();
357        let new = store.agent_token_load("uid-a").unwrap().unwrap();
358        let rebuilt = store.attach_token_index().unwrap();
359        assert_eq!(rebuilt.uid_for(&old), None);
360        assert_eq!(rebuilt.uid_for(&new).as_deref(), Some("uid-a"));
361        assert_eq!(rebuilt.len(), 1);
362    }
363
364    /// Purge revokes the token from the index as well as the table.
365    #[test]
366    fn purge_removes_the_token_from_the_index() {
367        let store = object_store();
368        let index = store.attach_token_index().unwrap();
369        let token = store.agent_token_ensure("uid-a").unwrap();
370        {
371            let conn = store.conn.lock().unwrap();
372            super::super::agents::purge_agent_dependents_for_tests(
373                &conn,
374                "uid-a",
375                store.token_index().as_deref(),
376            )
377            .unwrap();
378        }
379        assert_eq!(index.uid_for(&token), None);
380        assert_eq!(store.agent_token_load("uid-a").unwrap(), None);
381    }
382
383    /// Through the real deletion paths: deleting an agent revokes its token
384    /// from the index and tombstones every name its legacy signing keys may
385    /// sit under (spec §6.5.4) — for both names one deletion arrives by.
386    #[test]
387    fn deleting_an_agent_revokes_its_token_and_tombstones_its_names() {
388        use crate::backend::storage::agents::test_agent_def;
389        for via_instance_delete in [false, true] {
390            let store = object_store();
391            let index = store.attach_token_index().unwrap();
392            let mut def = test_agent_def("uid-agenty", "AgentY", "claude", "agent", 1, "");
393            def.slug = "agenty-2".to_string();
394            store.agent_def_insert(&mut def).unwrap();
395            let token = store.agent_token_ensure("uid-agenty").unwrap();
396            assert_eq!(index.uid_for(&token).as_deref(), Some("uid-agenty"));
397
398            let deleted = if via_instance_delete {
399                store.instance_delete("uid-agenty").unwrap()
400            } else {
401                store.agent_def_delete("uid-agenty").unwrap()
402            };
403            assert!(deleted, "instance_delete={via_instance_delete}");
404            assert_eq!(
405                index.uid_for(&token),
406                None,
407                "instance_delete={via_instance_delete}"
408            );
409            let tombstones = {
410                let conn = store.conn.lock().unwrap();
411                super::super::agents::key_tombstones_for_tests(&conn)
412            };
413            let names: Vec<&str> = tombstones.iter().map(|(n, _)| n.as_str()).collect();
414            assert!(
415                names.contains(&"agenty") && names.contains(&"agenty-2"),
416                "{tombstones:?}"
417            );
418            assert!(tombstones.iter().all(|(_, uid)| uid == "uid-agenty"));
419        }
420    }
421
422    /// The colliding-names fixture: deleting the second "AgentY" (slug
423    /// agenty-2) must not tombstone `agenty`, the first one's slug — its
424    /// signing keys sit under that name, and a tombstone would cost the
425    /// rightful, live owner its key at M4d (adversarial review of #3571).
426    #[test]
427    fn deleting_one_of_two_same_named_agents_spares_the_others_slug() {
428        use crate::backend::storage::agents::test_agent_def;
429        let store = object_store();
430        for (id, name, slug) in [
431            ("uid-first", "AgentY", "agenty"),
432            ("uid-second", "AGENTY", "agenty-2"),
433        ] {
434            let mut def = test_agent_def(id, name, "claude", "agent", 1, "");
435            def.slug = slug.to_string();
436            store.agent_def_insert(&mut def).unwrap();
437        }
438        assert!(store.agent_def_delete("uid-second").unwrap());
439        let tombstones = {
440            let conn = store.conn.lock().unwrap();
441            super::super::agents::key_tombstones_for_tests(&conn)
442        };
443        assert_eq!(
444            tombstones,
445            vec![("agenty-2".to_string(), "uid-second".to_string())],
446            "only the deleted agent's own slug"
447        );
448    }
449
450    /// Identity M4a-3 (spec §6.5.4): deleting an agent deletes the signing
451    /// keys filed under its slug, so a later agent taking the name gets
452    /// fresh ones instead of the dead agent's — through both deletion paths.
453    /// The colliding-names fixture: deleting the second "AgentY" (agenty-2)
454    /// leaves the first one's `agenty` keys alone.
455    #[test]
456    fn deleting_an_agent_deletes_the_keys_filed_under_its_slug() {
457        use crate::backend::storage::agents::test_agent_def;
458        for via_instance_delete in [false, true] {
459            let store = object_store();
460            for (id, name, slug) in [
461                ("uid-first", "AgentY", "agenty"),
462                ("uid-second", "AGENTY", "agenty-2"),
463            ] {
464                let mut def = test_agent_def(id, name, "claude", "agent", 1, "");
465                def.slug = slug.to_string();
466                store.agent_def_insert(&mut def).unwrap();
467            }
468            for name in ["agenty", "agenty-2"] {
469                store.agent_jekt_key_ensure(name).unwrap();
470                store.agent_lan_key_ensure(name).unwrap();
471                store.agent_wan_key_ensure(name).unwrap();
472            }
473            let old_lan = store.agent_lan_key_load("agenty-2").unwrap().unwrap();
474
475            let deleted = if via_instance_delete {
476                store.instance_delete("uid-second").unwrap()
477            } else {
478                store.agent_def_delete("uid-second").unwrap()
479            };
480            assert!(deleted, "instance_delete={via_instance_delete}");
481            assert!(store.agent_jekt_key_load("agenty-2").unwrap().is_none());
482            assert!(store.agent_lan_key_load("agenty-2").unwrap().is_none());
483            assert!(store.agent_wan_key_load("agenty-2").unwrap().is_none());
484            assert!(
485                store.agent_jekt_key_load("agenty").unwrap().is_some(),
486                "the live agent's keys stay"
487            );
488            assert!(store.agent_lan_key_load("agenty").unwrap().is_some());
489            assert!(store.agent_wan_key_load("agenty").unwrap().is_some());
490
491            // A reuser of the name is minted a fresh keypair, not handed the
492            // dead agent's.
493            let reused = store.agent_lan_key_ensure("agenty-2").unwrap();
494            assert_ne!(
495                reused.public_key, old_lan.public_key,
496                "instance_delete={via_instance_delete}"
497            );
498        }
499    }
500
501    /// W3-S (`SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md` §2.2): agent WAN keys
502    /// live in the channel-wide `wan.db` now, and the same purge reaches it
503    /// through both deletion paths — the name's reuser gets a new key, and
504    /// the colliding live agent keeps its own.
505    #[test]
506    fn deleting_an_agent_deletes_its_wan_key_from_the_channel_wide_store() {
507        use crate::backend::storage::agents::test_agent_def;
508        for via_instance_delete in [false, true] {
509            let store = object_store();
510            let (_wan_dir, wan) = crate::backend::storage::wan_identity::attach_temp_wan_identity(&store);
511            for (id, name, slug) in [
512                ("uid-first", "AgentY", "agenty"),
513                ("uid-second", "AGENTY", "agenty-2"),
514            ] {
515                let mut def = test_agent_def(id, name, "claude", "agent", 1, "");
516                def.slug = slug.to_string();
517                store.agent_def_insert(&mut def).unwrap();
518            }
519            for name in ["agenty", "agenty-2"] {
520                wan.agent_key_ensure(name, None).unwrap();
521            }
522            let old = wan.agent_key_load("agenty-2").unwrap().unwrap();
523
524            let deleted = if via_instance_delete {
525                store.instance_delete("uid-second").unwrap()
526            } else {
527                store.agent_def_delete("uid-second").unwrap()
528            };
529            assert!(deleted, "instance_delete={via_instance_delete}");
530            assert!(wan.agent_key_load("agenty-2").unwrap().is_none(), "instance_delete={via_instance_delete}");
531            assert!(wan.agent_key_load("agenty").unwrap().is_some(), "the live agent's WAN key stays");
532            assert_ne!(wan.agent_key_ensure("agenty-2", None).unwrap().public_key, old.public_key);
533        }
534    }
535
536    /// Identity M4d-1 (spec §6.5.10): deleting an agent also deletes keys
537    /// filed under the other names it answered to — display name,
538    /// `instance_name`, and `agent.open`'s fallback id — except a name another
539    /// agent signs under (here: another row holds `zed-bot` as its slug).
540    #[test]
541    fn deleting_an_agent_deletes_the_keys_under_all_its_names() {
542        use crate::backend::storage::agents::test_agent_def;
543        let store = object_store();
544        let mut zed = test_agent_def("uid-zed", "Zed Bot", "claude", "agent", 1, "");
545        zed.slug = "zb".to_string();
546        store.agent_def_insert(&mut zed).unwrap();
547        store
548            .conn()
549            .lock()
550            .unwrap()
551            .execute("UPDATE db_agents SET instance_name = 'Zeddy' WHERE id = 'uid-zed'", [])
552            .unwrap();
553        let mut other = test_agent_def("uid-other", "Other", "claude", "agent", 1, "");
554        other.slug = "zed-bot".to_string();
555        store.agent_def_insert(&mut other).unwrap();
556        for name in ["zb", "zed bot", "zeddy", "zed-bot"] {
557            store.agent_lan_key_ensure(name).unwrap();
558            store.agent_jekt_key_ensure(name).unwrap();
559        }
560
561        assert!(store.agent_def_delete("uid-zed").unwrap());
562        for gone in ["zb", "zed bot", "zeddy"] {
563            assert!(store.agent_lan_key_load(gone).unwrap().is_none(), "{gone}");
564            assert!(store.agent_jekt_key_load(gone).unwrap().is_none(), "{gone}");
565        }
566        assert!(
567            store.agent_lan_key_load("zed-bot").unwrap().is_some(),
568            "the fallback id another agent holds as its slug stays"
569        );
570        assert!(store.agent_jekt_key_load("zed-bot").unwrap().is_some());
571
572        // Two template-created agents named "Agent (v2)" (slugs agent-v2,
573        // agent-v2-2) both sign their first session as the fallback id
574        // `agent--v2-`: deleting one leaves it for the other (review of #3633).
575        for (id, slug) in [("uid-v2a", "agent-v2"), ("uid-v2b", "agent-v2-2")] {
576            let mut def = test_agent_def(id, "Agent (v2)", "claude", "agent", 1, "");
577            def.slug = slug.to_string();
578            store.agent_def_insert(&mut def).unwrap();
579        }
580        store.agent_lan_key_ensure("agent--v2-").unwrap();
581        assert!(store.agent_def_delete("uid-v2a").unwrap());
582        assert!(
583            store.agent_lan_key_load("agent--v2-").unwrap().is_some(),
584            "the same-named sibling still signs under it"
585        );
586
587        // Renamed after its first launch: the launch name, kept as
588        // `instance_name`, keyed its first session's fallback — purged too
589        // (Codex P1 on #3633).
590        let mut renamed = test_agent_def("uid-renamed", "New Name", "claude", "agent", 1, "");
591        renamed.slug = "new-name".to_string();
592        store.agent_def_insert(&mut renamed).unwrap();
593        store
594            .conn()
595            .lock()
596            .unwrap()
597            .execute("UPDATE db_agents SET instance_name = 'Old (launch)' WHERE id = 'uid-renamed'", [])
598            .unwrap();
599        store.agent_lan_key_ensure("old--launch-").unwrap();
600        assert!(store.agent_def_delete("uid-renamed").unwrap());
601        assert!(store.agent_lan_key_load("old--launch-").unwrap().is_none());
602
603        // The picker's rename overwrites both the display name and
604        // instance_name; the old name is remembered, so its fallback key
605        // is still purged at delete (Codex P1 on #3633).
606        let mut v2 = test_agent_def("uid-v2-renamed", "Agent (v2)", "claude", "agent", 1, "");
607        v2.slug = "agent-v2-r".to_string();
608        store.agent_def_insert(&mut v2).unwrap();
609        store
610            .conn()
611            .lock()
612            .unwrap()
613            .execute("UPDATE db_agents SET instance_name = 'Agent (v2)' WHERE id = 'uid-v2-renamed'", [])
614            .unwrap();
615        // The earlier "Agent (v2)" pair is gone, so nobody else signs as
616        // agent--v2- now except this row's first session.
617        assert!(store.agent_def_delete("uid-v2b").unwrap());
618        store.agent_lan_key_ensure("agent--v2-").unwrap();
619        v2.name = "New Name".to_string();
620        store.agent_def_update(&mut v2).unwrap();
621        assert!(store.instance_rename("uid-v2-renamed", "New Name").unwrap());
622        assert!(store.agent_def_delete("uid-v2-renamed").unwrap());
623        assert!(
624            store.agent_lan_key_load("agent--v2-").unwrap().is_none(),
625            "the pre-rename fallback key is purged"
626        );
627
628        // Any write path is recorded — a raw UPDATE stands in for the
629        // continuation fold — and never evicted, however many renames
630        // (Codex P1/P2 on #3633).
631        let mut many = test_agent_def("uid-many", "First Name", "claude", "agent", 1, "");
632        many.slug = "many".to_string();
633        store.agent_def_insert(&mut many).unwrap();
634        store.agent_lan_key_ensure("first-name").unwrap();
635        for i in 0..25 {
636            store
637                .conn()
638                .lock()
639                .unwrap()
640                .execute(
641                    "UPDATE db_agents SET name = ?1, instance_name = ?1 WHERE id = 'uid-many'",
642                    rusqlite::params![format!("Name {i}")],
643                )
644                .unwrap();
645        }
646        assert!(store.agent_def_delete("uid-many").unwrap());
647        assert!(store.agent_lan_key_load("first-name").unwrap().is_none(), "the first name, 25 renames ago");
648    }
649
650    /// Slug ownership is folded as the key tables fold (`to_lowercase`), not
651    /// with SQLite's ASCII-only `lower()`: agents with slugs `Ä` and `ä`
652    /// share the key filed under `ä`, so deleting one must leave it for the
653    /// other (Codex P2 on #3575).
654    #[test]
655    fn a_non_ascii_slug_held_by_another_agent_keeps_its_keys() {
656        let store = store_with_slugs(&[("uid-upper", "Ä", false), ("uid-lower", "ä", false)]);
657        store.agent_lan_key_ensure("ä").unwrap();
658        assert!(store.agent_def_delete("uid-lower").unwrap());
659        assert!(
660            store.agent_lan_key_load("ä").unwrap().is_some(),
661            "the live `Ä` agent's key stays"
662        );
663    }
664
665    /// The guard, through the real deletion path: a slug another row holds —
666    /// an ordinary row carrying the same slug (the old consolidation left
667    /// such duplicates), or a template, whose `agent.open` launches sign
668    /// under it — keeps its keys (adversarial review of #3575).
669    #[test]
670    fn a_slug_another_row_or_a_template_holds_keeps_its_keys() {
671        for other_is_template in [false, true] {
672            let store = store_with_slugs(&[
673                ("uid-dup-a", "claude", other_is_template),
674                ("uid-dup-b", "claude", false),
675            ]);
676            store.agent_jekt_key_ensure("claude").unwrap();
677            store.agent_lan_key_ensure("claude").unwrap();
678            assert!(store.agent_def_delete("uid-dup-b").unwrap());
679            assert!(
680                store.agent_lan_key_load("claude").unwrap().is_some()
681                    && store.agent_jekt_key_load("claude").unwrap().is_some(),
682                "template={other_is_template}"
683            );
684        }
685    }
686
687    /// Rows with exactly these slugs — forced, since insertion would
688    /// suffix a collision away.
689    fn store_with_slugs(rows: &[(&str, &str, bool)]) -> Store {
690        use crate::backend::storage::agents::test_agent_def;
691        let store = object_store();
692        for (id, slug, template) in rows {
693            let mut def = test_agent_def(id, slug, "claude", "agent", 1, "");
694            if *template {
695                def.is_seeded = 1;
696            }
697            store.agent_def_insert(&mut def).unwrap();
698            store.test_force_slug(id, slug).unwrap();
699        }
700        store
701    }
702}