Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/oauth/source.rs

Raw
//! Selected renewable credential module (`SMH-SPEC-SPEC0001`, `SMH-SPEC-PLUG0001`).
use super::login::SubscriptionProvider;
use crate::plugins::registry::{CredentialModuleSnapshot, PackageRegistry};
use crate::plugins::{Capability, PluginManifest};
use crate::wasm::{PluginEngine, PluginGeneration, PluginRegistry};
use smith::error::{Result, SmithError};
use smith::provider::ProviderCredentialBinding;
use smith::tool::CancelHandle;
use std::sync::Arc;
use std::sync::mpsc::{self, SyncSender};

/// Opaque selected profile plus explicit fixture namespace, never a token.
#[derive(Clone)]
pub struct SubscriptionCredential {
    profile: String,
    fixture_issuer: Option<String>,
    module_override: Option<String>,
    kernel: Arc<CredentialKernel>,
}

#[cfg(test)]
const CREDENTIAL_SOURCE: &str = "openai-chatgpt-plan@1";
#[cfg(test)]
const CREDENTIAL_CONSUMER: &str = "smith:protocol-openai-responses/openai-chatgpt-plan";
const CREDENTIAL_COMMANDS_MAX: usize = 1;
const CREDENTIAL_ACTIVE_CALLS_MAX: usize = 1;

/// One selected generation pinned from provenance through renewal.
pub(crate) struct SubscriptionCall {
    kernel: Arc<CredentialKernel>,
    call_id: Option<u64>,
    binding: ProviderCredentialBinding,
}

struct CredentialKernel {
    project: Option<super::google::CodeAssistProject>,
    provider: SubscriptionProvider,
    sender: SyncSender<CredentialCommand>,
    thread: Option<std::thread::JoinHandle<()>>,
}

enum CredentialCommand {
    Begin {
        profile: String,
        module_override: Option<String>,
        load: Option<crate::wasm::GenerationLoader>,
        reply: SyncSender<Result<(u64, ProviderCredentialBinding)>>,
    },
    Renew {
        call_id: u64,
        profile: String,
        fixture_issuer: Option<String>,
        cancel: CancelHandle,
        reply: SyncSender<Result<[String; 3]>>,
    },
    Abandon(u64),
    #[cfg(test)]
    ActiveManifestSha256 {
        call_id: u64,
        reply: SyncSender<Result<String>>,
    },
    #[cfg(test)]
    GenerationLoads {
        reply: SyncSender<usize>,
    },
    Stop,
}

struct ActiveGeneration {
    call_id: u64,
    generation: PluginGeneration,
    return_to_registry: bool,
}

impl std::fmt::Debug for SubscriptionCredential {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SubscriptionCredential")
            .field("profile", &self.profile)
            .field("fixture_issuer", &self.fixture_issuer)
            .field("module_override", &self.module_override)
            .finish_non_exhaustive()
    }
}

impl PartialEq for SubscriptionCredential {
    fn eq(&self, other: &Self) -> bool {
        self.provider() == other.provider()
            && self.profile == other.profile
            && self.fixture_issuer == other.fixture_issuer
            && self.module_override == other.module_override
    }
}

impl Eq for SubscriptionCredential {}

#[cfg(test)]
impl SubscriptionCredential {
    fn generation_loads(&self) -> usize {
        let (reply, result) = mpsc::sync_channel(CREDENTIAL_COMMANDS_MAX);
        self.kernel
            .sender
            .send(CredentialCommand::GenerationLoads { reply })
            .unwrap();
        result.recv().unwrap()
    }
}

impl SubscriptionCredential {
    /// Select exactly one profile without consulting API-key sources.
    /// # Errors
    /// Rejects invalid profile identity, non-loopback fixture authority, or an unusable credential module.
    pub fn new(profile: String, fixture_issuer: Option<String>) -> Result<Self> {
        Self::for_provider(SubscriptionProvider::OpenAi, profile, fixture_issuer)
    }

    /// Select one vendor-isolated subscription profile without consulting API-key sources.
    /// # Errors
    /// Rejects invalid identity, missing profile, or untrusted fixture authority.
    pub fn for_provider(
        provider: SubscriptionProvider,
        profile: String,
        fixture_issuer: Option<String>,
    ) -> Result<Self> {
        if profile.len() != 64 || !profile.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(fault("subscription requires an explicit valid profile ID"));
        }
        let profile_store = super::login::profile_store_for(provider, fixture_issuer.as_deref())?;
        Self::new_with_profile_store_for(
            provider,
            profile,
            fixture_issuer,
            PackageRegistry::at_default(),
            &profile_store,
        )
    }

    #[cfg(test)]
    fn new_with_profile_store(
        profile: String,
        fixture_issuer: Option<String>,
        packages: PackageRegistry,
        profile_store: &super::ProfileStore,
    ) -> Result<Self> {
        Self::new_with_profile_store_for(
            SubscriptionProvider::OpenAi,
            profile,
            fixture_issuer,
            packages,
            profile_store,
        )
    }

    fn new_with_profile_store_for(
        provider: SubscriptionProvider,
        profile: String,
        fixture_issuer: Option<String>,
        packages: PackageRegistry,
        profile_store: &super::ProfileStore,
    ) -> Result<Self> {
        profile_store
            .renewable_profile_available(&profile)
            .map_err(|error| fault(error.message()))?;
        let authority = super::login::authority_at_for(
            provider,
            fixture_issuer.as_deref(),
            Some(&profile),
            profile_store.clone(),
        )?;
        let project = if provider == SubscriptionProvider::Google {
            Some(
                authority
                    .selected
                    .as_ref()
                    .and_then(|metadata| metadata.code_assist_project.clone())
                    .ok_or_else(|| fault("Google profile has no admitted Code Assist project"))?,
            )
        } else {
            None
        };
        let mut kernel = CredentialKernel::start_for(provider, packages)?;
        kernel.project = project;
        Ok(Self {
            profile,
            fixture_issuer,
            module_override: None,
            kernel: Arc::new(kernel),
        })
    }

    pub(crate) fn google_project(&self) -> Option<&str> {
        self.kernel
            .project
            .as_ref()
            .map(super::google::CodeAssistProject::as_str)
    }

    /// Select one installed credential-module implementation for this subscription.
    /// # Errors
    /// Rejects empty or oversized package identities before plugin discovery.
    pub fn with_module_override(mut self, module_override: String) -> Result<Self> {
        if module_override.is_empty() || module_override.len() > 256 {
            return Err(fault("subscription credential module identity is invalid"));
        }
        self.module_override = Some(module_override);
        Ok(self)
    }

    /// Only inference authority permitted for this profile namespace.
    #[must_use]
    pub fn endpoint(&self) -> &str {
        self.fixture_issuer
            .as_deref()
            .unwrap_or_else(|| self.provider().endpoint())
    }

    pub(crate) fn provider(&self) -> SubscriptionProvider {
        self.kernel.provider
    }

    pub(crate) fn profile_id(&self) -> &str {
        &self.profile
    }

    pub(crate) fn fixture_issuer(&self) -> Option<&str> {
        self.fixture_issuer.as_deref()
    }

    pub(crate) fn module_override(&self) -> Option<&str> {
        self.module_override.as_deref()
    }

    #[cfg(test)]
    pub(crate) fn begin_call(&self) -> Result<SubscriptionCall> {
        self.begin_call_with_loader(None)
    }

    pub(crate) fn begin_call_with_loader(
        &self,
        load: Option<crate::wasm::GenerationLoader>,
    ) -> Result<SubscriptionCall> {
        let (reply, result) = mpsc::sync_channel(CREDENTIAL_COMMANDS_MAX);
        self.kernel
            .sender
            .send(CredentialCommand::Begin {
                profile: self.profile.clone(),
                module_override: self.module_override.clone(),
                load,
                reply,
            })
            .map_err(|_| fault("credential kernel stopped"))?;
        let (call_id, binding) = result
            .recv()
            .map_err(|_| fault("credential kernel stopped"))??;
        Ok(SubscriptionCall {
            kernel: Arc::clone(&self.kernel),
            call_id: Some(call_id),
            binding,
        })
    }
}

impl SubscriptionCall {
    pub(crate) const fn binding(&self) -> &ProviderCredentialBinding {
        &self.binding
    }

    pub(crate) fn renew(
        mut self,
        profile: &str,
        fixture_issuer: Option<&str>,
        cancel: CancelHandle,
    ) -> Result<[String; 3]> {
        let call_id = self
            .call_id
            .take()
            .ok_or_else(|| fault("credential call already consumed"))?;
        let (reply, result) = mpsc::sync_channel(CREDENTIAL_COMMANDS_MAX);
        self.kernel
            .sender
            .send(CredentialCommand::Renew {
                call_id,
                profile: profile.to_string(),
                fixture_issuer: fixture_issuer.map(str::to_string),
                cancel,
                reply,
            })
            .map_err(|_| fault("credential kernel stopped"))?;
        result
            .recv()
            .map_err(|_| fault("credential kernel stopped"))?
    }
}

#[cfg(test)]
impl SubscriptionCall {
    fn active_manifest_sha256(&self) -> Result<String> {
        let call_id = self
            .call_id
            .ok_or_else(|| fault("credential call already consumed"))?;
        let (reply, result) = mpsc::sync_channel(CREDENTIAL_COMMANDS_MAX);
        self.kernel
            .sender
            .send(CredentialCommand::ActiveManifestSha256 { call_id, reply })
            .map_err(|_| fault("credential kernel stopped"))?;
        result
            .recv()
            .map_err(|_| fault("credential kernel stopped"))?
    }
}

impl Drop for SubscriptionCall {
    fn drop(&mut self) {
        if let Some(call_id) = self.call_id.take() {
            let _sent = self.kernel.sender.send(CredentialCommand::Abandon(call_id));
        }
    }
}

impl CredentialKernel {
    fn start_for(provider: SubscriptionProvider, packages: PackageRegistry) -> Result<Self> {
        Self::start_with_store_for(provider, packages, None)
    }

    #[cfg(test)]
    fn start_with_store(
        packages: PackageRegistry,
        profile_store: Option<super::ProfileStore>,
    ) -> Result<Self> {
        Self::start_with_store_for(SubscriptionProvider::OpenAi, packages, profile_store)
    }

    fn start_with_store_for(
        provider: SubscriptionProvider,
        packages: PackageRegistry,
        profile_store: Option<super::ProfileStore>,
    ) -> Result<Self> {
        let (sender, receiver) = mpsc::sync_channel(CREDENTIAL_COMMANDS_MAX);
        let (ready_sender, ready) = mpsc::sync_channel(CREDENTIAL_COMMANDS_MAX);
        let thread = std::thread::spawn(move || {
            let engine = match PluginEngine::new() {
                Ok(engine) => engine,
                Err(error) => {
                    let _sent = ready_sender.send(Err(error));
                    return;
                }
            };
            let mut registry = PluginRegistry::new();
            let loaded =
                load_generations(&engine, &packages).and_then(|(generations, snapshot)| {
                    registry.publish_all(generations)?;
                    Ok(snapshot)
                });
            let snapshot = match loaded {
                Ok(snapshot) => snapshot,
                Err(error) => {
                    let _sent = ready_sender.send(Err(error));
                    return;
                }
            };
            let _sent = ready_sender.send(Ok(()));
            run_kernel(
                provider,
                receiver,
                &engine,
                &packages,
                profile_store.as_ref(),
                registry,
                snapshot,
            );
        });
        match ready.recv() {
            Ok(Ok(())) => Ok(Self {
                project: None,
                provider,
                sender,
                thread: Some(thread),
            }),
            Ok(Err(error)) => {
                let _joined = thread.join();
                Err(error)
            }
            Err(_) => {
                let _joined = thread.join();
                Err(fault("credential kernel failed to start"))
            }
        }
    }
}

impl Drop for CredentialKernel {
    fn drop(&mut self) {
        let _sent = self.sender.send(CredentialCommand::Stop);
        if let Some(thread) = self.thread.take() {
            let _joined = thread.join();
        }
    }
}

fn run_kernel(
    provider: SubscriptionProvider,
    receiver: mpsc::Receiver<CredentialCommand>,
    engine: &PluginEngine,
    packages: &PackageRegistry,
    profile_store: Option<&super::ProfileStore>,
    mut registry: PluginRegistry,
    mut snapshot: CredentialModuleSnapshot,
) {
    let mut active: Option<ActiveGeneration> = None;
    let mut next_call_id = 0_u64;
    #[cfg(test)]
    let mut generation_loads = 1_usize;
    for command in receiver {
        match command {
            CredentialCommand::Begin {
                profile,
                module_override,
                load,
                reply,
            } => {
                let result = (|| {
                    if active.is_some() {
                        return Err(fault(&format!(
                            "credential kernel reached its active-call limit of {CREDENTIAL_ACTIVE_CALLS_MAX}"
                        )));
                    }
                    let return_to_registry = load.is_none();
                    let generation = if let Some(load) = load {
                        load()?
                    } else {
                        #[cfg(test)]
                        {
                            generation_loads +=
                                reload_registry(engine, packages, &mut registry, &mut snapshot)?
                                    .attempted_loads();
                        }
                        #[cfg(not(test))]
                        {
                            reload_registry(engine, packages, &mut registry, &mut snapshot)?;
                        }
                        registry.take_credential_source_with_override(
                            provider.consumer(),
                            provider.source(),
                            module_override.as_deref(),
                        )?
                    };
                    let binding = ProviderCredentialBinding {
                        module_id: format!("{}/{}", generation.manifest().id(), provider.source()),
                        profile_id: profile,
                    };
                    let call_id = next_call_id;
                    next_call_id = next_call_id.wrapping_add(1);
                    active = Some(ActiveGeneration {
                        call_id,
                        generation,
                        return_to_registry,
                    });
                    Ok((call_id, binding))
                })();
                let _sent = reply.send(result);
            }
            CredentialCommand::Renew {
                call_id,
                profile,
                fixture_issuer,
                cancel,
                reply,
            } => {
                let result = renew_credential(
                    (provider, profile_store),
                    &mut active,
                    &mut registry,
                    call_id,
                    &profile,
                    fixture_issuer.as_deref(),
                    cancel,
                );
                let _sent = reply.send(result);
            }
            CredentialCommand::Abandon(call_id) => {
                if active
                    .as_ref()
                    .is_some_and(|entry| entry.call_id == call_id)
                    && let Some(active_generation) = active.take()
                    && active_generation.return_to_registry
                {
                    registry.return_credential_generation(active_generation.generation);
                }
            }
            #[cfg(test)]
            CredentialCommand::ActiveManifestSha256 { call_id, reply } => {
                let result = active
                    .as_ref()
                    .filter(|entry| entry.call_id == call_id)
                    .map(|entry| entry.generation.manifest_sha256().to_string())
                    .ok_or_else(|| fault("credential call is no longer active"));
                let _sent = reply.send(result);
            }
            #[cfg(test)]
            CredentialCommand::GenerationLoads { reply } => {
                let _sent = reply.send(generation_loads);
            }
            CredentialCommand::Stop => break,
        }
    }
}

fn renew_credential(
    authority: (SubscriptionProvider, Option<&super::ProfileStore>),
    active: &mut Option<ActiveGeneration>,
    registry: &mut PluginRegistry,
    call_id: u64,
    profile: &str,
    fixture_issuer: Option<&str>,
    cancel: CancelHandle,
) -> Result<[String; 3]> {
    let (provider, profile_store) = authority;
    match active.take() {
        Some(mut active_generation) if active_generation.call_id == call_id => {
            let authority = profile_store.as_ref().map_or_else(
                || super::login::authority_for(provider, fixture_issuer, Some(profile)),
                |store| {
                    super::login::authority_at_for(
                        provider,
                        fixture_issuer,
                        Some(profile),
                        (*store).clone(),
                    )
                },
            );
            let result = authority.and_then(|authority| {
                active_generation
                    .generation
                    .configure_login_authority(authority);
                active_generation.generation.renew_credential_module(
                    profile,
                    fixture_issuer,
                    cancel,
                )
            });
            if active_generation.return_to_registry {
                registry.return_credential_generation(active_generation.generation);
            }
            result
        }
        Some(active_generation) => {
            if active_generation.return_to_registry {
                registry.return_credential_generation(active_generation.generation);
            }
            Err(fault("credential kernel call identity mismatch"))
        }
        None => Err(fault("credential call is no longer active")),
    }
}

enum ReloadOutcome {
    Unchanged,
    Published,
    RetainedCandidate,
    RetainedDiscovery,
}

impl ReloadOutcome {
    #[cfg(test)]
    const fn attempted_loads(&self) -> usize {
        match self {
            Self::Published | Self::RetainedCandidate => 1,
            Self::Unchanged | Self::RetainedDiscovery => 0,
        }
    }
}

fn reload_registry(
    engine: &PluginEngine,
    packages: &PackageRegistry,
    registry: &mut PluginRegistry,
    snapshot: &mut CredentialModuleSnapshot,
) -> Result<ReloadOutcome> {
    let changed = packages.credential_modules_changed(snapshot);
    match changed {
        Ok(false) => Ok(ReloadOutcome::Unchanged),
        Ok(true) => {
            match load_generations(engine, packages).and_then(|(candidate, candidate_snapshot)| {
                registry.publish_all(candidate)?;
                Ok(candidate_snapshot)
            }) {
                Ok(candidate_snapshot) => {
                    *snapshot = candidate_snapshot;
                    Ok(ReloadOutcome::Published)
                }
                Err(_error) if !registry.is_empty() => Ok(ReloadOutcome::RetainedCandidate),
                Err(error) => Err(error),
            }
        }
        Err(_error) if !registry.is_empty() => Ok(ReloadOutcome::RetainedDiscovery),
        Err(error) => Err(error),
    }
}

fn load_generations(
    engine: &PluginEngine,
    packages: &PackageRegistry,
) -> Result<(Vec<PluginGeneration>, CredentialModuleSnapshot)> {
    let embedded = embedded_generation(engine)?;
    let (mut generations, snapshot) = packages.load_credential_modules_with_snapshot(engine)?;
    generations.push(embedded);
    Ok((generations, snapshot))
}

pub(crate) fn embedded_generation(engine: &PluginEngine) -> Result<PluginGeneration> {
    let manifest = PluginManifest::parse(
        "id \"smith:oauth\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"smith_plugin_oauth.wasm\"\ncapability \"secret-proxy\"",
    )?;
    PluginGeneration::load_embedded(
        engine,
        manifest,
        include_bytes!(concat!(env!("OUT_DIR"), "/smith_plugin_oauth.wasm")),
        &[Capability::SecretProxy],
    )
}

fn fault(message: &str) -> SmithError {
    SmithError::Config {
        field: "oauth.profile".into(),
        message: message.into(),
    }
}

#[cfg(all(test, target_arch = "x86_64"))]
mod tests {
    use super::*;
    use std::path::Path;

    fn scratch_root(name: &str) -> std::path::PathBuf {
        std::env::temp_dir().join(format!(
            "smith-oauth-source-{name}-{}",
            smith::id::SessionId::new()
        ))
    }

    fn credential(root: &Path) -> SubscriptionCredential {
        let package = root.join("package");
        write_package(&package, "0.1.0", true);
        let engine = PluginEngine::new().unwrap();
        let packages = PackageRegistry::at(root.join("registry"));
        packages
            .link(&engine, &package, &[Capability::SecretProxy])
            .unwrap();
        let profile = "a".repeat(64);
        let store = super::super::ProfileStore::at(root.join("profiles"));
        store.host_id().unwrap();
        std::fs::write(
            root.join("profiles/profiles.json"),
            serde_json::json!({
                "version": 2,
                "host_id": store.host_id().unwrap(),
                "profiles": [{
                    "metadata": {
                        "flow": "DynamicOidc",
                        "connection_id": "openai-chatgpt-plan",
                        "id": profile,
                        "issuer": "http://127.0.0.1:1",
                        "subject": "fixture-subject",
                        "client_id": "oaiapp_fixture",
                        "workspace": null,
                        "label": "fixture",
                        "scopes": ["openid", "chatgpt.tokens.use.direct"],
                        "expires_at": 4_102_444_800_u64,
                    },
                    "tokens": {
                        "access": "fixture-access",
                        "refresh": "fixture-refresh",
                        "identity": "fixture-identity",
                    },
                    "refresh_pending": false,
                }],
            })
            .to_string(),
        )
        .unwrap();
        SubscriptionCredential {
            profile,
            fixture_issuer: Some("http://127.0.0.1:1".into()),
            module_override: Some("fixture:credential".into()),
            kernel: Arc::new(CredentialKernel::start_with_store(packages, Some(store)).unwrap()),
        }
    }

    fn manifest(version: &str, secret_proxy: bool) -> String {
        let capability = if secret_proxy {
            "capability \"secret-proxy\"\n"
        } else {
            ""
        };
        format!(
            "id \"fixture:credential\"\nversion \"{version}\"\nworld \"0.1.0\"\nartifact \"oauth.wasm\"\n{capability}"
        )
    }

    fn manifest_sha256(version: &str, secret_proxy: bool) -> String {
        smith::sha256::digest_hex(manifest(version, secret_proxy).as_bytes())
    }

    fn write_package(root: &Path, version: &str, secret_proxy: bool) {
        std::fs::create_dir_all(root).unwrap();
        std::fs::write(root.join("plugin.kdl"), manifest(version, secret_proxy)).unwrap();
        std::fs::write(
            root.join("oauth.wasm"),
            include_bytes!(concat!(env!("OUT_DIR"), "/smith_plugin_oauth.wasm")),
        )
        .unwrap();
    }

    fn unavailable_credential(
        root: &Path,
        tokens: Option<super::super::TokenSet>,
        refresh_pending: bool,
    ) -> (PackageRegistry, super::super::ProfileStore) {
        let package = root.join("package");
        write_package(&package, "0.1.0", true);
        let engine = PluginEngine::new().unwrap();
        let packages = PackageRegistry::at(root.join("registry"));
        packages
            .link(&engine, &package, &[Capability::SecretProxy])
            .unwrap();
        std::fs::write(package.join("oauth.wasm"), b"invalid component").unwrap();
        let store = super::super::ProfileStore::at(root.join("profiles"));
        store.host_id().unwrap();
        store
            .save(super::super::Profile {
                metadata: super::super::ProfileMetadata {
                    flow: super::super::LoginFlow::DynamicOidc,
                    connection_id: "openai-chatgpt-plan".into(),
                    id: "a".repeat(64),
                    issuer: "http://127.0.0.1:1".into(),
                    subject: "fixture-subject".into(),
                    client_id: "oaiapp_fixture".into(),
                    workspace: None,
                    code_assist_project: None,
                    label: "fixture".into(),
                    scopes: vec!["openid".into(), "chatgpt.tokens.use.direct".into()],
                    expires_at: 4_102_444_800,
                },
                tokens,
                refresh_pending,
            })
            .unwrap();
        (packages, store)
    }

    #[test]
    fn signed_out_profile_rejects_before_credential_kernel_starts() {
        let root = scratch_root("signed-out-admission");
        let (packages, store) = unavailable_credential(&root, None, false);
        let error = SubscriptionCredential::new_with_profile_store(
            "a".repeat(64),
            Some("http://127.0.0.1:1".into()),
            packages,
            &store,
        )
        .unwrap_err();
        assert!(
            error.to_string().contains("OAuth session unusable"),
            "{error}"
        );
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn pending_profile_rejects_before_credential_kernel_starts() {
        let root = scratch_root("pending-admission");
        let (packages, store) = unavailable_credential(
            &root,
            Some(super::super::TokenSet {
                access: "fixture-access".into(),
                refresh: "fixture-refresh".into(),
                identity: "fixture-identity".into(),
            }),
            true,
        );
        let error = SubscriptionCredential::new_with_profile_store(
            "a".repeat(64),
            Some("http://127.0.0.1:1".into()),
            packages,
            &store,
        )
        .unwrap_err();
        assert!(
            error.to_string().contains("OAuth session unusable"),
            "{error}"
        );
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn rejected_registration_candidate_retains_last_published_generation() {
        let root = scratch_root("retained-registration");
        let package = root.join("package");
        let registry_root = root.join("registry");
        write_package(&package, "0.1.0", true);
        let engine = PluginEngine::new().unwrap();
        let packages = PackageRegistry::at(registry_root);
        packages
            .link(&engine, &package, &[Capability::SecretProxy])
            .unwrap();
        let mut generations = PluginRegistry::new();
        let (candidate, mut snapshot) = load_generations(&engine, &packages).unwrap();
        generations.publish_all(candidate).unwrap();
        let previous = manifest_sha256("0.1.0", true);
        write_package(&package, "0.2.0", false);

        assert!(reload_registry(&engine, &packages, &mut generations, &mut snapshot).is_ok());
        assert_eq!(
            generations
                .bind_credential_source_with_override(
                    CREDENTIAL_CONSUMER,
                    CREDENTIAL_SOURCE,
                    Some("fixture:credential"),
                )
                .unwrap()
                .manifest_sha256(),
            previous
        );
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn candidate_snapshot_tracks_generation_bytes_not_a_later_file_replacement() {
        let root = scratch_root("candidate-snapshot");
        let package = root.join("package");
        let registry_root = root.join("registry");
        write_package(&package, "0.1.0", true);
        let engine = PluginEngine::new().unwrap();
        let packages = PackageRegistry::at(registry_root);
        packages
            .link(&engine, &package, &[Capability::SecretProxy])
            .unwrap();
        let (initial, _) = load_generations(&engine, &packages).unwrap();
        let mut generations = PluginRegistry::new();
        generations.publish_all(initial).unwrap();

        write_package(&package, "0.2.0", true);
        let (candidate, mut snapshot) = load_generations(&engine, &packages).unwrap();
        write_package(&package, "0.3.0", true);
        generations.publish_all(candidate).unwrap();

        assert!(matches!(
            reload_registry(&engine, &packages, &mut generations, &mut snapshot),
            Ok(ReloadOutcome::Published)
        ));
        assert_eq!(
            generations
                .bind_credential_source_with_override(
                    CREDENTIAL_CONSUMER,
                    CREDENTIAL_SOURCE,
                    Some("fixture:credential"),
                )
                .unwrap()
                .manifest_sha256(),
            manifest_sha256("0.3.0", true)
        );
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn failed_discovery_retains_generation_without_attempting_candidate_load() {
        let root = scratch_root("retained-discovery-load-count");
        let package = root.join("package");
        let credential = credential(&root);
        let previous = manifest_sha256("0.1.0", true);

        std::fs::remove_file(package.join("oauth.wasm")).unwrap();
        let missing = credential.begin_call().unwrap();
        assert_eq!(credential.generation_loads(), 1);
        assert_eq!(missing.active_manifest_sha256().unwrap(), previous);
        drop(missing);

        std::fs::write(
            package.join("oauth.wasm"),
            include_bytes!(concat!(env!("OUT_DIR"), "/smith_plugin_oauth.wasm")),
        )
        .unwrap();
        std::fs::write(package.join("plugin.kdl"), "not kdl").unwrap();
        let malformed = credential.begin_call().unwrap();
        assert_eq!(credential.generation_loads(), 1);
        assert_eq!(malformed.active_manifest_sha256().unwrap(), previous);
        drop(malformed);
        drop(credential);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn unchanged_credential_modules_do_not_load_a_second_generation() {
        let root = scratch_root("unchanged-generation");
        let credential = credential(&root);
        assert_eq!(credential.generation_loads(), 1);
        let call = credential.begin_call().unwrap();
        assert_eq!(credential.generation_loads(), 1);
        drop(call);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn active_call_renews_pinned_generation_then_next_call_uses_valid_replacement() {
        let root = scratch_root("pinned-renewal");
        let package = root.join("package");
        let credential = credential(&root);
        let initial = manifest_sha256("0.1.0", true);
        assert_eq!(credential.generation_loads(), 1);
        let call = credential.begin_call().unwrap();
        assert_eq!(credential.generation_loads(), 1);
        assert_eq!(
            call.binding().module_id,
            "fixture:credential/openai-chatgpt-plan@1"
        );
        assert_eq!(call.active_manifest_sha256().unwrap(), initial);
        write_package(&package, "0.2.0", true);
        assert_eq!(call.active_manifest_sha256().unwrap(), initial);
        call.renew(
            credential.profile_id(),
            credential.fixture_issuer(),
            CancelHandle::new(),
        )
        .unwrap();

        let replacement = credential.begin_call().unwrap();
        assert_eq!(credential.generation_loads(), 2);
        assert_eq!(
            replacement.active_manifest_sha256().unwrap(),
            manifest_sha256("0.2.0", true)
        );
        drop(replacement);
        std::fs::write(package.join("oauth.wasm"), b"invalid component").unwrap();

        let retained = credential.begin_call().unwrap();
        assert_eq!(credential.generation_loads(), 3);
        assert_eq!(
            retained.active_manifest_sha256().unwrap(),
            manifest_sha256("0.2.0", true)
        );
        drop(retained);
        drop(credential);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn round_selected_source_renews_without_independent_discovery() {
        let root = scratch_root("round-selected-source");
        let credential = credential(&root);
        let packages = PackageRegistry::at(root.join("registry"));
        let engine = PluginEngine::new().unwrap();
        let (generations, _) = load_generations(&engine, &packages).unwrap();
        let mut published = PluginRegistry::new();
        published.publish_all(generations).unwrap();
        let selected = published
            .bind_credential_source_with_override(
                CREDENTIAL_CONSUMER,
                CREDENTIAL_SOURCE,
                Some("fixture:credential"),
            )
            .unwrap();
        let load = Arc::new(selected.protocol_loader()) as crate::wasm::GenerationLoader;
        let initial = selected.manifest_sha256().to_string();
        // The round has selected its immutable source before any renewal call.
        write_package(&root.join("package"), "0.2.0", true);
        let call = credential.begin_call_with_loader(Some(load)).unwrap();
        assert_eq!(call.active_manifest_sha256().unwrap(), initial);
        assert_eq!(credential.generation_loads(), 1);
        call.renew(
            credential.profile_id(),
            credential.fixture_issuer(),
            CancelHandle::new(),
        )
        .unwrap();
        let (generations, _) = load_generations(&engine, &packages).unwrap();
        published.publish_all(generations).unwrap();
        let selected = published
            .bind_credential_source_with_override(
                CREDENTIAL_CONSUMER,
                CREDENTIAL_SOURCE,
                Some("fixture:credential"),
            )
            .unwrap();
        let load = Arc::new(selected.protocol_loader()) as crate::wasm::GenerationLoader;
        std::fs::write(
            root.join("package/oauth.wasm"),
            b"replaced after source publication",
        )
        .unwrap();
        let next = credential.begin_call_with_loader(Some(load)).unwrap();
        assert_eq!(
            next.active_manifest_sha256().unwrap(),
            manifest_sha256("0.2.0", true)
        );
        assert_eq!(credential.generation_loads(), 1);
        next.renew(
            credential.profile_id(),
            credential.fixture_issuer(),
            CancelHandle::new(),
        )
        .unwrap();
        drop(credential);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn active_call_keeps_kernel_alive_until_last_owner_drops() {
        let root = scratch_root("owner-drop");
        let credential = credential(&root);
        let call = credential.begin_call().unwrap();
        drop(credential);
        assert!(call.active_manifest_sha256().is_ok());
        let (finished, joined) = mpsc::sync_channel(1);
        std::thread::spawn(move || {
            drop(call);
            let _sent = finished.send(());
        });
        joined
            .recv_timeout(std::time::Duration::from_secs(15))
            .unwrap();
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn subscription_credential_handle_has_exact_x86_64_layout() {
        assert_eq!(
            std::mem::size_of::<SubscriptionCredential>(),
            80,
            "subscription credential holds profile metadata plus one worker handle"
        );
    }
}