Skip to main content

agentmux_srv_core/
adoption.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Carry what channels kept to themselves into the shared store.
5//!
6//! Auth is shared by every channel now (`SPEC_SHARED_AUTH_ACROSS_CHANNELS_2026_10_03.md`),
7//! but until 2026-10-03 every non-`stable` channel isolated it, so real data sits
8//! in `channels/<ch>/identity-store.db` files the shared store has never seen. On
9//! the first shared boot this pass copies it across, read-only on the source:
10//!
11//! | What | From | Why |
12//! |---|---|---|
13//! | Global Memory (global, non-system bundles) and their versions | every channel store, newest wins | each channel kept its own; the same entry written twice is one entry |
14//! | Native memory and its versions | every channel store, newest wins | the shared store has none; the entries are scattered over older channels |
15//! | Accounts | this channel's own isolated store and the newest same-branch predecessor | a login belongs to the build that made it; adopting every channel's would flood Connectors → Accounts with test accounts |
16//!
17//! Everything else is left alone. Non-global bundles in particular are mostly
18//! per-agent bundles each channel made for itself (4,740 distinct ones across the
19//! owner's 46 stores).
20//!
21//! **Idempotent, and deletions stick.** A ledger (`adoption-ledger.json` in the
22//! shared dir; a file, because a schema change to the shared store would stop an
23//! older build opening it) records the keys already considered and each source's
24//! stamp. An item deleted afterwards is not put back, and a source that has not
25//! changed is not reopened. An account row keeps its stored `OAuthConfigDir`
26//! pointing at the source channel's folder: the spawn path uses the stored dir,
27//! so the login works at once, with no copy of the credentials.
28
29use std::collections::{BTreeMap, BTreeSet, HashSet};
30use std::path::{Path, PathBuf};
31use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
32
33use rusqlite::types::Value;
34use rusqlite::{params_from_iter, Connection, OpenFlags};
35use serde::{Deserialize, Serialize};
36
37use crate::backend::storage::store::Store;
38
39const LEDGER_FILE: &str = "adoption-ledger.json";
40static TMP_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
41/// Longest a boot waits for the pass; what is left is picked up next boot.
42pub(crate) const BOOT_BUDGET: Duration = Duration::from_secs(8);
43
44/// What a source file looked like when it was last fully processed: the database
45/// and its write-ahead log (a WAL-mode database's newest writes live there).
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47struct Stamp {
48    modified_ms: u64,
49    size: u64,
50    wal_modified_ms: u64,
51    wal_size: u64,
52}
53
54#[derive(Debug, Default, Serialize, Deserialize)]
55struct Ledger {
56    sources: BTreeMap<String, Stamp>,
57    keys: BTreeSet<String>,
58}
59
60/// Counts for the boot log and the tests.
61#[derive(Debug, Default, Clone, PartialEq, Eq)]
62pub(crate) struct Report {
63    pub sources_read: usize,
64    pub sources_unchanged: usize,
65    pub sources_failed: usize,
66    pub global_memory_added: usize,
67    pub global_memory_updated: usize,
68    pub native_memory_added: usize,
69    pub native_memory_updated: usize,
70    pub accounts_added: usize,
71    /// Rows the target refused (a name already taken by another id, a missing
72    /// required column): skipped, not fatal.
73    pub rows_refused: usize,
74    /// Rows left out because they were adopted once and deleted since.
75    pub deleted_stay_deleted: usize,
76    pub budget_exhausted: bool,
77}
78
79impl Report {
80    pub(crate) fn changed_anything(&self) -> bool {
81        self.global_memory_added
82            + self.global_memory_updated
83            + self.native_memory_added
84            + self.native_memory_updated
85            + self.accounts_added
86            > 0
87    }
88}
89
90pub(crate) struct Inputs<'a> {
91    /// The true global root (`~/.agentmux`).
92    pub home: &'a Path,
93    /// The directory holding `adoption-ledger.json` (`<home>/shared`).
94    pub shared_dir: &'a Path,
95    /// This channel's id (`AGENTMUX_CHANNEL`).
96    pub channel: &'a str,
97    /// This channel's own directory (`AGENTMUX_INSTANCE_DIR`), if known.
98    pub instance_dir: Option<&'a Path>,
99    /// The shared store's file: never a source.
100    pub target_path: &'a Path,
101    pub budget: Duration,
102}
103
104/// The sources for one pass. The predecessor is the newest other build of this
105/// branch (same `local-<branch>-<hash>-` prefix) whose store holds an account.
106#[derive(Debug, Default)]
107pub(crate) struct Sources {
108    /// Every channel's identity store, newest first.
109    pub all: Vec<PathBuf>,
110    /// This channel's own store and its predecessor's, for accounts.
111    pub accounts: Vec<PathBuf>,
112}
113
114fn modified(p: &Path) -> Option<SystemTime> {
115    std::fs::metadata(p).and_then(|m| m.modified()).ok()
116}
117
118fn same_file(a: &Path, b: &Path) -> bool {
119    canonical(a) == canonical(b)
120}
121
122/// `p` resolved to its canonical form, or `p` itself when that fails. Each
123/// candidate is resolved once: `canonicalize` opens the file on Windows, and
124/// comparing every pair of channel stores with it cost about 130 ms per boot
125/// on a host with ~50 channels.
126fn canonical(p: &Path) -> PathBuf {
127    std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
128}
129
130/// `local-<branch>-<hash6>-<8 hex>` → its prefix up to and including the last `-`.
131/// A per-build channel's name ends in an 8-hex build suffix; the part before it
132/// names the branch, so another build of the same branch shares the prefix.
133fn build_prefix(channel: &str) -> Option<&str> {
134    let (prefix, suffix) = channel.rsplit_once('-')?;
135    let is_build = suffix.len() == 8 && suffix.bytes().all(|b| b.is_ascii_hexdigit());
136    (channel.starts_with("local-") && is_build).then(|| &channel[..prefix.len() + 1])
137}
138
139pub(crate) fn discover_sources(inp: &Inputs) -> Sources {
140    let mut found: Vec<(SystemTime, PathBuf)> = Vec::new();
141    let target = canonical(inp.target_path);
142    let mut seen: HashSet<PathBuf> = HashSet::new();
143    let mut push = |p: PathBuf| {
144        if !p.is_file() {
145            return;
146        }
147        let c = canonical(&p);
148        if c != target && seen.insert(c) {
149            if let Some(t) = modified(&p) {
150                found.push((t, p));
151            }
152        }
153    };
154    if let Ok(rd) = std::fs::read_dir(inp.home.join("channels")) {
155        for e in rd.flatten() {
156            push(e.path().join("identity-store.db"));
157        }
158    }
159    // `task dev` instance folders (`dev/<branch>/<clone>/`) are deliberately NOT
160    // scanned: every agent's dev builds make one, hundreds on a busy host, and
161    // their stores are throwaway test data. A dev channel's OWN store is still
162    // a source, through `instance_dir` below.
163    if let Some(dir) = inp.instance_dir {
164        push(dir.join("identity-store.db"));
165    }
166    // Newest first, so the first copy of an entry seen is the one that wins and
167    // an older copy is only a fallback for what is still missing.
168    found.sort_by_key(|(t, _)| std::cmp::Reverse(*t));
169
170    let mut accounts = Vec::new();
171    if let Some(dir) = inp.instance_dir {
172        let own = dir.join("identity-store.db");
173        if own.is_file() && !same_file(&own, inp.target_path) {
174            accounts.push(own);
175        }
176    }
177    if let Some(prefix) = build_prefix(inp.channel) {
178        let own_name = inp.channel;
179        let predecessor = found
180            .iter()
181            .filter(|(_, p)| {
182                p.parent()
183                    .and_then(|d| d.file_name())
184                    .and_then(|n| n.to_str())
185                    .is_some_and(|n| n != own_name && n.starts_with(prefix) && build_prefix(n).is_some())
186            })
187            // The build you upgraded from is the newest one that holds a login:
188            // a build that was only opened and closed has nothing to carry.
189            // `found` is newest first, so this opens stores only until the
190            // first one with a login, not every older build of the branch.
191            .find(|(_, p)| has_accounts(p))
192            .map(|(_, p)| p.clone());
193        if let Some(p) = predecessor {
194            if !accounts.iter().any(|q| same_file(q, &p)) {
195                accounts.push(p);
196            }
197        }
198    }
199    Sources { all: found.into_iter().map(|(_, p)| p).collect(), accounts }
200}
201
202/// Whether the store at `path` holds at least one account.
203fn has_accounts(path: &Path) -> bool {
204    open_source(path)
205        .ok()
206        .and_then(|c| c.query_row("SELECT COUNT(*) FROM db_accounts", [], |r| r.get::<_, i64>(0)).ok())
207        .is_some_and(|n| n > 0)
208}
209
210fn ms(t: Option<SystemTime>) -> u64 {
211    t.and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as u64)
212}
213
214fn stamp_of(path: &Path) -> Stamp {
215    let wal = PathBuf::from(format!("{}-wal", path.display()));
216    Stamp {
217        modified_ms: ms(modified(path)),
218        size: std::fs::metadata(path).map_or(0, |m| m.len()),
219        wal_modified_ms: ms(modified(&wal)),
220        wal_size: std::fs::metadata(&wal).map_or(0, |m| m.len()),
221    }
222}
223
224fn load_ledger(shared_dir: &Path) -> Ledger {
225    match std::fs::read_to_string(shared_dir.join(LEDGER_FILE)) {
226        Ok(s) => serde_json::from_str(&s).unwrap_or_else(|e| {
227            // Keep the unreadable file for inspection instead of overwriting it.
228            let aside = shared_dir.join(format!("{LEDGER_FILE}.corrupt"));
229            let _ = std::fs::rename(shared_dir.join(LEDGER_FILE), &aside);
230            tracing::warn!(error = %e, kept = %aside.display(), "adoption: ledger unreadable, starting a new one");
231            Ledger::default()
232        }),
233        Err(_) => Ledger::default(),
234    }
235}
236
237/// Write the ledger. Several channels share one machine now, so two boots can
238/// run at once: the file on disk is read again and merged first (keys only ever
239/// get added, so a union loses nothing another boot recorded), and the temp
240/// file is unique so two writers never interleave in one file.
241fn save_ledger(shared_dir: &Path, ledger: &Ledger) {
242    let mut merged = std::fs::read_to_string(shared_dir.join(LEDGER_FILE))
243        .ok()
244        .and_then(|s| serde_json::from_str::<Ledger>(&s).ok())
245        .unwrap_or_default();
246    merged.keys.extend(ledger.keys.iter().cloned());
247    for (k, v) in &ledger.sources {
248        merged.sources.insert(k.clone(), v.clone());
249    }
250    let n = TMP_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
251    let tmp = shared_dir.join(format!("{LEDGER_FILE}.{}.{n}.tmp", std::process::id()));
252    let ledger = &merged;
253    let result = serde_json::to_vec(ledger)
254        .map_err(|e| e.to_string())
255        .and_then(|b| std::fs::write(&tmp, b).map_err(|e| e.to_string()))
256        .and_then(|_| std::fs::rename(&tmp, shared_dir.join(LEDGER_FILE)).map_err(|e| e.to_string()));
257    if result.is_err() {
258        let _ = std::fs::remove_file(&tmp);
259    }
260    if let Err(e) = result {
261        tracing::warn!(error = %e, "adoption: could not save the ledger; the next boot repeats the pass");
262    }
263}
264
265fn open_source(path: &Path) -> rusqlite::Result<Connection> {
266    let c = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX)?;
267    c.busy_timeout(Duration::from_millis(500))?;
268    Ok(c)
269}
270
271fn table_cols(c: &Connection, table: &str) -> Vec<String> {
272    let Ok(mut stmt) = c.prepare(&format!("PRAGMA table_info({table})")) else { return Vec::new() };
273    stmt.query_map([], |r| r.get::<_, String>(1)).map(|rows| rows.flatten().collect()).unwrap_or_default()
274}
275
276fn quote_ident(s: &str) -> String {
277    format!("\"{}\"", s.replace('"', "\"\""))
278}
279
280fn quote_lit(s: &str) -> String {
281    format!("'{}'", s.replace('\'', "''"))
282}
283
284fn value_text(v: &Value) -> String {
285    match v {
286        Value::Null => String::new(),
287        Value::Integer(i) => i.to_string(),
288        Value::Real(f) => f.to_string(),
289        Value::Text(t) => t.clone(),
290        Value::Blob(b) => format!("blob{}", b.len()),
291    }
292}
293
294/// How one table is copied.
295struct Spec<'a> {
296    table: &'static str,
297    /// Ledger key prefix.
298    cat: &'static str,
299    key: &'a [&'static str],
300    /// An INTEGER column; a source row with a larger value replaces the target's.
301    newer: Option<&'static str>,
302    /// A WHERE clause over the source table.
303    filter: String,
304}
305
306#[derive(Default)]
307struct Copied {
308    added: Vec<Vec<String>>,
309    updated: Vec<Vec<String>>,
310    refused: usize,
311    deleted_stay_deleted: usize,
312}
313
314/// Copy `spec`'s rows from `src` into `dst`. Only columns both tables have are
315/// copied, so a source from an older or newer schema works.
316fn copy_table(src: &Connection, dst: &Connection, spec: &Spec, ledger: &mut Ledger) -> Copied {
317    let mut out = Copied::default();
318    let (sc, dc) = (table_cols(src, spec.table), table_cols(dst, spec.table));
319    if sc.is_empty() || dc.is_empty() || spec.key.iter().any(|k| !sc.contains(&k.to_string()) || !dc.contains(&k.to_string())) {
320        return out;
321    }
322    let cols: Vec<&String> = dc.iter().filter(|c| sc.contains(c)).collect();
323    let col_list = cols.iter().map(|c| quote_ident(c)).collect::<Vec<_>>().join(", ");
324    let sql = format!("SELECT {col_list} FROM {} WHERE {}", spec.table, spec.filter);
325    let rows: Vec<Vec<Value>> = match src.prepare(&sql).and_then(|mut s| {
326        let n = cols.len();
327        s.query_map([], |r| (0..n).map(|i| r.get::<_, Value>(i)).collect::<rusqlite::Result<Vec<_>>>())
328            .map(|it| it.flatten().collect())
329    }) {
330        Ok(r) => r,
331        Err(_) => return out,
332    };
333    let idx = |name: &str| cols.iter().position(|c| c.as_str() == name);
334    let key_idx: Vec<usize> = spec.key.iter().filter_map(|k| idx(k)).collect();
335    let where_key = spec.key.iter().enumerate().map(|(i, k)| format!("{} = ?{}", quote_ident(k), i + 1)).collect::<Vec<_>>().join(" AND ");
336    let placeholders = (1..=cols.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", ");
337    let insert_sql = format!("INSERT INTO {} ({col_list}) VALUES ({placeholders})", spec.table);
338    for row in rows {
339        let key_vals: Vec<Value> = key_idx.iter().map(|&i| row[i].clone()).collect();
340        let key_text: Vec<String> = key_vals.iter().map(value_text).collect();
341        let ledger_key = format!("{}:{}", spec.cat, key_text.join("|"));
342        let existing: Option<Value> = match spec.newer {
343            Some(n) => dst
344                .query_row(&format!("SELECT {} FROM {} WHERE {where_key}", quote_ident(n), spec.table), params_from_iter(key_vals.iter()), |r| r.get::<_, Value>(0))
345                .ok(),
346            None => dst
347                .query_row(&format!("SELECT 1 FROM {} WHERE {where_key}", spec.table), params_from_iter(key_vals.iter()), |r| r.get::<_, Value>(0))
348                .ok(),
349        };
350        match existing {
351            None => {
352                if ledger.keys.contains(&ledger_key) {
353                    out.deleted_stay_deleted += 1;
354                    continue;
355                }
356                match dst.execute(&insert_sql, params_from_iter(row.iter())) {
357                    Ok(_) => {
358                        ledger.keys.insert(ledger_key);
359                        out.added.push(key_text);
360                    }
361                    Err(_) => out.refused += 1,
362                }
363            }
364            Some(have) => {
365                ledger.keys.insert(ledger_key);
366                let (Some(n), Value::Integer(have_n)) = (spec.newer, &have) else { continue };
367                let Some(ni) = idx(n) else { continue };
368                let Value::Integer(src_n) = &row[ni] else { continue };
369                if src_n > have_n {
370                    let set_cols: Vec<usize> = (0..cols.len()).filter(|i| !key_idx.contains(i)).collect();
371                    if set_cols.is_empty() {
372                        continue;
373                    }
374                    let set = set_cols.iter().enumerate().map(|(j, &i)| format!("{} = ?{}", quote_ident(cols[i]), spec.key.len() + j + 1)).collect::<Vec<_>>().join(", ");
375                    let sql = format!("UPDATE {} SET {set} WHERE {where_key}", spec.table);
376                    let params: Vec<Value> = key_vals.iter().cloned().chain(set_cols.iter().map(|&i| row[i].clone())).collect();
377                    match dst.execute(&sql, params_from_iter(params.iter())) {
378                        Ok(_) => out.updated.push(key_text),
379                        Err(_) => out.refused += 1,
380                    }
381                }
382            }
383        }
384    }
385    out
386}
387
388fn in_list(values: impl Iterator<Item = String>) -> Option<String> {
389    let v: Vec<String> = values.map(|s| quote_lit(&s)).collect();
390    (!v.is_empty()).then(|| v.join(", "))
391}
392
393/// Global Memory and its versions, from one source.
394fn adopt_global_memory(src: &Connection, dst: &Connection, ledger: &mut Ledger, r: &mut Report) {
395    let has_system = table_cols(src, "db_bundles").iter().any(|c| c == "is_system");
396    let filter = if has_system { "is_global = 1 AND COALESCE(is_system, 0) = 0" } else { "is_global = 1" };
397    let c = copy_table(src, dst, &Spec { table: "db_bundles", cat: "gm", key: &["id"], newer: Some("updated_at"), filter: filter.into() }, ledger);
398    r.global_memory_added += c.added.len();
399    r.global_memory_updated += c.updated.len();
400    r.rows_refused += c.refused;
401    r.deleted_stay_deleted += c.deleted_stay_deleted;
402    let ids = c.added.iter().chain(c.updated.iter()).map(|k| k[0].clone());
403    if let Some(list) = in_list(ids) {
404        let v = copy_table(src, dst, &Spec { table: "db_bundle_versions", cat: "gmv", key: &["id"], newer: None, filter: format!("bundle_id IN ({list})") }, ledger);
405        r.rows_refused += v.refused;
406    }
407}
408
409/// Native memory and its versions, from one source.
410fn adopt_native_memory(src: &Connection, dst: &Connection, ledger: &mut Ledger, r: &mut Report) {
411    let c = copy_table(src, dst, &Spec { table: "db_agent_native_memory", cat: "nm", key: &["agent_id", "filename"], newer: Some("updated_at"), filter: "1 = 1".into() }, ledger);
412    r.native_memory_added += c.added.len();
413    r.native_memory_updated += c.updated.len();
414    r.rows_refused += c.refused;
415    r.deleted_stay_deleted += c.deleted_stay_deleted;
416    let pairs = c.added.iter().chain(c.updated.iter()).map(|k| format!("{}|{}", k[0], k[1]));
417    if let Some(list) = in_list(pairs) {
418        let v = copy_table(src, dst, &Spec { table: "db_agent_native_memory_versions", cat: "nmv", key: &["id"], newer: None, filter: format!("(agent_id || '|' || filename) IN ({list})") }, ledger);
419        r.rows_refused += v.refused;
420    }
421}
422
423/// Accounts, from one source. Per-agent cloud credentials are not adopted:
424/// they belong to the MuxBus account the source channel signed in as, which
425/// need not be this channel's, and they are provisioned again on first use.
426fn adopt_accounts(src: &Connection, dst: &Connection, ledger: &mut Ledger, r: &mut Report) {
427    let a = copy_table(src, dst, &Spec { table: "db_accounts", cat: "acct", key: &["id"], newer: None, filter: "1 = 1".into() }, ledger);
428    r.accounts_added += a.added.len();
429    r.rows_refused += a.refused;
430    r.deleted_stay_deleted += a.deleted_stay_deleted;
431}
432
433/// Run one pass into `target`. Never fails the boot: a source that cannot be
434/// read is counted and skipped, and a pass out of budget resumes next boot.
435pub(crate) fn adopt(target: &Store, inp: &Inputs) -> Report {
436    let started = Instant::now();
437    let mut report = Report::default();
438    let sources = discover_sources(inp);
439    let mut ledger = load_ledger(inp.shared_dir);
440    let conn = match target.conn().lock() {
441        Ok(c) => c,
442        Err(e) => e.into_inner(),
443    };
444    let accounts: HashSet<PathBuf> = sources.accounts.iter().map(|a| canonical(a)).collect();
445    for path in &sources.all {
446        if started.elapsed() > inp.budget {
447            report.budget_exhausted = true;
448            break;
449        }
450        let key = path.display().to_string();
451        let stamp = stamp_of(path);
452        let for_accounts = accounts.contains(&canonical(path));
453        // A source already processed in this role, unchanged since, is skipped.
454        // The role is part of the key so a source that later becomes a
455        // predecessor is still read for accounts.
456        let ledger_key = format!("{key}#{}", if for_accounts { "all+accounts" } else { "all" });
457        if ledger.sources.get(&ledger_key) == Some(&stamp) {
458            report.sources_unchanged += 1;
459            continue;
460        }
461        let src = match open_source(path) {
462            Ok(c) => c,
463            Err(e) => {
464                tracing::debug!(source = %path.display(), error = %e, "adoption: cannot open a source");
465                report.sources_failed += 1;
466                continue;
467            }
468        };
469        if conn.execute_batch("BEGIN IMMEDIATE").is_err() {
470            report.sources_failed += 1;
471            continue;
472        }
473        // Keys are recorded as rows go in; if the transaction does not commit
474        // the rows are gone, so the keys must go too. Otherwise they would
475        // read as "adopted, then deleted" and the rows would never come back.
476        let keys_before = ledger.keys.clone();
477        let report_before = report.clone();
478        adopt_global_memory(&src, &conn, &mut ledger, &mut report);
479        adopt_native_memory(&src, &conn, &mut ledger, &mut report);
480        if for_accounts {
481            adopt_accounts(&src, &conn, &mut ledger, &mut report);
482        }
483        if conn.execute_batch("COMMIT").is_err() {
484            let _ = conn.execute_batch("ROLLBACK");
485            ledger.keys = keys_before;
486            report = report_before;
487            report.sources_failed += 1;
488            continue;
489        }
490        ledger.sources.insert(ledger_key, stamp);
491        report.sources_read += 1;
492    }
493    drop(conn);
494    save_ledger(inp.shared_dir, &ledger);
495    report
496}
497
498/// The boot entry point, for a channel running with shared auth.
499pub fn run_at_boot(target: &Store, target_path: &Path) {
500    let Some(shared_dir) = crate::registry::resolve_global_shared_root() else { return };
501    let Some(home) = shared_dir.parent().map(Path::to_path_buf) else { return };
502    let channel = crate::backend::reactive::registry::local_channel_id();
503    let instance_dir = std::env::var_os("AGENTMUX_INSTANCE_DIR").map(PathBuf::from);
504    let inputs = Inputs {
505        home: &home,
506        shared_dir: &shared_dir,
507        channel: &channel,
508        instance_dir: instance_dir.as_deref(),
509        target_path,
510        budget: BOOT_BUDGET,
511    };
512    let started = Instant::now();
513    let r = adopt(target, &inputs);
514    if r.changed_anything() || r.sources_failed > 0 || r.budget_exhausted {
515        tracing::info!(
516            sources_read = r.sources_read,
517            sources_unchanged = r.sources_unchanged,
518            sources_failed = r.sources_failed,
519            global_memory = r.global_memory_added + r.global_memory_updated,
520            native_memory = r.native_memory_added + r.native_memory_updated,
521            accounts = r.accounts_added,
522            refused = r.rows_refused,
523            kept_deleted = r.deleted_stay_deleted,
524            budget_exhausted = r.budget_exhausted,
525            elapsed_ms = started.elapsed().as_millis() as u64,
526            "adoption: carried earlier per-channel auth state into the shared store"
527        );
528    } else {
529        tracing::debug!(sources_unchanged = r.sources_unchanged, "adoption: nothing new to carry over");
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536    use std::fs;
537
538    /// A shared-schema store at `path` (parents created).
539    fn store_at(path: &Path) -> Store {
540        fs::create_dir_all(path.parent().unwrap()).unwrap();
541        Store::open_shared(path).unwrap()
542    }
543
544    fn sql(s: &Store, q: &str) {
545        s.conn().lock().unwrap().execute_batch(q).unwrap();
546    }
547
548    fn count(s: &Store, q: &str) -> i64 {
549        s.conn().lock().unwrap().query_row(q, [], |r| r.get(0)).unwrap()
550    }
551
552    fn text(s: &Store, q: &str) -> String {
553        s.conn().lock().unwrap().query_row(q, [], |r| r.get(0)).unwrap()
554    }
555
556    fn bundle(s: &Store, id: &str, name: &str, global: bool, system: bool, updated: i64, body: &str) {
557        sql(
558            s,
559            &format!(
560                "INSERT INTO db_bundles (id, name, is_global, is_system, updated_at, instructions) \
561                 VALUES ('{id}', '{name}', {}, {}, {updated}, '{body}'); \
562                 INSERT INTO db_bundle_versions (id, bundle_id, name, instructions, content_hash) \
563                 VALUES ('v-{id}-{updated}', '{id}', '{name}', '{body}', 'h{updated}');",
564                global as i32, system as i32
565            ),
566        );
567    }
568
569    fn native(s: &Store, agent: &str, file: &str, updated: i64, body: &str) {
570        sql(
571            s,
572            &format!(
573                "INSERT INTO db_agent_native_memory (agent_id, filename, content, updated_at) \
574                 VALUES ('{agent}', '{file}', '{body}', {updated}); \
575                 INSERT INTO db_agent_native_memory_versions (id, agent_id, filename, content, content_hash, created_at) \
576                 VALUES ('nv-{agent}-{file}-{updated}', '{agent}', '{file}', '{body}', 'h{updated}', {updated});"
577            ),
578        );
579    }
580
581    fn account(s: &Store, id: &str) {
582        sql(
583            s,
584            &format!(
585                "INSERT INTO db_accounts (id, name, provider, kind, secret_ref) \
586                 VALUES ('{id}', 'acct-{id}', 'claude', 'oauth', '{{\"type\":\"OAuthConfigDir\",\"dir\":\"/old/{id}\"}}')"
587            ),
588        );
589    }
590
591    fn credential(s: &Store, agent: &str) {
592        sql(s, &format!("INSERT INTO db_agent_credentials (agent_id, client_id) VALUES ('{agent}', 'client-{agent}')"));
593    }
594
595    struct Fixture {
596        _tmp: tempfile::TempDir,
597        home: PathBuf,
598        shared: PathBuf,
599        target_path: PathBuf,
600        target: Store,
601    }
602
603    impl Fixture {
604        fn new() -> Self {
605            let tmp = tempfile::tempdir().unwrap();
606            let home = tmp.path().to_path_buf();
607            let shared = home.join("shared");
608            let target_path = shared.join("store.db");
609            let target = store_at(&target_path);
610            Fixture { _tmp: tmp, home, shared, target_path, target }
611        }
612
613        fn channel_store(&self, channel: &str) -> Store {
614            store_at(&self.home.join("channels").join(channel).join("identity-store.db"))
615        }
616
617        fn store_path(&self, channel: &str) -> PathBuf {
618            self.home.join("channels").join(channel).join("identity-store.db")
619        }
620
621        fn run(&self, channel: &str) -> Report {
622            let instance = self.home.join("channels").join(channel);
623            let inputs = Inputs {
624                home: &self.home,
625                shared_dir: &self.shared,
626                channel,
627                instance_dir: Some(&instance),
628                target_path: &self.target_path,
629                budget: Duration::from_secs(30),
630            };
631            adopt(&self.target, &inputs)
632        }
633    }
634
635    fn set_age(path: &Path, secs_ago: u64) {
636        let f = fs::OpenOptions::new().write(true).open(path).unwrap();
637        f.set_modified(SystemTime::now() - Duration::from_secs(secs_ago)).unwrap();
638    }
639
640    #[test]
641    fn a_build_channel_names_its_branch_prefix() {
642        assert_eq!(build_prefix("local-main-b28b7a-051fbf53"), Some("local-main-b28b7a-"));
643        assert_eq!(
644            build_prefix("local-agent1-release-patch-bump-abe85c-306df097"),
645            Some("local-agent1-release-patch-bump-abe85c-")
646        );
647        // not a per-build channel: no 8-hex suffix, or not a local- build
648        assert_eq!(build_prefix("stable"), None);
649        assert_eq!(build_prefix("dev-some-branch"), None);
650        assert_eq!(build_prefix("local-main-b28b7a-xyz"), None);
651        assert_eq!(build_prefix("custom-channel-051fbf53"), None);
652    }
653
654    #[test]
655    fn the_predecessor_is_the_newest_other_build_of_the_same_branch() {
656        let f = Fixture::new();
657        for ch in ["local-main-b28b7a-00000001", "local-main-b28b7a-00000002", "local-main-b28b7a-00000003", "local-other-111111-00000004"] {
658            account(&f.channel_store(ch), &format!("acct-in-{ch}"));
659        }
660        for (ch, age) in [
661            ("local-main-b28b7a-00000001", 900),
662            ("local-main-b28b7a-00000002", 500),
663            ("local-main-b28b7a-00000003", 10),
664            ("local-other-111111-00000004", 100),
665        ] {
666            set_age(&f.store_path(ch), age);
667        }
668        let instance = f.home.join("channels/local-main-b28b7a-00000003");
669        let inputs = Inputs {
670            home: &f.home,
671            shared_dir: &f.shared,
672            channel: "local-main-b28b7a-00000003",
673            instance_dir: Some(&instance),
674            target_path: &f.target_path,
675            budget: Duration::from_secs(5),
676        };
677        let s = discover_sources(&inputs);
678        let names: Vec<String> =
679            s.accounts.iter().map(|p| p.parent().unwrap().file_name().unwrap().to_string_lossy().into_owned()).collect();
680        // its own store, then the newest OTHER build of the same branch (not the other branch's, not the older one)
681        assert_eq!(names, ["local-main-b28b7a-00000003", "local-main-b28b7a-00000002"]);
682        // every channel store is a source for memory, newest first, and the target is never one
683        assert_eq!(s.all.len(), 4);
684        assert!(s.all.windows(2).all(|w| modified(&w[0]) >= modified(&w[1])));
685        assert!(!s.all.iter().any(|p| same_file(p, &f.target_path)));
686    }
687
688    #[test]
689    fn a_build_that_holds_no_login_is_passed_over_as_the_predecessor() {
690        let f = Fixture::new();
691        // the newest other build was only opened and closed; the one before it holds the login
692        let old = f.channel_store("local-main-b28b7a-00000001");
693        account(&old, "acct-real");
694        f.channel_store("local-main-b28b7a-00000002");
695        f.channel_store("local-main-b28b7a-00000003");
696        set_age(&f.store_path("local-main-b28b7a-00000001"), 900);
697        set_age(&f.store_path("local-main-b28b7a-00000002"), 100);
698        let instance = f.home.join("channels/local-main-b28b7a-00000003");
699        let inputs = Inputs {
700            home: &f.home,
701            shared_dir: &f.shared,
702            channel: "local-main-b28b7a-00000003",
703            instance_dir: Some(&instance),
704            target_path: &f.target_path,
705            budget: Duration::from_secs(5),
706        };
707        let s = discover_sources(&inputs);
708        let names: Vec<String> =
709            s.accounts.iter().map(|p| p.parent().unwrap().file_name().unwrap().to_string_lossy().into_owned()).collect();
710        assert_eq!(names, ["local-main-b28b7a-00000003", "local-main-b28b7a-00000001"]);
711        let r = adopt(&f.target, &inputs);
712        assert_eq!(r.accounts_added, 1, "{r:?}");
713    }
714
715    #[test]
716    fn global_memory_is_unioned_newest_wins_and_leaves_the_rest_behind() {
717        let f = Fixture::new();
718        let a = f.channel_store("local-main-b28b7a-0000000a");
719        let b = f.channel_store("local-main-b28b7a-0000000b");
720        set_age(&f.store_path("local-main-b28b7a-0000000a"), 200);
721        set_age(&f.store_path("local-main-b28b7a-0000000b"), 100);
722        bundle(&a, "gm-x", "GitHub and AWS access", true, false, 10, "old text");
723        bundle(&a, "junk-1", "Camper - ABF", false, false, 10, "a per-agent bundle");
724        bundle(&b, "gm-x", "GitHub and AWS access", true, false, 20, "newer text");
725        bundle(&b, "gm-y", "Use gh-agent", true, false, 5, "second entry");
726        bundle(&b, "sys-1", "System global", true, true, 5, "seeded by the app");
727
728        let r = f.run("local-main-b28b7a-0000000c");
729        assert_eq!(r.global_memory_added, 2, "{r:?}");
730        // (a fresh shared store seeds its own `blank` bundle, which is not ours to count)
731        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_bundles WHERE id <> 'blank'"), 2);
732        assert_eq!(
733            text(&f.target, "SELECT instructions FROM db_bundles WHERE id = 'gm-x'"),
734            "newer text",
735            "the newest copy wins"
736        );
737        assert_eq!(
738            count(&f.target, "SELECT COUNT(*) FROM db_bundles WHERE id IN ('junk-1', 'sys-1')"),
739            0,
740            "non-global and system bundles stay behind"
741        );
742        assert!(
743            count(&f.target, "SELECT COUNT(*) FROM db_bundle_versions WHERE bundle_id = 'gm-x'") >= 1,
744            "versions come along"
745        );
746        // read-only on the sources
747        assert_eq!(count(&a, "SELECT COUNT(*) FROM db_bundles WHERE id = 'gm-x'"), 1);
748        assert_eq!(count(&a, "SELECT COUNT(*) FROM db_bundles WHERE id <> 'blank'"), 2, "nothing was removed from the source");
749    }
750
751    #[test]
752    fn native_memory_is_unioned_by_agent_and_file_newest_wins() {
753        let f = Fixture::new();
754        let a = f.channel_store("local-main-b28b7a-0000000a");
755        let b = f.channel_store("local-main-b28b7a-0000000b");
756        set_age(&f.store_path("local-main-b28b7a-0000000a"), 200);
757        native(&a, "agent-1", "notes.md", 5, "older notes");
758        native(&a, "agent-1", "only-in-a.md", 5, "a own");
759        native(&b, "agent-1", "notes.md", 9, "newer notes");
760        native(&b, "agent-2", "other.md", 1, "b own");
761
762        let r = f.run("local-main-b28b7a-0000000c");
763        assert_eq!(r.native_memory_added, 3, "{r:?}");
764        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_agent_native_memory"), 3);
765        assert_eq!(
766            text(&f.target, "SELECT content FROM db_agent_native_memory WHERE agent_id='agent-1' AND filename='notes.md'"),
767            "newer notes"
768        );
769        assert!(count(&f.target, "SELECT COUNT(*) FROM db_agent_native_memory_versions") >= 3);
770    }
771
772    #[test]
773    fn accounts_come_only_from_this_channel_and_its_predecessor_and_credentials_not_at_all() {
774        let f = Fixture::new();
775        let own = f.channel_store("local-main-b28b7a-0000000c");
776        let pred = f.channel_store("local-main-b28b7a-0000000b");
777        let stranger = f.channel_store("local-main-b28b7a-0000000a");
778        let other_branch = f.channel_store("local-other-111111-0000000d");
779        set_age(&f.store_path("local-main-b28b7a-0000000a"), 300);
780        set_age(&f.store_path("local-main-b28b7a-0000000b"), 100);
781        set_age(&f.store_path("local-other-111111-0000000d"), 50);
782        account(&own, "acct-own");
783        credential(&own, "agent-own");
784        account(&pred, "acct-pred");
785        credential(&pred, "agent-pred");
786        account(&stranger, "acct-stranger");
787        credential(&stranger, "agent-stranger");
788        account(&other_branch, "acct-other-branch");
789
790        let r = f.run("local-main-b28b7a-0000000c");
791        assert_eq!(r.accounts_added, 2, "{r:?}");
792        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_agent_credentials"), 0, "credentials are not adopted");
793        let ids = text(&f.target, "SELECT group_concat(id) FROM (SELECT id FROM db_accounts ORDER BY id)");
794        assert_eq!(ids, "acct-own,acct-pred");
795        // the stored folder still points at the source channel, so the login works at once
796        assert!(text(&f.target, "SELECT secret_ref FROM db_accounts WHERE id='acct-pred'").contains("/old/acct-pred"));
797    }
798
799    #[test]
800    fn a_second_pass_reads_nothing_and_changes_nothing() {
801        let f = Fixture::new();
802        let a = f.channel_store("local-main-b28b7a-0000000a");
803        bundle(&a, "gm-x", "Entry", true, false, 10, "text");
804        native(&a, "agent-1", "n.md", 1, "x");
805        let first = f.run("local-main-b28b7a-0000000c");
806        assert!(first.changed_anything() && first.sources_read >= 1);
807        let second = f.run("local-main-b28b7a-0000000c");
808        assert!(!second.changed_anything(), "{second:?}");
809        assert_eq!(second.sources_read, 0, "an unchanged source is not reopened: {second:?}");
810        assert!(second.sources_unchanged >= 1);
811    }
812
813    #[test]
814    fn something_deleted_after_adoption_is_not_put_back() {
815        let f = Fixture::new();
816        let pred = f.channel_store("local-main-b28b7a-0000000b");
817        f.channel_store("local-main-b28b7a-0000000c");
818        account(&pred, "acct-pred");
819        bundle(&pred, "gm-x", "Entry", true, false, 10, "text");
820        native(&pred, "agent-1", "n.md", 1, "x");
821        let r = f.run("local-main-b28b7a-0000000c");
822        assert_eq!((r.accounts_added, r.global_memory_added, r.native_memory_added), (1, 1, 1), "{r:?}");
823
824        // the owner deletes all three from the shared store...
825        sql(
826            &f.target,
827            "DELETE FROM db_accounts; DELETE FROM db_bundle_versions; DELETE FROM db_bundles; DELETE FROM db_agent_native_memory;",
828        );
829        // ...and the source changes (the old build is still running and writes something)
830        native(&pred, "agent-9", "later.md", 2, "new unrelated entry");
831        set_age(&f.store_path("local-main-b28b7a-0000000b"), 1);
832        let r2 = f.run("local-main-b28b7a-0000000c");
833        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_accounts"), 0, "{r2:?}");
834        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_bundles"), 0);
835        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_agent_native_memory WHERE agent_id = 'agent-1'"), 0);
836        assert_eq!(
837            count(&f.target, "SELECT COUNT(*) FROM db_agent_native_memory WHERE agent_id = 'agent-9'"),
838            1,
839            "genuinely new data still arrives"
840        );
841        assert!(r2.deleted_stay_deleted >= 3, "{r2:?}");
842    }
843
844    #[test]
845    fn a_name_the_target_already_has_under_another_id_is_refused_not_fatal() {
846        let f = Fixture::new();
847        bundle(&f.target, "mine", "Same name", true, false, 1, "target own");
848        let a = f.channel_store("local-main-b28b7a-0000000a");
849        bundle(&a, "theirs", "Same name", true, false, 99, "source copy");
850        bundle(&a, "gm-ok", "Different name", true, false, 1, "fine");
851        let r = f.run("local-main-b28b7a-0000000c");
852        assert_eq!(r.rows_refused, 1, "{r:?}");
853        assert_eq!(r.global_memory_added, 1);
854        assert_eq!(text(&f.target, "SELECT instructions FROM db_bundles WHERE name='Same name'"), "target own");
855    }
856
857    #[test]
858    fn a_source_with_an_older_schema_is_still_read() {
859        let f = Fixture::new();
860        // an old per-channel store: no is_system column, fewer bundle columns, no versions table
861        let dir = f.home.join("channels/local-main-b28b7a-0000000a");
862        fs::create_dir_all(&dir).unwrap();
863        let old = Connection::open(dir.join("identity-store.db")).unwrap();
864        old.execute_batch(
865            "CREATE TABLE db_bundles (id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, is_global INTEGER NOT NULL DEFAULT 0, instructions TEXT NOT NULL DEFAULT '', updated_at INTEGER NOT NULL DEFAULT 0);
866             INSERT INTO db_bundles (id, name, is_global, instructions, updated_at) VALUES ('gm-old', 'Old entry', 1, 'from an old build', 3);
867             CREATE TABLE db_agent_native_memory (agent_id TEXT NOT NULL, filename TEXT NOT NULL, content TEXT NOT NULL, updated_at INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (agent_id, filename));
868             INSERT INTO db_agent_native_memory VALUES ('agent-1', 'f.md', 'old memory', 3);",
869        )
870        .unwrap();
871        drop(old);
872        let r = f.run("local-main-b28b7a-0000000c");
873        assert_eq!((r.global_memory_added, r.native_memory_added), (1, 1), "{r:?}");
874        assert_eq!(text(&f.target, "SELECT instructions FROM db_bundles WHERE id='gm-old'"), "from an old build");
875    }
876
877    #[test]
878    fn a_broken_source_is_counted_and_the_pass_carries_on() {
879        let f = Fixture::new();
880        let dir = f.home.join("channels/local-main-b28b7a-0000000a");
881        fs::create_dir_all(&dir).unwrap();
882        fs::write(dir.join("identity-store.db"), b"this is not a sqlite database at all").unwrap();
883        let good = f.channel_store("local-main-b28b7a-0000000b");
884        bundle(&good, "gm-x", "Entry", true, false, 1, "text");
885        let r = f.run("local-main-b28b7a-0000000c");
886        assert_eq!(r.global_memory_added, 1, "{r:?}");
887    }
888
889    #[test]
890    fn the_shared_store_is_never_read_as_a_source() {
891        let f = Fixture::new();
892        // a store at a channel path that IS the target
893        bundle(&f.target, "gm-own", "Already shared", true, false, 1, "x");
894        let inputs = Inputs {
895            home: &f.home,
896            shared_dir: &f.shared,
897            channel: "local-main-b28b7a-0000000c",
898            instance_dir: None,
899            target_path: &f.target_path,
900            budget: Duration::from_secs(5),
901        };
902        // the target lives under shared/, outside channels/, and is excluded even if listed
903        let s = discover_sources(&inputs);
904        assert!(s.all.is_empty() && s.accounts.is_empty());
905        let r = adopt(&f.target, &inputs);
906        assert_eq!(r.sources_read, 0, "{r:?}");
907        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_bundles WHERE id <> 'blank'"), 1);
908    }
909
910    #[test]
911    fn a_source_whose_commit_fails_leaves_no_ledger_trace_and_is_retried() {
912        let f = Fixture::new();
913        let a = f.channel_store("local-main-b28b7a-0000000a");
914        bundle(&a, "gm-x", "Entry", true, false, 10, "text");
915        // A deferred foreign key violated by a trigger makes COMMIT (not the INSERT) fail.
916        sql(
917            &f.target,
918            "CREATE TABLE fk_parent (id TEXT PRIMARY KEY);
919             CREATE TABLE fk_child (pid TEXT REFERENCES fk_parent(id) DEFERRABLE INITIALLY DEFERRED);
920             CREATE TRIGGER break_commit AFTER INSERT ON db_bundles BEGIN INSERT INTO fk_child VALUES ('missing'); END;",
921        );
922        let r = f.run("local-main-b28b7a-0000000c");
923        assert_eq!(r.sources_failed, 1, "{r:?}");
924        assert_eq!(r.global_memory_added, 0, "a rolled-back source counts nothing: {r:?}");
925        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_bundles WHERE id <> 'blank'"), 0);
926
927        // The keys must not have been recorded, or the retry would read them as "deleted".
928        sql(&f.target, "DROP TRIGGER break_commit");
929        let again = f.run("local-main-b28b7a-0000000c");
930        assert_eq!(again.global_memory_added, 1, "{again:?}");
931        assert_eq!(again.deleted_stay_deleted, 0, "{again:?}");
932        assert_eq!(count(&f.target, "SELECT COUNT(*) FROM db_bundles WHERE id = 'gm-x'"), 1);
933    }
934
935    #[test]
936    fn two_boots_saving_the_ledger_merge_instead_of_overwriting() {
937        let f = Fixture::new();
938        let mut one = Ledger::default();
939        one.keys.insert("gm:one".into());
940        let mut two = Ledger::default();
941        two.keys.insert("gm:two".into());
942        save_ledger(&f.shared, &one);
943        // the second boot never saw the first one's keys
944        save_ledger(&f.shared, &two);
945        let saved = load_ledger(&f.shared);
946        assert!(saved.keys.contains("gm:one") && saved.keys.contains("gm:two"), "{:?}", saved.keys);
947        let leftovers: Vec<_> = fs::read_dir(&f.shared)
948            .unwrap()
949            .flatten()
950            .map(|e| e.file_name().to_string_lossy().into_owned())
951            .filter(|n| n.ends_with(".tmp"))
952            .collect();
953        assert!(leftovers.is_empty(), "temp files left behind: {leftovers:?}");
954    }
955
956    #[test]
957    fn an_unreadable_ledger_is_kept_aside_not_overwritten() {
958        let f = Fixture::new();
959        fs::write(f.shared.join(LEDGER_FILE), b"{ this is not json").unwrap();
960        let ledger = load_ledger(&f.shared);
961        assert!(ledger.keys.is_empty());
962        assert!(f.shared.join(format!("{LEDGER_FILE}.corrupt")).is_file(), "the unreadable file is kept for inspection");
963    }
964
965    /// Phase 0 of `SPEC_SHARED_AUTH_ACROSS_CHANNELS_2026_10_03.md`: run the real
966    /// pass over a real `~/.agentmux` into a throwaway store and print what it
967    /// would carry over, counts only. The sources are opened read-only and the
968    /// target is a temp file, so nothing real is written.
969    ///
970    /// ```text
971    /// AGENTMUX_ADOPTION_DRYRUN_HOME=~/.agentmux
972    /// AGENTMUX_ADOPTION_DRYRUN_CHANNEL=local-main-b28b7a-ffffffff
973    /// cargo test -p agentmux-srv-core --lib -- --ignored --nocapture adoption_dry_run
974    /// ```
975    #[test]
976    #[ignore = "reads a real home; run by hand"]
977    fn adoption_dry_run_against_a_real_home() {
978        let Some(home) = std::env::var_os("AGENTMUX_ADOPTION_DRYRUN_HOME").map(PathBuf::from) else {
979            eprintln!("AGENTMUX_ADOPTION_DRYRUN_HOME is not set; nothing to do");
980            return;
981        };
982        let channel = std::env::var("AGENTMUX_ADOPTION_DRYRUN_CHANNEL").unwrap_or_else(|_| "local-main-b28b7a-ffffffff".into());
983        let tmp = tempfile::tempdir().unwrap();
984        let shared = tmp.path().join("shared");
985        let target_path = shared.join("store.db");
986        let target = store_at(&target_path);
987        let instance = tmp.path().join("this-channel");
988        let inputs = Inputs { home: &home, shared_dir: &shared, channel: &channel, instance_dir: Some(&instance), target_path: &target_path, budget: Duration::from_secs(120) };
989        let src = discover_sources(&inputs);
990        eprintln!("sources: {} (accounts from {} of them)", src.all.len(), src.accounts.len());
991        for p in &src.accounts {
992            eprintln!("  accounts from: {}", p.parent().and_then(|d| d.file_name()).unwrap().to_string_lossy());
993        }
994        let started = Instant::now();
995        let r = adopt(&target, &inputs);
996        eprintln!("{r:#?}
997elapsed: {} ms", started.elapsed().as_millis());
998        eprintln!(
999            "target now holds: {} global memory, {} native memory, {} accounts, {} agent credentials",
1000            count(&target, "SELECT COUNT(*) FROM db_bundles WHERE is_global = 1 AND is_system = 0"),
1001            count(&target, "SELECT COUNT(*) FROM db_agent_native_memory"),
1002            count(&target, "SELECT COUNT(*) FROM db_accounts"),
1003            count(&target, "SELECT COUNT(*) FROM db_agent_credentials"),
1004        );
1005    }
1006}