Skip to main content

agentmux_srv_core/identity/resolver/
inject.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The credential-injection entry points and the layer-3 spawn gate.
5//!
6//! Split out of the single ~2193-line `resolver.rs` (pure relocation, no
7//! behavior change): `inject_identity_env` / `inject_identity_env_async`
8//! (thin public wrappers), `IdentityBinding` + `resolve_bindings_for_instance`
9//! (direct-link lookup), and `inject_identity_env_with_broker` — the
10//! security-critical credential-injection gate. Every test that exercises
11//! `inject_identity_env_with_broker` moved here WITH it, as one atomic unit,
12//! per the module split's constraint that this function and its tests must
13//! never be separated.
14//!
15//! **Before touching `gate_oauth_failure` / `inject_identity_env_with_broker`:**
16//! see the warning doc comment directly above `inject_identity_env_with_broker`
17//! below.
18
19use std::collections::HashMap;
20use std::path::PathBuf;
21use std::sync::Arc;
22
23use crate::backend::providers::resolve_provider_alias;
24use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
25use crate::backend::storage::StoreError;
26use crate::backend::mps::Broker;
27
28use super::errors::{refusal_linked, SpawnGateError};
29use super::oauth_probe::{oauth_status, probe_oauth_status};
30use super::provider::{provider_class, ProviderClass};
31use super::secret::{resolve_account_secret, resolve_secret};
32
33/// Inject identity-derived env vars into the spawn map for a block.
34///
35/// Synchronous, broker-less entry point — in production only the durable-jekt
36/// sign-in recheck (server/jekt_held.rs) calls it. The CLI-spawn paths use
37/// [`inject_identity_env_async`] instead (via `build_persistent_spawn_env` in
38/// server/agent_handlers/input.rs). Resolution flow:
39///
40/// 1. Look up the active `AgentInstance` for this block. If none
41///    exists, the caller didn't go through a launch — return
42///    immediately, no injection (unless the block names a deleted agent:
43///    that is refused with `SpawnGateError::AgentDeleted`, #3577).
44/// 2. Read its `identity_id`. Empty / "blank" no longer short-circuits to
45///    ambient creds (see #2463 — this used to bypass the layer-3 gate
46///    entirely, so whether a spawn required a bound account depended on
47///    whether a stray ambient credential happened to exist on the test
48///    machine). It now falls through to the same steps below, which gate
49///    purely on the agent definition's own provider — identical to how a
50///    non-empty-but-unresolvable `identity_id` (e.g. a legacy sentinel)
51///    already behaved.
52/// 3. Read the `db_agent_identity_links` rows for the instance's definition.
53/// 4. For each binding: fetch the account, resolve its `SecretRef`,
54///    look up the provider's env-var matrix, write each var into
55///    `env_vars`.
56///    - **Api-key-class** per-binding failures are logged and skipped —
57///      other bindings still inject (historical behavior).
58///    - **Oauth-class** failures (account row missing, lookup error,
59///      non-OAuthConfigDir secret_ref) are always BLOCKING: the function
60///      returns [`SpawnGateError`] before the CLI process is created.
61///      `use_ambient_login` no longer exempts an agent and is not read
62///      here (the opt-out was retired).
63/// 5. If the agent definition's own provider is oauth-class and no binding
64///    for it exists at all (fresh/never-bound or post-delete-cascade), the
65///    same gate applies — implicit ambient fallback is how the
66///    delete-doesn't-deauthenticate gap happened (spec §2.2 edge case).
67///
68/// Layer 3 of SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md. Before
69/// it, this function was intentionally infallible ("the spawn never aborts
70/// because a secret didn't resolve") — that is still true for api-key-class
71/// bindings, but oauth-class resolution failures now fail the spawn by
72/// default so account deletion is honest at the next spawn.
73pub fn inject_identity_env(
74    mstore: Arc<Store>,
75    id_store: Arc<Store>,
76    identity_store: Arc<Store>,
77    block_id: &str,
78    env_vars: &mut HashMap<String, String>,
79) -> Result<(), SpawnGateError> {
80    inject_identity_env_with_broker(mstore, id_store, identity_store, None, block_id, env_vars)
81}
82
83/// The optional broker lets the OAuth-class branch publish
84/// `identityaccounts:changed` on a status change discovered by the expiry
85/// probe. `None` skips the publish; the `agentinput` turn
86/// (server/agent_handlers/input.rs) and `agent.send` (app_api/agent_io.rs)
87/// pass `Some(broker.clone())` through `build_persistent_spawn_env` so any
88/// live account list flips its status badge without a reload. Per spec §4.4.
89///
90/// Async wrapper around [`inject_identity_env_with_broker`] for use from
91/// async spawn handlers. The underlying path does blocking I/O — synchronous
92/// SQLite reads and, for `SecretRef::Keychain` accounts, a blocking
93/// `keyring` (D-Bus Secret Service on Linux) read — so it runs on a blocking
94/// thread via `spawn_blocking` rather than stalling an async runtime worker.
95/// Takes ownership of `env_vars` and returns it with identity vars merged in.
96///
97/// `Err(SpawnGateError)` is the layer-3 spawn gate (see
98/// [`inject_identity_env`]): the caller must NOT spawn the CLI and must
99/// surface the error on the agent pane like any other spawn failure. A
100/// task-join failure also fails CLOSED (`InjectionUnavailable`, blocking
101/// the spawn) — see that variant's doc for why an open fallback would
102/// systemically bypass the gate after any store panic.
103pub async fn inject_identity_env_async(
104    mstore: Arc<Store>,
105    id_store: Arc<Store>,
106    identity_store: Arc<Store>,
107    broker: Option<Arc<Broker>>,
108    block_id: String,
109    env_vars: HashMap<String, String>,
110    own_claude_endpoint: bool,
111) -> Result<HashMap<String, String>, SpawnGateError> {
112    match tokio::task::spawn_blocking(move || {
113        let mut env = env_vars;
114        inject_identity_env_for_spawn(mstore, id_store, identity_store, broker, &block_id, &mut env, own_claude_endpoint)
115            .map(|()| env)
116    })
117    .await
118    {
119        Ok(result) => result,
120        Err(e) => {
121            // Fail CLOSED. A join failure means the closure panicked (or
122            // was cancelled) — the gate never rendered a verdict, and the
123            // panic has likely poisoned the Store mutex, so failing open
124            // here would bypass the oauth gate for every later
125            // spawn too (reagent P1, PR #2164 round 1). See
126            // SpawnGateError::InjectionUnavailable.
127            tracing::warn!(
128                target: "identity",
129                error = %e,
130                "identity.spawn.blocked: injection task join failed — failing closed"
131            );
132            Err(SpawnGateError::InjectionUnavailable { detail: e.to_string() })
133        }
134    }
135}
136
137/// Resolved (provider, account) pair ready for env injection.
138///
139/// Historically a row of the `db_identity_bindings` table (retired in
140/// Phase 4c of SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md); now purely
141/// an internal shape built from `AgentIdentityLink` rows.
142struct IdentityBinding {
143    provider: String,
144    account_id: String,
145}
146
147/// Resolve the identity bindings for an instance from the **direct**
148/// agent↔account links only.
149///
150/// Phase 3 slice 2 PR-B (the flip): the resolver previously dual-read —
151/// preferring `db_agent_identity_links` keyed on the instance's DEFINITION
152/// id, falling back to the bundle bindings (`db_identity_bindings`) when no
153/// direct links existed (PR-A, #1927). That fallback was removed here, and
154/// Phase 4c of SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md later dropped
155/// `db_identity_bundles`/`db_identity_bindings` entirely — every write path
156/// (launch flow, per-agent Accounts tab, OAuth Connect/Reconnect) writes a
157/// direct link, and migrations (#1927/#1952, since retired) backfilled
158/// direct links for every pre-existing bundle binding before the drop.
159///
160/// `parent_template_id`: the launch's eligible TEMPLATE parent's own id —
161/// `""` unless the caller has already confirmed, via
162/// `template_parent_id_if_seeded`, that `db_agents.parent_template_id`
163/// actually points at a row with `is_seeded = 1`. That column is NOT
164/// exclusively "which template was I launched from": `forkagentdefinition`
165/// (`template.rs`) reuses the same column to record a plain agent fork's
166/// SOURCE agent id, `is_seeded = 0`. reagent P0 on #3092 caught an earlier
167/// version of this fallback trusting the column unconditionally — a fork
168/// of any regular agent that had a bound identity would silently inherit
169/// and spawn on the SOURCE agent's credentials whatever its own links said.
170/// A fork gets its source's account once, as its own link written when it is
171/// created (`inherit_source_account_links`, `template.rs`); then only its own
172/// links count, so unlinking a fork never falls back to its source.
173/// Callers MUST resolve this through `template_parent_id_if_seeded`, never
174/// pass `d.parent_id` directly.
175///
176/// Agent-concept consolidation's definition flip
177/// (`SPEC_AGENT_ARCHITECTURE_2026_05_27.md` Phase 3d) made `agent_def_get`
178/// resolve a template launch's own row for the first time, which enabled
179/// Step 5's definition-provider gate for that whole agent class — but
180/// binding an identity to a TEMPLATE (the Agent Setup modal's supported
181/// target) has always written the link under the TEMPLATE's id, never the
182/// launch's own id, since nothing writes a launch-scoped link. Without
183/// this fallback, enabling Step 5 would have converted every template
184/// launch with a genuinely configured account into a hard spawn failure —
185/// the direct link lookup below finds nothing under the launch's own id
186/// regardless of whether an account is actually bound, because it never
187/// was.
188///
189/// `broker` publishes `identity:no-direct-links` when the direct set is
190/// empty — a standing diagnostic for a non-sentinel identity resolving to
191/// zero links (e.g. a stale/migrated-away instance). `None` in tests /
192/// call sites that don't have a broker handle.
193/// `parent_id`'s eligible-template gate for `resolve_bindings_for_instance`
194/// (see that function's doc comment for the P0 this closes): returns
195/// `parent_id` back only when it names a row with `is_seeded = 1` — a
196/// genuine template — never for a plain agent-to-agent fork, which reuses
197/// the same `parent_id`/`parent_template_id` column for unrelated lineage.
198/// `mstore` is the store `parent_id` was read from (the same one
199/// `agent_def_get` resolved the launch's own row through); an empty
200/// `parent_id`, a lookup failure, or a parent that resolves but isn't
201/// seeded all return `""` — "no eligible template parent," not an error.
202pub(super) fn template_parent_id_if_seeded(mstore: &Store, parent_id: &str) -> String {
203    if parent_id.is_empty() {
204        return String::new();
205    }
206    match mstore.agent_def_get(parent_id) {
207        Ok(Some(parent)) if parent.is_seeded == 1 => parent_id.to_string(),
208        Ok(Some(_)) => String::new(), // a fork's source, not a template — reagent P0 on #3092
209        Ok(None) => String::new(),
210        Err(e) => {
211            tracing::warn!(
212                target: "identity",
213                "template-parent lookup failed for {}: {} — treating as no eligible template parent",
214                parent_id,
215                e,
216            );
217            String::new()
218        }
219    }
220}
221
222fn resolve_bindings_for_instance(
223    id_store: &Store,
224    instance: &crate::backend::storage::store::AgentInstance,
225    parent_template_id: &str,
226    broker: Option<&Arc<Broker>>,
227) -> Vec<IdentityBinding> {
228    let direct = id_store
229        .agent_identity_list_for_agent(&instance.definition_id)
230        .unwrap_or_else(|e| {
231            tracing::warn!(
232                target: "identity",
233                "direct-link lookup failed for definition {}: {}",
234                instance.definition_id,
235                e,
236            );
237            Vec::new()
238        });
239
240    if direct.is_empty() && !parent_template_id.is_empty() {
241        let from_template = id_store
242            .agent_identity_list_for_agent(parent_template_id)
243            .unwrap_or_else(|e| {
244                tracing::warn!(
245                    target: "identity",
246                    "template link fallback failed for template {}: {}",
247                    parent_template_id,
248                    e,
249                );
250                Vec::new()
251            });
252        if !from_template.is_empty() {
253            return from_template
254                .into_iter()
255                .map(|l| IdentityBinding { provider: l.provider, account_id: l.account_id })
256                .collect();
257        }
258    }
259
260    if direct.is_empty() {
261        // Distinct log line + event so a non-sentinel identity resolving
262        // to zero links (e.g. an agent that was never linked to an
263        // account) is visible, not silently indistinguishable from
264        // routine "no accounts configured." Whether the spawn proceeds
265        // is decided by the caller's layer-3 definition-provider gate
266        // (oauth-class CLI provider with no bound account → blocked).
267        tracing::warn!(
268            target: "identity",
269            "no direct account links for definition {} (identity {}) — \
270             nothing to inject.",
271            instance.definition_id,
272            instance.identity_id,
273        );
274        if let Some(b) = broker {
275            let event = crate::backend::mps_events::NoDirectLinksEvent {
276                definition_id: instance.definition_id.clone(),
277                identity_id: instance.identity_id.clone(),
278            };
279            // Persisted (unlike the rest of this file's ephemeral
280            // events) — nothing subscribes live yet, so without
281            // persistence a future frontend surface polling via
282            // read_event_history would see nothing. Small window;
283            // this is a diagnostic, not an audit log.
284            b.publish_event::<crate::backend::mps_events::IdentityNoDirectLinks>(&event, vec![], 20);
285        }
286    }
287
288    direct
289        .into_iter()
290        .map(|l| IdentityBinding {
291            provider: l.provider,
292            account_id: l.account_id,
293        })
294        .collect()
295}
296
297/// Resolve an account by id, checking `id_store` first — the
298/// authoritative, per-account-isolatable primary, which is what preserves
299/// the disposable-test-account isolation guarantee — and falling
300/// back to `identity_store`'s read-through mirror
301/// (`IDENTITY_STORE_SCHEMA_VERSION` v2,
302/// `docs/specs/SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md` §3.1) only when the
303/// primary lookup misses. Returns the account alongside WHICH store it
304/// came from, so a caller that later writes a status update (the OAuth
305/// expiry probe below) writes it back to the SAME store instead of always
306/// assuming `id_store` — writing to the wrong store would silently create
307/// a second, never-read copy.
308///
309/// reagentx P0 review on PR #2632: before this, the link resolved via
310/// `identity_store` (always global) but the account it pointed at could
311/// still only exist in `id_store`, which is empty on a fresh, isolated
312/// channel — the reported continuity bug wasn't actually fixed end to end
313/// without this fallback.
314pub fn resolve_account(
315    id_store: &Arc<Store>,
316    identity_store: &Arc<Store>,
317    account_id: &str,
318) -> Result<Option<(IdentityAccount, Arc<Store>)>, StoreError> {
319    if let Some(a) = id_store.identity_get(account_id)? {
320        return Ok(Some((a, id_store.clone())));
321    }
322    if let Some(a) = identity_store.identity_get(account_id)? {
323        return Ok(Some((a, identity_store.clone())));
324    }
325    Ok(None)
326}
327
328/// SPAWN-PATH account lookup — **current channel's `id_store` only, never the
329/// global mirror.**
330///
331/// Deliberately NOT [`resolve_account`]: that function's global fallback is
332/// correct for read-only/display callers (the Connectors → Accounts list, link
333/// summaries — they should still describe an account that exists elsewhere),
334/// but using it to satisfy a *spawn* lets an agent in a fresh channel launch
335/// against a credential authenticated in a DIFFERENT channel. That is exactly
336/// the per-channel-isolation bypass the operator asked to close:
337///
338/// > "we want per-channel isolation. a user needs a login anytime in the
339/// > channel. the problem is agents are able to login in a channel without a
340/// > claude auth."
341///
342/// **This intentionally reverses part of reagentx's P0 on PR #2632.** That
343/// review added the fallback to preserve binding continuity across a
344/// version/channel switch, which was the right call under the then-current
345/// requirement. The requirement has since changed: per-channel isolation is a
346/// wanted feature, and re-login-per-channel is the accepted cost. The fallback
347/// is retained for display paths precisely so that continuity fix isn't lost
348/// where it was actually about *describing* an account rather than *launching*
349/// with one. See
350/// `docs/analysis/ANALYSIS_PER_CHANNEL_AUTH_BYPASSES_2026_08_31.md` §2 (#1).
351///
352/// No dangling-link deadlock results from the stricter lookup:
353/// `db_agent_identity_links` is `PRIMARY KEY (agent_id, provider)`, so a
354/// re-login in the new channel REPLACES the link rather than leaving a stale
355/// one that would block every future spawn.
356pub fn resolve_account_for_spawn(
357    id_store: &Arc<Store>,
358    account_id: &str,
359) -> Result<Option<(IdentityAccount, Arc<Store>)>, StoreError> {
360    Ok(id_store
361        .identity_get(account_id)?
362        .map(|a| (a, id_store.clone())))
363}
364
365/// Read-only lookup of a block's identity-bound OAuth config dir — the same
366/// directory `inject_identity_env_with_broker`'s OAuth branch would inject,
367/// without any of that function's side effects (no token-expiry probe, no
368/// account-status upsert, no `identityaccounts:changed` publish, no
369/// `SpawnGateError` on failure). For a background caller that only needs to
370/// know WHERE to look (e.g. `subagent_watcher` deciding which directory to
371/// watch at agent registration, not spawn) rather than what to inject.
372///
373/// Deliberately does not call `inject_identity_env`/`inject_identity_env_with_broker`:
374/// those also resolve API-key-class secrets into the caller's env map (a
375/// leak risk for a caller that only wants a path) and perform real writes —
376/// none of which belong on every registration, only on an actual spawn/turn.
377/// See `SPEC_SUBAGENT_WATCHER_IDENTITY_BOUND_CONFIG_DIR_2026_08_22.md`.
378///
379/// Returns `None` (never an error) for: no instance for this block, no
380/// definition, a non-OAuth-class (or unrecognized) provider, no direct
381/// binding for that provider, an account row that doesn't resolve, or a
382/// `secret_ref` that isn't `OAuthConfigDir` — every one of these is exactly
383/// "nothing bound, fall back to the old behavior" for a caller that isn't
384/// gating a spawn.
385pub fn resolve_bound_oauth_config_dir(
386    mstore: &Arc<Store>,
387    id_store: &Arc<Store>,
388    identity_store: &Arc<Store>,
389    block_id: &str,
390) -> Option<PathBuf> {
391    let instance = mstore.instance_get_active_for_block(block_id).ok().flatten()?;
392    bound_oauth_config_dir(mstore, id_store, identity_store, &instance)
393}
394
395/// [`resolve_bound_oauth_config_dir`] for a **Claude** agent row by its id,
396/// with no block — memory resolution's question (#3603): where does this
397/// agent's Claude run, so where are its memories (`projects/<cwd>/memory`,
398/// a Claude layout). `None` for any other provider, and for an account bound
399/// to the ambient `~/.claude` — the spawn refuses that dir, and memory
400/// writes must never land in the user's own Claude projects.
401pub fn resolve_bound_claude_config_dir_for_agent(
402    mstore: &Store,
403    id_store: &Arc<Store>,
404    identity_store: &Arc<Store>,
405    agent_id: &str,
406) -> Option<PathBuf> {
407    let instance = mstore.instance_get(agent_id).ok().flatten()?;
408    let def = mstore.agent_def_get(&instance.definition_id).ok().flatten()?;
409    let provider = id_store.resolve_effective_provider_id(&def);
410    if resolve_provider_alias(&provider) != "claude" {
411        return None;
412    }
413    let dir = bound_oauth_config_dir(mstore, id_store, identity_store, &instance)?;
414    let claude = crate::backend::providers::get_provider("claude")?;
415    if crate::backend::providers::is_provider_ambient_home_dir(claude, &dir.to_string_lossy()) {
416        return None;
417    }
418    Some(dir)
419}
420
421/// Whether an agent has any identity binding — its own links, or its
422/// template's when it has none — checked without the binding resolver's
423/// "no links" warning. For callers that ask on every sweep (memory), so an
424/// unlinked agent costs a lookup, not a log line.
425pub fn agent_has_identity_binding(mstore: &Store, identity_store: &Store, agent_id: &str) -> bool {
426    let direct = identity_store
427        .agent_identity_list_for_agent(agent_id)
428        .map(|l| !l.is_empty())
429        .unwrap_or(false);
430    if direct {
431        return true;
432    }
433    let Some(def) = mstore.agent_def_get(agent_id).ok().flatten() else {
434        return false;
435    };
436    let parent = template_parent_id_if_seeded(mstore, &def.parent_id);
437    !parent.is_empty()
438        && identity_store
439            .agent_identity_list_for_agent(&parent)
440            .map(|l| !l.is_empty())
441            .unwrap_or(false)
442}
443
444fn bound_oauth_config_dir(
445    mstore: &Store,
446    id_store: &Arc<Store>,
447    identity_store: &Arc<Store>,
448    instance: &crate::backend::storage::store::AgentInstance,
449) -> Option<PathBuf> {
450    let def = mstore.agent_def_get(&instance.definition_id).ok().flatten()?;
451    let effective_provider = id_store.resolve_effective_provider_id(&def);
452    let canonical_provider = resolve_provider_alias(&effective_provider).to_string();
453    if !matches!(provider_class(&canonical_provider), Some(ProviderClass::OAuth { .. })) {
454        return None;
455    }
456
457    let template_parent_id = template_parent_id_if_seeded(mstore, &def.parent_id);
458    let bindings = resolve_bindings_for_instance(identity_store, instance, &template_parent_id, None);
459    if let Some(dir) = steps::key_route_dir(&bindings, &canonical_provider) { return Some(dir); }
460    let binding = bindings.iter().find(|b| resolve_provider_alias(&b.provider) == canonical_provider)?;
461    // Per-channel only, matching the spawn gate exactly: this function's whole
462    // contract is "where WOULD the spawn inject," so resolving an account the
463    // spawn itself would now refuse would point a watcher at a directory no
464    // agent can actually launch against.
465    let (account, _store) = resolve_account_for_spawn(id_store, &binding.account_id).ok().flatten()?;
466    match account.secret_ref {
467        SecretRef::OAuthConfigDir { dir } => Some(PathBuf::from(dir)),
468        _ => None,
469    }
470}
471
472/// The agent a block names (`agentId`, or legacy `agent:id`), if any.
473pub fn block_agent_id(mstore: &Store, block_id: &str) -> Option<String> {
474    let block: crate::backend::obj::Block = mstore.get(block_id).ok().flatten()?;
475    crate::backend::obj::block_meta_agent_id(&block.meta)
476        .map(str::trim)
477        .filter(|s| !s.is_empty())
478        .map(str::to_string)
479}
480
481/// **Before touching `gate_oauth_failure` / `inject_identity_env_with_broker`:**
482/// this module is where `SPEC_PROVIDER_ISOLATION_2026_06_20.md`'s INV-A
483/// ("never the user's global `~/.<P>` dir") is enforced — or, once already,
484/// silently stopped being enforced. Read
485/// `docs/retro/retro-auth-isolation-invariant-silently-orphaned-2026-07-14.md`
486/// first. Short version: an unbound oauth-class provider used to
487/// auto-route to an AgentMux-owned isolated dir (no user action, no global
488/// exposure); a 2026-07-08 refactor orphaned that path without meaning to,
489/// and it was never restored. Today's gate always blocks an unbound
490/// oauth-class provider; the per-agent "true ambient" opt-out
491/// (`use_ambient_login`) is no longer read.
492pub fn inject_identity_env_with_broker(
493    mstore: Arc<Store>,
494    id_store: Arc<Store>,
495    identity_store: Arc<Store>,
496    broker: Option<Arc<Broker>>,
497    block_id: &str,
498    env_vars: &mut HashMap<String, String>,
499) -> Result<(), SpawnGateError> {
500    inject_identity_env_for_spawn(mstore, id_store, identity_store, broker, block_id, env_vars, false)
501}
502
503/// [`inject_identity_env_with_broker`] for a spawn that may bring its own Claude endpoint.
504/// `own_claude_endpoint` is true for a Claude Code agent whose environment names a model server of its
505/// own (`spawn_env::endpoint`): the person's Claude account is discarded for that agent and its own
506/// authentication (a Vault key opened to it, or a placeholder) is put in after this step, so the
507/// account is neither injected nor required: an unlinked agent, or one whose account no longer
508/// resolves, is not refused for it. Every other check stays: the instance lookup, other providers'
509/// bindings, and the deleted-agent check at the gate's exit.
510pub fn inject_identity_env_for_spawn(
511    mstore: Arc<Store>,
512    id_store: Arc<Store>,
513    identity_store: Arc<Store>,
514    broker: Option<Arc<Broker>>,
515    block_id: &str,
516    env_vars: &mut HashMap<String, String>,
517    own_claude_endpoint: bool,
518) -> Result<(), SpawnGateError> {
519    // Step 1: instance lookup — per-channel, always reads from mstore.
520    let instance = match mstore.instance_get_active_for_block(block_id) {
521        Ok(Some(i)) => i,
522        Ok(None) => return steps::check_row_less_block(&mstore, block_id),
523        Err(e) => {
524            tracing::warn!(target: "identity", "instance lookup failed for block {}: {}", block_id, e);
525            return Ok(());
526        }
527    };
528
529    let on_route = steps::on_model_route(&mstore, &instance);
530
531    // Layer-3 gate input: the agent definition's own CLI provider.
532    let (def_provider, parent_template_id) = steps::definition_provider(&mstore, &id_store, &instance);
533
534    // Step 3: bindings — global, reads from id_store. Direct-links-only
535    // as of Phase 3 slice 2 PR-B (the flip) — see resolve_bindings_for_instance's
536    // doc comment for the transitional gap this closes and the one it
537    // doesn't (#1624 PR-C). Falls back to the launch's TEMPLATE's own links
538    // when the launch has none of its own (codex P1 on #3092) — binding an
539    // identity to a template has always written the link under the
540    // template's id, never a launch's.
541    //
542    // NOTE: an empty set no longer short-circuits — it falls through to the
543    // definition-provider gate (step 5; spec §2.2 edge case: an agent whose
544    // oauth-class CLI provider has no binding at all is blocked).
545    let bindings = resolve_bindings_for_instance(&identity_store, &instance, &parent_template_id, broker.as_ref());
546
547    // Diagnostic only (#30077): an empty legacy identity_id is normal; say what resolves creds (debug).
548    steps::note_blank_identity(&instance, block_id, &bindings, on_route);
549    // Step 4: per-binding resolution + env injection.
550    let mut injector = steps::BindingInjector {
551        id_store: &id_store,
552        identity_store: &identity_store,
553        broker: broker.as_ref(),
554        instance: &instance, injected_oauth: std::collections::HashSet::new(), mstore: &mstore, def_provider: def_provider.as_deref(), own_endpoint: own_claude_endpoint,
555    };
556    for binding in &bindings {
557        injector.inject(binding, env_vars)?;
558    }
559
560    // Step 5: the definition-provider gate (spec §2.2 edge case).
561    let brings_own_login = on_route || (own_claude_endpoint && def_provider.as_deref() == Some("claude"));
562     if !brings_own_login { steps::gate_unbound_provider(def_provider.clone(), &injector.injected_oauth, &bindings, &identity_store, &instance, &parent_template_id)?; }
563
564    // #3577, re-checked at the gate's own exit.
565    steps::recheck_agent_not_deleted(&mstore, &instance)
566}
567
568#[path = "inject_steps.rs"]
569pub mod steps;
570
571#[cfg(test)]
572mod tests {
573    #[path = "../../inject_own_endpoint_tests.rs"]
574    pub mod own_endpoint;
575    #[path = "../../inject_key_route_tests.rs"]
576    pub mod key_route;
577    use super::*;
578    use super::super::oauth_probe::oauth_status;
579    use crate::backend::storage::store::{
580        AgentInstance, IdentityAccount, Bundle, SecretRef,
581    };
582
583    fn make_store() -> Arc<Store> {
584        Arc::new(Store::open_in_memory().unwrap())
585    }
586
587    /// A store with a shared definition registry (in `tmp`) — the thing that
588    /// remembers a deleted agent as a retired record.
589    fn store_with_def_registry(tmp: &tempfile::TempDir) -> Arc<Store> {
590        let store = make_store();
591        let defs = crate::registry::DefinitionStore::open(tmp.path().join("definitions")).unwrap();
592        store.set_def_registry(Arc::new(defs));
593        store
594    }
595
596    /// #3577: a pane whose agent was deleted (row gone, registry record
597    /// retired) is refused at the gate instead of spawning on the shared
598    /// login with no identity.
599    #[test]
600    fn a_block_naming_a_deleted_agent_is_refused() {
601        let tmp = tempfile::tempdir().unwrap();
602        let store = store_with_def_registry(&tmp);
603        let mut def = crate::backend::storage::agents::test_agent_def(
604            "agent-deleted-3577",
605            "Gone",
606            "claude",
607            "agent",
608            1,
609            "",
610        );
611        store.agent_def_insert(&mut def).unwrap();
612        assert!(
613            store
614                .shared_def_registry()
615                .unwrap()
616                .exists("agent-deleted-3577"),
617            "precondition: mirrored"
618        );
619        assert!(store.agent_def_delete("agent-deleted-3577").unwrap());
620        insert_block_for_agent(&store, "block-deleted-3577", "agent-deleted-3577");
621
622        let mut env = HashMap::new();
623        let res = inject_identity_env_with_broker(
624            store.clone(),
625            store.clone(),
626            store.clone(),
627            None,
628            "block-deleted-3577",
629            &mut env,
630        );
631        assert_eq!(
632            res,
633            Err(SpawnGateError::AgentDeleted {
634                agent_id: "agent-deleted-3577".to_string()
635            })
636        );
637    }
638
639    /// Only a positive "deleted" signal refuses. A block naming a template
640    /// id (a template session, a quick-launch provider key), a live
641    /// cross-channel agent (active registry record, no local row), or
642    /// anything at all when there is no registry to ask, keeps today's
643    /// ungated behaviour.
644    #[test]
645    fn a_row_less_block_not_naming_a_deleted_agent_is_not_refused() {
646        let tmp = tempfile::tempdir().unwrap();
647        let store = store_with_def_registry(&tmp);
648        let mut tpl = crate::backend::storage::agents::test_agent_def(
649            "claude", "Claude", "claude", "agent", 1, "",
650        );
651        tpl.is_seeded = 1;
652        store.agent_def_insert(&mut tpl).unwrap();
653        store
654            .shared_def_registry()
655            .unwrap()
656            .upsert(&crate::registry::DefinitionRecord {
657                schema_version: crate::registry::DEF_MAX_SUPPORTED_SCHEMA,
658                data: crate::registry::DefinitionRecordV1 {
659                    id: "agent-elsewhere-3577".to_string(),
660                    name: "Elsewhere".to_string(),
661                    provider: "claude".to_string(),
662                    ..Default::default()
663                },
664            })
665            .unwrap();
666        insert_block_for_agent(&store, "block-template-3577", "claude");
667        insert_block_for_agent(&store, "block-cross-3577", "agent-elsewhere-3577");
668        insert_block_for_agent(&store, "block-unknown-3577", "never-existed");
669        for block in [
670            "block-template-3577",
671            "block-cross-3577",
672            "block-unknown-3577",
673        ] {
674            let mut env = HashMap::new();
675            let res = inject_identity_env_with_broker(
676                store.clone(),
677                store.clone(),
678                store.clone(),
679                None,
680                block,
681                &mut env,
682            );
683            assert_eq!(res, Ok(()), "{block}");
684        }
685
686        // No registry at all: a deleted agent cannot be told apart, so the
687        // gate stays open rather than guessing.
688        let bare = make_store();
689        insert_block_for_agent(&bare, "block-bare-3577", "agent-deleted-anywhere");
690        let mut env = HashMap::new();
691        assert_eq!(
692            inject_identity_env_with_broker(
693                bare.clone(),
694                bare.clone(),
695                bare.clone(),
696                None,
697                "block-bare-3577",
698                &mut env
699            ),
700            Ok(())
701        );
702    }
703
704    fn make_account(
705        id: &str,
706        provider: &str,
707        secret_ref: SecretRef,
708    ) -> IdentityAccount {
709        IdentityAccount {
710            id: id.to_string(),
711            name: format!("{}-{}", provider, id),
712            provider: provider.to_string(),
713            kind: "pat".to_string(),
714            display_name: String::new(),
715            secret_ref,
716            context: serde_json::json!({}),
717            status: "unknown".to_string(),
718            created_at: 0,
719            updated_at: 0,
720        }
721    }
722
723    /// Insert a Block row whose `meta.agentId` points at the agent
724    /// def. Phase 3b.4 made `instance_get_active_for_block` resolve
725    /// via the block→agent reference (instead of filtering instance
726    /// rows by status), so every resolver test that exercises the
727    /// inject path needs a real block in the store.
728    fn insert_block_for_agent(store: &Store, block_id: &str, agent_id: &str) {
729        use crate::backend::obj::{Block, MetaMapType};
730        let mut block = Block {
731            oid: block_id.to_string(),
732            parentoref: String::new(),
733            version: 0,
734            runtimeopts: None,
735            stickers: None,
736            meta: {
737                let mut m = MetaMapType::new();
738                m.insert("view".to_string(), serde_json::json!("agent"));
739                m.insert("agentId".to_string(), serde_json::json!(agent_id));
740                m
741            },
742            subblockids: None,
743        };
744        store.insert(&mut block).unwrap();
745    }
746
747    /// A genuinely writable temp path for a test's `SecretRef::OAuthConfigDir`.
748    ///
749    /// `inject_identity_env` now really seeds a `CLAUDE.md` into the bound dir
750    /// and FAILS CLOSED if it can't (SPEC_ISOLATE_HOST_CLAUDE_MD_2026_08_31.md),
751    /// so these tests need a dir that actually exists/can be created rather
752    /// than a synthetic absolute path. The previous `/var/agentmux/...`
753    /// literals were unwritable on Linux CI (`Permission denied`) while
754    /// silently resolving to the current drive on Windows — green locally,
755    /// red on the ubuntu leg.
756    fn test_config_dir(name: &str) -> String {
757        std::env::temp_dir()
758            .join(format!("agentmux-inject-test-{}-{name}", std::process::id()))
759            .to_string_lossy()
760            .into_owned()
761    }
762
763    fn make_instance(block_id: &str, identity_id: &str) -> AgentInstance {
764        AgentInstance {
765            identity_id: identity_id.to_string(),
766            ..crate::backend::storage::agents::test_agent_instance(&format!("inst-{block_id}"), "def-1", block_id, 0)
767        }
768    }
769
770    #[cfg(debug_assertions)]
771    #[test]
772    fn inject_oauth_class_sets_config_dir_env_var() {
773        let store = make_store();
774
775        let mut def = crate::backend::storage::store::AgentDefinition {
776            slug: String::new(),
777            icon: "✦".to_string(),
778            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
779        };
780        store.agent_def_insert(&mut def).unwrap();
781
782        let claude = make_account(
783            "acct-claude",
784            "claude",
785            SecretRef::OAuthConfigDir {
786                dir: test_config_dir("id-oauth"),
787            },
788        );
789        store.identity_upsert(&claude).unwrap();
790        store
791            .agent_identity_link("def-1", "acct-claude", "claude")
792            .unwrap();
793
794        insert_block_for_agent(&store, "block-oauth", "def-1");
795        let inst = make_instance("block-oauth", "id-oauth");
796        store.instance_create(&inst).unwrap();
797
798        let mut env: HashMap<String, String> = HashMap::new();
799        // Spec §2.5 regression: a resolvable oauth account injects
800        // unchanged — the layer-3 gate never fires.
801        inject_identity_env(store.clone(), store.clone(), store, "block-oauth", &mut env).unwrap();
802
803        // OAuth dispatch sets the provider's config-dir env var.
804        assert_eq!(
805            env.get("CLAUDE_CONFIG_DIR").cloned(),
806            Some(test_config_dir("id-oauth")),
807        );
808        // And does NOT set the anthropic api-key env var — dispatch
809        // is by provider class, not by token shape.
810        assert!(env.get("ANTHROPIC_API_KEY").is_none());
811    }
812
813    /// docs/specs/SPEC_BLOCK_AMBIENT_HOME_DIR_IDENTITY_BINDING_2026_08_25.md —
814    /// the enforcement that closes the real, currently-live gap found in
815    /// docs/status/STATUS_IDENTITY_ISOLATION_GATE_NOT_ENFORCING_2026_08_20.md
816    /// §8 (an account whose `secret_ref.dir` was the literal ambient home).
817    /// Uses the REAL `get_home_dir()` (not a mock) so this exercises the
818    /// exact same resolution production code does — deterministic
819    /// regardless of whether `~/.claude` actually exists on the test
820    /// machine, since `paths_resolve_to_same_dir`'s lexical fallback
821    /// handles "doesn't exist" and its canonicalize branch handles
822    /// "exists" identically correctly (see providers.rs's own tests).
823    #[cfg(debug_assertions)]
824    #[test]
825    fn inject_oauth_class_blocks_spawn_when_config_dir_is_the_ambient_home() {
826        let store = make_store();
827
828        let mut def = crate::backend::storage::store::AgentDefinition {
829            slug: String::new(),
830            icon: "✦".to_string(),
831            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
832        };
833        store.agent_def_insert(&mut def).unwrap();
834
835        let ambient_claude_dir = crate::backend::base::get_home_dir()
836            .join(".claude")
837            .to_string_lossy()
838            .into_owned();
839        let claude = make_account(
840            "acct-ambient",
841            "claude",
842            SecretRef::OAuthConfigDir { dir: ambient_claude_dir.clone() },
843        );
844        store.identity_upsert(&claude).unwrap();
845        store
846            .agent_identity_link("def-1", "acct-ambient", "claude")
847            .unwrap();
848
849        insert_block_for_agent(&store, "block-ambient", "def-1");
850        let inst = make_instance("block-ambient", "id-ambient");
851        store.instance_create(&inst).unwrap();
852
853        let mut env: HashMap<String, String> = HashMap::new();
854        let err = inject_identity_env(store.clone(), store.clone(), store, "block-ambient", &mut env)
855            .expect_err("spawn must be refused when the bound account's config dir is the ambient home");
856
857        match err {
858            SpawnGateError::AmbientHomeDirNotAllowed { provider, dir } => {
859                assert_eq!(provider, "claude");
860                assert_eq!(dir, ambient_claude_dir);
861            }
862            other => panic!("expected AmbientHomeDirNotAllowed, got {other:?}"),
863        }
864        // The gate must block BEFORE anything is injected — no partial
865        // env-var leak from the refused binding.
866        assert!(env.get("CLAUDE_CONFIG_DIR").is_none());
867    }
868
869    /// Codex P1 + ReAgent P1 on PR #2854: seeding the CLAUDE.md isolation
870    /// placeholder must fail closed, not warn-and-continue — otherwise the
871    /// agent spawns with a CLAUDE_CONFIG_DIR that still has no CLAUDE.md,
872    /// exactly the condition that falls through to the ambient home. An
873    /// empty `dir` (rejected by seed_claude_md_placeholder_if_missing's own
874    /// InvalidInput guard) is a deterministic, cross-platform way to
875    /// trigger a seed failure without relying on real filesystem
876    /// permissions. It is also NOT the ambient home, so this exercises the
877    /// seed check specifically, not the AmbientHomeDirNotAllowed path
878    /// covered by the test above.
879    #[cfg(debug_assertions)]
880    #[test]
881    fn inject_oauth_class_blocks_spawn_when_claude_md_seed_fails() {
882        let store = make_store();
883
884        let mut def = crate::backend::storage::store::AgentDefinition {
885            slug: String::new(),
886            icon: "✦".to_string(),
887            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
888        };
889        store.agent_def_insert(&mut def).unwrap();
890
891        let claude = make_account(
892            "acct-empty-dir",
893            "claude",
894            SecretRef::OAuthConfigDir { dir: String::new() },
895        );
896        store.identity_upsert(&claude).unwrap();
897        store
898            .agent_identity_link("def-1", "acct-empty-dir", "claude")
899            .unwrap();
900
901        insert_block_for_agent(&store, "block-empty-dir", "def-1");
902        let inst = make_instance("block-empty-dir", "id-empty-dir");
903        store.instance_create(&inst).unwrap();
904
905        let mut env: HashMap<String, String> = HashMap::new();
906        let err = inject_identity_env(store.clone(), store.clone(), store, "block-empty-dir", &mut env)
907            .expect_err("spawn must be refused when the CLAUDE.md isolation seed fails");
908
909        match err {
910            SpawnGateError::ClaudeMdSeedFailed { provider, dir, .. } => {
911                assert_eq!(provider, "claude");
912                assert_eq!(dir, "");
913            }
914            other => panic!("expected ClaudeMdSeedFailed, got {other:?}"),
915        }
916        // The gate must block BEFORE anything is injected — no partial
917        // env-var leak from the refused binding.
918        assert!(env.get("CLAUDE_CONFIG_DIR").is_none());
919    }
920
921    /// **Behavior deliberately REVERSED 2026-08-31 (operator instruction).**
922    ///
923    /// This test previously asserted the opposite: that a spawn MUST succeed
924    /// by falling back to the global mirror when the per-channel `id_store`
925    /// lacks the account (reagentx P0 on PR #2632, protecting binding
926    /// continuity across a version/channel switch).
927    ///
928    /// Per-channel isolation is a wanted feature, and that fallback is exactly
929    /// what let an agent in a fresh channel launch against another channel's
930    /// credential with no account of its own. The operator's requirement:
931    ///
932    /// > "we want per-channel isolation. a user needs a login anytime in the
933    /// > channel."
934    ///
935    /// So the same scenario must now BLOCK, surfacing the ordinary
936    /// `MissingCredentials` auth card, and the user logs in for this channel.
937    /// The old continuity guarantee is intentionally given up here; the
938    /// fallback survives only for read-only/display callers.
939    /// See `docs/analysis/ANALYSIS_PER_CHANNEL_AUTH_BYPASSES_2026_08_31.md`.
940    #[cfg(debug_assertions)]
941    #[test]
942    fn inject_refuses_an_account_that_only_exists_in_the_global_mirror() {
943        let mstore = make_store();
944        // Deliberately EMPTY of the account and link — simulates a fresh,
945        // isolated per-channel id_store on a new channel/version.
946        let id_store = make_store();
947        // Real identity-store schema (no account_id/agent_id FK, matching
948        // production's Store::open_identity_store — NOT open_in_memory's
949        // channel schema, which still has both FKs and would reject this
950        // link since "def-1" only exists in mstore's own definitions
951        // table, a different physical store). Simulates the post-migration
952        // state: both the link AND the account mirror row live here,
953        // exactly what m0022_identity_store_links_backfill produces.
954        let identity_store_tmp = tempfile::NamedTempFile::new().unwrap();
955        let identity_store = Arc::new(Store::open_identity_store(identity_store_tmp.path()).unwrap());
956
957        let mut def = crate::backend::storage::store::AgentDefinition {
958            slug: String::new(),
959            icon: "✦".to_string(),
960            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
961        };
962        mstore.agent_def_insert(&mut def).unwrap();
963
964        let claude = make_account(
965            "acct-migrated",
966            "claude",
967            SecretRef::OAuthConfigDir {
968                dir: test_config_dir("id-migrated"),
969            },
970        );
971        identity_store.identity_upsert(&claude).unwrap();
972        identity_store
973            .agent_identity_link("def-1", "acct-migrated", "claude")
974            .unwrap();
975
976        insert_block_for_agent(&mstore, "block-continuing", "def-1");
977        let inst = make_instance("block-continuing", "id-continuing");
978        mstore.instance_create(&inst).unwrap();
979
980        let mut env: HashMap<String, String> = HashMap::new();
981        let res = inject_identity_env(mstore, id_store, identity_store, "block-continuing", &mut env);
982
983        assert!(
984            matches!(res, Err(SpawnGateError::MissingCredentials { .. })),
985            "an account that exists ONLY in the global mirror must NOT satisfy a spawn in \
986             this channel — that is the per-channel-isolation bypass; expected \
987             MissingCredentials, got {res:?}"
988        );
989        assert!(
990            env.get("CLAUDE_CONFIG_DIR").is_none(),
991            "nothing may be injected from a refused cross-channel account"
992        );
993    }
994
995    /// **Behavior deliberately REVERSED 2026-08-31 (operator instruction)** —
996    /// companion to the test above, closing the same bypass from the other
997    /// direction.
998    ///
999    /// Originally reagentx round-3 P0 on PR #2632: it proved that an account
1000    /// written through `identity_upsert_with_mirror` (every live write path —
1001    /// `identity.account.upsert`, OAuth persist) still resolved after a
1002    /// channel switch, not just migration-backfilled ones.
1003    ///
1004    /// That is now precisely the wrong outcome: it made the bypass apply to
1005    /// *newly created* accounts too, so every fresh channel silently inherited
1006    /// the last one's credential. The dual-write itself is retained (display
1007    /// callers still use `resolve_account`'s fallback to describe an account);
1008    /// what changed is that a mirror row can no longer authorize a SPAWN.
1009    #[cfg(debug_assertions)]
1010    #[test]
1011    fn inject_refuses_a_mirror_written_account_after_a_channel_switch() {
1012        let mstore = make_store();
1013        let id_store = make_store();
1014        let identity_store_tmp = tempfile::NamedTempFile::new().unwrap();
1015        let identity_store = Arc::new(Store::open_identity_store(identity_store_tmp.path()).unwrap());
1016
1017        // `make_instance` below hardcodes `definition_id: "def-1"` — match it
1018        // rather than parameterizing a helper shared with other tests.
1019        let mut def = crate::backend::storage::store::AgentDefinition {
1020            slug: String::new(),
1021            icon: "✦".to_string(),
1022            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1023        };
1024        mstore.agent_def_insert(&mut def).unwrap();
1025
1026        // "Before the channel switch": the account is created live, via the
1027        // same helper `identity.account.upsert`/OAuth persist use — writing
1028        // to id_store (the then-current, then-primary store) AND dual-
1029        // writing the mirror into identity_store.
1030        let claude = make_account(
1031            "acct-fresh",
1032            "claude",
1033            SecretRef::OAuthConfigDir {
1034                dir: test_config_dir("id-fresh"),
1035            },
1036        );
1037        id_store.identity_upsert_with_mirror(&identity_store, &claude).unwrap();
1038        identity_store
1039            .agent_identity_link("def-1", "acct-fresh", "claude")
1040            .unwrap();
1041
1042        insert_block_for_agent(&mstore, "block-fresh", "def-1");
1043        let inst = make_instance("block-fresh", "id-fresh");
1044        mstore.instance_create(&inst).unwrap();
1045
1046        // "After the channel switch": a brand-new, empty id_store — the
1047        // account row created above must be unreachable here, exactly like
1048        // a fresh per-channel-isolated store on a new channel.
1049        let id_store_after_switch = make_store();
1050
1051        let mut env: HashMap<String, String> = HashMap::new();
1052        let res = inject_identity_env(mstore, id_store_after_switch, identity_store, "block-fresh", &mut env);
1053
1054        assert!(
1055            matches!(res, Err(SpawnGateError::MissingCredentials { .. })),
1056            "REVERSED 2026-08-31: a mirror row must no longer carry a spawn across a channel \
1057             switch, however it was written — dual-writing the mirror is not a substitute for \
1058             logging in on this channel; expected MissingCredentials, got {res:?}"
1059        );
1060        assert!(env.get("CLAUDE_CONFIG_DIR").is_none());
1061    }
1062
1063    // reagentx P1 on PR #2605: this is the ordinary spawn path (not
1064    // `auth.start`) — it reads a PREVIOUSLY STORED OAuthConfigDir, which
1065    // is exactly the case an account provisioned before the history-link
1066    // feature existed (or since its last `auth.start`) is in. Proves the
1067    // link now gets (re-)created here too, not only at auth.start.
1068    #[cfg(debug_assertions)]
1069    #[test]
1070    fn inject_oauth_class_links_conversation_history_on_the_ordinary_spawn_path() {
1071        let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK
1072            .lock()
1073            .unwrap_or_else(|e| e.into_inner());
1074        let tmp = tempfile::TempDir::new().unwrap();
1075        std::env::set_var("AGENTMUX_HOME_OVERRIDE", tmp.path());
1076        std::env::set_var("AGENTMUX_ISOLATED_AUTH", "1");
1077        let paths = agentmux_common::DataPaths::resolve(
1078            "0.0.0-test",
1079            &agentmux_common::RuntimeMode::Installed,
1080        )
1081        .unwrap();
1082        paths.ensure_dirs().unwrap();
1083        for (k, v) in paths.to_env_vars() {
1084            std::env::set_var(k, v);
1085        }
1086
1087        // A credential dir that ALREADY exists on disk, under the isolated
1088        // (per-channel) tree, with real pre-existing history in it — the
1089        // account was provisioned (auth.start ran) before this test's
1090        // spawn-time call, exactly like a real already-connected account.
1091        let isolated_dir = paths.instance_dir.join("identities").join("acct-claude").join("claude");
1092        std::fs::create_dir_all(isolated_dir.join("projects")).unwrap();
1093        std::fs::write(
1094            isolated_dir.join("projects").join("existing-session.jsonl"),
1095            b"pre-existing history",
1096        )
1097        .unwrap();
1098
1099        let store = make_store();
1100        let mut def = crate::backend::storage::store::AgentDefinition {
1101            slug: String::new(),
1102            icon: "✦".to_string(),
1103            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1104        };
1105        store.agent_def_insert(&mut def).unwrap();
1106
1107        let claude = make_account(
1108            "acct-claude",
1109            "claude",
1110            SecretRef::OAuthConfigDir { dir: isolated_dir.to_string_lossy().to_string() },
1111        );
1112        store.identity_upsert(&claude).unwrap();
1113        store.agent_identity_link("def-1", "acct-claude", "claude").unwrap();
1114        insert_block_for_agent(&store, "block-oauth-history", "def-1");
1115        let inst = make_instance("block-oauth-history", "id-oauth");
1116        store.instance_create(&inst).unwrap();
1117
1118        let mut env: HashMap<String, String> = HashMap::new();
1119        inject_identity_env(store.clone(), store.clone(), store, "block-oauth-history", &mut env).unwrap();
1120
1121        let global_history = paths.identity_history_dir("acct-claude", "claude", "projects");
1122        let via_link = std::fs::read(global_history.join("existing-session.jsonl"))
1123            .expect("pre-existing history must have been migrated to the global location by the spawn-time link");
1124        assert_eq!(via_link, b"pre-existing history");
1125
1126        std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
1127        std::env::remove_var("AGENTMUX_ISOLATED_AUTH");
1128        for (k, _) in paths.to_env_vars() {
1129            std::env::remove_var(k);
1130        }
1131    }
1132
1133    #[cfg(debug_assertions)]
1134    #[test]
1135    fn inject_oauth_class_blocks_account_with_non_oauth_secret_ref() {
1136        // An oauth-class provider (claude) bound to an account whose
1137        // SecretRef is the API-key shape (Env) is a misconfiguration:
1138        // the account is unresolvable for the provider, so the layer-3
1139        // gate blocks the spawn instead of
1140        // mis-injecting the wrong secret or silently launching on the
1141        // user's global login.
1142        let store = make_store();
1143
1144        let mut def = crate::backend::storage::store::AgentDefinition {
1145            slug: String::new(),
1146            icon: "✦".to_string(),
1147            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1148        };
1149        store.agent_def_insert(&mut def).unwrap();
1150
1151        let bad = make_account(
1152            "acct-bad",
1153            "claude",
1154            SecretRef::Env {
1155                env_var: "CLAUDE_TOKEN_NOT_A_DIR".to_string(),
1156            },
1157        );
1158        store.identity_upsert(&bad).unwrap();
1159        store
1160            .agent_identity_link("def-1", "acct-bad", "claude")
1161            .unwrap();
1162
1163        insert_block_for_agent(&store, "block-bad", "def-1");
1164        let inst = make_instance("block-bad", "id-bad");
1165        store.instance_create(&inst).unwrap();
1166
1167        let mut env: HashMap<String, String> = HashMap::new();
1168        let res = inject_identity_env(store.clone(), store.clone(), store, "block-bad", &mut env);
1169
1170        // Blocking spawn-gate error — and nothing injected.
1171        assert_eq!(
1172            res,
1173            Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: true }),
1174        );
1175        assert!(env.get("CLAUDE_CONFIG_DIR").is_none());
1176        assert!(env.is_empty());
1177    }
1178
1179    #[cfg(debug_assertions)]
1180    #[test]
1181    fn inject_oauth_class_succeeds_when_the_only_binding_is_under_a_legacy_alias() {
1182        // codex P1 on PR #2377: a definition's own `provider` is canonical
1183        // ("claude"), but its only db_agent_identity_links row is still
1184        // under a legacy alias ("claude-code") — carried forward from
1185        // before providers.rs's alias table existed, or a definition/link
1186        // pair that otherwise drifted. The binding injects successfully
1187        // (provider_class already resolves aliases), but before this fix
1188        // the def-provider gate compared the raw `injected_oauth`/binding
1189        // provider strings against the canonical def_provider and treated
1190        // the alias-bound account as "no account bound at all" — blocking
1191        // a spawn that had already successfully injected valid credentials
1192        // moments earlier in the same function.
1193        let store = make_store();
1194
1195        let mut def = crate::backend::storage::store::AgentDefinition {
1196            slug: String::new(),
1197            icon: "✦".to_string(),
1198            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1199        };
1200        store.agent_def_insert(&mut def).unwrap();
1201
1202        let claude = make_account(
1203            "acct-alias",
1204            "claude-code",
1205            SecretRef::OAuthConfigDir {
1206                dir: test_config_dir("id-alias"),
1207            },
1208        );
1209        store.identity_upsert(&claude).unwrap();
1210        // Bound under the alias, not the canonical "claude".
1211        store
1212            .agent_identity_link("def-1", "acct-alias", "claude-code")
1213            .unwrap();
1214
1215        insert_block_for_agent(&store, "block-alias", "def-1");
1216        let inst = make_instance("block-alias", "id-alias");
1217        store.instance_create(&inst).unwrap();
1218
1219        let mut env: HashMap<String, String> = HashMap::new();
1220        let res = inject_identity_env(store.clone(), store.clone(), store, "block-alias", &mut env);
1221
1222        assert!(res.is_ok(), "expected Ok, got {res:?}");
1223        assert_eq!(
1224            env.get("CLAUDE_CONFIG_DIR").cloned(),
1225            Some(test_config_dir("id-alias")),
1226        );
1227    }
1228
1229    // ── Layer 3 — spawn gating (SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4
1230    //    _2026_07_14.md §2.2/§2.5) ────────────────────────────────────
1231
1232    /// Fixture def for the gating tests — oauth-class CLI provider
1233    /// (claude). `use_ambient_login` is settable only to prove it is inert.
1234    fn gate_def(use_ambient_login: i64) -> crate::backend::storage::store::AgentDefinition {
1235        crate::backend::storage::store::AgentDefinition {
1236            slug: String::new(),
1237            icon: "✦".to_string(),
1238            use_ambient_login,
1239            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1240        }
1241    }
1242
1243    /// Delete an account row while KEEPING its link — the post-delete
1244    /// shape on a legacy DB (analysis §2.4: real installs got the links
1245    /// table via ALTER RENAME with no FK cascade clause, so orphan links
1246    /// are real). FKs are toggled off for the surgical delete so the
1247    /// test store's DDL-level cascade doesn't fire.
1248    fn delete_account_row_keep_link(store: &Store, account_id: &str) {
1249        let conn = store.conn().lock().unwrap();
1250        conn.execute_batch(&format!(
1251            "PRAGMA foreign_keys=OFF;
1252             DELETE FROM db_accounts WHERE id = '{account_id}';
1253             PRAGMA foreign_keys=ON;"
1254        ))
1255        .unwrap();
1256    }
1257
1258    #[test]
1259    fn spawn_blocked_when_bound_oauth_account_missing_and_flag_false() {
1260        // Spec §2.5 test 1: binding → missing account → flag false →
1261        // spawn-assembly returns the blocking error (not a skip).
1262        let store = make_store();
1263        let mut def = gate_def(0);
1264        store.agent_def_insert(&mut def).unwrap();
1265
1266        let claude = make_account(
1267            "acct-gone",
1268            "claude",
1269            SecretRef::OAuthConfigDir {
1270                dir: test_config_dir("id-x"),
1271            },
1272        );
1273        store.identity_upsert(&claude).unwrap();
1274        store
1275            .agent_identity_link("def-1", "acct-gone", "claude")
1276            .unwrap();
1277        // Delete the account row out from under the link — the exact
1278        // post-`deleteidentityaccount` shape the resolver used to
1279        // log-and-skip ("row not found — skipping", analysis §2.3).
1280        delete_account_row_keep_link(&store, "acct-gone");
1281
1282        insert_block_for_agent(&store, "block-gate-1", "def-1");
1283        let inst = make_instance("block-gate-1", "id-x");
1284        store.instance_create(&inst).unwrap();
1285
1286        let mut env: HashMap<String, String> = HashMap::new();
1287        let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-1", &mut env);
1288
1289        assert_eq!(
1290            res,
1291            Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: true }),
1292        );
1293        // Nothing was injected — the CLI process must never be created.
1294        assert!(env.is_empty());
1295        // The error's Display is the user-facing pane message (spec §2.2
1296        // wording) — pin the load-bearing pieces.
1297        let msg = res.unwrap_err().to_string();
1298        assert!(msg.contains("no credentials for claude"), "got: {msg}");
1299        assert!(msg.contains("Bind an account for this provider in Connectors → Accounts"), "got: {msg}");
1300    }
1301
1302    #[test]
1303    fn spawn_still_blocked_when_bound_oauth_account_missing_and_flag_true() {
1304        // Was spawn_proceeds_ambient_when_bound_oauth_account_missing_and_flag_true
1305        // — the ambient opt-in it exercised is retired
1306        // (PLAN_LOGIN_SINGLE_PATH_CONSOLIDATION_2026_07_20.md §7). A missing
1307        // account now blocks the spawn unconditionally; `use_ambient_login`
1308        // no longer changes the outcome. This test pins that the flag is
1309        // truly inert, not just untested.
1310        let store = make_store();
1311        let mut def = gate_def(1);
1312        store.agent_def_insert(&mut def).unwrap();
1313
1314        let claude = make_account(
1315            "acct-gone-2",
1316            "claude",
1317            SecretRef::OAuthConfigDir {
1318                dir: test_config_dir("id-y"),
1319            },
1320        );
1321        store.identity_upsert(&claude).unwrap();
1322        store
1323            .agent_identity_link("def-1", "acct-gone-2", "claude")
1324            .unwrap();
1325        delete_account_row_keep_link(&store, "acct-gone-2");
1326
1327        insert_block_for_agent(&store, "block-gate-2", "def-1");
1328        let inst = make_instance("block-gate-2", "id-y");
1329        store.instance_create(&inst).unwrap();
1330
1331        let mut env: HashMap<String, String> = HashMap::new();
1332        let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-2", &mut env);
1333
1334        assert_eq!(
1335            res,
1336            Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: true }),
1337        );
1338        assert!(env.is_empty());
1339    }
1340
1341    #[test]
1342    fn spawn_blocked_when_oauth_def_provider_has_no_binding_and_flag_false() {
1343        // Spec §2.2 edge case: an agent whose oauth-class CLI provider has
1344        // NO binding at all (never bound, or the link was cascaded away by
1345        // an account delete) is blocked without the opt-in — implicit
1346        // ambient is how the delete-doesn't-deauthenticate gap happened.
1347        // (A retired migration grandfathered pre-existing linkless agents
1348        // to flag=1; `inject_no_direct_links_injects_nothing` covers that
1349        // side.)
1350        //
1351        // THIS TEST IS THE INV-A REGRESSION CANARY
1352        // (`docs/retro/retro-auth-isolation-invariant-silently-orphaned-2026-07-14.md`):
1353        // a completely unconfigured agent (zero bindings, default flag)
1354        // is the exact shape that used to fall through to the user's
1355        // global `~/.claude` before commit `e5ab2d09` orphaned the
1356        // isolated-auto-provision path. If a future refactor makes this
1357        // assert start failing (env no longer empty, or `res` becomes
1358        // `Ok`), read that retro before "fixing" the test — the failure
1359        // is very likely the invariant regressing a second time, not the
1360        // test being wrong.
1361        let store = make_store();
1362        let mut def = gate_def(0);
1363        store.agent_def_insert(&mut def).unwrap();
1364
1365        insert_block_for_agent(&store, "block-gate-3", "def-1");
1366        let inst = make_instance("block-gate-3", "id-z");
1367        store.instance_create(&inst).unwrap();
1368
1369        let mut env: HashMap<String, String> = HashMap::new();
1370        let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-3", &mut env);
1371
1372        assert_eq!(
1373            res,
1374            Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: false }),
1375        );
1376        assert!(env.is_empty());
1377    }
1378
1379    /// Regression guard for the definition flip (agent-concept
1380    /// consolidation, `SPEC_AGENT_ARCHITECTURE_2026_05_27.md` Phase 3d).
1381    ///
1382    /// `agent_def_get(&instance.definition_id)` used to be scoped to
1383    /// `db_agent_definitions` and 404 for ANY template launch, since a
1384    /// launch's own row lives only in `db_agents` with no legacy
1385    /// counterpart. `def_provider` (Step 2, above) was therefore always
1386    /// `None` for a template launch — and Step 5's definition-provider gate
1387    /// (`if let Some(p) = def_provider { ... }`) is a no-op when
1388    /// `def_provider` is `None`. So a template-launched agent whose CLI
1389    /// provider is oauth-class, with genuinely ZERO identity binding, was
1390    /// launching WITHOUT ever being checked by the one gate that exists
1391    /// specifically to block exactly that — the definition flip closes
1392    /// this by letting `agent_def_get` resolve the launch's own row, so
1393    /// `def_provider` is `Some("claude")` and Step 5 applies to it like any
1394    /// other agent. (`use_ambient_login` is confirmed inert for this gate
1395    /// either way, per `gate_oauth_failure`'s own doc comment and
1396    /// `spawn_still_blocked_when_bound_oauth_account_missing_and_flag_true`
1397    /// above — this test does not depend on it and sets it to demonstrate
1398    /// that non-effect explicitly.)
1399    ///
1400    /// This template genuinely has NO identity link either — the sibling
1401    /// test `spawn_proceeds_when_a_template_launch_inherits_the_templates_
1402    /// own_identity_link` covers the case that made enabling Step 5 for
1403    /// launches unsafe on its own (codex P1 on #3092): a template WITH a
1404    /// real bound account must still let its launches spawn.
1405    #[test]
1406    fn spawn_is_gated_for_a_template_launch_with_no_binding_where_it_used_to_be_invisible_to_the_gate() {
1407        let store = make_store();
1408        let mut tpl = gate_def(1); // use_ambient_login=1 — must NOT matter, see doc comment.
1409        tpl.id = "tpl-ambient".to_string();
1410        tpl.is_seeded = 1;
1411        store.agent_def_insert(&mut tpl).unwrap();
1412
1413        // A launch of the template: `is_seeded = 1` means `instance_create`
1414        // creates a NEW row keyed by the launch id, not the template's —
1415        // exactly the shape that used to be invisible to `agent_def_get`.
1416        let inst = crate::backend::storage::store::AgentInstance {
1417            identity_id: "id-ambient".to_string(),
1418            ..crate::backend::storage::agents::test_agent_instance("launch-ambient", "tpl-ambient", "block-gate-ambient", 0)
1419        };
1420        let canonical = store.instance_create(&inst).unwrap();
1421        assert_eq!(canonical.id, "launch-ambient", "sanity: a template launch creates its own row");
1422
1423        insert_block_for_agent(&store, "block-gate-ambient", "launch-ambient");
1424
1425        let mut env: HashMap<String, String> = HashMap::new();
1426        let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-ambient", &mut env);
1427
1428        assert_eq!(
1429            res,
1430            Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: false }),
1431            "a template launch's zero-binding oauth-class provider must now reach Step 5's gate, not skip it",
1432        );
1433        assert!(env.is_empty());
1434    }
1435
1436    /// Codex P1 on #3092: enabling Step 5 for launch rows (the previous
1437    /// test) would have converted every LEGITIMATELY-configured template
1438    /// launch into a hard spawn failure, without this fallback. Binding an
1439    /// identity to a template — the Agent Setup modal's supported target —
1440    /// has always written the link under the TEMPLATE's id; nothing writes
1441    /// a launch-scoped link. `resolve_bindings_for_instance` now falls back
1442    /// to the template's own links when the launch has none of its own, so
1443    /// a template's real binding still resolves (and injects) once launched.
1444    #[test]
1445    fn spawn_proceeds_when_a_template_launch_inherits_the_templates_own_identity_link() {
1446        let store = make_store();
1447        let mut tpl = gate_def(0);
1448        tpl.id = "tpl-bound".to_string();
1449        tpl.is_seeded = 1;
1450        store.agent_def_insert(&mut tpl).unwrap();
1451
1452        let claude = make_account(
1453            "acct-tpl",
1454            "claude",
1455            SecretRef::OAuthConfigDir { dir: test_config_dir("id-tpl-bound") },
1456        );
1457        store.identity_upsert(&claude).unwrap();
1458        // The link is bound to the TEMPLATE's own id, exactly as the Agent
1459        // Setup modal does today — never the launch's.
1460        store.agent_identity_link("tpl-bound", "acct-tpl", "claude").unwrap();
1461
1462        let inst = crate::backend::storage::store::AgentInstance {
1463            identity_id: "id-tpl-bound".to_string(),
1464            ..crate::backend::storage::agents::test_agent_instance("launch-bound", "tpl-bound", "block-gate-bound", 0)
1465        };
1466        let canonical = store.instance_create(&inst).unwrap();
1467        assert_eq!(canonical.id, "launch-bound", "sanity: a template launch creates its own row");
1468        // Sanity: the launch's own row genuinely has no direct link — any
1469        // pass here must come from the template fallback, not a stray
1470        // direct one.
1471        assert!(store.agent_identity_list_for_agent("launch-bound").unwrap().is_empty());
1472
1473        insert_block_for_agent(&store, "block-gate-bound", "launch-bound");
1474
1475        let mut env: HashMap<String, String> = HashMap::new();
1476        let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-bound", &mut env);
1477
1478        assert_eq!(res, Ok(()), "a template's own real binding must still let its launches spawn");
1479        assert_eq!(
1480            env.get("CLAUDE_CONFIG_DIR").map(String::as_str),
1481            Some(test_config_dir("id-tpl-bound").as_str()),
1482            "the template's bound config dir must actually be injected, not just pass the gate",
1483        );
1484    }
1485
1486    /// reagent P0 on #3092: `db_agents.parent_template_id` is NOT
1487    /// exclusively "which template was I launched from" —
1488    /// `forkagentdefinition` (`template.rs`) reuses the same column to
1489    /// record a plain agent fork's SOURCE agent id, `is_seeded = 0`. An
1490    /// earlier version of the template-link fallback above trusted the
1491    /// column unconditionally: a fork of ANY regular agent with a bound
1492    /// identity would silently inherit and spawn on the SOURCE agent's
1493    /// credentials through the resolver, whatever links the fork itself
1494    /// had — a credential-scope leak across agents. `template_parent_id_if_seeded`
1495    /// closes this by only falling back when the parent actually has
1496    /// `is_seeded = 1`. (A new fork gets its source's link copied as its own;
1497    /// this test's fork has none, as after an unlink.)
1498    #[test]
1499    fn a_fork_of_a_regular_agent_does_not_inherit_the_sources_identity_link() {
1500        let store = make_store();
1501        let mut source = gate_def(0);
1502        source.id = "agent-source".to_string();
1503        source.is_seeded = 0; // a regular agent, NOT a template
1504        store.agent_def_insert(&mut source).unwrap();
1505
1506        let claude = make_account(
1507            "acct-source",
1508            "claude",
1509            SecretRef::OAuthConfigDir { dir: test_config_dir("id-source-only") },
1510        );
1511        store.identity_upsert(&claude).unwrap();
1512        store.agent_identity_link("agent-source", "acct-source", "claude").unwrap();
1513
1514        // A plain, non-template fork with parent_id = the source's id,
1515        // accounts reset to empty, and — critically — no identity link of
1516        // its own (as after the user unlinks the one it was created with).
1517        let mut fork = gate_def(0);
1518        fork.id = "agent-fork".to_string();
1519        fork.is_seeded = 0;
1520        fork.parent_id = "agent-source".to_string();
1521        fork.accounts = String::new();
1522        store.agent_def_insert(&mut fork).unwrap();
1523
1524        let inst = crate::backend::storage::store::AgentInstance {
1525            identity_id: "id-fork".to_string(),
1526            ..crate::backend::storage::agents::test_agent_instance("agent-fork", "agent-fork", "block-gate-fork", 0)
1527        };
1528        let canonical = store.instance_create(&inst).unwrap();
1529        assert_eq!(canonical.id, "agent-fork", "sanity: a fork of a non-template agent folds into its own row");
1530        assert!(store.agent_identity_list_for_agent("agent-fork").unwrap().is_empty(), "sanity: the fork has no link of its own");
1531
1532        insert_block_for_agent(&store, "block-gate-fork", "agent-fork");
1533
1534        let mut env: HashMap<String, String> = HashMap::new();
1535        let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-fork", &mut env);
1536
1537        assert_eq!(
1538            res,
1539            Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: false }),
1540            "a fork must NOT silently inherit and spawn on its source agent's credentials",
1541        );
1542        assert!(env.is_empty(), "nothing must be injected — especially not the source's config dir");
1543    }
1544
1545    #[test]
1546    fn inject_no_instance_does_nothing() {
1547        let store = make_store();
1548        let mut env: HashMap<String, String> = HashMap::new();
1549        inject_identity_env(store.clone(), store.clone(), store, "block-no-instance", &mut env).unwrap();
1550        assert!(env.is_empty());
1551    }
1552
1553    // #30077's tests live in their own file (inject/tests/blank_identity.rs) so this file,
1554    // over the size ratchet, does not grow.
1555    pub mod blank_identity;
1556
1557    #[cfg(debug_assertions)]
1558    #[test]
1559    fn inject_full_round_trip_plaintext_dev() {
1560        let store = make_store();
1561
1562        // Agent definition.
1563        let mut def = crate::backend::storage::store::AgentDefinition {
1564            seat: None,
1565            conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1566            id: "def-1".to_string(),
1567            slug: String::new(),
1568            name: "T".to_string(),
1569            icon: "✦".to_string(),
1570            // Not oauth-class — the layer-3 gate only applies to providers
1571            // `provider_class` classifies as OAuth-class (claude / codex /
1572            // gemini / copilot as of
1573            // REPORT_AUTH_ARCHITECTURE_STATE_AND_RETHINK_2026_07_21.md
1574            // §2.5/§6), so a non-oauth def here keeps this test focused on
1575            // the api-key round trip below without a claude account fixture
1576            // it doesn't otherwise need.
1577            provider: "openai".to_string(),
1578            description: String::new(),
1579            working_directory: String::new(),
1580            shell: String::new(),
1581            provider_flags: String::new(),
1582            auto_start: 0,
1583            restart_on_crash: 0,
1584            idle_timeout_minutes: 0,
1585            created_at: 0,
1586            agent_type: String::new(),
1587            environment: String::new(),
1588            agent_bus_id: String::new(),
1589            is_seeded: 0,
1590            accounts: String::new(),
1591            parent_id: String::new(),
1592            branch_label: String::new(),
1593            updated_at: 0,
1594            user_hidden: 0,
1595            container_image: String::new(),
1596            container_volumes: "[]".to_string(),
1597            container_name: String::new(),
1598            use_ambient_login: 0,
1599            model_vendor_base_url: String::new(),
1600            memory_id: String::new(),
1601        };
1602        store.agent_def_insert(&mut def).unwrap();
1603
1604        // GitHub account connected with OAuth: its secret is the token blob.
1605        let github = make_account(
1606            "acct-gh",
1607            "github",
1608            SecretRef::PlaintextDev {
1609                plaintext_dev: r#"{"access_token":"gho_round_trip","refresh_token":null,"expires_at":0}"#.to_string(),
1610            },
1611        );
1612        store.identity_upsert(&github).unwrap();
1613        store
1614            .agent_identity_link("def-1", "acct-gh", "github")
1615            .unwrap();
1616
1617        // Anthropic account.
1618        let anthropic = make_account(
1619            "acct-anth",
1620            "anthropic",
1621            SecretRef::PlaintextDev {
1622                plaintext_dev: "sk-ant-round_trip".to_string(),
1623            },
1624        );
1625        store.identity_upsert(&anthropic).unwrap();
1626        store
1627            .agent_identity_link("def-1", "acct-anth", "anthropic")
1628            .unwrap();
1629
1630        // Instance for the block, pointing at id-work.
1631        insert_block_for_agent(&store, "block-1", "def-1");
1632        let inst = make_instance("block-1", "id-work");
1633        store.instance_create(&inst).unwrap();
1634
1635        let mut env: HashMap<String, String> = HashMap::new();
1636        inject_identity_env(store.clone(), store.clone(), store, "block-1", &mut env).unwrap();
1637
1638        // Both standard env-var names, with the access token, not the blob.
1639        assert_eq!(env.get("GITHUB_TOKEN").map(String::as_str), Some("gho_round_trip"));
1640        assert_eq!(env.get("GH_TOKEN").map(String::as_str), Some("gho_round_trip"));
1641        // Anthropic writes its single env var.
1642        assert_eq!(
1643            env.get("ANTHROPIC_API_KEY").map(String::as_str),
1644            Some("sk-ant-round_trip"),
1645        );
1646    }
1647
1648    #[cfg(debug_assertions)]
1649    #[test]
1650    fn inject_via_direct_link_round_trip() {
1651        // A DIRECT agent<->account link resolves and injects the
1652        // account's env vars. Mirrors `inject_full_round_trip_plaintext_dev`.
1653        let store = make_store();
1654
1655        let mut def = crate::backend::storage::store::AgentDefinition {
1656            seat: None,
1657            conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1658            id: "def-1".to_string(),
1659            slug: String::new(),
1660            name: "T".to_string(),
1661            icon: "✦".to_string(),
1662            // Not oauth-class (§4.3) — see the identical note in
1663            // inject_full_round_trip_plaintext_dev above.
1664            provider: "openai".to_string(),
1665            description: String::new(),
1666            working_directory: String::new(),
1667            shell: String::new(),
1668            provider_flags: String::new(),
1669            auto_start: 0,
1670            restart_on_crash: 0,
1671            idle_timeout_minutes: 0,
1672            created_at: 0,
1673            agent_type: String::new(),
1674            environment: String::new(),
1675            agent_bus_id: String::new(),
1676            is_seeded: 0,
1677            accounts: String::new(),
1678            parent_id: String::new(),
1679            branch_label: String::new(),
1680            updated_at: 0,
1681            user_hidden: 0,
1682            container_image: String::new(),
1683            container_volumes: "[]".to_string(),
1684            container_name: String::new(),
1685            use_ambient_login: 0,
1686            model_vendor_base_url: String::new(),
1687            memory_id: String::new(),
1688        };
1689        store.agent_def_insert(&mut def).unwrap();
1690
1691        let github = make_account(
1692            "acct-gh",
1693            "github",
1694            SecretRef::PlaintextDev {
1695                plaintext_dev: "ghp_direct".to_string(),
1696            },
1697        );
1698        store.identity_upsert(&github).unwrap();
1699        store
1700            .agent_identity_link("def-1", "acct-gh", "github")
1701            .unwrap();
1702
1703        insert_block_for_agent(&store, "block-direct", "def-1");
1704        let inst = make_instance("block-direct", "id-direct");
1705        store.instance_create(&inst).unwrap();
1706
1707        let mut env: HashMap<String, String> = HashMap::new();
1708        inject_identity_env(store.clone(), store.clone(), store, "block-direct", &mut env).unwrap();
1709
1710        assert_eq!(env.get("GITHUB_TOKEN").map(String::as_str), Some("ghp_direct"));
1711        assert_eq!(env.get("GH_TOKEN").map(String::as_str), Some("ghp_direct"));
1712    }
1713
1714    #[cfg(debug_assertions)]
1715    #[test]
1716    fn inject_no_direct_links_injects_nothing() {
1717        // An instance with a non-sentinel identity_id but no
1718        // db_agent_identity_links row for its definition — e.g. an
1719        // account exists but was never linked — injects nothing.
1720        let store = make_store();
1721
1722        let mut def = crate::backend::storage::store::AgentDefinition {
1723            seat: None,
1724            conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1725            id: "def-1".to_string(),
1726            slug: String::new(),
1727            name: "T".to_string(),
1728            icon: "✦".to_string(),
1729            // Not oauth-class (§4.3) — this test targets the zero-direct-
1730            // links path itself, which is a distinct concern from the
1731            // layer-3 oauth gate (covered separately by the spawn_blocked_*
1732            // tests below).
1733            provider: "openai".to_string(),
1734            description: String::new(),
1735            working_directory: String::new(),
1736            shell: String::new(),
1737            provider_flags: String::new(),
1738            auto_start: 0,
1739            restart_on_crash: 0,
1740            idle_timeout_minutes: 0,
1741            created_at: 0,
1742            agent_type: String::new(),
1743            environment: String::new(),
1744            agent_bus_id: String::new(),
1745            is_seeded: 0,
1746            accounts: String::new(),
1747            parent_id: String::new(),
1748            branch_label: String::new(),
1749            updated_at: 0,
1750            user_hidden: 0,
1751            container_image: String::new(),
1752            container_volumes: "[]".to_string(),
1753            container_name: String::new(),
1754            use_ambient_login: 0,
1755            model_vendor_base_url: String::new(),
1756            memory_id: String::new(),
1757        };
1758        store.agent_def_insert(&mut def).unwrap();
1759
1760        let github = make_account(
1761            "acct-unlinked",
1762            "github",
1763            SecretRef::PlaintextDev {
1764                plaintext_dev: "ghp_unlinked".to_string(),
1765            },
1766        );
1767        store.identity_upsert(&github).unwrap();
1768
1769        insert_block_for_agent(&store, "block-unlinked", "def-1");
1770        let inst = make_instance("block-unlinked", "id-unused");
1771        store.instance_create(&inst).unwrap();
1772
1773        let mut env: HashMap<String, String> = HashMap::new();
1774        inject_identity_env(store.clone(), store.clone(), store, "block-unlinked", &mut env).unwrap();
1775
1776        // Nothing injected — an account with no direct link is invisible
1777        // to the resolver.
1778        assert!(env.get("GITHUB_TOKEN").is_none());
1779        assert!(env.is_empty());
1780    }
1781
1782    #[cfg(debug_assertions)]
1783    #[test]
1784    fn inject_no_direct_links_publishes_event() {
1785        // Same setup as inject_no_direct_links_injects_nothing, but
1786        // asserts the diagnostic MuxEvent fires — the standing signal
1787        // for #1624 so a future frontend surface (or just log triage) can
1788        // see when a non-sentinel identity resolves to zero direct links.
1789        let store = make_store();
1790
1791        let mut def = crate::backend::storage::store::AgentDefinition {
1792            seat: None,
1793            conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1794            id: "def-1".to_string(),
1795            slug: String::new(),
1796            name: "T".to_string(),
1797            icon: "✦".to_string(),
1798            // Not oauth-class (§4.3) — same rationale as
1799            // inject_no_direct_links_injects_nothing above.
1800            provider: "openai".to_string(),
1801            description: String::new(),
1802            working_directory: String::new(),
1803            shell: String::new(),
1804            provider_flags: String::new(),
1805            auto_start: 0,
1806            restart_on_crash: 0,
1807            idle_timeout_minutes: 0,
1808            created_at: 0,
1809            agent_type: String::new(),
1810            environment: String::new(),
1811            agent_bus_id: String::new(),
1812            is_seeded: 0,
1813            accounts: String::new(),
1814            parent_id: String::new(),
1815            branch_label: String::new(),
1816            updated_at: 0,
1817            user_hidden: 0,
1818            container_image: String::new(),
1819            container_volumes: "[]".to_string(),
1820            container_name: String::new(),
1821            use_ambient_login: 0,
1822            model_vendor_base_url: String::new(),
1823            memory_id: String::new(),
1824        };
1825        store.agent_def_insert(&mut def).unwrap();
1826
1827        let github = make_account(
1828            "acct-unlinked-2",
1829            "github",
1830            SecretRef::PlaintextDev {
1831                plaintext_dev: "ghp_unlinked_2".to_string(),
1832            },
1833        );
1834        store.identity_upsert(&github).unwrap();
1835
1836        insert_block_for_agent(&store, "block-unlinked-2", "def-1");
1837        let inst = make_instance("block-unlinked-2", "id-unused-2");
1838        store.instance_create(&inst).unwrap();
1839
1840        let broker = Arc::new(Broker::new());
1841        let mut env: HashMap<String, String> = HashMap::new();
1842        inject_identity_env_with_broker(
1843            store.clone(),
1844            store.clone(),
1845            store,
1846            Some(broker.clone()),
1847            "block-unlinked-2",
1848            &mut env,
1849        )
1850        .unwrap();
1851
1852        // The event is persisted (see resolve_bindings_for_instance's
1853        // publish) precisely so it's readable here without needing a live
1854        // subscriber wired up at publish time.
1855        let history = broker.read_event_history("identity:no-direct-links", "", 10);
1856        let event = history.last().expect("expected identity:no-direct-links event");
1857        assert_eq!(
1858            event.data.as_ref().and_then(|d| d.get("definition_id")).and_then(|v| v.as_str()),
1859            Some("def-1"),
1860        );
1861    }
1862
1863    #[cfg(debug_assertions)]
1864    #[test]
1865    fn inject_partial_success_skips_failed_bindings() {
1866        let store = make_store();
1867
1868        let mut def = crate::backend::storage::store::AgentDefinition {
1869            seat: None,
1870            conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1871            id: "def-1".to_string(),
1872            slug: String::new(),
1873            name: "T".to_string(),
1874            icon: "✦".to_string(),
1875            // Not oauth-class (§4.3) — this test targets partial-success
1876            // skip behavior across api-key bindings, unrelated to the
1877            // layer-3 oauth gate.
1878            provider: "openai".to_string(),
1879            description: String::new(),
1880            working_directory: String::new(),
1881            shell: String::new(),
1882            provider_flags: String::new(),
1883            auto_start: 0,
1884            restart_on_crash: 0,
1885            idle_timeout_minutes: 0,
1886            created_at: 0,
1887            agent_type: String::new(),
1888            environment: String::new(),
1889            agent_bus_id: String::new(),
1890            is_seeded: 0,
1891            accounts: String::new(),
1892            parent_id: String::new(),
1893            branch_label: String::new(),
1894            updated_at: 0,
1895            user_hidden: 0,
1896            container_image: String::new(),
1897            container_volumes: "[]".to_string(),
1898            container_name: String::new(),
1899            use_ambient_login: 0,
1900            model_vendor_base_url: String::new(),
1901            memory_id: String::new(),
1902        };
1903        store.agent_def_insert(&mut def).unwrap();
1904
1905        // Working account.
1906        let good = make_account(
1907            "acct-good",
1908            "github",
1909            SecretRef::PlaintextDev {
1910                plaintext_dev: "ghp_good".to_string(),
1911            },
1912        );
1913        store.identity_upsert(&good).unwrap();
1914        store
1915            .agent_identity_link("def-1", "acct-good", "github")
1916            .unwrap();
1917
1918        // Account whose Env-backed secret references a missing var.
1919        let bad = make_account(
1920            "acct-bad",
1921            "anthropic",
1922            SecretRef::Env {
1923                env_var: "AGENTMUX_TEST_DEFINITELY_NOT_SET_4242".to_string(),
1924            },
1925        );
1926        store.identity_upsert(&bad).unwrap();
1927        store
1928            .agent_identity_link("def-1", "acct-bad", "anthropic")
1929            .unwrap();
1930
1931        insert_block_for_agent(&store, "block-mixed", "def-1");
1932        let inst = make_instance("block-mixed", "id-mixed");
1933        store.instance_create(&inst).unwrap();
1934
1935        let mut env: HashMap<String, String> = HashMap::new();
1936        inject_identity_env(store.clone(), store.clone(), store, "block-mixed", &mut env).unwrap();
1937
1938        // GitHub injection succeeded.
1939        assert_eq!(env.get("GITHUB_TOKEN").map(String::as_str), Some("ghp_good"));
1940        assert_eq!(env.get("GH_TOKEN").map(String::as_str), Some("ghp_good"));
1941        // Anthropic was skipped (env var missing) but didn't abort.
1942        assert!(env.get("ANTHROPIC_API_KEY").is_none());
1943    }
1944
1945    #[cfg(debug_assertions)]
1946    #[test]
1947    fn inject_unknown_provider_is_skipped() {
1948        let store = make_store();
1949
1950        let mut def = crate::backend::storage::store::AgentDefinition {
1951            seat: None,
1952            conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1953            id: "def-1".to_string(),
1954            slug: String::new(),
1955            name: "T".to_string(),
1956            icon: "✦".to_string(),
1957            // Not oauth-class (§4.3) — this test targets the unknown-
1958            // provider skip path, unrelated to the layer-3 oauth gate.
1959            provider: "openai".to_string(),
1960            description: String::new(),
1961            working_directory: String::new(),
1962            shell: String::new(),
1963            provider_flags: String::new(),
1964            auto_start: 0,
1965            restart_on_crash: 0,
1966            idle_timeout_minutes: 0,
1967            created_at: 0,
1968            agent_type: String::new(),
1969            environment: String::new(),
1970            agent_bus_id: String::new(),
1971            is_seeded: 0,
1972            accounts: String::new(),
1973            parent_id: String::new(),
1974            branch_label: String::new(),
1975            updated_at: 0,
1976            user_hidden: 0,
1977            container_image: String::new(),
1978            container_volumes: "[]".to_string(),
1979            container_name: String::new(),
1980            use_ambient_login: 0,
1981            model_vendor_base_url: String::new(),
1982            memory_id: String::new(),
1983        };
1984        store.agent_def_insert(&mut def).unwrap();
1985
1986        let custom = make_account(
1987            "acct-custom",
1988            "custom",
1989            SecretRef::PlaintextDev {
1990                plaintext_dev: "ignored".to_string(),
1991            },
1992        );
1993        store.identity_upsert(&custom).unwrap();
1994        store
1995            .agent_identity_link("def-1", "acct-custom", "custom")
1996            .unwrap();
1997
1998        insert_block_for_agent(&store, "block-future", "def-1");
1999        let inst = make_instance("block-future", "id-future");
2000        store.instance_create(&inst).unwrap();
2001
2002        let mut env: HashMap<String, String> = HashMap::new();
2003        inject_identity_env(store.clone(), store.clone(), store, "block-future", &mut env).unwrap();
2004        // No env-var matrix for "custom" — nothing injected, no panic.
2005        assert!(env.is_empty());
2006    }
2007
2008    /// Helper: write a Claude-shape `.credentials.json` into a temp dir
2009    /// and return the dir path. `expires_ms` controls validity; `with_refresh`
2010    /// toggles the refreshToken field so the resolver can distinguish
2011    /// `Expired` (refresh present) from `NeedsReauth` (no refresh).
2012    ///
2013    /// Duplicated from `oauth_probe::tests` (same helper, different file)
2014    /// rather than shared cross-module — kept the modularization split a
2015    /// pure relocation with no new cross-file test-only visibility surface.
2016    fn write_claude_creds(
2017        dir: &std::path::Path,
2018        expires_ms: i64,
2019        with_refresh: bool,
2020    ) {
2021        std::fs::create_dir_all(dir).unwrap();
2022        let body = serde_json::json!({
2023            "claudeAiOauth": {
2024                "accessToken": "test-access",
2025                "refreshToken": if with_refresh { "test-refresh" } else { "" },
2026                "expiresAt": expires_ms,
2027            }
2028        });
2029        std::fs::write(
2030            dir.join(".credentials.json"),
2031            serde_json::to_string(&body).unwrap(),
2032        )
2033        .unwrap();
2034    }
2035
2036    #[cfg(debug_assertions)]
2037    #[test]
2038    fn inject_oauth_class_probes_and_flips_status_to_needs_reauth() {
2039        // Full integration: an oauth-class binding pointing at a
2040        // bundle dir with NO token file → the probe surfaces
2041        // `needs_reauth` and the resolver upserts the account row
2042        // with the new status. Spec §4.4.
2043        //
2044        // Uses "codex", not "claude": the macOS Keychain carve-out added
2045        // in oauth_probe.rs (retro-macos-keychain-credential-isolation-gap-
2046        // 2026-08-17.md) makes a missing token file for "claude" return
2047        // `None` (no status change) on macOS specifically, since Claude
2048        // Code never writes `.credentials.json` there regardless of the
2049        // config dir. "codex" isn't covered by that carve-out, so it keeps
2050        // this test's original, platform-independent needs_reauth signal.
2051        let store = make_store();
2052
2053        let mut def = crate::backend::storage::store::AgentDefinition {
2054            slug: String::new(),
2055            icon: "✦".to_string(),
2056            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "codex", "", 0, "")
2057        };
2058        store.agent_def_insert(&mut def).unwrap();
2059
2060        // Bundle dir intentionally empty — probe should report
2061        // needs_reauth (no token file).
2062        let tmp = tempfile::tempdir().unwrap();
2063        let bundle_dir = tmp.path().to_str().unwrap().to_string();
2064
2065        let codex_acct = IdentityAccount {
2066            id: "acct-codex".to_string(),
2067            name: "codex-acct-codex".to_string(),
2068            provider: "codex".to_string(),
2069            kind: "oauth".to_string(),
2070            display_name: String::new(),
2071            secret_ref: SecretRef::OAuthConfigDir { dir: bundle_dir },
2072            context: serde_json::json!({}),
2073            // Start as "valid" — the probe should flip it to
2074            // "needs_reauth".
2075            status: oauth_status::VALID.to_string(),
2076            created_at: 0,
2077            updated_at: 0,
2078        };
2079        store.identity_upsert(&codex_acct).unwrap();
2080        store
2081            .agent_identity_link("def-1", "acct-codex", "codex")
2082            .unwrap();
2083
2084        insert_block_for_agent(&store, "block-probe", "def-1");
2085        let inst = make_instance("block-probe", "id-probe");
2086        store.instance_create(&inst).unwrap();
2087
2088        let mut env: HashMap<String, String> = HashMap::new();
2089        inject_identity_env(store.clone(), store.clone(), store.clone(), "block-probe", &mut env).unwrap();
2090
2091        // Env injection still happened (resolver doesn't block on
2092        // probe outcome — the CLI launches with the dir env var set
2093        // and will trigger OAuth itself when it sees no tokens).
2094        assert!(env.get("CODEX_HOME").is_some());
2095
2096        // Status row was UPDATED to needs_reauth.
2097        let after = store.identity_get("acct-codex").unwrap().unwrap();
2098        assert_eq!(after.status, oauth_status::NEEDS_REAUTH);
2099    }
2100
2101    #[cfg(target_os = "macos")]
2102    #[cfg(debug_assertions)]
2103    #[test]
2104    fn inject_oauth_class_self_heals_stale_needs_reauth_for_claude_on_macos() {
2105        // Codex P1 on PR #2645: an account probed BEFORE the macOS
2106        // Keychain carve-out existed may already have `needs_reauth`
2107        // persisted from the old, buggy behavior. Without a self-heal,
2108        // that account stays stuck showing "reconnect" forever, since a
2109        // `None` probe never upserts anything — this proves the resolver
2110        // corrects it back to "unknown" (not a fabricated "valid") the
2111        // next time the agent spawns.
2112        let store = make_store();
2113
2114        // gate_def's own provider is already "claude" — see its doc comment.
2115        let mut def = gate_def(0);
2116        store.agent_def_insert(&mut def).unwrap();
2117
2118        // Bundle dir intentionally empty, same as the pre-fix broken case —
2119        // but the account already carries the stale needs_reauth status
2120        // the old probe would have written.
2121        let tmp = tempfile::tempdir().unwrap();
2122        let bundle_dir = tmp.path().to_str().unwrap().to_string();
2123
2124        let stale = IdentityAccount {
2125            id: "acct-stale".to_string(),
2126            name: "claude-acct-stale".to_string(),
2127            provider: "claude".to_string(),
2128            kind: "oauth".to_string(),
2129            display_name: String::new(),
2130            secret_ref: SecretRef::OAuthConfigDir { dir: bundle_dir },
2131            context: serde_json::json!({}),
2132            status: oauth_status::NEEDS_REAUTH.to_string(),
2133            created_at: 0,
2134            updated_at: 0,
2135        };
2136        store.identity_upsert(&stale).unwrap();
2137        store
2138            .agent_identity_link("def-1", "acct-stale", "claude")
2139            .unwrap();
2140
2141        insert_block_for_agent(&store, "block-self-heal", "def-1");
2142        let inst = make_instance("block-self-heal", "id-self-heal");
2143        store.instance_create(&inst).unwrap();
2144
2145        let mut env: HashMap<String, String> = HashMap::new();
2146        inject_identity_env(store.clone(), store.clone(), store.clone(), "block-self-heal", &mut env).unwrap();
2147
2148        let after = store.identity_get("acct-stale").unwrap().unwrap();
2149        assert_eq!(
2150            after.status, "unknown",
2151            "a stale pre-carve-out needs_reauth must self-heal to unknown, not stay stuck"
2152        );
2153    }
2154
2155    #[cfg(debug_assertions)]
2156    #[test]
2157    fn inject_oauth_class_probe_canonicalizes_a_legacy_alias_binding() {
2158        // codex P2 on PR #2377 (third round): probe_oauth_status only
2159        // recognizes canonical provider strings ("claude"/"codex"/
2160        // "openclaw") — passing the raw alias ("claude-code") a
2161        // migrated/legacy binding may still carry always returned None,
2162        // silently never refreshing that account's status. Same fixture
2163        // as inject_oauth_class_probes_and_flips_status_to_needs_reauth
2164        // above, but bound under the alias instead of the canonical id.
2165        //
2166        // Uses "codex-cli" → "codex", not "claude-code" → "claude": the
2167        // macOS Keychain carve-out (oauth_probe.rs) means a missing token
2168        // file for "claude" returns `None` on macOS regardless of whether
2169        // canonicalization ran, which would make this test unable to
2170        // distinguish "canonicalization is broken" from "hit the carve-out"
2171        // on that platform. "codex" isn't covered by the carve-out, so it
2172        // keeps the original, platform-independent needs_reauth signal.
2173        let store = make_store();
2174
2175        let mut def = crate::backend::storage::store::AgentDefinition {
2176            slug: String::new(),
2177            icon: "✦".to_string(),
2178            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "codex", "", 0, "")
2179        };
2180        store.agent_def_insert(&mut def).unwrap();
2181
2182        let tmp = tempfile::tempdir().unwrap();
2183        let bundle_dir = tmp.path().to_str().unwrap().to_string();
2184
2185        let codex_acct = IdentityAccount {
2186            id: "acct-alias".to_string(),
2187            name: "codex-cli-acct-alias".to_string(),
2188            provider: "codex-cli".to_string(),
2189            kind: "oauth".to_string(),
2190            display_name: String::new(),
2191            secret_ref: SecretRef::OAuthConfigDir { dir: bundle_dir },
2192            context: serde_json::json!({}),
2193            status: oauth_status::VALID.to_string(),
2194            created_at: 0,
2195            updated_at: 0,
2196        };
2197        store.identity_upsert(&codex_acct).unwrap();
2198        // Bound under the alias, not the canonical "codex".
2199        store
2200            .agent_identity_link("def-1", "acct-alias", "codex-cli")
2201            .unwrap();
2202
2203        insert_block_for_agent(&store, "block-probe-alias", "def-1");
2204        let inst = make_instance("block-probe-alias", "id-probe-alias");
2205        store.instance_create(&inst).unwrap();
2206
2207        let mut env: HashMap<String, String> = HashMap::new();
2208        inject_identity_env(store.clone(), store.clone(), store.clone(), "block-probe-alias", &mut env).unwrap();
2209
2210        assert!(env.get("CODEX_HOME").is_some());
2211        // Status row was UPDATED to needs_reauth — proves the probe ran
2212        // with the canonicalized provider id, not the raw alias (which
2213        // would have returned None and left status untouched at "valid").
2214        let after = store.identity_get("acct-alias").unwrap().unwrap();
2215        assert_eq!(after.status, oauth_status::NEEDS_REAUTH);
2216    }
2217
2218    #[cfg(debug_assertions)]
2219    #[test]
2220    fn inject_oauth_class_probe_preserves_status_when_valid() {
2221        // Future-dated token + status already "valid" → no-op
2222        // upsert (no spurious updated_at churn). The assertion is
2223        // that the status remains "valid" — proving the probe
2224        // didn't misclassify a working session.
2225        let store = make_store();
2226
2227        let mut def = crate::backend::storage::store::AgentDefinition {
2228            slug: String::new(),
2229            icon: "✦".to_string(),
2230            ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
2231        };
2232        store.agent_def_insert(&mut def).unwrap();
2233
2234        let tmp = tempfile::tempdir().unwrap();
2235        let now_ms = agentmux_common::time::now_ms();
2236        write_claude_creds(tmp.path(), now_ms + 3_600_000, true);
2237
2238        let claude = IdentityAccount {
2239            id: "acct-ok".to_string(),
2240            name: "claude-acct-ok".to_string(),
2241            provider: "claude".to_string(),
2242            kind: "oauth".to_string(),
2243            display_name: String::new(),
2244            secret_ref: SecretRef::OAuthConfigDir {
2245                dir: tmp.path().to_str().unwrap().to_string(),
2246            },
2247            context: serde_json::json!({}),
2248            status: oauth_status::VALID.to_string(),
2249            created_at: 0,
2250            updated_at: 0,
2251        };
2252        store.identity_upsert(&claude).unwrap();
2253        store
2254            .agent_identity_link("def-1", "acct-ok", "claude")
2255            .unwrap();
2256
2257        insert_block_for_agent(&store, "block-ok", "def-1");
2258        let inst = make_instance("block-ok", "id-ok");
2259        store.instance_create(&inst).unwrap();
2260
2261        let mut env: HashMap<String, String> = HashMap::new();
2262        inject_identity_env(store.clone(), store.clone(), store.clone(), "block-ok", &mut env).unwrap();
2263
2264        let after = store.identity_get("acct-ok").unwrap().unwrap();
2265        assert_eq!(after.status, oauth_status::VALID);
2266        // updated_at unchanged — the resolver only upserts when the
2267        // probed status differs from the stored value.
2268        assert_eq!(after.updated_at, 0);
2269    }
2270
2271    // P0 regression test (found in a follow-up scoping pass after
2272    // agent_open.rs's identical bug was fixed in PR #2587 round 3):
2273    // the layer-3 gate must resolve the definition's provider through
2274    // its bound ABF bundle (`id_store.resolve_effective_provider_id`),
2275    // not `d.provider` directly. Uses two genuinely separate stores —
2276    // mstore (definition, block, instance) and id_store (bundle,
2277    // account, link) — so the test can't pass by accident the way it
2278    // would if both roles were backed by the same `Arc<Store>`, which
2279    // every OTHER test in this module does (matching production's
2280    // AppState.mstore/id_store split, but meaning none of them could
2281    // have caught this class of bug).
2282    //
2283    // Scenario: the agent says "codex"; its bound bundle, from before
2284    // bundles stopped carrying a harness, says "claude", and the agent has
2285    // a Claude account bound. The agent owns its harness
2286    // (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1), so the gate checks
2287    // codex, finds no codex account, and refuses; the bundle's value never
2288    // decides. (The §3.3 migration makes the two agree before this rule
2289    // takes effect, so a real agent doesn't land here.)
2290    #[test]
2291    fn spawn_gate_checks_the_agents_own_provider_not_its_bundles() {
2292        let mstore = make_store();
2293        // Real shared-store schema, not open_in_memory's channel schema —
2294        // db_agent_identity_links only has a `db_agents` FK in the
2295        // channel schema (`run_object_schema` in migrations.rs); the
2296        // shared-store schema (`run_shared_store_schema`) deliberately
2297        // omits it, since agent
2298        // definitions never live in the shared store. Using two
2299        // open_in_memory() stores here would incorrectly enforce an FK
2300        // that doesn't exist in production's real id_store.
2301        let id_store_tmp = tempfile::NamedTempFile::new().unwrap();
2302        let id_store = Arc::new(Store::open_shared(id_store_tmp.path()).unwrap());
2303        // Same reasoning as id_store above, for the new always-global
2304        // identity store (SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md):
2305        // open_identity_store's real schema (no db_accounts FK at all — see
2306        // its own doc comment) rather than open_in_memory's channel schema.
2307        let identity_store_tmp = tempfile::NamedTempFile::new().unwrap();
2308        let identity_store = Arc::new(Store::open_identity_store(identity_store_tmp.path()).unwrap());
2309
2310        let mut def = crate::backend::storage::store::AgentDefinition {
2311            seat: None,
2312            conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
2313            id: "def-1".to_string(),
2314            slug: String::new(),
2315            name: "T".to_string(),
2316            icon: "✦".to_string(),
2317            // Drifted: the definition's own column says codex...
2318            provider: "codex".to_string(),
2319            description: String::new(),
2320            working_directory: String::new(),
2321            shell: String::new(),
2322            provider_flags: String::new(),
2323            auto_start: 0,
2324            restart_on_crash: 0,
2325            idle_timeout_minutes: 0,
2326            created_at: 0,
2327            agent_type: String::new(),
2328            environment: String::new(),
2329            agent_bus_id: String::new(),
2330            is_seeded: 0,
2331            accounts: String::new(),
2332            parent_id: String::new(),
2333            branch_label: String::new(),
2334            updated_at: 0,
2335            user_hidden: 0,
2336            container_image: String::new(),
2337            container_volumes: "[]".to_string(),
2338            container_name: String::new(),
2339            use_ambient_login: 0,
2340            model_vendor_base_url: String::new(),
2341            // ...but its bound bundle (below, in id_store) says claude.
2342            memory_id: "bundle-1".to_string(),
2343        };
2344        mstore.agent_def_insert(&mut def).unwrap();
2345
2346        let bundle = Bundle {
2347            id: "bundle-1".to_string(),
2348            name: "Drift Test Bundle".to_string(),
2349            description: String::new(),
2350            is_blank: false,
2351            is_global: false,
2352            provider: "claude".to_string(),
2353            model: "anthropic".to_string(),
2354            instructions: String::new(),
2355            instructions_by_provider: "{}".to_string(),
2356            context_files: "[]".to_string(),
2357            mcp_servers: "[]".to_string(),
2358            skills: "[]".to_string(),
2359            sort_order: 0,
2360            created_at: 0,
2361            updated_at: 0,
2362            is_system: false,
2363        };
2364        id_store.bundle_upsert(&bundle).unwrap();
2365
2366        let claude = make_account(
2367            "acct-drift",
2368            "claude",
2369            SecretRef::OAuthConfigDir {
2370                dir: test_config_dir("id-drift"),
2371            },
2372        );
2373        id_store.identity_upsert_with_mirror(&identity_store, &claude).unwrap();
2374        identity_store
2375            .agent_identity_link("def-1", "acct-drift", "claude")
2376            .unwrap();
2377
2378        insert_block_for_agent(&mstore, "block-drift", "def-1");
2379        let inst = make_instance("block-drift", "id-drift");
2380        mstore.instance_create(&inst).unwrap();
2381
2382        let mut env: HashMap<String, String> = HashMap::new();
2383        let res = inject_identity_env(mstore, id_store, identity_store, "block-drift", &mut env);
2384
2385        // The gate checks the agent's own provider (codex), which has no
2386        // account bound; the bundle's claude is only a hint.
2387        assert!(
2388            matches!(&res, Err(SpawnGateError::MissingCredentials { provider, .. }) if provider == "codex"),
2389            "the agent owns its harness; the bundle's provider is a hint (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1): {res:?}"
2390        );
2391    }
2392
2393    fn make_agent_def_with_provider(id: &str, provider: &str) -> crate::backend::storage::store::AgentDefinition {
2394        crate::backend::storage::store::AgentDefinition {
2395            slug: String::new(),
2396            icon: "✦".to_string(),
2397            ..crate::backend::storage::agents::test_agent_def(id, "T", provider, "", 0, "")
2398        }
2399    }
2400
2401    // SPEC_SUBAGENT_WATCHER_IDENTITY_BOUND_CONFIG_DIR_2026_08_22.md
2402    #[cfg(debug_assertions)]
2403    #[test]
2404    fn resolve_bound_oauth_config_dir_resolves_the_identity_bound_dir() {
2405        let store = make_store();
2406        let mut def = make_agent_def_with_provider("def-1", "claude");
2407        store.agent_def_insert(&mut def).unwrap();
2408
2409        let claude = make_account(
2410            "acct-claude",
2411            "claude",
2412            SecretRef::OAuthConfigDir {
2413                dir: test_config_dir("id-bound"),
2414            },
2415        );
2416        store.identity_upsert(&claude).unwrap();
2417        store.agent_identity_link("def-1", "acct-claude", "claude").unwrap();
2418
2419        insert_block_for_agent(&store, "block-bound", "def-1");
2420        let inst = make_instance("block-bound", "id-bound");
2421        store.instance_create(&inst).unwrap();
2422
2423        let resolved = resolve_bound_oauth_config_dir(&store, &store, &store, "block-bound");
2424        assert_eq!(
2425            resolved,
2426            Some(std::path::PathBuf::from(test_config_dir("id-bound"))),
2427        );
2428    }
2429
2430    #[cfg(debug_assertions)]
2431    #[test]
2432    fn resolve_bound_oauth_config_dir_none_when_no_instance_for_block() {
2433        let store = make_store();
2434        let resolved = resolve_bound_oauth_config_dir(&store, &store, &store, "no-such-block");
2435        assert_eq!(resolved, None);
2436    }
2437
2438    #[cfg(debug_assertions)]
2439    #[test]
2440    fn resolve_bound_oauth_config_dir_none_for_api_key_class_provider() {
2441        let store = make_store();
2442        // github is API-key class, not OAuth — never resolves to a config dir.
2443        let mut def = make_agent_def_with_provider("def-1", "github");
2444        store.agent_def_insert(&mut def).unwrap();
2445
2446        let github = make_account(
2447            "acct-gh",
2448            "github",
2449            SecretRef::PlaintextDev { plaintext_dev: "ghp_x".to_string() },
2450        );
2451        store.identity_upsert(&github).unwrap();
2452        store.agent_identity_link("def-1", "acct-gh", "github").unwrap();
2453
2454        insert_block_for_agent(&store, "block-gh", "def-1");
2455        let inst = make_instance("block-gh", "id-gh");
2456        store.instance_create(&inst).unwrap();
2457
2458        let resolved = resolve_bound_oauth_config_dir(&store, &store, &store, "block-gh");
2459        assert_eq!(resolved, None);
2460    }
2461
2462    #[cfg(debug_assertions)]
2463    #[test]
2464    fn resolve_bound_oauth_config_dir_none_when_oauth_provider_has_no_binding() {
2465        let store = make_store();
2466        let mut def = make_agent_def_with_provider("def-1", "claude");
2467        store.agent_def_insert(&mut def).unwrap();
2468        // No account, no link — an ambient/unbound agent.
2469
2470        insert_block_for_agent(&store, "block-unbound", "def-1");
2471        let inst = make_instance("block-unbound", "");
2472        store.instance_create(&inst).unwrap();
2473
2474        let resolved = resolve_bound_oauth_config_dir(&store, &store, &store, "block-unbound");
2475        assert_eq!(resolved, None, "ambient/unbound agents must fall through, not error");
2476    }
2477
2478    // Proves the "no side effects" claim in the doc comment, not just states
2479    // it: an oauth probe on the real path would flip this account's status
2480    // from "unknown" (probe_oauth_status sees no token file at this
2481    // nonexistent dir and returns needs_reauth) — resolve_bound_oauth_config_dir
2482    // must leave it untouched since it never calls the probe/upsert at all.
2483    #[cfg(debug_assertions)]
2484    #[test]
2485    fn resolve_bound_oauth_config_dir_does_not_mutate_account_status() {
2486        let store = make_store();
2487        let mut def = make_agent_def_with_provider("def-1", "claude");
2488        store.agent_def_insert(&mut def).unwrap();
2489
2490        let claude = make_account(
2491            "acct-claude",
2492            "claude",
2493            SecretRef::OAuthConfigDir { dir: "/nonexistent/dir/for/probe".to_string() },
2494        );
2495        store.identity_upsert(&claude).unwrap();
2496        store.agent_identity_link("def-1", "acct-claude", "claude").unwrap();
2497
2498        insert_block_for_agent(&store, "block-status", "def-1");
2499        let inst = make_instance("block-status", "id-status");
2500        store.instance_create(&inst).unwrap();
2501
2502        let _ = resolve_bound_oauth_config_dir(&store, &store, &store, "block-status");
2503
2504        let reread = store.identity_get("acct-claude").unwrap().unwrap();
2505        assert_eq!(reread.status, "unknown", "status must be untouched — no probe/upsert side effect");
2506    }
2507}