Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/wasm/composition.rs

Raw
//! Structured guest composition (`SMH-SPEC-PLUG0001`, `SMH-SPEC-WASM0001`).
//! Executables move out of their slots while running; the remaining pool moves
//! down the synchronous call stack, never aliases a running store, and never waits.
//! Host allocation ceilings are soft (RULES Memory): actual requested bytes accumulate
//! across setup, guests and tagged workers. Boundary checks stop execution after a
//! crossing; bounded transient overshoot is reported, never clamped or prepaid.
//! Supported composed effects: bounded workspace writes and logs. Reads, edits,
//! directory traversal, process, network and credential effects are rejected.
//! Credential-bearing instances cannot participate; ordinary dispatch is unchanged.

use super::kernel::Watchdog;
use super::{
    Engine, LOG_BYTES_MAX, LOG_ENTRIES_MAX, LOG_GRANT, Linker, LogHost, NetScopeHost,
    PluginCeilings, PluginGeneration, PluginHostState, PluginRegistry, Result, SecretProxyHost,
    TABLE_ELEMENTS_MAX, ToolArguments, ToolComponentProvenance, ToolEffectContext, ToolPolicy,
    ToolPolicyState, ToolSchema, ToolingHost, WORKSPACE_GRANT, attach_workspace_effects,
    attached_effect_context, bindings, plugin_fault, qualified_tool_name, redact_secret_message,
};
use smith_core::tools::InvocationStop;
use std::path::Path;
use std::time::{Duration, Instant};
use wasmtime::StoreContextMut;

const HOST_ALLOCATION_BYTES_MAX: u64 = 16 * 1024 * 1024;
const COMPONENT_HANDLES_MAX: usize = 1024;
pub(super) const LIFT_BYTES_MAX: usize = 64 * 1024;
const CONVERSION_BYTES_MAX: usize = 8 * 1024 * 1024;
const OUTPUT_BYTES_MAX: usize = 1024 * 1024;
const CALLS_MAX: u16 = 32;
const DEPTH_MAX: u16 = 8;
const DEADLINE: Duration = Duration::from_secs(30);

/// Explicit directed caller/target grants; each edge delegates a descendant
/// directory relative to the caller's current held descriptor, never ambient process authority.
#[derive(Clone, Debug, Default)]
pub struct CompositionGrants {
    edges: Vec<[String; 3]>,
    limits: Option<Box<CompositionLimits>>,
}

/// Tightened shared limits for one composed root invocation.
#[derive(Clone, Copy, Debug)]
pub struct CompositionResourceLimits {
    /// Guest linear-memory bytes.
    pub memory_bytes: usize,
    /// Guest table elements.
    pub table_elements: usize,
    /// Lift/lower conversion bytes.
    pub conversion_bytes: usize,
    /// Guest and host-effect result bytes.
    pub output_bytes: usize,
    /// Component resource handles.
    pub component_handles: usize,
    /// Nested invocation count.
    pub calls: u16,
    /// Nested invocation depth.
    pub depth: u16,
}

#[derive(Clone, Debug)]
pub(super) struct CompositionLimits {
    pub(super) fuel: u64,
    pub(super) timeout_nanoseconds: u64,
    pub(super) allocation_bytes: u64,
    pub(super) memory_bytes: usize,
    pub(super) table_elements: usize,
    pub(super) conversion_bytes: usize,
    pub(super) output_bytes: usize,
    pub(super) component_handles: usize,
    pub(super) calls: u16,
    pub(super) depth: u16,
}

impl Default for CompositionLimits {
    fn default() -> Self {
        Self {
            fuel: PluginCeilings::default().fuel,
            timeout_nanoseconds: DEADLINE.as_secs() * 1_000_000_000,
            allocation_bytes: HOST_ALLOCATION_BYTES_MAX,
            memory_bytes: PluginCeilings::default().memory_bytes,
            table_elements: TABLE_ELEMENTS_MAX,
            conversion_bytes: CONVERSION_BYTES_MAX,
            output_bytes: OUTPUT_BYTES_MAX,
            component_handles: COMPONENT_HANDLES_MAX,
            calls: CALLS_MAX,
            depth: DEPTH_MAX,
        }
    }
}

impl CompositionGrants {
    pub(super) fn limits(&self) -> CompositionLimits {
        self.limits.as_deref().cloned().unwrap_or_default()
    }

    fn limits_mut(&mut self) -> &mut CompositionLimits {
        self.limits
            .get_or_insert_with(|| Box::new(CompositionLimits::default()))
    }

    pub(super) const fn has_delegations(&self) -> bool {
        !self.edges.is_empty()
    }

    /// Tighten root compute fuel and absolute timeout without granting authority.
    ///
    /// # Errors
    /// Rejects zero limits or limits exceeding product ceilings.
    pub fn with_execution_limits(mut self, fuel: u64, timeout: Duration) -> Result<Self> {
        if fuel == 0
            || fuel > PluginCeilings::default().fuel
            || timeout.is_zero()
            || timeout > DEADLINE
        {
            return Err(plugin_fault(
                "composition execution limits must tighten positive product ceilings",
            ));
        }
        self.limits_mut().fuel = fuel;
        self.limits_mut().timeout_nanoseconds =
            u64::try_from(timeout.as_nanos()).map_err(|error| plugin_fault(error.to_string()))?;
        Ok(self)
    }

    /// Tighten the soft requested-allocation threshold, never guest authority.
    ///
    /// # Errors
    /// Rejects zero or a threshold exceeding the product ceiling.
    pub fn with_host_allocation_limit(mut self, bytes: u64) -> Result<Self> {
        if bytes == 0 || bytes > HOST_ALLOCATION_BYTES_MAX {
            return Err(plugin_fault(
                "composition host allocation threshold must tighten a positive product ceiling",
            ));
        }
        self.limits_mut().allocation_bytes = bytes;
        Ok(self)
    }

    /// Tighten shared composed resource ceilings without granting authority.
    ///
    /// # Errors
    ///
    /// Rejects zero values or values exceeding product ceilings.
    pub fn with_resource_limits(mut self, resources: CompositionResourceLimits) -> Result<Self> {
        if resources.memory_bytes == 0
            || resources.memory_bytes > PluginCeilings::default().memory_bytes
            || resources.table_elements == 0
            || resources.table_elements > TABLE_ELEMENTS_MAX
            || resources.conversion_bytes == 0
            || resources.conversion_bytes > CONVERSION_BYTES_MAX
            || resources.output_bytes == 0
            || resources.output_bytes > OUTPUT_BYTES_MAX
            || resources.component_handles == 0
            || resources.component_handles > COMPONENT_HANDLES_MAX
            || resources.calls == 0
            || resources.calls > CALLS_MAX
            || resources.depth == 0
            || resources.depth > DEPTH_MAX
        {
            return Err(plugin_fault(
                "composition resource limits must tighten positive product ceilings",
            ));
        }
        let limits = self.limits_mut();
        limits.memory_bytes = resources.memory_bytes;
        limits.table_elements = resources.table_elements;
        limits.conversion_bytes = resources.conversion_bytes;
        limits.output_bytes = resources.output_bytes;
        limits.component_handles = resources.component_handles;
        limits.calls = resources.calls;
        limits.depth = resources.depth;
        Ok(self)
    }

    /// Parse repeated `qualified-caller=qualified-target#relative-directory` grants.
    /// No guest can supply or modify these host-owned edges.
    ///
    /// # Errors
    /// Rejects malformed identities, duplicate edges, absolute/traversing paths, or excess edges.
    pub fn from_specs(specifications: &[String]) -> Result<Self> {
        if specifications.len() > 64 {
            return Err(plugin_fault("composition grants exceed 64 edges"));
        }
        let mut edges = Vec::with_capacity(specifications.len());
        for specification in specifications {
            let (caller, rest) = specification
                .split_once('=')
                .ok_or_else(|| plugin_fault("delegation requires caller=target#directory"))?;
            let (target, directory) = rest
                .split_once('#')
                .ok_or_else(|| plugin_fault("delegation requires target#directory"))?;
            if !qualified(caller)
                || !qualified(target)
                || directory.is_empty()
                || directory.len() > 1024
                || Path::new(directory).is_absolute()
                || Path::new(directory).components().any(|part| {
                    !matches!(
                        part,
                        std::path::Component::Normal(_) | std::path::Component::CurDir
                    )
                })
                || edges
                    .iter()
                    .any(|edge: &[String; 3]| edge[0] == caller && edge[1] == target)
            {
                return Err(plugin_fault("invalid or duplicate composition delegation"));
            }
            edges.push([caller.into(), target.into(), directory.into()]);
        }
        Ok(Self {
            edges,
            ..Self::default()
        })
    }

    fn directory(&self, caller: &str, target: &str) -> Option<&str> {
        self.edges
            .iter()
            .find(|edge| edge[0] == caller && edge[1] == target)
            .map(|edge| edge[2].as_str())
    }

    fn reaches(&self, root: &str, participant: &str) -> bool {
        let mut reachable = vec![root];
        let mut cursor = 0;
        while cursor < reachable.len() {
            let caller = reachable[cursor];
            if caller == participant {
                return true;
            }
            for edge in &self.edges {
                if edge[0] == caller && !reachable.contains(&edge[1].as_str()) {
                    reachable.push(&edge[1]);
                }
            }
            cursor += 1;
        }
        false
    }
}

const fn delegated_grants(target: u8, inherited: u8) -> u8 {
    target & inherited & (WORKSPACE_GRANT | LOG_GRANT)
}

fn qualified(name: &str) -> bool {
    name.len() <= 256
        && name.split_once('/').is_some_and(|(plugin, tool)| {
            plugin.contains(':') && !tool.is_empty() && !tool.contains('/')
        })
}

struct Target {
    name: String,
    local_name: String,
    schema: ToolSchema,
    slot: usize,
}

pub(super) struct InvocationPool {
    slots: Vec<Option<PluginGeneration>>,
    targets: Vec<Target>,
    grants: CompositionGrants,
    policy: ToolPolicy,
    charged: Vec<bool>,
    caller: String,
    deadline: Instant,
    fuel: u64,
    memory_bytes: usize,
    table_elements: usize,
    conversion_bytes: usize,
    output_bytes: usize,
    log_bytes: usize,
    log_entries: usize,
    calls: u16,
    depth: u16,
    // Host-issued WASI resources; component-private resource.new stays engine-metered.
    sealed_handles: u32,
    allocation: Option<smith_alloc::AllocationGroup>,
}

impl PluginRegistry {
    pub(super) fn invoke_composed(
        &mut self,
        name: &str,
        input: &str,
        effects: &mut ToolEffectContext<'_>,
        grants: &CompositionGrants,
        policy: &ToolPolicy,
    ) -> Result<String> {
        let allocation = smith_alloc::AllocationGroup::new().map_err(|error| {
            plugin_fault(format!("composition allocation observation: {error:?}"))
        })?;
        let guard = allocation.enter();
        let _unscoped = effects.hold_allocation_observer(Box::new(AllocationObserver {
            allocation: allocation.clone(),
            threshold_bytes: grants.limits().allocation_bytes,
            _guard: guard,
        }));
        let result =
            self.invoke_composed_metered(name, input, effects, grants, policy, &allocation);
        allocation_checkpoint(&allocation, grants.limits().allocation_bytes, effects)?;
        result
    }

    #[expect(
        clippy::too_many_lines,
        reason = "composition admission validates every pool invariant before guest execution"
    )]
    fn invoke_composed_metered(
        &mut self,
        name: &str,
        input: &str,
        effects: &mut ToolEffectContext<'_>,
        grants: &CompositionGrants,
        policy: &ToolPolicy,
        allocation: &smith_alloc::AllocationGroup,
    ) -> Result<String> {
        if let Some(first) = self.generations.first()
            && self.generations.iter().any(|generation| {
                !Engine::same(
                    first.instance.store.engine(),
                    generation.instance.store.engine(),
                )
            })
        {
            return stop(
                effects,
                InvocationStop::Sandbox,
                "composition rejects mixed engines",
            );
        }
        if self.generations.len() > 64
            || self
                .generations
                .iter()
                .map(|generation| generation.tools.len())
                .sum::<usize>()
                > 128
            || policy.states.len() > 128
            || policy.states.iter().any(|(name, _)| name.len() > 256)
            || input.len() > LIFT_BYTES_MAX
            || self.generations.iter().any(|generation| {
                generation.tools.len() > 128
                    || generation.tools.iter().any(|tool| {
                        tool.name.len() > 256 || tool.input_schema_json.len() > LIFT_BYTES_MAX
                    })
            })
        {
            return stop(
                effects,
                InvocationStop::HostAllocation,
                "composition registry metadata exceeds bounded setup",
            );
        }
        let targets = self
            .generations
            .iter()
            .enumerate()
            .flat_map(|(slot, generation)| {
                generation.tools.iter().map(move |tool| {
                    Ok(Target {
                        name: qualified_tool_name(generation.manifest.id(), &tool.name),
                        local_name: tool.name.clone(),
                        schema: ToolSchema::from_json(&tool.input_schema_json)
                            .map_err(|error| plugin_fault(error.to_string()))?,
                        slot,
                    })
                })
            })
            .collect::<Result<Vec<_>>>()?;
        let target = targets
            .iter()
            .position(|target| target.name == name)
            .ok_or_else(|| {
                plugin_fault("composition root is not registered by qualified identity")
            })?;
        let root = &targets[target].name;
        if self.generations.iter().any(|generation| {
            generation.component_private_resources
                && generation.tools.iter().any(|tool| {
                    grants.reaches(
                        root,
                        &qualified_tool_name(generation.manifest.id(), &tool.name),
                    )
                })
        }) {
            return stop(
                effects,
                InvocationStop::Sandbox,
                "composition rejects canonical component-private resource.new",
            );
        }
        let engine = self.generations[targets[target].slot]
            .instance
            .store
            .engine()
            .clone();
        let limits = grants.limits();
        let deadline = Instant::now() + Duration::from_nanos(limits.timeout_nanoseconds);
        let watchdog = Watchdog::start(engine, effects.cancel_handle(), deadline)?;
        effects.confine_workspace()?;
        let sealed_handles = self.generations.iter().fold(0_u32, |total, generation| {
            total.saturating_add(generation.instance.store.data().sealed_handles)
        });
        let mut pool = Box::new(InvocationPool {
            charged: vec![false; self.generations.len()],
            slots: std::mem::take(&mut self.generations)
                .into_iter()
                .map(Some)
                .collect(),
            targets,
            grants: grants.clone(),
            policy: policy.clone(),
            caller: String::new(),
            deadline,
            fuel: limits.fuel,
            memory_bytes: 0,
            table_elements: 0,
            conversion_bytes: 0,
            output_bytes: 0,
            log_bytes: 0,
            log_entries: 0,
            calls: 0,
            depth: 0,
            sealed_handles,
            allocation: Some(allocation.clone()),
        });
        let result = pool.enter(target, input, effects, None, u8::MAX);
        self.generations = pool.slots.into_iter().flatten().collect();
        drop(watchdog);
        result
    }
}

struct AllocationObserver {
    allocation: smith_alloc::AllocationGroup,
    _guard: smith_alloc::AllocationGroupGuard,
    threshold_bytes: u64,
}

impl smith_core::tools::InvocationAllocationObserver for AllocationObserver {
    fn report(&self) -> Result<smith_core::tools::InvocationAllocationReport> {
        let observed = self.allocation.allocated().map_err(|error| {
            plugin_fault(format!("composition allocation observation: {error:?}"))
        })?;
        Ok(smith_core::tools::InvocationAllocationReport {
            threshold_bytes: self.threshold_bytes,
            actual_bytes: observed.bytes,
            cleanup_bytes: 0,
            excess_bytes: observed.bytes.saturating_sub(self.threshold_bytes),
            allocations: observed.allocations,
            stopped_bytes: None,
        })
    }
}

fn allocation_checkpoint(
    allocation: &smith_alloc::AllocationGroup,
    threshold_bytes: u64,
    effects: &mut ToolEffectContext<'_>,
) -> Result<()> {
    let observed = allocation.allocated().map_err(|error| {
        effects.stop(InvocationStop::HostAllocation);
        plugin_fault(format!("composition allocation observation: {error:?}"))
    })?;
    effects.report_allocation(threshold_bytes, observed.bytes, observed.allocations);
    if observed.bytes > threshold_bytes {
        return stop(
            effects,
            InvocationStop::HostAllocation,
            &format!(
                "composition host allocation: threshold_bytes={} actual_bytes={} excess_bytes={} allocations={}",
                threshold_bytes,
                observed.bytes,
                observed.bytes - threshold_bytes,
                observed.allocations,
            ),
        );
    }
    Ok(())
}

impl InvocationPool {
    fn checkpoint(&self, effects: &mut ToolEffectContext<'_>) -> Result<()> {
        if self.sealed_handles as usize > self.grants.limits().component_handles {
            return stop(
                effects,
                InvocationStop::Sandbox,
                "composition component handle limit",
            );
        }
        if let Some(allocation) = &self.allocation {
            allocation_checkpoint(allocation, self.grants.limits().allocation_bytes, effects)?;
        }
        let reason = effects.stop_reason().or_else(|| {
            if Instant::now() >= self.deadline {
                Some(InvocationStop::Deadline)
            } else if effects.cancel_handle().is_cancelled() {
                Some(InvocationStop::Cancelled)
            } else {
                None
            }
        });
        if let Some(reason) = reason {
            return stop(effects, reason, "composition interrupted");
        }
        Ok(())
    }

    fn reserve_host_call(&mut self, effects: &mut ToolEffectContext<'_>) -> Result<()> {
        self.checkpoint(effects)?;
        charge(
            &mut self.conversion_bytes,
            LIFT_BYTES_MAX,
            self.grants.limits().conversion_bytes,
            effects,
            InvocationStop::Conversion,
        )
    }

    // Moving the pool into the running store leaves only its detached executable
    // on this stack frame. No running store remains reachable from the pool.
    fn enter(
        self: &mut Box<Self>,
        target: usize,
        input: &str,
        effects: &mut ToolEffectContext<'_>,
        directory: Option<&str>,
        inherited: u8,
    ) -> Result<String> {
        self.checkpoint(effects)?;
        if self.depth >= self.grants.limits().depth || self.calls >= self.grants.limits().calls {
            return stop(
                effects,
                InvocationStop::HostAllocation,
                "composition call/depth budget exhausted",
            );
        }
        let target = &self.targets[target];
        if self.policy.state(&target.name) == ToolPolicyState::Disabled {
            return stop(
                effects,
                InvocationStop::Sandbox,
                "composition target is disabled",
            );
        }
        if input.len() > LIFT_BYTES_MAX {
            return stop(
                effects,
                InvocationStop::Conversion,
                "composition input exceeds lift allowance",
            );
        }
        let arguments =
            ToolArguments::from_json(input).map_err(|error| plugin_fault(error.to_string()))?;
        target
            .schema
            .validate(arguments.view())
            .map_err(|error| plugin_fault(format!("composition target schema: {error}")))?;
        let slot = target.slot;
        let local_name = target.local_name.clone();
        let name = target.name.clone();
        let Some(mut generation) = self.slots[slot].take() else {
            return stop(
                effects,
                InvocationStop::Sandbox,
                "composition target instance is busy",
            );
        };
        let provenance = ToolComponentProvenance {
            source_id: generation.manifest.id().into(),
            manifest_sha256: generation.manifest_sha256.clone(),
            component_sha256: generation.component_sha256.clone(),
        };
        let original_grants = generation.instance.store.data().grants;
        let hostcall_fuel = generation.instance.store.hostcall_fuel();
        let component_handles = generation.instance.store.max_component_handles();
        if let Err(error) = self.prepare(&mut generation.instance, slot, effects) {
            self.slots[slot] = Some(generation);
            return Err(error);
        }
        generation.instance.store.data_mut().grants = delegated_grants(original_grants, inherited);
        let caller = std::mem::replace(&mut self.caller, name.clone());
        self.calls += 1;
        self.depth += 1;
        // Empty shell avoids pointer erasure and interior mutability. Only the
        // owned pool crosses into StoreData; the shell is never used for dispatch.
        let pool = std::mem::replace(self, Box::new(Self::empty()));
        generation.instance.store.data_mut().composition = Some(pool);
        let run = |effects: &mut ToolEffectContext<'_>| {
            call_guest(&mut generation.instance, &local_name, input, effects)
        };
        let result = if let Some(directory) = directory {
            let mut entered = false;
            let result = effects.with_workspace_subdirectory(directory, |effects| {
                entered = true;
                effects.with_child(&name, input, Some(provenance), run)
            });
            if !entered {
                effects.stop(InvocationStop::Sandbox);
            }
            result
        } else {
            effects.set_component_provenance(provenance);
            let mut run = run;
            run(effects)
        };
        if let Some(pool) = generation.instance.store.data_mut().composition.take() {
            *self = pool;
        }
        self.caller = caller;
        self.depth -= 1;
        self.fuel = generation.instance.store.get_fuel().unwrap_or(0);
        generation.instance.store.data_mut().grants = original_grants;
        generation.instance.store.set_hostcall_fuel(hostcall_fuel);
        generation
            .instance
            .store
            .set_max_component_handles(component_handles);
        generation.instance.store.set_epoch_deadline(u64::MAX / 2);
        self.slots[slot] = Some(generation);
        self.checkpoint(effects)?;
        result
    }

    fn prepare(
        &mut self,
        instance: &mut super::PluginInstance,
        slot: usize,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<()> {
        self.reserve_host_call(effects)?;
        if !instance.store.data().secret_values.is_empty() {
            return stop(
                effects,
                InvocationStop::Sandbox,
                "composition cannot reuse a credential-bearing instance",
            );
        }
        if !self.charged[slot] {
            charge(
                &mut self.memory_bytes,
                instance.store.data().memory_bytes,
                self.grants.limits().memory_bytes,
                effects,
                InvocationStop::Memory,
            )?;
            charge(
                &mut self.table_elements,
                instance.store.data().table_elements,
                self.grants.limits().table_elements,
                effects,
                InvocationStop::Table,
            )?;
            self.charged[slot] = true;
        }
        instance
            .store
            .set_fuel(self.fuel)
            .map_err(|error| plugin_fault(error.to_string()))?;
        instance.reset_log_budget();
        instance.store.set_hostcall_fuel(LIFT_BYTES_MAX);
        instance
            .store
            .set_max_component_handles(self.grants.limits().component_handles);
        instance.store.set_epoch_deadline(1);
        instance.store.epoch_deadline_callback(epoch_checkpoint);
        Ok(())
    }

    fn empty() -> Self {
        Self {
            slots: Vec::new(),
            targets: Vec::new(),
            grants: CompositionGrants::default(),
            policy: ToolPolicy::default(),
            charged: Vec::new(),
            caller: String::new(),
            deadline: Instant::now(),
            fuel: 0,
            memory_bytes: 0,
            table_elements: 0,
            conversion_bytes: 0,
            output_bytes: 0,
            log_bytes: 0,
            log_entries: 0,
            calls: 0,
            depth: 0,
            sealed_handles: 0,
            allocation: None,
        }
    }
}

#[cfg(test)]
thread_local! {
    static EPOCH_READY: std::cell::RefCell<Option<std::sync::mpsc::SyncSender<()>>> = const { std::cell::RefCell::new(None) };
}

#[cfg(test)]
pub(super) fn signal_guest_epoch(ready: std::sync::mpsc::SyncSender<()>) {
    EPOCH_READY.with(|slot| {
        assert!(slot.replace(Some(ready)).is_none());
    });
}

fn epoch_checkpoint(
    mut store: StoreContextMut<'_, PluginHostState>,
) -> wasmtime::Result<wasmtime::UpdateDeadline> {
    if let Some(pool) = &store.data().composition {
        #[cfg(test)]
        EPOCH_READY.with(|slot| {
            if let Some(ready) = slot.borrow_mut().take() {
                ready.send(()).unwrap();
            }
        });
        if Instant::now() >= pool.deadline {
            return Err(wasmtime::Error::msg("composition deadline"));
        }
        let mut effects = attached_effect_context(&mut store.data_mut().workspace_effects)
            .map_err(wasmtime::Error::msg)?;
        if effects.cancel_handle().is_cancelled() {
            effects.stop(InvocationStop::Cancelled);
            return Err(wasmtime::Error::msg("composition cancelled"));
        }
    }
    Ok(wasmtime::UpdateDeadline::Continue(1))
}

fn call_guest(
    instance: &mut super::PluginInstance,
    local_name: &str,
    input: &str,
    effects: &mut ToolEffectContext<'_>,
) -> Result<String> {
    let _attachment = attach_workspace_effects(&instance.store, effects)?;
    let outcome =
        instance
            .bindings
            .smith_plugin_plugin()
            .call_invoke(&mut instance.store, local_name, input);
    let result = match outcome {
        Ok(result) => result
            .map(|text| redact_secret_message(&text, &instance.store.data().secret_values))
            .map_err(|message| {
                plugin_fault(format!(
                    "plugin error: {}",
                    redact_secret_message(&message, &instance.store.data().secret_values)
                ))
            }),
        Err(error) => {
            let reason = if matches!(
                error.downcast_ref::<wasmtime::Trap>(),
                Some(wasmtime::Trap::OutOfFuel)
            ) {
                InvocationStop::Fuel
            } else if Instant::now()
                >= instance
                    .store
                    .data()
                    .composition
                    .as_ref()
                    .map_or_else(Instant::now, |pool| pool.deadline)
            {
                InvocationStop::Deadline
            } else if effects.cancel_handle().is_cancelled() {
                InvocationStop::Cancelled
            } else {
                InvocationStop::Sandbox
            };
            stop(effects, reason, &format!("composition guest trap: {error}"))
        }
    };
    let pool = instance
        .store
        .data_mut()
        .composition
        .as_mut()
        .ok_or_else(|| plugin_fault("composition pool missing after guest return"))?;
    pool.checkpoint(effects)?;
    let bytes = result
        .as_ref()
        .map_or_else(|error| error.to_string().len(), String::len);
    // This runs inside with_child: an exhausted output allowance cannot leave
    // a successful child completion, while completed primitives remain Applied.
    charge(
        &mut pool.output_bytes,
        bytes,
        pool.grants.limits().output_bytes,
        effects,
        InvocationStop::Output,
    )?;
    result
}

fn charge(
    used: &mut usize,
    amount: usize,
    limit: usize,
    effects: &mut ToolEffectContext<'_>,
    reason: InvocationStop,
) -> Result<()> {
    if amount > limit.saturating_sub(*used) {
        return stop(effects, reason, "composition shared budget exhausted");
    }
    *used += amount;
    Ok(())
}

fn stop<T>(
    effects: &mut ToolEffectContext<'_>,
    reason: InvocationStop,
    message: &str,
) -> Result<T> {
    effects.stop(reason);
    Err(plugin_fault(message))
}

fn invoke(
    mut store: StoreContextMut<'_, PluginHostState>,
    (target, input): (String, String),
) -> wasmtime::Result<(std::result::Result<String, String>,)> {
    let fuel = store.get_fuel()?;
    let state = store.data_mut();
    let mut effects =
        attached_effect_context(&mut state.workspace_effects).map_err(wasmtime::Error::msg)?;
    let Some(mut pool) = state.composition.take() else {
        return Err(wasmtime::Error::msg(
            "composition unavailable outside an invocation",
        ));
    };
    pool.fuel = fuel;
    let result = (|| {
        pool.reserve_host_call(&mut effects)?;
        let Some(directory) = pool
            .grants
            .directory(&pool.caller, &target)
            .map(str::to_owned)
        else {
            return stop(
                &mut effects,
                InvocationStop::Sandbox,
                "composition caller has no explicit target delegation",
            );
        };
        let Some(target) = pool.targets.iter().position(|entry| entry.name == target) else {
            return stop(
                &mut effects,
                InvocationStop::Sandbox,
                "composition target requires exact qualified identity",
            );
        };
        if state.grants & WORKSPACE_GRANT == 0 {
            return stop(
                &mut effects,
                InvocationStop::Sandbox,
                "composition caller has no inherited workspace authority",
            );
        }
        pool.enter(target, &input, &mut effects, Some(&directory), state.grants)
    })();
    let hard = effects.stop_reason().is_some() || effects.cancel_handle().is_cancelled();
    drop(effects);
    let remaining = pool.fuel;
    state.composition = Some(pool);
    store.set_fuel(remaining)?;
    if hard {
        return Err(wasmtime::Error::msg("composition terminal failure"));
    }
    Ok((result.map_err(|error| error.to_string()),))
}

fn supported_effect(state: &PluginHostState) -> std::result::Result<(), String> {
    if state.composition.is_some() {
        return Err("composition supports bounded filesystem writes and logs only".into());
    }
    Ok(())
}

fn effect<T, Error: std::fmt::Debug>(
    mut store: StoreContextMut<'_, PluginHostState>,
    run: impl FnOnce(&mut PluginHostState) -> std::result::Result<T, Error>,
    bytes: impl FnOnce(&T) -> usize,
) -> wasmtime::Result<(std::result::Result<T, Error>,)> {
    if store.data().lifecycle_deadline.is_some() {
        let result = run(store.data_mut());
        let state = store.data_mut();
        let fatal = state.fatal_recording_failure.get();
        let effects =
            attached_effect_context(&mut state.workspace_effects).map_err(wasmtime::Error::msg)?;
        if fatal || effects.stop_reason().is_some() || effects.cancel_handle().is_cancelled() {
            return Err(wasmtime::Error::msg(
                "lifecycle terminal host import failure",
            ));
        }
        return Ok((result,));
    }
    if store.data().composition.is_none() {
        return Ok((run(store.data_mut()),));
    }
    {
        let state = store.data_mut();
        let mut effects =
            attached_effect_context(&mut state.workspace_effects).map_err(wasmtime::Error::msg)?;
        if let Some(pool) = &mut state.composition {
            pool.reserve_host_call(&mut effects)
                .map_err(|error| wasmtime::Error::msg(error.to_string()))?;
        }
    }
    let result = run(store.data_mut());
    let state = store.data_mut();
    let mut effects =
        attached_effect_context(&mut state.workspace_effects).map_err(wasmtime::Error::msg)?;
    if let Some(pool) = &mut state.composition {
        pool.checkpoint(&mut effects)
            .map_err(|error| wasmtime::Error::msg(error.to_string()))?;
        match &result {
            Ok(value) => charge(
                &mut pool.output_bytes,
                bytes(value),
                pool.grants.limits().output_bytes,
                &mut effects,
                InvocationStop::Output,
            )
            .map_err(|error| wasmtime::Error::msg(error.to_string()))?,
            Err(message) => {
                effects.stop(InvocationStop::Sandbox);
                return Err(wasmtime::Error::msg(format!("{message:?}")));
            }
        }
    }
    Ok((result,))
}

// Resource-producing imports reserve against the live root aggregate, including
// suspended stores and handles retained from prior invocations. No guest authority
// is added: sealed handles still carry no ambient WASI state.
pub(super) fn wasi_resource<T>(
    mut store: StoreContextMut<'_, PluginHostState>,
    conversion_bytes: usize,
    run: impl FnOnce(&mut PluginHostState) -> T,
) -> wasmtime::Result<T> {
    if let Some(pool) = &store.data().composition
        && pool.sealed_handles as usize >= pool.grants.limits().component_handles
    {
        let mut effects = attached_effect_context(&mut store.data_mut().workspace_effects)
            .map_err(wasmtime::Error::msg)?;
        effects.stop(InvocationStop::Sandbox);
        return Err(wasmtime::Error::msg("composition component handle limit"));
    }
    wasi_effect(store, conversion_bytes, run)
}

pub(super) fn mint_sealed_handle(state: &mut PluginHostState) {
    state.sealed_handles = state.sealed_handles.saturating_add(1);
    if let Some(pool) = &mut state.composition {
        pool.sealed_handles = pool.sealed_handles.saturating_add(1);
    }
}

pub(super) fn drop_sealed_handle(state: &mut PluginHostState) {
    state.sealed_handles = state.sealed_handles.saturating_sub(1);
    if let Some(pool) = &mut state.composition {
        pool.sealed_handles = pool.sealed_handles.saturating_sub(1);
    }
}

pub(super) fn wasi_effect<T>(
    mut store: StoreContextMut<'_, PluginHostState>,
    conversion_bytes: usize,
    run: impl FnOnce(&mut PluginHostState) -> T,
) -> wasmtime::Result<T> {
    let checkpoint = |state: &mut PluginHostState| -> wasmtime::Result<()> {
        if let Some(pool) = &mut state.composition {
            let mut effects = attached_effect_context(&mut state.workspace_effects)
                .map_err(wasmtime::Error::msg)?;
            pool.checkpoint(&mut effects)
                .map_err(|error| wasmtime::Error::msg(error.to_string()))?;
        }
        Ok(())
    };
    checkpoint(store.data_mut())?;
    let state = store.data_mut();
    if let Some(pool) = &mut state.composition {
        let mut effects =
            attached_effect_context(&mut state.workspace_effects).map_err(wasmtime::Error::msg)?;
        charge(
            &mut pool.conversion_bytes,
            conversion_bytes,
            pool.grants.limits().conversion_bytes,
            &mut effects,
            InvocationStop::Conversion,
        )
        .map_err(|error| wasmtime::Error::msg(error.to_string()))?;
    }
    let result = run(store.data_mut());
    checkpoint(store.data_mut())?;
    Ok(result)
}

pub(super) fn link(linker: &mut Linker<PluginHostState>) -> wasmtime::Result<()> {
    use bindings::smith::plugin::tooling::{
        CommandRequest, DirectoryQuery, FileEdit, FileRead, FileWrite,
    };
    linker.allow_shadowing(true);
    linker
        .instance("smith:plugin/composition@0.1.0")?
        .func_wrap("invoke", invoke)?;
    let mut tooling = linker.instance("smith:plugin/tooling@0.1.0")?;
    tooling.func_wrap("read", |store, (request,): (FileRead,)| {
        effect(
            store,
            |state| {
                if state.composition.is_some() && request.max_bytes > LIFT_BYTES_MAX as u64 {
                    return Err("composition read exceeds bounded output".into());
                }
                supported_effect(state)?;
                ToolingHost::read(state, request)
            },
            |value| value.text.len(),
        )
    })?;
    tooling.func_wrap("write", |store, (request,): (FileWrite,)| {
        effect(
            store,
            |state| {
                if state.composition.is_some()
                    && (request.path.len() > 1024 || request.content.len() > LIFT_BYTES_MAX)
                {
                    return Err("composition write exceeds bounded path/content".into());
                }
                ToolingHost::write(state, request)
            },
            |()| 0,
        )
    })?;
    tooling.func_wrap("edit", |store, (request,): (FileEdit,)| {
        effect(
            store,
            |state| {
                supported_effect(state)?;
                ToolingHost::edit(state, request)
            },
            |()| 0,
        )
    })?;
    tooling.func_wrap("list-directory", |store, (request,): (DirectoryQuery,)| {
        effect(
            store,
            |state| {
                supported_effect(state)?;
                ToolingHost::list_directory(state, request)
            },
            |value| value.iter().map(String::len).sum(),
        )
    })?;
    tooling.func_wrap("find", |store, (request,): (DirectoryQuery,)| {
        effect(
            store,
            |state| {
                supported_effect(state)?;
                ToolingHost::find(state, request)
            },
            |value| value.iter().map(String::len).sum(),
        )
    })?;
    tooling.func_wrap("grep", |store, (request,): (DirectoryQuery,)| {
        effect(
            store,
            |state| {
                supported_effect(state)?;
                ToolingHost::grep(state, request)
            },
            |value| value.iter().map(String::len).sum(),
        )
    })?;
    tooling.func_wrap("run-command", |store, (request,): (CommandRequest,)| {
        effect(
            store,
            |state| {
                supported_effect(state)?;
                ToolingHost::run_command(state, request)
            },
            String::len,
        )
    })?;
    link_effects(linker)
}

fn link_effects(linker: &mut Linker<PluginHostState>) -> wasmtime::Result<()> {
    linker.instance("smith:plugin/log@0.1.0")?.func_wrap(
        "write",
        |store, (level, message): (String, String)| {
            effect(
                store,
                |state| {
                    if let Some(pool) = &mut state.composition {
                        let mut effects = attached_effect_context(&mut state.workspace_effects)?;
                        charge(
                            &mut pool.log_entries,
                            1,
                            LOG_ENTRIES_MAX,
                            &mut effects,
                            InvocationStop::Log,
                        )
                        .map_err(|error| error.to_string())?;
                        charge(
                            &mut pool.log_bytes,
                            level.len() + message.len(),
                            LOG_BYTES_MAX,
                            &mut effects,
                            InvocationStop::Log,
                        )
                        .map_err(|error| error.to_string())?;
                    }
                    LogHost::write(state, level, message)
                },
                |()| 0,
            )
        },
    )?;
    linker.instance("smith:plugin/net-scope@0.1.0")?.func_wrap(
        "request",
        |store, (request,): (bindings::smith::plugin::net_scope::HttpRequest,)| {
            effect(
                store,
                |state| {
                    supported_effect(state)?;
                    NetScopeHost::request(state, request)
                },
                |value| {
                    value.body.len()
                        + value
                            .headers
                            .iter()
                            .map(|header| header.name.len() + header.value.len())
                            .sum::<usize>()
                },
            )
        },
    )?;

    link_secrets(linker)
}

fn link_secrets(linker: &mut Linker<PluginHostState>) -> wasmtime::Result<()> {
    use bindings::smith::plugin::secret_proxy::{CredentialExchange, LoginPolicy, ProfileRef};
    let mut secret = linker.instance("smith:plugin/secret-proxy@0.1.0")?;
    secret.func_wrap("exchange", |store, (request,): (CredentialExchange,)| {
        effect(
            store,
            |state| {
                supported_effect(state)?;
                SecretProxyHost::exchange(state, request)
            },
            |value| value.id.len(),
        )
    })?;
    secret.func_wrap("authorize", |store, (policy,): (LoginPolicy,)| {
        effect(
            store,
            |state| {
                supported_effect(state).map_err(|_| {
                    bindings::smith::plugin::secret_proxy::AuthorizationFault::Authority
                })?;
                SecretProxyHost::authorize(state, policy)
            },
            |value| value.id.len(),
        )
    })?;
    secret.func_wrap("end-session", |store, (profile,): (ProfileRef,)| {
        effect(
            store,
            |state| {
                supported_effect(state).map_err(|_| {
                    bindings::smith::plugin::secret_proxy::AuthorizationFault::Authority
                })?;
                SecretProxyHost::end_session(state, profile)
            },
            |_| 0,
        )
    })?;
    secret.func_wrap(
        "renew",
        |store, (profile, policy): (ProfileRef, LoginPolicy)| {
            effect(
                store,
                |state| {
                    supported_effect(state).map_err(|_| {
                        bindings::smith::plugin::secret_proxy::AuthorizationFault::Authority
                    })?;
                    SecretProxyHost::renew(state, profile, policy)
                },
                |value| value.id.len(),
            )
        },
    )?;
    Ok(())
}

#[cfg(test)]
mod tests {
    //! SMH-SPEC-PLUG0001: authority intersection never widens; root limits remain cumulative.
    use super::*;
    use crate::wasm::{NET_SCOPE_GRANT, PROCESS_GRANT, SECRET_PROXY_GRANT};

    #[test]
    fn mixed_engine_pool_rejected_before_guest_entry() {
        use crate::wasm::{Capability, PluginEngine, PluginManifest};
        let directory = std::env::temp_dir().join(format!(
            "smith-mixed-engines-{}",
            smith::id::SessionId::new()
        ));
        std::fs::create_dir(&directory).unwrap();
        let artifact = super::super::nested_tests::fixture_component_source(
            &directory,
            include_str!("../../tests/fixtures/composition.rs"),
        );
        let mut registry = PluginRegistry::new();
        let generations = ["root", "target"].map(|name| {
            let engine = PluginEngine::new().unwrap();
            let manifest = PluginManifest::parse(&format!("id \"fixture:{name}\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"guest.wasm\"\ncapability \"workspace\"\n")).unwrap();
            PluginGeneration::load(&engine, manifest, &artifact, &[Capability::Workspace]).unwrap()
        });
        registry.publish_all(generations.into()).unwrap();
        let mut session = smith_core::tools::ToolSession::new(&directory);
        let mut effects = ToolEffectContext::for_operation(&mut session, "fixture");
        let error = registry
            .invoke_composed(
                "fixture:root/fixture",
                r#"{"mode":"child-error"}"#,
                &mut effects,
                &CompositionGrants::default(),
                &ToolPolicy::default(),
            )
            .unwrap_err();
        assert!(error.to_string().contains("mixed engines"), "{error}");
        assert_eq!(registry.generations.len(), 2);
        assert!(!directory.join("written.txt").exists());
        drop(registry);
        std::fs::remove_dir_all(directory).unwrap();
    }

    #[test]
    fn child_output_exhaustion_cannot_record_success() {
        use crate::wasm::{Capability, PluginEngine, PluginManifest};
        use smith_core::tools::ToolDispatcher;
        struct Dispatch(Box<InvocationPool>);
        impl ToolDispatcher for Dispatch {
            fn invoke(
                &mut self,
                _: &str,
                _: &ToolArguments,
                effects: &mut ToolEffectContext<'_>,
            ) -> Result<String> {
                effects.confine_workspace()?;
                self.0
                    .enter(0, r#"{"mode":"child"}"#, effects, Some("."), u8::MAX)
            }
        }
        let directory = std::env::temp_dir().join(format!(
            "smith-child-output-{}",
            smith::id::SessionId::new()
        ));
        std::fs::create_dir(&directory).unwrap();
        let artifact = super::super::nested_tests::fixture_component_source(
            &directory,
            include_str!("../../tests/fixtures/composition.rs"),
        );
        let engine = PluginEngine::new().unwrap();
        let manifest = PluginManifest::parse("id \"fixture:target\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"guest.wasm\"\ncapability \"workspace\"\n").unwrap();
        let generation =
            PluginGeneration::load(&engine, manifest, &artifact, &[Capability::Workspace]).unwrap();
        let mut pool = Box::new(InvocationPool::empty());
        pool.deadline = Instant::now() + DEADLINE;
        pool.fuel = PluginCeilings::default().fuel;
        pool.output_bytes = OUTPUT_BYTES_MAX;
        pool.charged.push(false);
        pool.targets.push(Target {
            name: "fixture:target/fixture".into(),
            local_name: "fixture".into(),
            schema: ToolSchema::from_json(&generation.tools[0].input_schema_json).unwrap(),
            slot: 0,
        });
        pool.slots.push(Some(generation));
        let path = directory.join("session.smh");
        let (mut tools, storage) =
            super::super::nested_tests::admitted_tools(&path, Box::new(Dispatch(pool)), true);
        assert!(
            tools
                .invoke("fixture", &ToolArguments::empty_object())
                .is_err()
        );
        assert_eq!(
            std::fs::read_to_string(directory.join("written.txt")).unwrap(),
            "child committed"
        );
        drop(tools);
        drop(storage);
        let reader = smith_core::store::SessionReader::open(&path).unwrap();
        let mut completions = Vec::new();
        reader
            .scan(
                smith::config::Config::default_valid().frame_bytes_max,
                |frame| {
                    if let smith_core::frame::Frame::NestedCommit { entry } = frame
                        && let smith_core::session::EntryContent::Meta { kind, detail } =
                            smith_core::session::EntryContent::decode(&entry.content)?
                        && kind == smith_core::metadata::NESTED_COMPLETION_KIND
                    {
                        completions.push(serde_json::to_value(detail).unwrap());
                    }
                    Ok(())
                },
            )
            .unwrap();
        assert_eq!(completions.len(), 2);
        assert_eq!(
            completions[0]["ok"], true,
            "completed primitive remains successful"
        );
        assert_eq!(
            completions[1]["ok"], false,
            "child budget must fail before its completion"
        );
        drop(reader);
        std::fs::remove_dir_all(directory).unwrap();
    }

    #[test]
    fn delegated_authority_never_widens() {
        for target in 0..=u8::MAX {
            for inherited in 0..=u8::MAX {
                let authority = delegated_grants(target, inherited);
                assert_eq!(authority & !target, 0);
                assert_eq!(authority & !inherited, 0);
                assert_eq!(
                    authority & (PROCESS_GRANT | NET_SCOPE_GRANT | SECRET_PROXY_GRANT),
                    0
                );
                for ancestor in 0..32 {
                    assert_eq!(delegated_grants(ancestor, authority) & !authority, 0);
                }
            }
        }
    }

    #[test]
    fn composition_grants_reject_identity_and_directory_ambiguity() {
        for specification in [
            "a=b#A",
            "fixture:a/tool=fixture:b/tool#../B",
            "fixture:a/tool=fixture:b/tool#/A",
            "fixture:a/tool=fixture:b/tool#",
            "fixture:a/tool=fixture:b/tool/other#A",
        ] {
            assert!(
                CompositionGrants::from_specs(&[specification.into()]).is_err(),
                "{specification}"
            );
        }
        let grant = "fixture:a/tool=fixture:b/tool#A".to_string();
        assert!(CompositionGrants::from_specs(&[grant.clone(), grant.clone()]).is_err());
        let grants = CompositionGrants::from_specs(&[grant]).unwrap();
        assert_eq!(
            grants.directory("fixture:a/tool", "fixture:b/tool"),
            Some("A")
        );
        assert_eq!(grants.directory("fixture:c/tool", "fixture:b/tool"), None);
    }

    #[test]
    fn composition_resource_limits_tighten_every_shared_ceiling() {
        let limits = CompositionGrants::default()
            .with_resource_limits(CompositionResourceLimits {
                memory_bytes: 1,
                table_elements: 1,
                conversion_bytes: 1,
                output_bytes: 1,
                component_handles: 1,
                calls: 1,
                depth: 1,
            })
            .unwrap()
            .limits();
        assert_eq!(limits.memory_bytes, 1);
        assert_eq!(limits.table_elements, 1);
        assert_eq!(limits.conversion_bytes, 1);
        assert_eq!(limits.output_bytes, 1);
        assert_eq!(limits.component_handles, 1);
        assert_eq!(limits.calls, 1);
        assert_eq!(limits.depth, 1);
        assert!(
            CompositionGrants::default()
                .with_resource_limits(CompositionResourceLimits {
                    memory_bytes: 0,
                    table_elements: 1,
                    conversion_bytes: 1,
                    output_bytes: 1,
                    component_handles: 1,
                    calls: 1,
                    depth: 1
                })
                .is_err()
        );
        assert!(
            CompositionGrants::default()
                .with_resource_limits(CompositionResourceLimits {
                    memory_bytes: 1,
                    table_elements: 1,
                    conversion_bytes: 1,
                    output_bytes: 1,
                    component_handles: COMPONENT_HANDLES_MAX + 1,
                    calls: 1,
                    depth: 1
                })
                .is_err()
        );
    }

    #[test]
    fn composition_layout_and_charge_allocation_pins() {
        assert_eq!(std::mem::size_of::<CompositionGrants>(), 32);
        assert_eq!(std::mem::size_of::<PluginHostState>(), 296);
        assert_eq!(std::mem::size_of::<InvocationPool>(), 240);
        let (grants, allocation) =
            smith_alloc::measure(smith_alloc::Scope::KernelCall, CompositionGrants::default);
        assert_eq!(allocation.allocations, 0);
        assert_eq!(allocation.bytes, 0);
        assert!(grants.edges.is_empty());
        let (pool, allocation) = smith_alloc::measure(smith_alloc::Scope::KernelCall, || {
            Box::new(InvocationPool::empty())
        });
        assert_eq!(allocation.allocations, 1);
        assert_eq!(allocation.bytes, 240);
        let (_, allocation) = smith_alloc::measure(smith_alloc::Scope::KernelCall, || {
            for target in 0..=u8::MAX {
                std::hint::black_box(delegated_grants(target, WORKSPACE_GRANT));
            }
        });
        assert_eq!(allocation.allocations, 0);
        assert_eq!(allocation.bytes, 0);
        drop(pool);
    }

    #[test]
    fn missing_attachment_does_not_drop_executable_pool() {
        use wasmtime::AsContextMut;
        let engine = super::super::PluginEngine::new().unwrap();
        let state = PluginHostState {
            monotonic_now: 0,
            ceilings: PluginCeilings::default(),
            grants: 0,
            effects_enabled: true,
            lifecycle_deadline: None,
            lifecycle_allocation_bytes: 0,
            plugin_id: String::new(),
            net_scopes: Vec::new(),
            secret_grants: Vec::new(),
            oauth_authority: None,
            workspace_effects: super::super::WorkspaceEffects::default(),
            fatal_recording_failure: std::cell::Cell::new(false),
            log_bytes: 0,
            log_entries: Vec::new(),
            secret_values: Vec::new(),
            resolved_secret_refs: Vec::new(),
            mock_effects: None,
            composition: Some(Box::new(InvocationPool::empty())),
            memory_bytes: 0,
            table_elements: 0,
            sealed_handles: 0,
        };
        let mut store = wasmtime::Store::new(engine.engine(), state);
        store.set_fuel(100).unwrap();
        assert!(
            invoke(
                store.as_context_mut(),
                ("fixture:target/fixture".into(), "{}".into())
            )
            .is_err()
        );
        assert!(store.data().composition.is_some());
    }

    #[test]
    fn shared_charges_are_exact_and_fail_before_increment() {
        let dir = std::env::temp_dir();
        let mut session = smith_core::tools::ToolSession::new(&dir);
        let mut effects = ToolEffectContext::for_operation(&mut session, "read");
        let mut used = 0;
        charge(&mut used, 3, 8, &mut effects, InvocationStop::Output).unwrap();
        charge(&mut used, 5, 8, &mut effects, InvocationStop::Output).unwrap();
        assert!(charge(&mut used, 1, 8, &mut effects, InvocationStop::Output).is_err());
        assert_eq!(used, 8);
        assert!(effects.cancel_handle().is_cancelled());
    }
}