Skip to main content

agentmux_srv_core/backend/storage/agents/
purge.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Removing an agent's dependent rows when the agent itself is deleted.
5
6use super::*;
7
8#[cfg(test)]
9pub(crate) fn purge_agent_dependents_for_tests(
10    conn: &rusqlite::Connection,
11    id: &str,
12    tokens: Option<&super::super::agent_tokens::TokenIndex>,
13) -> Result<usize, StoreError> {
14    purge_agent_dependents(conn, id, tokens)
15}
16
17pub(super) fn purge_agent_dependents(
18    conn: &rusqlite::Connection,
19    id: &str,
20    tokens: Option<&super::super::agent_tokens::TokenIndex>,
21) -> Result<usize, StoreError> {
22    const BY_AGENT_ID: &[&str] = &[
23        "db_agent_content",
24        "db_agent_skills",
25        "db_agent_history",
26        "db_agent_identity_links",
27        "db_agent_skills_ref",
28        "db_agent_mcp_ref",
29        "db_agent_mcp_binding",
30        "db_agent_credentials",
31        "db_agent_native_memory",
32        "db_agent_native_memory_versions",
33        "db_agent_jekt_keys",
34        "db_agent_lan_keys",
35        // v37, identity M1: the agent's local identity token dies with it.
36        "db_agent_tokens",
37        // The agent's Bundles list.
38        "db_agent_bundles",
39        // What the user typed to it, and its unsent draft.
40        "db_agent_input_history",
41        "db_agent_input_drafts",
42        "db_agent_input_history_backfilled",
43        "db_agent_input_history_trash",
44    ];
45    let present: std::collections::HashSet<String> = {
46        let mut stmt = conn.prepare("SELECT name FROM sqlite_master WHERE type='table'")?;
47        let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
48        rows.collect::<Result<_, _>>()?
49    };
50    let mut removed = 0usize;
51    for table in BY_AGENT_ID {
52        if !present.contains(*table) {
53            continue;
54        }
55        // Table names are compile-time constants from the list above, never
56        // caller input — the id itself is still bound as a parameter.
57        removed += conn.execute(&format!("DELETE FROM {table} WHERE agent_id=?1"), params![id])?;
58        // Identity M4a: the index follows the token row's own delete, not
59        // the purge's overall result (spec §6.5.3).
60        if *table == "db_agent_tokens" {
61            if let Some(tokens) = tokens {
62                tokens.forget_uid(id);
63            }
64        }
65    }
66    // A channel's cached cloud credentials sit behind its `<channel>/` prefix
67    // when channels share the store (`muxbus::agent_credential_prefix_for`), so
68    // the plain delete above misses them: a deleted agent's client secret must
69    // not stay on disk in any channel's rows.
70    if present.contains("db_agent_credentials") {
71        removed += conn.execute(
72            "DELETE FROM db_agent_credentials WHERE instr(agent_id, '/') > 0 AND substr(agent_id, instr(agent_id, '/') + 1) = ?1",
73            params![id],
74        )?;
75    }
76    // Identity M4d-2: the UID-keyed signing keys, keyed by `uid`.
77    for table in ["db_agent_lan_keys_by_uid", "db_agent_wan_keys_by_uid"] {
78        if present.contains(table) {
79            removed += conn.execute(&format!("DELETE FROM {table} WHERE uid=?1"), params![id])?;
80        }
81    }
82    // The slugs it was renamed from (`former_slugs`), keyed by `agent_uid`.
83    if present.contains("db_agent_former_slugs") {
84        removed += conn.execute("DELETE FROM db_agent_former_slugs WHERE agent_uid=?1", params![id])?;
85    }
86    // The two that key on the agent differently.
87    if present.contains("db_conversation_trust_grants") {
88        removed += conn.execute(
89            "DELETE FROM db_conversation_trust_grants WHERE agent_id=?1 OR granted_peer_agent_id=?1",
90            params![id],
91        )?;
92    }
93    if present.contains("db_agent_activity_summaries") {
94        removed += conn.execute(
95            "DELETE FROM db_agent_activity_summaries WHERE definition_id=?1",
96            params![id],
97        )?;
98    }
99    // v40, durable jekt: messages held for the deleted agent die with it —
100    // their bodies must not linger, nor be delivered if the UID is ever
101    // recreated (Codex P1 on #3632).
102    if present.contains("db_jekt_held") {
103        removed += conn.execute("DELETE FROM db_jekt_held WHERE target_uid=?1", params![id])?;
104    }
105    Ok(removed)
106}