Skip to main content

agentmux_srv_core/backend/slug_migration/
steps_db.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The database steps: S2 (every `objects.db`'s slug and former slugs), S3
5//! (name-keyed signing keys), S4 (`wan.db`), S5 (the MuxBus credential, kept),
6//! S6 (name-only rows) and S7's rows (persisted `cmd:env`). Each runs in one
7//! transaction per database, through a raw connection, so another version's
8//! `objects.db` is changed only where the step says and is never upgraded.
9
10use std::collections::BTreeMap;
11use std::path::Path;
12
13use rusqlite::{params, Connection, OptionalExtension};
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16
17use super::home::{fold, has_column, in_tx, open_ro, open_rw, table_exists};
18use super::steps::{parse, to_value, Agent, Ctx};
19
20const KEY_TABLES: [&str; 3] = ["db_agent_jekt_keys", "db_agent_lan_keys", "db_agent_wan_keys"];
21
22fn err(e: rusqlite::Error) -> String {
23    e.to_string()
24}
25
26fn path_str(p: &Path) -> String {
27    p.display().to_string()
28}
29
30// ── S2: db_agents.slug and db_agent_former_slugs ─────────────────────
31
32#[derive(Debug, Serialize, Deserialize)]
33struct S2Db {
34    db: String,
35    slug: Option<String>,
36    had_table: bool,
37    had_former: bool,
38}
39
40pub(super) fn s2_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
41    let mut out = Vec::new();
42    for db in ctx.objects_dbs() {
43        let conn = open_ro(&db)?;
44        if !super::home::has_agent_slugs(&conn) {
45            continue;
46        }
47        let row: Option<Option<String>> =
48            conn.query_row("SELECT slug FROM db_agents WHERE id = ?1", [&a.uid], |r| r.get(0)).optional().map_err(err)?;
49        let Some(slug) = row else { continue };
50        let had_table = table_exists(&conn, "db_agent_former_slugs");
51        let had_former = had_table
52            && conn
53                .query_row("SELECT 1 FROM db_agent_former_slugs WHERE agent_uid = ?1 AND slug = ?2", [&a.uid, &fold(&a.old)], |_| Ok(()))
54                .optional()
55                .map_err(err)?
56                .is_some();
57        out.push(S2Db { db: path_str(&db), slug, had_table, had_former });
58    }
59    to_value(&out)
60}
61
62pub(super) fn s2_apply(ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
63    let mut changes = Vec::new();
64    for b in parse::<Vec<S2Db>>(before)? {
65        let conn = open_rw(Path::new(&b.db))?;
66        let (renamed, recorded) = in_tx(&conn, |c| {
67            let renamed = c
68                .execute("UPDATE db_agents SET slug = ?1 WHERE id = ?2 AND (slug IS NULL OR slug != ?1)", [&a.new, &a.uid])
69                .map_err(err)?;
70            c.execute_batch(crate::backend::storage::agents::FORMER_SLUGS_SCHEMA).map_err(err)?;
71            let recorded = c
72                .execute(
73                    "INSERT OR IGNORE INTO db_agent_former_slugs (agent_uid, slug, retired_at)
74                     SELECT ?1, ?2, ?3 WHERE EXISTS (SELECT 1 FROM db_agents WHERE id = ?1)",
75                    params![a.uid, fold(&a.old), ctx.retired_at],
76                )
77                .map_err(err)?;
78            Ok((renamed, recorded))
79        })?;
80        if renamed + recorded > 0 {
81            changes.push(format!("{}: slug {} -> {}, {} recorded as a former slug", b.db, a.old, a.new, fold(&a.old)));
82        }
83    }
84    Ok(changes)
85}
86
87pub(super) fn s2_undo(a: &Agent, before: &Value) -> Result<Vec<String>, String> {
88    let mut changes = Vec::new();
89    for b in parse::<Vec<S2Db>>(before)? {
90        let conn = open_rw(Path::new(&b.db))?;
91        in_tx(&conn, |c| {
92            c.execute("UPDATE db_agents SET slug = ?1 WHERE id = ?2", params![b.slug, a.uid]).map_err(err)?;
93            if !b.had_former && table_exists(c, "db_agent_former_slugs") {
94                c.execute("DELETE FROM db_agent_former_slugs WHERE agent_uid = ?1 AND slug = ?2", [&a.uid, &fold(&a.old)])
95                    .map_err(err)?;
96            }
97            if !b.had_table && table_exists(c, "db_agent_former_slugs") {
98                let left: i64 = c.query_row("SELECT COUNT(*) FROM db_agent_former_slugs", [], |r| r.get(0)).map_err(err)?;
99                if left == 0 {
100                    c.execute_batch("DROP TABLE db_agent_former_slugs").map_err(err)?;
101                }
102            }
103            Ok(())
104        })?;
105        changes.push(format!("{}: slug back to {}", b.db, b.slug.as_deref().unwrap_or("(none)")));
106    }
107    Ok(changes)
108}
109
110// ── S3: name-keyed signing keys, rotated ─────────────────────────────
111
112#[derive(Debug, Serialize, Deserialize)]
113struct S3Db {
114    db: String,
115    /// (table, name) of each key row deleted. Its contents stay in the
116    /// backup copy of this database.
117    rows: Vec<(String, String)>,
118    tombstones: bool,
119    tombstone: Option<(String, i64)>,
120}
121
122/// The names S3 and S4 clear: the old one, and the new one in case a row
123/// was left under it, so the agent's next spawn mints fresh keys instead of
124/// inheriting one (the planner already made sure no other agent holds it).
125fn key_names(a: &Agent) -> [String; 2] {
126    [fold(&a.old), fold(&a.new)]
127}
128
129pub(super) fn s3_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
130    let mut out = Vec::new();
131    for db in ctx.objects_dbs() {
132        let conn = open_ro(&db)?;
133        let mut rows = Vec::new();
134        for table in KEY_TABLES.iter().filter(|t| table_exists(&conn, t)) {
135            for name in key_names(a) {
136                let mut stmt = conn.prepare(&format!("SELECT agent_id FROM {table} WHERE agent_id = ?1 COLLATE NOCASE")).map_err(err)?;
137                for id in stmt.query_map([&name], |r| r.get::<_, String>(0)).map_err(err)? {
138                    rows.push((table.to_string(), id.map_err(err)?));
139                }
140            }
141        }
142        let tombstones = table_exists(&conn, "db_agent_key_tombstones");
143        let tombstone = if tombstones {
144            conn.query_row("SELECT deleted_uid, deleted_at FROM db_agent_key_tombstones WHERE name = ?1", [&fold(&a.old)], |r| {
145                Ok((r.get(0)?, r.get(1)?))
146            })
147            .optional()
148            .map_err(err)?
149        } else {
150            None
151        };
152        out.push(S3Db { db: path_str(&db), rows, tombstones, tombstone });
153    }
154    to_value(&out)
155}
156
157pub(super) fn s3_apply(_ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
158    let mut changes = Vec::new();
159    for b in parse::<Vec<S3Db>>(before)? {
160        let conn = open_rw(Path::new(&b.db))?;
161        let (removed, tombstoned) = in_tx(&conn, |c| {
162            let mut removed = 0;
163            for (table, name) in &b.rows {
164                removed += c.execute(&format!("DELETE FROM {table} WHERE agent_id = ?1"), [name]).map_err(err)?;
165            }
166            let mut tombstoned = 0;
167            if b.tombstones {
168                tombstoned = c.execute(
169                    "INSERT INTO db_agent_key_tombstones (name, deleted_uid, deleted_at) VALUES (?1, ?2, ?3)
170                     ON CONFLICT(name) DO UPDATE SET deleted_uid = excluded.deleted_uid, deleted_at = excluded.deleted_at
171                     WHERE deleted_uid != excluded.deleted_uid",
172                    params![fold(&a.old), a.uid, agentmux_common::time::now_secs()],
173                )
174                .map_err(err)?;
175            }
176            Ok((removed, tombstoned))
177        })?;
178        if removed > 0 {
179            changes.push(format!("{}: {removed} signing key row(s) under {} or {} deleted", b.db, fold(&a.old), fold(&a.new)));
180        }
181        if tombstoned > 0 {
182            changes.push(format!("{}: {} tombstoned", b.db, fold(&a.old)));
183        }
184    }
185    Ok(changes)
186}
187
188/// Rows matching a filter: `(table, sql filter, params)`.
189type Rows = [(String, String, Vec<String>)];
190
191/// Delete `clear`, then put `rows` back from the backup copy of `db`, then
192/// run `extra`, in one transaction.
193fn restore_rows(ctx: &Ctx, db: &Path, clear: &Rows, rows: &Rows, extra: impl FnOnce(&Connection) -> Result<(), String>) -> Result<usize, String> {
194    let conn = open_rw(db)?;
195    let attached = if rows.is_empty() {
196        false
197    } else {
198        let copy = ctx.backup_of(db)?;
199        conn.execute("ATTACH DATABASE ?1 AS bk", [copy.display().to_string()]).map_err(err)?;
200        true
201    };
202    let result = in_tx(&conn, |c| {
203        for (table, filter, args) in clear.iter().filter(|(t, _, _)| table_exists(c, t)) {
204            c.execute(&format!("DELETE FROM main.{table} WHERE {filter}"), rusqlite::params_from_iter(args)).map_err(err)?;
205        }
206        let mut restored = 0;
207        for (table, filter, args) in rows {
208            restored += c
209                .execute(&format!("INSERT OR IGNORE INTO main.{table} SELECT * FROM bk.{table} WHERE {filter}"), rusqlite::params_from_iter(args))
210                .map_err(err)?;
211        }
212        extra(c)?;
213        Ok(restored)
214    });
215    if attached {
216        let _ = conn.execute_batch("DETACH DATABASE bk");
217    }
218    result
219}
220
221pub(super) fn s3_undo(ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
222    let mut changes = Vec::new();
223    for b in parse::<Vec<S3Db>>(before)? {
224        let rows: Vec<(String, String, Vec<String>)> =
225            b.rows.iter().map(|(t, n)| (t.clone(), "agent_id = ?1".to_string(), vec![n.clone()])).collect();
226        // Keys minted under the new name since (a relaunch) go too: no agent
227        // holds that name once the rename is undone.
228        let clear: Vec<(String, String, Vec<String>)> =
229            KEY_TABLES.iter().map(|t| (t.to_string(), "agent_id = ?1 COLLATE NOCASE".to_string(), vec![fold(&a.new)])).collect();
230        let restored = restore_rows(ctx, Path::new(&b.db), &clear, &rows, |c| {
231            if !b.tombstones {
232                return Ok(());
233            }
234            match &b.tombstone {
235                Some((uid, at)) => c
236                    .execute(
237                        "INSERT OR REPLACE INTO db_agent_key_tombstones (name, deleted_uid, deleted_at) VALUES (?1, ?2, ?3)",
238                        params![fold(&a.old), uid, at],
239                    )
240                    .map(|_| ()),
241                None => c
242                    .execute("DELETE FROM db_agent_key_tombstones WHERE name = ?1 AND deleted_uid = ?2", [&fold(&a.old), &a.uid])
243                    .map(|_| ()),
244            }
245            .map_err(err)
246        })?;
247        changes.push(format!("{}: {restored} signing key row(s) restored from the backup", b.db));
248    }
249    Ok(changes)
250}
251
252// ── S4: wan.db ───────────────────────────────────────────────────────
253
254#[derive(Debug, Serialize, Deserialize)]
255struct S4Db {
256    db: String,
257    keys: Vec<String>,
258    publications: Vec<(String, String)>,
259}
260
261pub(super) fn s4_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
262    let mut out = Vec::new();
263    for db in ctx.wan_dbs() {
264        let conn = open_ro(&db)?;
265        let mut keys = Vec::new();
266        let mut publications = Vec::new();
267        for name in key_names(a) {
268            if table_exists(&conn, "wan_agent_keys") {
269                let mut stmt = conn.prepare("SELECT agent_id FROM wan_agent_keys WHERE agent_id = ?1 COLLATE NOCASE").map_err(err)?;
270                for id in stmt.query_map([&name], |r| r.get::<_, String>(0)).map_err(err)? {
271                    keys.push(id.map_err(err)?);
272                }
273            }
274            if table_exists(&conn, "wan_agent_key_publications") {
275                let mut stmt = conn
276                    .prepare("SELECT agent_id, directory FROM wan_agent_key_publications WHERE agent_id = ?1 COLLATE NOCASE")
277                    .map_err(err)?;
278                for row in stmt.query_map([&name], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(err)? {
279                    publications.push(row.map_err(err)?);
280                }
281            }
282        }
283        if !keys.is_empty() || !publications.is_empty() {
284            out.push(S4Db { db: path_str(&db), keys, publications });
285        }
286    }
287    to_value(&out)
288}
289
290pub(super) fn s4_apply(_ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
291    let mut changes = Vec::new();
292    for b in parse::<Vec<S4Db>>(before)? {
293        let conn = open_rw(Path::new(&b.db))?;
294        let removed = in_tx(&conn, |c| {
295            let mut n = 0;
296            for id in &b.keys {
297                n += c.execute("DELETE FROM wan_agent_keys WHERE agent_id = ?1", [id]).map_err(err)?;
298            }
299            for (id, dir) in &b.publications {
300                n += c.execute("DELETE FROM wan_agent_key_publications WHERE agent_id = ?1 AND directory = ?2", [id, dir]).map_err(err)?;
301            }
302            Ok(n)
303        })?;
304        if removed > 0 {
305            changes.push(format!(
306                "{}: the WAN key and {} publication record(s) under {} retired",
307                b.db,
308                b.publications.len(),
309                fold(&a.old)
310            ));
311        }
312    }
313    Ok(changes)
314}
315
316pub(super) fn s4_undo(ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
317    let mut changes = Vec::new();
318    for b in parse::<Vec<S4Db>>(before)? {
319        let clear: Vec<(String, String, Vec<String>)> = ["wan_agent_keys", "wan_agent_key_publications"]
320            .iter()
321            .map(|t| (t.to_string(), "agent_id = ?1 COLLATE NOCASE".to_string(), vec![fold(&a.new)]))
322            .collect();
323        let mut rows: Vec<(String, String, Vec<String>)> =
324            b.keys.iter().map(|id| ("wan_agent_keys".to_string(), "agent_id = ?1".to_string(), vec![id.clone()])).collect();
325        rows.extend(b.publications.iter().map(|(id, dir)| {
326            ("wan_agent_key_publications".to_string(), "agent_id = ?1 AND directory = ?2".to_string(), vec![id.clone(), dir.clone()])
327        }));
328        let restored = restore_rows(ctx, Path::new(&b.db), &clear, &rows, |_| Ok(()))?;
329        changes.push(format!("{}: {restored} WAN row(s) restored from the backup", b.db));
330    }
331    Ok(changes)
332}
333
334// ── S5: the MuxBus credential, kept ──────────────────────────────────
335
336pub(super) fn s5_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
337    let mut found = Vec::new();
338    for db in ctx.host_stores().into_iter().chain(ctx.objects_dbs()) {
339        let conn = open_ro(&db)?;
340        if !table_exists(&conn, "db_agent_credentials") {
341            continue;
342        }
343        let mut stmt = conn
344            .prepare(
345                "SELECT agent_id FROM db_agent_credentials WHERE agent_id = ?1 COLLATE NOCASE
346                 OR (instr(agent_id, '/') > 0 AND substr(agent_id, instr(agent_id, '/') + 1) = ?1 COLLATE NOCASE)",
347            )
348            .map_err(err)?;
349        for id in stmt.query_map([&fold(&a.old)], |r| r.get::<_, String>(0)).map_err(err)? {
350            found.push(format!("{}: {}", db.display(), id.map_err(err)?));
351        }
352    }
353    to_value(&found)
354}
355
356pub(super) fn s5_apply(before: &Value) -> Result<Vec<String>, String> {
357    let found: Vec<String> = parse(before)?;
358    Ok(found.into_iter().map(|f| format!("{f} kept for the 30-day receive-only grace subscription")).collect())
359}
360
361// ── S6: rows that name the agent and carry no uid ────────────────────
362
363#[derive(Debug, Serialize, Deserialize)]
364struct S6Update {
365    db: String,
366    table: String,
367    id: String,
368    /// Each column it sets, with the value it had.
369    set: Vec<(String, String)>,
370}
371
372#[derive(Debug, Serialize, Deserialize)]
373struct S6Grant {
374    db: String,
375    agent_id: String,
376    peer: String,
377    tier: String,
378    granted_at: i64,
379    new_existed: bool,
380}
381
382#[derive(Debug, Default, Serialize, Deserialize)]
383struct S6Before {
384    updates: Vec<S6Update>,
385    grants: Vec<S6Grant>,
386}
387
388/// The name-only rules: (table, the name column, its uid column, extra filter).
389const NAME_ONLY: [(&str, &str, &str, &str); 4] = [
390    ("db_cron_jobs", "target", "target_uid", ""),
391    ("db_jobs", "target", "target_uid", ""),
392    ("db_work_queue", "target_agent", "target_agent_uid", "AND state IN ('open', 'claimed')"),
393    ("db_work_queue", "claimed_by", "claimed_by_uid", "AND state = 'claimed'"),
394];
395
396fn renamed(name: &str, a: &Agent) -> String {
397    if fold(name) == fold(&a.old) {
398        fold(&a.new)
399    } else {
400        name.to_string()
401    }
402}
403
404pub(super) fn s6_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
405    let mut b = S6Before::default();
406    for db in ctx.host_stores().into_iter().chain(ctx.objects_dbs()) {
407        let conn = open_ro(&db)?;
408        for (table, col, uid_col, filter) in NAME_ONLY {
409            if !table_exists(&conn, table) || !has_column(&conn, table, uid_col) {
410                continue;
411            }
412            let mut stmt = conn
413                .prepare(&format!("SELECT id, {col} FROM {table} WHERE {uid_col} = '' AND {col} = ?1 COLLATE NOCASE {filter}"))
414                .map_err(err)?;
415            for row in stmt.query_map([&a.old], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(err)? {
416                let (id, name) = row.map_err(err)?;
417                b.updates.push(S6Update {
418                    db: path_str(&db),
419                    table: table.to_string(),
420                    id,
421                    set: vec![(col.to_string(), name), (uid_col.to_string(), String::new())],
422                });
423            }
424        }
425        if table_exists(&conn, "db_conversation_trust_grants") {
426            let mut stmt = conn
427                .prepare(
428                    "SELECT agent_id, granted_peer_agent_id, tier, granted_at FROM db_conversation_trust_grants
429                     WHERE agent_id = ?1 OR granted_peer_agent_id = ?1",
430                )
431                .map_err(err)?;
432            let rows: Vec<(String, String, String, i64)> = stmt
433                .query_map([&fold(&a.old)], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
434                .map_err(err)?
435                .collect::<Result<_, _>>()
436                .map_err(err)?;
437            for (agent_id, peer, tier, granted_at) in rows {
438                let new_existed = conn
439                    .query_row(
440                        "SELECT 1 FROM db_conversation_trust_grants WHERE agent_id = ?1 AND granted_peer_agent_id = ?2 AND tier = ?3",
441                        [&renamed(&agent_id, a), &renamed(&peer, a), &tier],
442                        |_| Ok(()),
443                    )
444                    .optional()
445                    .map_err(err)?
446                    .is_some();
447                b.grants.push(S6Grant { db: path_str(&db), agent_id, peer, tier, granted_at, new_existed });
448            }
449        }
450    }
451    to_value(&b)
452}
453
454/// The value S6 gives a column: the uid for a uid column, the new name for
455/// a name column.
456fn s6_value(col: &str, a: &Agent) -> String {
457    if col.ends_with("_uid") {
458        a.uid.clone()
459    } else {
460        fold(&a.new)
461    }
462}
463
464fn by_db<T>(items: &[T], db: impl Fn(&T) -> &str) -> BTreeMap<String, Vec<&T>> {
465    let mut out: BTreeMap<String, Vec<&T>> = BTreeMap::new();
466    for item in items {
467        out.entry(db(item).to_string()).or_default().push(item);
468    }
469    out
470}
471
472pub(super) fn s6_apply(_ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
473    let b: S6Before = parse(before)?;
474    let mut changes = Vec::new();
475    let mut dbs: Vec<String> = b.updates.iter().map(|u| u.db.clone()).chain(b.grants.iter().map(|g| g.db.clone())).collect();
476    dbs.sort();
477    dbs.dedup();
478    let updates = by_db(&b.updates, |u| &u.db);
479    let grants = by_db(&b.grants, |g| &g.db);
480    for db in dbs {
481        let conn = open_rw(Path::new(&db))?;
482        let n = in_tx(&conn, |c| {
483            let mut n = 0;
484            for u in updates.get(&db).into_iter().flatten() {
485                let (name_col, old_name) = &u.set[0];
486                let assigns = u.set.iter().map(|(col, _)| format!("{col} = ?")).collect::<Vec<_>>().join(", ");
487                let mut args: Vec<String> = u.set.iter().map(|(col, _)| s6_value(col, a)).collect();
488                args.push(u.id.clone());
489                args.push(old_name.clone());
490                n += c
491                    .execute(&format!("UPDATE {} SET {assigns} WHERE id = ? AND {name_col} = ?", u.table), rusqlite::params_from_iter(&args))
492                    .map_err(err)?;
493            }
494            for g in grants.get(&db).into_iter().flatten() {
495                n += c
496                    .execute(
497                        "DELETE FROM db_conversation_trust_grants WHERE agent_id = ?1 AND granted_peer_agent_id = ?2 AND tier = ?3",
498                        [&g.agent_id, &g.peer, &g.tier],
499                    )
500                    .map_err(err)?;
501                c.execute(
502                    "INSERT OR IGNORE INTO db_conversation_trust_grants (agent_id, granted_peer_agent_id, tier, granted_at) VALUES (?1, ?2, ?3, ?4)",
503                    params![renamed(&g.agent_id, a), renamed(&g.peer, a), g.tier, g.granted_at],
504                )
505                .map_err(err)?;
506            }
507            Ok(n)
508        })?;
509        if n > 0 {
510            changes.push(format!("{db}: {n} row(s) naming {} now name {} and carry its uid", fold(&a.old), fold(&a.new)));
511        }
512    }
513    Ok(changes)
514}
515
516pub(super) fn s6_undo(a: &Agent, before: &Value) -> Result<Vec<String>, String> {
517    let b: S6Before = parse(before)?;
518    let mut changes = Vec::new();
519    let mut dbs: Vec<String> = b.updates.iter().map(|u| u.db.clone()).chain(b.grants.iter().map(|g| g.db.clone())).collect();
520    dbs.sort();
521    dbs.dedup();
522    let updates = by_db(&b.updates, |u| &u.db);
523    let grants = by_db(&b.grants, |g| &g.db);
524    for db in dbs {
525        let conn = open_rw(Path::new(&db))?;
526        in_tx(&conn, |c| {
527            for u in updates.get(&db).into_iter().flatten() {
528                let (name_col, _) = &u.set[0];
529                let assigns = u.set.iter().map(|(col, _)| format!("{col} = ?")).collect::<Vec<_>>().join(", ");
530                let mut args: Vec<String> = u.set.iter().map(|(_, old)| old.clone()).collect();
531                args.push(u.id.clone());
532                args.push(s6_value(name_col, a));
533                c.execute(&format!("UPDATE {} SET {assigns} WHERE id = ? AND {name_col} = ?", u.table), rusqlite::params_from_iter(&args))
534                    .map_err(err)?;
535            }
536            for g in grants.get(&db).into_iter().flatten() {
537                c.execute(
538                    "INSERT OR IGNORE INTO db_conversation_trust_grants (agent_id, granted_peer_agent_id, tier, granted_at) VALUES (?1, ?2, ?3, ?4)",
539                    params![g.agent_id, g.peer, g.tier, g.granted_at],
540                )
541                .map_err(err)?;
542                if !g.new_existed {
543                    c.execute(
544                        "DELETE FROM db_conversation_trust_grants WHERE agent_id = ?1 AND granted_peer_agent_id = ?2 AND tier = ?3",
545                        [&renamed(&g.agent_id, a), &renamed(&g.peer, a), &g.tier],
546                    )
547                    .map_err(err)?;
548                }
549            }
550            Ok(())
551        })?;
552        changes.push(format!("{db}: name-only rows back to {}", fold(&a.old)));
553    }
554    Ok(changes)
555}
556
557// ── S7: persisted identity in cmd:env ────────────────────────────────
558
559#[derive(Debug, Clone, Serialize, Deserialize)]
560pub(super) struct S7Change {
561    /// JSON pointer to the `cmd:env` object, within the row's data.
562    pointer: String,
563    key: String,
564    old: String,
565}
566
567#[derive(Debug, Serialize, Deserialize)]
568struct S7Row {
569    db: String,
570    table: String,
571    oid: String,
572    /// The row's version before the step, which its undo puts back when
573    /// nothing else has written the row since.
574    version: i64,
575    changes: Vec<S7Change>,
576}
577
578/// The value an identity variable takes after the rename, if it named the
579/// old id: the id and slug variables and the git names equal to it, and a
580/// git email whose local part is it (the domain kept).
581fn rewrite(key: &str, value: &str, a: &Agent) -> Option<String> {
582    match key {
583        "AGENTMUX_AGENT_ID" | "MUXBUS_AGENT_ID" | "AGENTMUX_AGENT_SLUG" | "GIT_AUTHOR_NAME" | "GIT_COMMITTER_NAME" => {
584            (fold(value) == fold(&a.old)).then(|| a.new.clone())
585        }
586        "GIT_AUTHOR_EMAIL" | "GIT_COMMITTER_EMAIL" => {
587            let (local, domain) = value.split_once('@')?;
588            (fold(local) == fold(&a.old)).then(|| format!("{}@{domain}", fold(&a.new)))
589        }
590        _ => None,
591    }
592}
593
594fn escape(segment: &str) -> String {
595    segment.replace('~', "~0").replace('/', "~1")
596}
597
598/// Every identity variable in `value` (a block's meta, or a layout snapshot)
599/// that names the old id, in an object that is this agent's: its `agentId`
600/// is the uid, or it has none and its own id or slug variable names the old
601/// id. Another agent's block is never touched.
602fn collect(value: &Value, pointer: &str, a: &Agent, out: &mut Vec<S7Change>) {
603    match value {
604        Value::Object(map) => {
605            if let Some(Value::Object(env)) = map.get("cmd:env") {
606                let owner = ["agentId", "agent:id"].iter().find_map(|k| map.get(*k).and_then(Value::as_str)).filter(|s| !s.is_empty());
607                let names_old = ["AGENTMUX_AGENT_ID", "AGENTMUX_AGENT_SLUG"]
608                    .iter()
609                    .any(|k| env.get(*k).and_then(Value::as_str).is_some_and(|v| fold(v) == fold(&a.old)));
610                let ours = match owner {
611                    Some(uid) => uid == a.uid,
612                    None => names_old,
613                };
614                if ours {
615                    for (key, v) in env {
616                        if let Some(old) = v.as_str().filter(|v| rewrite(key, v, a).is_some()) {
617                            out.push(S7Change { pointer: format!("{pointer}/cmd:env"), key: key.clone(), old: old.to_string() });
618                        }
619                    }
620                }
621            }
622            for (k, child) in map.iter().filter(|(k, _)| k.as_str() != "cmd:env") {
623                collect(child, &format!("{pointer}/{}", escape(k)), a, out);
624            }
625        }
626        Value::Array(items) => {
627            for (i, child) in items.iter().enumerate() {
628                collect(child, &format!("{pointer}/{i}"), a, out);
629            }
630        }
631        _ => {}
632    }
633}
634
635/// Where each table keeps what S7 rewrites.
636const S7_ROOTS: [(&str, &str); 2] = [("db_block", "/meta"), ("db_client", "/meta/session:last_topology")];
637
638/// A row S7 would change: its table, oid, version and the variables.
639pub(super) type S7Found = (String, String, i64, Vec<S7Change>);
640
641pub(super) fn s7_rows(db: &Path, a: &Agent) -> Result<Vec<S7Found>, String> {
642    let conn = open_ro(db)?;
643    let mut out = Vec::new();
644    for (table, root) in S7_ROOTS.iter().filter(|(t, _)| table_exists(&conn, t)) {
645        let mut stmt = conn.prepare(&format!("SELECT oid, version, data FROM {table}")).map_err(err)?;
646        let rows = stmt
647            .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, Vec<u8>>(2)?)))
648            .map_err(err)?;
649        for row in rows {
650            let (oid, version, data) = row.map_err(err)?;
651            let Ok(value) = serde_json::from_slice::<Value>(&data) else { continue };
652            let Some(start) = value.pointer(root) else { continue };
653            let mut changes = Vec::new();
654            collect(start, root, a, &mut changes);
655            if !changes.is_empty() {
656                out.push((table.to_string(), oid, version, changes));
657            }
658        }
659    }
660    Ok(out)
661}
662
663pub(super) fn s7_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
664    let mut rows = Vec::new();
665    for db in ctx.objects_dbs() {
666        for (table, oid, version, changes) in s7_rows(&db, a)? {
667            rows.push(S7Row { db: path_str(&db), table, oid, version, changes });
668        }
669    }
670    Ok(serde_json::json!({ "rows": to_value(&rows)? }))
671}
672
673/// Rewrite each recorded variable whose value is still `from` to `to`, in
674/// every row of `before`; `forward` picks the direction.
675fn s7_write(a: &Agent, before: &Value, forward: bool) -> Result<Vec<String>, String> {
676    let rows: Vec<S7Row> = parse(&before["rows"])?;
677    let mut changes = Vec::new();
678    for (db, group) in by_db(&rows, |r| &r.db) {
679        let conn = open_rw(Path::new(&db))?;
680        let n = in_tx(&conn, |c| {
681            let mut n = 0;
682            for row in group {
683                let data: Option<Vec<u8>> =
684                    c.query_row(&format!("SELECT data FROM {} WHERE oid = ?1", row.table), [&row.oid], |r| r.get(0)).optional().map_err(err)?;
685                let Some(mut value) = data.and_then(|d| serde_json::from_slice::<Value>(&d).ok()) else { continue };
686                let mut changed = false;
687                for ch in &row.changes {
688                    let Some(new) = rewrite(&ch.key, &ch.old, a) else { continue };
689                    let (from, to) = if forward { (ch.old.as_str(), new.as_str()) } else { (new.as_str(), ch.old.as_str()) };
690                    let Some(env) = value.pointer_mut(&ch.pointer).and_then(Value::as_object_mut) else { continue };
691                    if env.get(&ch.key).and_then(Value::as_str) == Some(from) {
692                        env.insert(ch.key.clone(), Value::String(to.to_string()));
693                        changed = true;
694                    }
695                }
696                if changed {
697                    let bytes = serde_json::to_vec(&value).map_err(|e| e.to_string())?;
698                    if forward {
699                        c.execute(&format!("UPDATE {} SET data = ?1, version = version + 1 WHERE oid = ?2", row.table), params![bytes, row.oid])
700                    } else {
701                        c.execute(
702                            &format!("UPDATE {} SET data = ?1, version = CASE WHEN version = ?3 + 1 THEN ?3 ELSE version + 1 END WHERE oid = ?2", row.table),
703                            params![bytes, row.oid, row.version],
704                        )
705                    }
706                    .map_err(err)?;
707                    n += 1;
708                }
709            }
710            Ok(n)
711        })?;
712        if n > 0 {
713            let what = if forward { format!("now name {}", a.new) } else { format!("name {} again", a.old) };
714            changes.push(format!("{db}: {n} pane(s) or layout snapshot(s) whose persisted identity {what}"));
715        }
716    }
717    Ok(changes)
718}
719
720pub(super) fn s7_apply(_ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
721    s7_write(a, before, true)
722}
723
724pub(super) fn s7_undo(a: &Agent, before: &Value) -> Result<Vec<String>, String> {
725    s7_write(a, before, false)
726}
727
728/// The working folders of the agent's blocks (`cmd:cwd`), from every
729/// `objects.db`, for S7's `.mcp.json`.
730pub(super) fn block_cwds(ctx: &Ctx, a: &Agent) -> Result<Vec<String>, String> {
731    let mut out = Vec::new();
732    for db in ctx.objects_dbs() {
733        let conn = open_ro(&db)?;
734        if !table_exists(&conn, "db_block") {
735            continue;
736        }
737        let mut stmt = conn.prepare("SELECT data FROM db_block").map_err(err)?;
738        for data in stmt.query_map([], |r| r.get::<_, Vec<u8>>(0)).map_err(err)? {
739            let Ok(block) = serde_json::from_slice::<Value>(&data.map_err(err)?) else { continue };
740            let Some(meta) = block.get("meta") else { continue };
741            let ours = ["agentId", "agent:id"].iter().any(|k| meta.get(*k).and_then(Value::as_str) == Some(a.uid.as_str()));
742            if let Some(cwd) = meta.get("cmd:cwd").and_then(Value::as_str).filter(|c| ours && !c.trim().is_empty()) {
743                out.push(cwd.to_string());
744            }
745        }
746    }
747    Ok(out)
748}