Skip to main content

agentmux_srv_core/backend/storage/
identities.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Identity subsystem — accounts and the direct junction that ties
5//! them to agents.
6//!
7//! Layered model:
8//! - **`IdentityAccount`** (`db_accounts`): a single credential
9//!   pointer (provider + kind + secret_ref).
10//! - **`AgentIdentityLink`** (`db_agent_identity_links`): the sole
11//!   credential-resolution path — binds an agent (definition) to an
12//!   account directly, per provider.
13//!
14//! The Identity *bundle* layer (`Identity`/`IdentityBinding`,
15//! `db_identity_bundles`/`db_identity_bindings`) was retired in Phase 4c
16//! of `SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md` — direct links had
17//! already fully superseded it as the credential-resolution path (see
18//! `identity/resolver/inject.rs::resolve_bindings_for_instance`).
19//!
20//! Extracted from `store.rs` in Phase R.2 of the storage
21//! modularization plan
22//! (`docs/specs/SPEC_STORE_MODULARIZATION_2026_05_27.md`). The
23//! method surface is unchanged — `Store::identity_*` and
24//! `agent_identity_*` still live on `Store` via this `impl` block;
25//! existing imports of the structs from `storage::store::*` keep
26//! working thanks to re-exports.
27
28use rusqlite::params;
29use serde::{Deserialize, Serialize};
30
31use super::error::StoreError;
32use super::store::Store;
33
34/// The account's mark (in `context`): never move an agent onto it by itself.
35/// `server::account_episodes::failover` re-exports it.
36pub const NEVER_FAILOVER: &str = "never_failover";
37
38/// Provider-specific credential reference. Stored as JSON in
39/// `db_accounts.secret_ref`. `backend` is the discriminator.
40/// The actual secret value is NEVER stored in the DB — only how to
41/// look it up at launch time (env var, secrets-manager path, etc.).
42/// `PlaintextDev` exists for local dev convenience and must never be
43/// the default path in production builds.
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
45#[ts(export, export_to = "../../../frontend/types/rpc/")]
46#[serde(tag = "backend", rename_all = "snake_case")]
47pub enum SecretRef {
48    Env {
49        env_var: String,
50    },
51    SecretsManager {
52        sm_path: String,
53        #[serde(default, skip_serializing_if = "Option::is_none")]
54        #[ts(optional)]
55        sm_json_path: Option<String>,
56    },
57    PlaintextDev {
58        plaintext_dev: String,
59    },
60    /// **OAuth credentials stored as a filesystem pointer.** The CLI
61    /// (Claude Code, codex, openclaw, …) reads its OAuth tokens from
62    /// this directory at spawn time — agentmux only holds the path,
63    /// never the tokens themselves. Token refresh is the CLI's job;
64    /// the path stays stable across refreshes. Used by oauth-class
65    /// providers; the resolver (PR B) dispatches to a config-dir
66    /// env-var injection mode rather than the api-key env-var path.
67    /// See `docs/specs/archive/SPEC_OAUTH_IDENTITY_BUNDLES_2026_05_22.md`.
68    ///
69    /// Explicit `rename` — the enum-wide `rename_all = "snake_case"` splits
70    /// at every capital letter, including inside "OAuth" itself, producing
71    /// `o_auth_config_dir` (verified: that's what a live deserialization
72    /// failure actually expected). Every real account on disk was written
73    /// with `oauth_config_dir` (no extra underscore — how "OAuth" is
74    /// conventionally spelled), so the derived name silently stopped
75    /// matching stored data — this makes the wire format explicit instead
76    /// of relying on the derive macro to guess right for an acronym.
77    ///
78    /// The `alias` keeps accepting the derive-produced `o_auth_config_dir`
79    /// tag too: any account persisted by a backend running between this
80    /// variant's introduction and this fix would have round-tripped
81    /// self-consistently under that buggy tag, and `identity_list()` aborts
82    /// entirely on the first unparseable row — so dropping read support for
83    /// it would just move the "My Agents empty" incident to a different set
84    /// of accounts. Serialization always writes the canonical
85    /// `oauth_config_dir`; only deserialization accepts both.
86    /// ts-rs does NOT pick up the `serde(rename)` above — it emits the
87    /// derive-default `o_auth_config_dir`, i.e. exactly the legacy tag this
88    /// rename exists to stop writing. Without the `ts(rename)` below, the
89    /// generated binding would tell the frontend to discriminate on a tag the
90    /// server never serializes, silently reintroducing the "My Agents empty"
91    /// incident described above. No CI gate catches this: tsc passes (the
92    /// union simply never matches at runtime) and check-rpc-bindings passes
93    /// (the type exists and is current).
94    #[serde(rename = "oauth_config_dir", alias = "o_auth_config_dir")]
95    OAuthConfigDir {
96        /// Absolute path to the per-bundle, per-provider config
97        /// directory — e.g. `~/.agentmux/shared/identities/<id>/claude/`,
98        /// or the legacy `~/.claude/` for the Default migration bundle
99        /// (PR E).
100        dir: String,
101    },
102    /// **API key / token stored in the OS-native secret store** (macOS
103    /// Keychain / Windows Credential Manager / Linux Secret Service),
104    /// addressed by `(service, account)`. The plaintext is NEVER held in
105    /// the DB — only this pointer. Written by the account key flow
106    /// after a successful live validation; resolved to the real value at
107    /// agent spawn time via `crate::identity::secret_store`. See
108    /// docs/specs/archive/SPEC_TRUST_CENTER_2026_06_15.md §7/§12.2.
109    Keychain {
110        /// Keychain service string — always `"agentmux"`.
111        service: String,
112        /// Keychain account string — `"acct:<account_id>"`.
113        account: String,
114    },
115    /// **API key kept as an `api-key` entry of the Vault**, addressed by the entry's id. Written when a key is added in
116    /// Connectors > Accounts; the key is sealed in the entry and never held in the DB. Resolved with the Vault store
117    /// (`vault::account_key`); an account made before this holds `Keychain` and still reads from there.
118    Vault {
119        /// The Vault entry's id.
120        entry: String,
121        #[serde(default, skip_serializing_if = "Option::is_none")]
122        #[ts(optional)]
123        link_id: Option<String>,
124    },
125}
126
127/// An identity account (reusable credential, linked to agents via the
128/// `db_agent_identity_links` junction). Replaces the browser
129/// localStorage identity store.
130#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
131#[ts(export, export_to = "../../../frontend/types/rpc/")]
132pub struct IdentityAccount {
133    pub id: String,
134    pub name: String,
135    pub provider: String, // "github" | "aws" | "anthropic" | "custom"
136    pub kind: String,     // "pat" | "role" | "api_key" | "env_ref"
137    #[serde(default)]
138    pub display_name: String,
139    pub secret_ref: SecretRef,
140    /// Free-form JSON context (username, scopes, role ARN, etc.). Stored
141    /// verbatim; frontend types it by `provider`.
142    /// ts-rs has no `TS` impl for `serde_json::Value`, so this needs an
143    /// explicit type. `Record<string, unknown>` rather than bare `unknown`:
144    /// `default_context_json` is `{}` and every writer stores an object, so
145    /// the hand-written declaration's narrower type was accurate and emitting
146    /// `unknown` would lose real information (the same mistake a bare
147    /// `string` would be for a closed-set field).
148    #[serde(default = "default_context_json")]
149    #[ts(type = "Record<string, unknown>")]
150    pub context: serde_json::Value,
151    #[serde(default = "default_identity_status")]
152    pub status: String, // "unknown" | "ok" | "expired" | "invalid"
153    // `#[serde(default)]` — the `upsertidentityaccount` handler (agent_handlers/
154    // identity.rs) server-stamps both fields with `now` when they're `0`, but
155    // that logic runs AFTER `serde_json::from_value` succeeds. Every real
156    // frontend caller (persistSeededAccount, register-seeded-account.ts) omits
157    // both fields entirely, expecting the server to fill them in — without
158    // `default` here, deserialization rejects the payload before the handler's
159    // own timestamp logic ever runs, so every login's account-persist call
160    // failed 100% of the time with no visible
161    // error (report: REPORT_LOGIN_PERSIST_FAILURE_AND_STUCK_WORKING_2026_07_27.md).
162    #[serde(default)]
163    #[ts(type = "number")]
164    pub created_at: i64,
165    #[serde(default)]
166    #[ts(type = "number")]
167    pub updated_at: i64,
168}
169
170fn default_context_json() -> serde_json::Value {
171    serde_json::json!({})
172}
173
174fn default_identity_status() -> String {
175    "unknown".to_string()
176}
177
178/// Junction row: which identity an agent uses for a given provider.
179#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
180#[ts(export, export_to = "../../../frontend/types/rpc/")]
181pub struct AgentIdentityLink {
182    pub agent_id: String,
183    pub account_id: String,
184    pub provider: String,
185}
186
187/// What [`Store::identity_delete`] removed — the account row plus the
188/// cascaded `db_agent_identity_links` junction rows. Consumed by the
189/// `deleteidentityaccount` handler for `identity.delete:` logging and
190/// the layer-2/4 affected-agent disclosure
191/// (`SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md` §3/§4).
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct IdentityDeleteOutcome {
194    /// True iff the `db_accounts` row existed and was deleted.
195    pub deleted: bool,
196    /// Number of `db_agent_identity_links` rows removed in the same
197    /// transaction.
198    pub links_cascaded: usize,
199    /// The `agent_id`s whose links were cascaded — captured by SELECT
200    /// inside the same transaction, BEFORE the delete, so the set is
201    /// exact even though the rows are gone by the time this returns.
202    /// Any of these agents that has a live process still holds working
203    /// tokens until restarted; the handler publishes a per-agent
204    /// revocation event so the UI can disclose that (spec §3).
205    pub affected_agents: Vec<String>,
206}
207
208impl Store {
209    // ---- Identity account CRUD ----
210
211    /// List identity accounts. If `provider` is `Some`, filter to that
212    /// provider; otherwise return every account, ordered by most recent
213    /// update first (so the identity panel shows live accounts on top).
214    ///
215    /// A row whose `secret_ref`/`context` JSON fails to parse is skipped
216    /// (logged with its account id) rather than aborting the whole query —
217    /// one corrupted row must never hide every other account. This is the
218    /// isolation the `oauth_config_dir` tag-alias comment above already
219    /// flagged as missing ("`identity_list()` aborts entirely on the first
220    /// unparseable row") after that incident; this closes it at the source
221    /// instead of only patching the one wire-format mismatch that triggered
222    /// it. See `ANALYSIS_ARMORY_STASH_CREDENTIAL_VISIBILITY_GAP_2026_08_04 (never committed to this repo)`.
223    pub fn identity_list(
224        &self,
225        provider: Option<&str>,
226    ) -> Result<Vec<IdentityAccount>, StoreError> {
227        let conn = self.conn.lock().unwrap();
228        let mut rows_vec = Vec::new();
229        let map_row = |row: &rusqlite::Row| -> rusqlite::Result<IdentityAccount> {
230            let id: String = row.get(0)?;
231            let secret_ref_json: String = row.get(5)?;
232            let context_json: String = row.get(6)?;
233            let secret_ref = match serde_json::from_str(&secret_ref_json) {
234                Ok(s) => s,
235                Err(e) => {
236                    tracing::warn!(
237                        target: "identity",
238                        account_id = %id,
239                        error = %e,
240                        "identity_list: skipping account with malformed secret_ref JSON",
241                    );
242                    return Err(rusqlite::Error::FromSqlConversionFailure(
243                        5,
244                        rusqlite::types::Type::Text,
245                        Box::new(e),
246                    ));
247                }
248            };
249            Ok(IdentityAccount {
250                id,
251                name: row.get(1)?,
252                provider: row.get(2)?,
253                kind: row.get(3)?,
254                display_name: row.get(4)?,
255                secret_ref,
256                context: serde_json::from_str(&context_json)
257                    .unwrap_or_else(|_| serde_json::json!({})),
258                status: row.get(7)?,
259                created_at: row.get(8)?,
260                updated_at: row.get(9)?,
261            })
262        };
263        match provider {
264            Some(p) => {
265                let mut stmt = conn.prepare(
266                    "SELECT id, name, provider, kind, display_name, secret_ref, context,
267                            status, created_at, updated_at
268                     FROM db_accounts
269                     WHERE provider = ?1
270                     ORDER BY updated_at DESC",
271                )?;
272                let iter = stmt.query_map(params![p], map_row)?;
273                for r in iter {
274                    if let Ok(account) = r {
275                        rows_vec.push(account);
276                    }
277                }
278            }
279            None => {
280                let mut stmt = conn.prepare(
281                    "SELECT id, name, provider, kind, display_name, secret_ref, context,
282                            status, created_at, updated_at
283                     FROM db_accounts
284                     ORDER BY updated_at DESC",
285                )?;
286                let iter = stmt.query_map([], map_row)?;
287                for r in iter {
288                    if let Ok(account) = r {
289                        rows_vec.push(account);
290                    }
291                }
292            }
293        }
294        Ok(rows_vec)
295    }
296
297    pub fn identity_get(&self, id: &str) -> Result<Option<IdentityAccount>, StoreError> {
298        let conn = self.conn.lock().unwrap();
299        let mut stmt = conn.prepare(
300            "SELECT id, name, provider, kind, display_name, secret_ref, context,
301                    status, created_at, updated_at
302             FROM db_accounts WHERE id = ?1",
303        )?;
304        let result = stmt.query_row(params![id], |row| {
305            let secret_ref_json: String = row.get(5)?;
306            let context_json: String = row.get(6)?;
307            Ok(IdentityAccount {
308                id: row.get(0)?,
309                name: row.get(1)?,
310                provider: row.get(2)?,
311                kind: row.get(3)?,
312                display_name: row.get(4)?,
313                secret_ref: serde_json::from_str(&secret_ref_json).map_err(|e| {
314                    rusqlite::Error::FromSqlConversionFailure(
315                        5,
316                        rusqlite::types::Type::Text,
317                        Box::new(e),
318                    )
319                })?,
320                context: serde_json::from_str(&context_json)
321                    .unwrap_or_else(|_| serde_json::json!({})),
322                status: row.get(7)?,
323                created_at: row.get(8)?,
324                updated_at: row.get(9)?,
325            })
326        });
327        match result {
328            Ok(a) => Ok(Some(a)),
329            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
330            Err(e) => Err(e.into()),
331        }
332    }
333
334    /// Upsert an identity account. If `account.id` is empty the caller
335    /// must generate one first (we don't silently mint ids here — callers
336    /// should know whether they're creating vs updating).
337    /// Set one account's `context.email`, and nothing else: no other column,
338    /// no `updated_at`, and no row created — an account deleted since it was
339    /// read stays deleted, and a status or `secret_ref` written meanwhile
340    /// stands (SPEC_ACCOUNT_EMAIL_IN_ARMORY_2026_09_23.md §4's backfill runs
341    /// inside a list). Returns whether a row was updated.
342    pub fn identity_set_context_email(&self, id: &str, email: &str) -> Result<bool, StoreError> {
343        let conn = self.conn.lock().unwrap();
344        // A different address is a different group: the old number goes, and
345        // the next list numbers the account afresh (`identity::account_numbering`).
346        // A change of case or padding only is the same group and keeps it.
347        let n = conn.execute(
348            "UPDATE db_accounts
349                SET context = CASE
350                    WHEN json_valid(context) AND json_type(context) = 'object'
351                         AND lower(trim(COALESCE(json_extract(context, '$.email'), ''))) = lower(trim(?2))
352                    THEN json_set(context, '$.email', ?2)
353                    ELSE json_remove(json_set(
354                        CASE WHEN json_valid(context) AND json_type(context) = 'object'
355                             THEN context ELSE '{}' END,
356                        '$.email', ?2), '$.seq', '$.seqmax')
357                END
358              WHERE id = ?1",
359            params![id, email],
360        )?;
361        Ok(n > 0)
362    }
363
364    /// Set one account's numbering and nothing else (the same narrow write as
365    /// [`Self::identity_set_context_email`]): `context.seq`, the number that tells it
366    /// from other accounts with the same provider and email (left as it is when
367    /// `seq` is `None`), and `context.seqmax`, the highest number the group has
368    /// handed out, which survives the deletion of the account that held it.
369    pub fn identity_set_context_numbering(&self, id: &str, seq: Option<u32>, high: u32) -> Result<bool, StoreError> {
370        let conn = self.conn.lock().unwrap();
371        let n = conn.execute(
372            "UPDATE db_accounts
373                SET context = json_set(
374                        CASE WHEN json_valid(context) AND json_type(context) = 'object'
375                             THEN context ELSE '{}' END,
376                        '$.seq', COALESCE(?2, json_extract(context, '$.seq')),
377                        '$.seqmax', ?3)
378              WHERE id = ?1",
379            params![id, seq, high],
380        )?;
381        Ok(n > 0)
382    }
383
384    /// Mark one account "never fail over to this" (`context.never_failover`) or take the mark
385    /// off, and change nothing else (the same narrow write as [`Self::identity_set_context_email`]).
386    /// Returns whether a row was updated.
387    pub fn identity_set_never_failover(&self, id: &str, never: bool) -> Result<bool, StoreError> {
388        let conn = self.conn.lock().unwrap();
389        let object = "CASE WHEN json_valid(context) AND json_type(context) = 'object' THEN context ELSE '{}' END";
390        let sql = if never {
391            format!("UPDATE db_accounts SET context = json_set({object}, '$.never_failover', json('true')) WHERE id = ?1")
392        } else {
393            format!("UPDATE db_accounts SET context = json_remove({object}, '$.never_failover') WHERE id = ?1")
394        };
395        Ok(conn.execute(&sql, params![id])? > 0)
396    }
397
398    /// Set one account's `status`, and nothing else: no row is created, and
399    /// a context or `secret_ref` written meanwhile stands. For an OAuth
400    /// refresh that finds the grant gone (`needs_reauth`) or working again.
401    /// Returns whether a row was updated.
402    pub fn identity_set_status(&self, id: &str, status: &str) -> Result<bool, StoreError> {
403        let conn = self.conn.lock().unwrap();
404        let n = conn.execute("UPDATE db_accounts SET status = ?2 WHERE id = ?1", params![id, status])?;
405        Ok(n > 0)
406    }
407
408    pub fn identity_upsert(&self, account: &IdentityAccount) -> Result<(), StoreError> {
409        let conn = self.conn.lock().unwrap();
410        let secret_ref_json = serde_json::to_string(&account.secret_ref)?;
411        // A rewrite that doesn't carry the account's number keeps it
412        // (`identity::account_numbering::carry_over`).
413        let mut context = account.context.clone();
414        let stored: Option<String> = conn.query_row("SELECT context FROM db_accounts WHERE id = ?1", params![account.id], |r| r.get(0)).ok();
415        if let Some(stored) = stored.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok()) {
416            crate::identity::account_numbering::carry_over(&stored, &mut context);
417            // The operator's "never fail over to this" mark survives a re-sign-in that rebuilds the
418            // context; only `identity_set_never_failover` (or a context that says so) changes it.
419            let key = NEVER_FAILOVER;
420            if let (Some(mark), Some(ctx)) = (stored.get(key), context.as_object_mut()) {
421                ctx.entry(key).or_insert_with(|| mark.clone());
422            }
423        }
424        let context_json = serde_json::to_string(&context)?;
425        conn.execute(
426            "INSERT INTO db_accounts
427                (id, name, provider, kind, display_name, secret_ref, context,
428                 status, created_at, updated_at)
429             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
430             ON CONFLICT(id) DO UPDATE SET
431                name = excluded.name,
432                provider = excluded.provider,
433                kind = excluded.kind,
434                display_name = excluded.display_name,
435                secret_ref = CASE
436                    WHEN json_extract(excluded.secret_ref, '$.backend') = 'vault'
437                     AND json_extract(db_accounts.secret_ref, '$.backend') = 'vault'
438                     AND json_extract(excluded.secret_ref, '$.entry') = json_extract(db_accounts.secret_ref, '$.entry')
439                     AND json_extract(excluded.secret_ref, '$.link_id') IS NULL
440                     AND json_extract(db_accounts.secret_ref, '$.link_id') IS NOT NULL
441                    THEN db_accounts.secret_ref ELSE excluded.secret_ref END,
442                context = excluded.context,
443                status = excluded.status,
444                updated_at = excluded.updated_at",
445            params![
446                account.id,
447                account.name,
448                account.provider,
449                account.kind,
450                account.display_name,
451                secret_ref_json,
452                context_json,
453                account.status,
454                account.created_at,
455                account.updated_at,
456            ],
457        )?;
458        Ok(())
459    }
460
461    /// `identity_upsert(self)` — the authoritative, primary write — followed
462    /// by a BEST-EFFORT mirror write into `identity_store`, so a link
463    /// resolved from the always-global identity store (§SPEC_IDENTITY_STORE_
464    /// SPLIT_2026_08_17.md) doesn't dead-end resolving the account it
465    /// points at on a fresh, per-channel-isolated `self` after a version/
466    /// channel switch — see `identity::resolver::inject::resolve_account`.
467    ///
468    /// Call this instead of plain `identity_upsert` at every LIVE account-
469    /// creation/update call site (reagentx P0 review on PR #2632 — the
470    /// original fix only backfilled the mirror once, via migration, so any
471    /// account created/updated AFTER the fix shipped still had no mirror
472    /// entry and reproduced the exact reported bug on its own next channel
473    /// switch).
474    ///
475    /// `self` is the primary (`id_store`) — its result is authoritative and
476    /// propagated to the caller. `mirror`'s (`identity_store`'s) result is
477    /// logged on failure and otherwise ignored: the mirror existing at all
478    /// is a durability nicety for THIS specific continuity scenario, not a
479    /// correctness requirement the primary write should ever be blocked or
480    /// failed by.
481    pub fn identity_upsert_with_mirror(&self, mirror: &Store, account: &IdentityAccount) -> Result<(), StoreError> {
482        self.identity_upsert(account)?;
483        if let Err(e) = mirror.identity_upsert(account) {
484            tracing::warn!(
485                target: "identity",
486                account_id = %account.id,
487                error = %e,
488                "identity_upsert_with_mirror: primary write succeeded but mirror write failed \
489                 (non-fatal — this account may not resolve after a future channel switch \
490                 until the mirror is repaired)"
491            );
492        }
493        Ok(())
494    }
495
496    /// Delete an identity account AND every `db_agent_identity_links`
497    /// row referencing it, atomically (single transaction under the
498    /// connection lock).
499    ///
500    /// The cascade is EXPLICIT even though the current DDL carries
501    /// `FOREIGN KEY (account_id) … ON DELETE CASCADE`: databases whose
502    /// links table arrived via legacy `ALTER TABLE … RENAME` (forge era)
503    /// never got the FK clause retrofitted — `CREATE TABLE IF NOT EXISTS`
504    /// can't alter an existing table — so on real user databases the
505    /// DDL-level cascade silently doesn't exist and dangling links
506    /// survive the account row (auth-lifecycle gap §2.4,
507    /// `docs/analysis/ANALYSIS_ACCOUNT_DELETE_AUTH_LIFECYCLE_GAP_2026_07_14.md`).
508    /// `db_identity_bindings` (named by the report) was retired in Phase
509    /// 4c and no longer exists; links are the sole junction on accounts.
510    pub fn identity_delete(&self, id: &str) -> Result<IdentityDeleteOutcome, StoreError> {
511        let mut conn = self.conn.lock().unwrap();
512        let tx = conn.transaction()?;
513        // Capture the affected agent ids BEFORE the cascade delete, in
514        // the same transaction, so the set can't race a concurrent
515        // link/unlink (spec §3 — the handler publishes per-agent
516        // revocation events off this list).
517        let affected_agents: Vec<String> = {
518            let mut stmt = tx.prepare(
519                "SELECT agent_id FROM db_agent_identity_links
520                 WHERE account_id = ?1 ORDER BY agent_id",
521            )?;
522            let iter = stmt.query_map(params![id], |row| row.get::<_, String>(0))?;
523            let mut out = Vec::new();
524            for r in iter {
525                out.push(r?);
526            }
527            out
528        };
529        // Links first, so the count is exact even on fresh databases
530        // where the FK cascade would otherwise race this delete.
531        let links_cascaded = tx.execute(
532            "DELETE FROM db_agent_identity_links WHERE account_id = ?1",
533            params![id],
534        )?;
535        let rows = tx.execute("DELETE FROM db_accounts WHERE id = ?1", params![id])?;
536        tx.commit()?;
537        Ok(IdentityDeleteOutcome {
538            deleted: rows > 0,
539            links_cascaded,
540            affected_agents,
541        })
542    }
543
544    // ---- Agent ↔ Identity junction ----
545
546    /// Delete every `db_agent_identity_links` row for `account_id`, on
547    /// WHATEVER store this is called on — added for
548    /// `docs/specs/SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md`: since links now
549    /// live in a different physical store (`identity_store`) than accounts
550    /// (`id_store`), `identity_delete`'s own same-connection cascade above
551    /// no longer reaches them (it only ever deleted rows in the SAME store
552    /// as the account, which was always true before this split). Callers
553    /// deleting an account must call this on `identity_store` in addition
554    /// to `identity_delete` on `id_store` — see the `deleteidentityaccount`
555    /// handler. Returns the same `(count, affected_agents)` shape
556    /// `identity_delete` did, captured before the delete in one transaction
557    /// for the same race-safety reason.
558    pub fn agent_identity_unlink_by_account(&self, account_id: &str) -> Result<(usize, Vec<String>), StoreError> {
559        let mut conn = self.conn.lock().unwrap();
560        let tx = conn.transaction()?;
561        let affected_agents: Vec<String> = {
562            let mut stmt = tx.prepare(
563                "SELECT agent_id FROM db_agent_identity_links
564                 WHERE account_id = ?1 ORDER BY agent_id",
565            )?;
566            let iter = stmt.query_map(params![account_id], |row| row.get::<_, String>(0))?;
567            let mut out = Vec::new();
568            for r in iter {
569                out.push(r?);
570            }
571            out
572        };
573        let links_removed = tx.execute(
574            "DELETE FROM db_agent_identity_links WHERE account_id = ?1",
575            params![account_id],
576        )?;
577        tx.commit()?;
578        Ok((links_removed, affected_agents))
579    }
580
581    /// Link an agent to an identity for a given provider. Overwrites any
582    /// existing link for the same (agent_id, provider) — each agent has
583    /// at most one account per provider.
584    pub fn agent_identity_link(
585        &self,
586        agent_id: &str,
587        account_id: &str,
588        provider: &str,
589    ) -> Result<(), StoreError> {
590        let conn = self.conn.lock().unwrap();
591        conn.execute(
592            "INSERT INTO db_agent_identity_links (agent_id, account_id, provider)
593             VALUES (?1, ?2, ?3)
594             ON CONFLICT(agent_id, provider) DO UPDATE SET account_id = excluded.account_id",
595            params![agent_id, account_id, provider],
596        )?;
597        Ok(())
598    }
599
600    /// Remove the identity link for a given (agent_id, provider).
601    /// Returns true iff a link existed.
602    pub fn agent_identity_unlink(
603        &self,
604        agent_id: &str,
605        provider: &str,
606    ) -> Result<bool, StoreError> {
607        let conn = self.conn.lock().unwrap();
608        let rows = conn.execute(
609            "DELETE FROM db_agent_identity_links WHERE agent_id = ?1 AND provider = ?2",
610            params![agent_id, provider],
611        )?;
612        Ok(rows > 0)
613    }
614
615    /// List every (agent_id, account_id, provider) row in the table.
616    /// Used by the startup backfill to seed the shared store.
617    pub fn agent_identity_list_all(&self) -> Result<Vec<AgentIdentityLink>, StoreError> {
618        let conn = self.conn.lock().unwrap();
619        let mut stmt = conn.prepare(
620            "SELECT agent_id, account_id, provider FROM db_agent_identity_links ORDER BY agent_id, provider",
621        )?;
622        let iter = stmt.query_map([], |row| {
623            Ok(AgentIdentityLink {
624                agent_id: row.get(0)?,
625                account_id: row.get(1)?,
626                provider: row.get(2)?,
627            })
628        })?;
629        let mut out = Vec::new();
630        for r in iter {
631            out.push(r?);
632        }
633        Ok(out)
634    }
635
636    /// List all (agent_id, account_id, provider) triples for an agent.
637    pub fn agent_identity_list_for_agent(
638        &self,
639        agent_id: &str,
640    ) -> Result<Vec<AgentIdentityLink>, StoreError> {
641        let conn = self.conn.lock().unwrap();
642        let mut stmt = conn.prepare(
643            "SELECT agent_id, account_id, provider
644             FROM db_agent_identity_links
645             WHERE agent_id = ?1
646             ORDER BY provider",
647        )?;
648        let iter = stmt.query_map(params![agent_id], |row| {
649            Ok(AgentIdentityLink {
650                agent_id: row.get(0)?,
651                account_id: row.get(1)?,
652                provider: row.get(2)?,
653            })
654        })?;
655        let mut out = Vec::new();
656        for r in iter {
657            out.push(r?);
658        }
659        Ok(out)
660    }
661
662}
663
664#[cfg(test)]
665mod tests {
666    use rusqlite::params;
667
668    use super::super::store::{AgentDefinition, Store};
669    use super::*;
670
671    /// Pins the on-disk wire format directly, rather than round-tripping
672    /// through this crate's own serializer (which would happily agree with
673    /// itself even if `rename_all`'s derived tag drifted from what's
674    /// actually stored). `oauth_config_dir` here is copied verbatim from a
675    /// real account row in `~/.agentmux/shared/store.db` — this is the
676    /// literal regression that broke `identity_list()` (and therefore "My
677    /// Agents"/recent-sessions, which aborts entirely on the first
678    /// unparseable row) for every account written before the enum-wide
679    /// `rename_all = "snake_case"` derive silently started expecting
680    /// `o_auth_config_dir` instead (serde splits at every capital letter,
681    /// including inside "OAuth" itself).
682    #[test]
683    fn secret_ref_deserializes_real_stored_oauth_config_dir_json() {
684        let json = r#"{"backend":"oauth_config_dir","dir":"C:\\Users\\area54\\.agentmux\\shared\\identities\\bfa59d03-7a99-420e-b912-716bba1c462d\\claude"}"#;
685        let parsed: SecretRef = serde_json::from_str(json).expect("must deserialize real stored wire format");
686        match parsed {
687            SecretRef::OAuthConfigDir { dir } => {
688                assert!(dir.ends_with("claude"), "dir should round-trip: {dir}");
689            }
690            other => panic!("expected OAuthConfigDir, got {other:?}"),
691        }
692    }
693
694    /// Pins the OTHER wire format still sitting in some accounts: whatever
695    /// backend was running between this variant's introduction and the
696    /// `oauth_config_dir` rename above wrote (and read back) the
697    /// derive-produced `o_auth_config_dir` tag. Losing read support for it
698    /// reproduces the exact "My Agents empty" incident for those accounts —
699    /// `identity_list()` aborts entirely on the first unparseable row.
700    #[test]
701    fn secret_ref_deserializes_legacy_derive_produced_tag_json() {
702        let json = r#"{"backend":"o_auth_config_dir","dir":"C:\\Users\\area54\\.agentmux\\shared\\identities\\269c028b-3894-4231-b884-fa5d0ecfabdf\\claude"}"#;
703        let parsed: SecretRef = serde_json::from_str(json).expect("must deserialize legacy derive-produced wire format");
704        match parsed {
705            SecretRef::OAuthConfigDir { dir } => {
706                assert!(dir.ends_with("claude"), "dir should round-trip: {dir}");
707            }
708            other => panic!("expected OAuthConfigDir, got {other:?}"),
709        }
710    }
711
712    /// Pins the exact `upsertidentityaccount` payload shape sent by
713    /// `persistSeededAccount` (frontend/app/view/agent/flows/
714    /// register-seeded-account.ts) — no `created_at`/`updated_at` at all,
715    /// since the handler is documented to server-stamp them. Before
716    /// `#[serde(default)]` was added to those two fields, this exact shape
717    /// failed `serde_json::from_value` with "missing field `created_at`" on
718    /// every call, so every login silently never persisted an account row
719    /// (the credential landed on
720    /// disk, but no `db_accounts` row or agent link ever existed — see
721    /// REPORT_LOGIN_PERSIST_FAILURE_AND_STUCK_WORKING_2026_07_27.md).
722    #[test]
723    fn identity_account_deserializes_frontend_seed_payload_missing_timestamps() {
724        let json = r#"{
725            "id": "8d34a369-6ba6-4071-93bd-d4e051cdb457",
726            "name": "claude-oauth",
727            "provider": "claude",
728            "kind": "oauth",
729            "secret_ref": {"backend": "oauth_config_dir", "dir": "/tmp/claude"},
730            "status": "valid"
731        }"#;
732        let parsed: IdentityAccount =
733            serde_json::from_value(serde_json::from_str(json).unwrap())
734                .expect("must deserialize the frontend's timestamp-less seed payload");
735        assert_eq!(parsed.created_at, 0);
736        assert_eq!(parsed.updated_at, 0);
737        assert_eq!(parsed.status, "valid");
738    }
739
740    /// Serialization must always emit the canonical tag, never the legacy
741    /// alias — the alias is read-only backward compat, not a second valid
742    /// output format.
743    #[test]
744    fn secret_ref_serializes_oauth_config_dir_with_canonical_tag() {
745        let value = SecretRef::OAuthConfigDir {
746            dir: "/tmp/claude".to_string(),
747        };
748        let json = serde_json::to_string(&value).unwrap();
749        assert!(json.contains(r#""backend":"oauth_config_dir""#), "got: {json}");
750        assert!(!json.contains("o_auth_config_dir"), "got: {json}");
751    }
752
753    fn sample_account(id: &str, provider: &str) -> IdentityAccount {
754        IdentityAccount {
755            id: id.to_string(),
756            name: format!("asaf-{provider}"),
757            provider: provider.to_string(),
758            kind: "oauth".to_string(),
759            display_name: String::new(),
760            secret_ref: SecretRef::OAuthConfigDir {
761                dir: format!("/var/agentmux/identities/{id}/claude"),
762            },
763            context: serde_json::json!({}),
764            status: "ok".to_string(),
765            created_at: 0,
766            updated_at: 0,
767        }
768    }
769
770    fn sample_agent(id: &str, slug: &str) -> AgentDefinition {
771        AgentDefinition {
772            slug: slug.to_string(),
773            icon: "✦".to_string(),
774            ..crate::backend::storage::agents::test_agent_def(id, id, "claude", "host", 0, "")
775        }
776    }
777
778    fn count_links_for_account(store: &Store, account_id: &str) -> i64 {
779        let conn = store.conn.lock().unwrap();
780        conn.query_row(
781            "SELECT count(*) FROM db_agent_identity_links WHERE account_id = ?1",
782            params![account_id],
783            |r| r.get(0),
784        )
785        .unwrap()
786    }
787
788    /// Recreate `db_agent_identity_links` in the LEGACY shape: no
789    /// `FOREIGN KEY (account_id) … ON DELETE CASCADE`. This is the shape a
790    /// production `store.db`/`objects.db` still has when the table arrived
791    /// via `ALTER TABLE … RENAME` from the forge era —
792    /// `CREATE TABLE IF NOT EXISTS` never retrofits FK clauses onto an
793    /// existing table, so the DDL-level cascade only exists on fresh
794    /// databases. `identity_delete` must therefore cascade EXPLICITLY
795    /// rather than lean on the FK (the account-delete auth-lifecycle gap,
796    /// docs/analysis/ANALYSIS_ACCOUNT_DELETE_AUTH_LIFECYCLE_GAP_2026_07_14.md §2.4).
797    fn strip_links_fk(store: &Store) {
798        let conn = store.conn.lock().unwrap();
799        conn.execute_batch(
800            "DROP TABLE db_agent_identity_links;
801             CREATE TABLE db_agent_identity_links (
802                agent_id   TEXT NOT NULL,
803                account_id TEXT NOT NULL,
804                provider   TEXT NOT NULL,
805                PRIMARY KEY (agent_id, provider)
806             );",
807        )
808        .unwrap();
809    }
810
811    #[test]
812    fn identity_set_status_changes_only_the_status_of_an_existing_row() {
813        let store = Store::open_in_memory().unwrap();
814        let mut account = sample_account("acc-s", "google");
815        account.context = serde_json::json!({ "email": "me@example.com" });
816        store.identity_upsert(&account).unwrap();
817        assert!(store.identity_set_status("acc-s", "needs_reauth").unwrap());
818        let got = store.identity_get("acc-s").unwrap().unwrap();
819        assert_eq!(got.status, "needs_reauth");
820        assert_eq!(got.context, account.context);
821        assert_eq!(got.name, account.name);
822        // No row is created for an account that isn't there.
823        assert!(!store.identity_set_status("acc-gone", "valid").unwrap());
824        assert!(store.identity_get("acc-gone").unwrap().is_none());
825    }
826
827    #[test]
828    fn identity_delete_cascades_links_on_legacy_no_fk_schema() {
829        let store = Store::open_in_memory().unwrap();
830        strip_links_fk(&store);
831        store
832            .identity_upsert(&sample_account("acct-1", "anthropic"))
833            .unwrap();
834        store
835            .agent_identity_link("ag1", "acct-1", "anthropic")
836            .unwrap();
837        assert_eq!(count_links_for_account(&store, "acct-1"), 1);
838
839        let out = store.identity_delete("acct-1").unwrap();
840
841        assert!(store.identity_get("acct-1").unwrap().is_none());
842        assert_eq!(
843            count_links_for_account(&store, "acct-1"),
844            0,
845            "junction row must not survive the account row (dangling link)"
846        );
847        assert!(out.deleted);
848        assert_eq!(out.links_cascaded, 1, "explicit cascade must report the link row");
849        assert_eq!(
850            out.affected_agents,
851            vec!["ag1".to_string()],
852            "agent ids must be captured before the cascade delete (spec §3)"
853        );
854
855        // Second delete is a no-op on both tables.
856        let again = store.identity_delete("acct-1").unwrap();
857        assert!(!again.deleted);
858        assert_eq!(again.links_cascaded, 0);
859        assert!(again.affected_agents.is_empty());
860    }
861
862    #[test]
863    fn identity_delete_cascades_links_on_current_schema() {
864        // Fresh schema — the DDL-level FK cascade also exists here; the
865        // explicit cascade must coexist with it (and still report the row).
866        let store = Store::open_in_memory().unwrap();
867        let mut agent = sample_agent("ag1", "agent-x");
868        store.agent_def_insert(&mut agent).unwrap();
869        store
870            .identity_upsert(&sample_account("acct-1", "anthropic"))
871            .unwrap();
872        store
873            .agent_identity_link("ag1", "acct-1", "anthropic")
874            .unwrap();
875
876        let out = store.identity_delete("acct-1").unwrap();
877
878        assert!(store.identity_get("acct-1").unwrap().is_none());
879        assert_eq!(count_links_for_account(&store, "acct-1"), 0);
880        assert!(out.deleted);
881        assert_eq!(
882            out.links_cascaded, 1,
883            "explicit cascade runs before the FK cascade, so the count is exact"
884        );
885        assert_eq!(
886            out.affected_agents,
887            vec!["ag1".to_string()],
888            "capture must run before both the explicit and the FK cascade"
889        );
890    }
891
892    /// Multiple linked agents → all captured, in deterministic (sorted)
893    /// order. Account with NO links → empty set (the delete-time
894    /// disclosure must not fire).
895    #[test]
896    fn identity_delete_captures_all_affected_agents() {
897        let store = Store::open_in_memory().unwrap();
898        // Fresh schema enforces the links FK on agent_id, so the agent
899        // definitions must exist before linking.
900        for (id, slug) in [("ag-b", "agent-b"), ("ag-a", "agent-a"), ("ag-other", "agent-o")] {
901            let mut agent = sample_agent(id, slug);
902            store.agent_def_insert(&mut agent).unwrap();
903        }
904        store
905            .identity_upsert(&sample_account("acct-1", "anthropic"))
906            .unwrap();
907        store
908            .identity_upsert(&sample_account("acct-2", "anthropic"))
909            .unwrap();
910        store
911            .agent_identity_link("ag-b", "acct-1", "anthropic")
912            .unwrap();
913        store
914            .agent_identity_link("ag-a", "acct-1", "anthropic")
915            .unwrap();
916        // A link on a DIFFERENT account must not leak into the set.
917        store
918            .agent_identity_link("ag-other", "acct-2", "anthropic")
919            .unwrap();
920
921        let out = store.identity_delete("acct-1").unwrap();
922        assert!(out.deleted);
923        assert_eq!(out.links_cascaded, 2);
924        assert_eq!(
925            out.affected_agents,
926            vec!["ag-a".to_string(), "ag-b".to_string()],
927            "all linked agents captured, sorted, and scoped to the deleted account"
928        );
929
930        // Account with NO links → empty affected set (disclosure must
931        // not fire for it).
932        store
933            .identity_upsert(&sample_account("acct-3", "anthropic"))
934            .unwrap();
935        let out3 = store.identity_delete("acct-3").unwrap();
936        assert!(out3.deleted);
937        assert_eq!(out3.links_cascaded, 0);
938        assert!(
939            out3.affected_agents.is_empty(),
940            "linkless account delete must report an empty affected set"
941        );
942    }
943
944    /// The analysis report (§2.4) names `db_identity_bindings` as a second
945    /// cascade target. That table was retired in Phase 4c of
946    /// SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md and is DROPPED by the
947    /// schema (`DEAD_TABLE_DROPS`) — `db_agent_identity_links` is the sole
948    /// junction referencing `db_accounts.id`. Pin that here so the cascade
949    /// in `identity_delete` is provably complete.
950    #[test]
951    fn identity_bindings_table_is_retired() {
952        let store = Store::open_in_memory().unwrap();
953        let conn = store.conn.lock().unwrap();
954        let count: i64 = conn
955            .query_row(
956                "SELECT count(*) FROM sqlite_master
957                 WHERE type='table' AND name IN ('db_identity_bindings', 'db_identity_bundles')",
958                [],
959                |r| r.get(0),
960            )
961            .unwrap();
962        assert_eq!(count, 0, "retired bundle-binding tables must not exist");
963    }
964
965    // ---- Malformed secret_ref tolerance (ANALYSIS_ARMORY_STASH_CREDENTIAL_VISIBILITY_GAP_2026_08_04) ----
966
967    /// `identity_list` must return the good rows and skip the malformed
968    /// one — not abort the whole query. This is the actual bug: one
969    /// corrupted account made 9 real accounts invisible everywhere
970    /// `identity_list` is called (Connectors → Accounts' list, boot-time
971    /// identity sweep, post-login cache refresh).
972    #[test]
973    fn identity_list_skips_a_malformed_row_instead_of_failing_the_whole_query() {
974        let store = Store::open_in_memory().unwrap();
975        store
976            .identity_upsert(&sample_account("acct-good-1", "claude"))
977            .unwrap();
978        store
979            .identity_upsert(&sample_account("acct-good-2", "claude"))
980            .unwrap();
981        {
982            let conn = store.conn.lock().unwrap();
983            conn.execute(
984                "INSERT INTO db_accounts
985                    (id, name, provider, kind, display_name, secret_ref, context,
986                     status, created_at, updated_at)
987                 VALUES ('acct-bad', 'broken', 'claude', 'oauth', '',
988                         '{\"backend\":\"oauth_config_dir\",\"dir\":\"C:\\bad\\path\"}',
989                         '{}', 'unknown', 0, 0)",
990                [],
991            )
992            .unwrap();
993        }
994
995        let accounts = store
996            .identity_list(None)
997            .expect("must not fail even with a malformed row present");
998        let ids: Vec<&str> = accounts.iter().map(|a| a.id.as_str()).collect();
999        assert!(ids.contains(&"acct-good-1"));
1000        assert!(ids.contains(&"acct-good-2"));
1001        assert!(!ids.contains(&"acct-bad"), "malformed row must be excluded, not error the whole call");
1002        assert_eq!(accounts.len(), 2);
1003    }
1004
1005    /// The actual bug this whole store split fixes
1006    /// (docs/specs/REPORT_HISTORY_CONTINUITY_ACROSS_VERSION_UPGRADE_2026_08_17.md):
1007    /// a link written in one process's lifetime must be findable by a LATER,
1008    /// independent process opening the same always-global path — simulating
1009    /// "close AgentMux, a new version/channel starts, reopen the agent."
1010    ///
1011    /// Before this fix, the equivalent lookup went through `id_store`
1012    /// (`resolve_shared_store_path()`), which resolves to a fresh, empty
1013    /// per-channel file on every non-`"stable"` channel — the second `Store`
1014    /// below would have opened a DIFFERENT physical file in that world, and
1015    /// this assertion would fail. `Store::open_identity_store` never
1016    /// consults `isolated_auth_enabled()` at all, so two independent opens
1017    /// of the same path always see the same data regardless of what channel
1018    /// either "process" believes it's running on.
1019    #[test]
1020    fn identity_store_link_written_by_one_process_is_visible_to_a_later_independent_open() {
1021        let tmp = tempfile::NamedTempFile::new().unwrap();
1022
1023        // "Process 1" — e.g. the old version's srv instance.
1024        {
1025            let store = Store::open_identity_store(tmp.path()).unwrap();
1026            store
1027                .agent_identity_link("agent-continuing", "acct-real-login", "claude")
1028                .unwrap();
1029        } // dropped — simulates the process exiting (version closed).
1030
1031        // "Process 2" — e.g. the new version's srv instance, a completely
1032        // independent Store handle opening the identical always-global path.
1033        let store2 = Store::open_identity_store(tmp.path()).unwrap();
1034        let links = store2.agent_identity_list_for_agent("agent-continuing").unwrap();
1035        assert_eq!(
1036            links.len(),
1037            1,
1038            "the agent's account link must survive a full close/reopen cycle \
1039             (a version/channel switch) — this is conversation continuity"
1040        );
1041        assert_eq!(links[0].account_id, "acct-real-login");
1042        assert_eq!(links[0].provider, "claude");
1043    }
1044
1045    /// `db_agent_identity_links.account_id` must NOT carry a live FK to
1046    /// `db_accounts` in this store (unlike the per-channel `objects.db`
1047    /// schema) — even as of v2, `db_accounts` here is a read-through
1048    /// FALLBACK MIRROR only (reagentx P0 review on PR #2632), not the
1049    /// authoritative write path, and isn't guaranteed complete: a link can
1050    /// legitimately resolve to an account that hasn't been mirrored yet.
1051    /// A hard FK would make that (already-tolerated-elsewhere) case fail
1052    /// the write outright instead of just missing on read.
1053    #[test]
1054    fn identity_store_link_write_does_not_require_a_matching_accounts_row() {
1055        let store = Store::open_identity_store(":memory:".as_ref()).unwrap();
1056        // No db_accounts row for "acct-orphan-by-design" exists in this
1057        // store's (mirror-only) db_accounts table — the write must still
1058        // succeed.
1059        store
1060            .agent_identity_link("agent-x", "acct-orphan-by-design", "claude")
1061            .unwrap();
1062        let links = store.agent_identity_list_for_agent("agent-x").unwrap();
1063        assert_eq!(links.len(), 1);
1064    }
1065}
1066
1067#[cfg(test)]
1068mod secret_ref_wire_tests {
1069    use super::*;
1070    use serde_json::json;
1071
1072    // THE REASON `#[ts(rename)]` EXISTS ON OAuthConfigDir.
1073    //
1074    // ts-rs does not pick up `#[serde(rename = "oauth_config_dir")]`; left
1075    // alone it emits the derive-default `o_auth_config_dir` — the legacy tag
1076    // this rename exists to STOP writing. A frontend discriminating on that
1077    // tag would never match a real OAuth account, which is the
1078    // "My Agents empty" incident the variant's doc comment describes.
1079    //
1080    // No CI gate catches that: tsc passes (the union simply never matches at
1081    // runtime) and check-rpc-bindings passes (the type exists and is current).
1082    // So pin the serialized tag here, in Rust, where it is checkable.
1083    #[test]
1084    fn oauth_config_dir_serializes_with_the_canonical_tag() {
1085        let v = serde_json::to_value(SecretRef::OAuthConfigDir {
1086            dir: "/home/u/.claude".to_string(),
1087        })
1088        .expect("serializable");
1089        assert_eq!(v["backend"], "oauth_config_dir");
1090        assert_ne!(
1091            v["backend"], "o_auth_config_dir",
1092            "the derive-default tag must never be written; it is read-only legacy"
1093        );
1094    }
1095
1096    // The alias is still accepted on the way in — dropping it would strand
1097    // accounts persisted while the buggy tag was canonical.
1098    #[test]
1099    fn both_tags_still_deserialize() {
1100        for tag in ["oauth_config_dir", "o_auth_config_dir"] {
1101            let parsed: SecretRef =
1102                serde_json::from_value(json!({"backend": tag, "dir": "/d"})).unwrap_or_else(|e| {
1103                    panic!("tag {tag} must still deserialize: {e}")
1104                });
1105            assert!(matches!(parsed, SecretRef::OAuthConfigDir { .. }));
1106        }
1107    }
1108
1109    // display_name and status are #[serde(default)] on non-Option fields with
1110    // no skip_serializing_if, so the server ALWAYS writes them. The
1111    // hand-written declaration marked both optional, which the wire never was;
1112    // the generated binding makes them required.
1113    #[test]
1114    fn identity_account_always_writes_display_name_and_status() {
1115        let a: IdentityAccount = serde_json::from_value(json!({
1116            "id": "a1", "name": "n", "provider": "anthropic", "kind": "api_key",
1117            "secret_ref": {"backend": "env", "env_var": "K"},
1118        }))
1119        .expect("minimal account");
1120        let v = serde_json::to_value(&a).expect("serializable");
1121        let obj = v.as_object().expect("object");
1122        assert!(obj.contains_key("display_name"), "display_name is never omitted");
1123        assert!(obj.contains_key("status"), "status is never omitted");
1124        assert_eq!(v["context"], json!({}), "context defaults to an object, not null");
1125    }
1126}