Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-core/src/tools/nested_tests.rs

Raw
//! SMH-SPEC-SPEC0001: nested admission, acknowledgement, redaction, and bounds.
use super::*;
use crate::frame::Frame;
use crate::metadata::{NESTED_EFFECTS_MAX, NESTED_INTENT_KIND, NESTED_PAYLOAD_BYTES_MAX};
use crate::session::EntryContent;
use smith::message::{Message, Role};

#[test]
fn known_applied_mutation_survives_a_later_unknown_nested_effect() {
    assert_eq!(
        aggregate_mutation(MutationState::Applied, MutationState::Unknown),
        MutationState::Applied
    );
}

proptest::proptest! {
    #[test]
    fn mutation_aggregation_is_order_independent(left in 0usize..3, right in 0usize..3) {
        let states = [MutationState::NotApplied, MutationState::Unknown, MutationState::Applied];
        proptest::prop_assert_eq!(aggregate_mutation(states[left], states[right]), aggregate_mutation(states[right], states[left]));
    }

    #[test]
    fn mutation_aggregation_is_idempotent(index in 0usize..3) {
        let state = [MutationState::NotApplied, MutationState::Unknown, MutationState::Applied][index];
        proptest::prop_assert_eq!(aggregate_mutation(state, state), state);
    }
}

struct CatchingWrites;
impl ToolDispatcher for CatchingWrites {
    fn invoke(
        &mut self,
        _: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        let _first = effects.invoke("write", input);
        let second = ToolArguments::from_serializable(
            &serde_json::json!({"path":"second.txt","content":"never"}),
        )
        .unwrap();
        let _second = effects.invoke("write", &second);
        Ok("guest caught host errors".into())
    }
}

fn root(tools: &mut ToolSession) -> smith::id::EntryId {
    tools
        .session
        .append(EntryContentRef::Message(&Message::with_text(
            Role::User,
            "write",
        )))
        .unwrap()
        .id
}

#[test]
fn nested_completion_failure_poison_survives_guest_catching_error() {
    let dir = std::env::temp_dir().join(format!(
        "smith-nested-failure-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&dir).unwrap();
    let mut tools = ToolSession::new(&dir);
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(CatchingWrites));
    let completions = Arc::new(AtomicUsize::new(0));
    let seen = Arc::clone(&completions);
    let mut tools = tools.with_completion_boundary(submission, move |frame| {
        assert!(
            matches!(frame, Frame::NestedCommit { .. }),
            "outer success must not be attempted"
        );
        seen.fetch_add(1, Ordering::Relaxed);
        Err(SmithError::Cancelled)
    });
    let input =
        ToolArguments::from_serializable(&serde_json::json!({"path":"first.txt","content":"once"}))
            .unwrap();
    let error = tools.invoke("write", &input).unwrap_err();
    assert!(matches!(
        error,
        SmithError::RecordFailed {
            mutation_state: MutationState::Applied,
            ..
        }
    ));
    assert_eq!(
        std::fs::read_to_string(dir.join("first.txt")).unwrap(),
        "once"
    );
    assert!(!dir.join("second.txt").exists());
    assert!(tools.invoke("write", &input).is_err());
    assert_eq!(completions.load(Ordering::Relaxed), 1);
    assert_eq!(tools.session.active_branch().entries().len(), 3);
    assert!(tools.cancel_handle().is_cancelled());
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn nested_intent_failure_blocks_even_first_dispatch_and_outer_success() {
    let dir = std::env::temp_dir().join(format!(
        "smith-nested-intent-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&dir).unwrap();
    let mut tools = ToolSession::with_persist(&dir, Session::new(), |_, bytes| {
        if matches!(EntryContent::decode(bytes)?, EntryContent::Meta { kind, .. } if kind == NESTED_INTENT_KIND)
        {
            Err(SmithError::Cancelled)
        } else {
            Ok(())
        }
    });
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(CatchingWrites));
    let mut tools = tools.with_completion_boundary(submission, |_| {
        panic!("no completion may follow uncertain intent")
    });
    let input = ToolArguments::from_serializable(
        &serde_json::json!({"path":"first.txt","content":"never"}),
    )
    .unwrap();
    assert!(tools.invoke("write", &input).is_err());
    assert!(!dir.join("first.txt").exists());
    assert!(!dir.join("second.txt").exists());
    assert_eq!(tools.session.active_branch().entries().len(), 2);
    std::fs::remove_dir_all(dir).unwrap();
}

struct SpilledEvidence;
impl ToolDispatcher for SpilledEvidence {
    fn invoke(
        &mut self,
        _: &str,
        _: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        let evidence = "x".repeat(1024 * 1024);
        effects.begin_nested("http", &evidence)?;
        effects.finish_nested(true, MutationState::Applied, &evidence)?;
        Ok("complete".into())
    }
}

#[test]
fn one_mib_nested_input_and_output_complete_without_inline_rejection() {
    let mut tools = ToolSession::new(std::env::temp_dir());
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(SpilledEvidence));
    tools.register(smith::tool::ToolMetadata::new("fixture", "large evidence"));
    let mut tools = tools.with_completion_boundary(submission, |_| Ok(()));
    assert!(
        tools
            .invoke("fixture", &ToolArguments::empty_object())
            .unwrap()
            .ok
    );
}

struct LargePrimitives;
impl ToolDispatcher for LargePrimitives {
    fn invoke(
        &mut self,
        _: &str,
        _: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        let content = "line\n".repeat(16 * 1024);
        let write = ToolArguments::from_serializable(
            &serde_json::json!({"path":"large.txt", "content":content}),
        )
        .unwrap();
        effects.invoke_redacted("write", &write, str::to_string)?;
        let read = ToolArguments::from_serializable(
            &serde_json::json!({"path":"large.txt", "max_bytes":content.len()}),
        )
        .unwrap();
        assert_eq!(
            effects.invoke_redacted("read", &read, str::to_string)?,
            content
        );
        let process = ToolArguments::from_serializable(
            &serde_json::json!({"command":"printf '%050000d' 0; printf '%050000d' 0 >&2"}),
        )
        .unwrap();
        let output = effects.invoke_redacted("bash", &process, str::to_string)?;
        assert_eq!(output.bytes().filter(|byte| *byte == b'0').count(), 100000);
        Ok("complete".into())
    }
}

#[test]
fn workspace_arguments_results_and_process_output_share_the_spill_path() {
    let dir = std::env::temp_dir().join(format!(
        "smith-primitive-payload-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&dir).unwrap();
    let mut tools = ToolSession::new(&dir);
    let submission = root(&mut tools);
    tools.register(smith::tool::ToolMetadata::new(
        "fixture",
        "large primitives",
    ));
    tools.set_dispatcher(Box::new(LargePrimitives));
    let chunks = Arc::new(std::sync::Mutex::new(Vec::new()));
    let recorded = Arc::clone(&chunks);
    let mut tools = tools.with_completion_boundary(submission, move |frame| {
        if let Frame::NestedPayload { chunk } = frame {
            recorded.lock().unwrap().push(*chunk);
        }
        Ok(())
    });
    assert!(
        tools
            .invoke("fixture", &ToolArguments::empty_object())
            .unwrap()
            .ok
    );
    let chunks = chunks.lock().unwrap();
    for (index, phase) in [
        (0, crate::frame::NestedPayloadPhase::Input),
        (1, crate::frame::NestedPayloadPhase::Output),
        (2, crate::frame::NestedPayloadPhase::Output),
    ] {
        let value: Vec<_> = chunks
            .iter()
            .filter(|chunk| chunk.index == index && chunk.phase == phase)
            .flat_map(|chunk| chunk.bytes.iter().copied())
            .collect();
        assert!(value.len() > crate::metadata::NESTED_EFFECT_BYTES_MAX);
        assert!(std::str::from_utf8(&value).is_ok());
    }
    std::fs::remove_dir_all(dir).unwrap();
}

struct OversizedCompletion;
impl ToolDispatcher for OversizedCompletion {
    fn invoke(
        &mut self,
        _: &str,
        _: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        effects.begin_nested("read", "{}")?;
        assert!(
            effects
                .finish_nested(
                    true,
                    MutationState::NotApplied,
                    &"x".repeat(NESTED_PAYLOAD_BYTES_MAX + 1)
                )
                .is_err()
        );
        let write = ToolArguments::from_serializable(
            &serde_json::json!({"path":"never.txt","content":"blocked"}),
        )
        .unwrap();
        assert!(
            effects
                .invoke_redacted("write", &write, str::to_string)
                .is_err()
        );
        Ok("caught oversized completion".into())
    }
}

#[test]
fn oversized_nested_result_poison_blocks_later_dispatch_and_outer_success() {
    let dir = std::env::temp_dir().join(format!(
        "smith-nested-output-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&dir).unwrap();
    let mut tools = ToolSession::new(&dir);
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(OversizedCompletion));
    let mut tools = tools.with_completion_boundary(submission, |_| {
        panic!("oversized completion cannot persist or settle")
    });
    let input = ToolArguments::from_serializable(
        &serde_json::json!({"path":"large.txt","max_bytes":NESTED_PAYLOAD_BYTES_MAX + 1}),
    )
    .unwrap();
    let error = tools.invoke("read", &input).unwrap_err();
    assert!(matches!(
        error,
        SmithError::RecordFailed {
            mutation_state: MutationState::NotApplied,
            ..
        }
    ));
    assert!(!dir.join("never.txt").exists());
    assert_eq!(tools.session.active_branch().entries().len(), 3);
    std::fs::remove_dir_all(dir).unwrap();
}

struct BoundedEffects;
impl ToolDispatcher for BoundedEffects {
    fn invoke(
        &mut self,
        _: &str,
        _: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        assert!(
            effects
                .begin_nested("log", &"x".repeat(NESTED_PAYLOAD_BYTES_MAX + 1))
                .is_err()
        );
        for index in 0..NESTED_EFFECTS_MAX {
            effects.begin_nested("log", "redacted")?;
            assert!(effects.begin_nested("log", "depth two forbidden").is_err());
            assert_eq!(effects.next_index, index + 1);
            effects.finish_nested(true, MutationState::NotApplied, "recorded")?;
        }
        assert!(effects.begin_nested("log", "count overflow").is_err());
        assert_eq!(effects.stop_reason(), Some(InvocationStop::HostAllocation));
        assert!(effects.cancel_handle().is_cancelled());
        let write = ToolArguments::from_json(r#"{"path":"never.txt","content":"denied"}"#).unwrap();
        assert!(effects.invoke("write", &write).is_err());
        Ok("bounded".into())
    }
}

#[test]
fn nested_count_depth_and_payload_bounds_reject_before_admission() {
    let mut tools = ToolSession::new(std::env::temp_dir());
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(BoundedEffects));
    tools.register(smith::tool::ToolMetadata::new("fixture", "bounded effects"));
    let mut tools = tools.with_completion_boundary(submission, |_| Ok(()));
    assert!(
        tools
            .invoke("fixture", &ToolArguments::empty_object())
            .is_err()
    );
    let intents: Vec<_> = tools
        .session
        .active_branch()
        .entries()
        .iter()
        .filter_map(|entry| match tools.session.content(entry).unwrap() {
            EntryContent::Meta { kind, detail } if kind == NESTED_INTENT_KIND => Some(detail),
            _ => None,
        })
        .collect();
    assert_eq!(intents.len(), usize::from(NESTED_EFFECTS_MAX));
    for (index, intent) in intents.iter().enumerate() {
        assert_eq!(
            crate::metadata::nested_identity(intent.view()).unwrap().2 as usize,
            index
        );
    }
}

struct ComposedWrite;
impl ToolDispatcher for ComposedWrite {
    fn invoke(
        &mut self,
        _: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        effects.with_child("write", "child arguments", None, |child| {
            child.invoke("write", input)
        })?;
        Err(SmithError::Cancelled)
    }
}

#[test]
fn child_write_survives_parent_failure_with_explicit_ancestry() {
    use crate::store::{SessionReader, create_session};
    use smith::config::Config;
    let dir = std::env::temp_dir().join(format!("smith-causal-{}", smith::id::SessionId::new()));
    std::fs::create_dir(&dir).unwrap();
    let path = dir.join("session.smh");
    let config = Config::default_valid();
    let mut opened = create_session(&path, &Session::new(), config.clone()).unwrap();
    let receipt = opened
        .writer
        .admit(&Message::with_text(Role::User, "compose"), None, None)
        .unwrap();
    let session = opened.writer.claim(receipt.submission_id).unwrap();
    let writer = Arc::new(std::sync::Mutex::new(opened.writer));
    let entry_writer = Arc::clone(&writer);
    let mut tools = ToolSession::with_persist(&dir, session, move |entry, content| {
        entry_writer.lock().unwrap().append_entry(entry, content)
    })
    .with_completion_boundary(receipt.submission_id, move |frame| {
        writer.lock().unwrap().append_frame(&frame)
    });
    tools.set_dispatcher(Box::new(ComposedWrite));
    let input = ToolArguments::from_serializable(
        &serde_json::json!({"path":"child.txt","content":"durable"}),
    )
    .unwrap();
    let result = tools.invoke("write", &input);
    assert!(matches!(result, Err(SmithError::Cancelled)), "{result:?}");
    assert_eq!(
        std::fs::read_to_string(dir.join("child.txt")).unwrap(),
        "durable"
    );
    drop(tools);
    let reader = SessionReader::open(&path).unwrap();
    reader.validate_work(config.frame_bytes_max).unwrap();
    let mut nested = Vec::new();
    reader
        .scan(config.frame_bytes_max, |frame| {
            if let Frame::Known { entry } | Frame::NestedCommit { entry } = frame
                && let EntryContent::Meta { kind, detail } = EntryContent::decode(&entry.content)?
                && (kind == crate::metadata::NESTED_INTENT_KIND
                    || kind == crate::metadata::NESTED_COMPLETION_KIND)
            {
                nested.push((
                    entry.id,
                    entry.parent,
                    serde_json::to_value(detail).unwrap(),
                ));
            }
            Ok(())
        })
        .unwrap();
    assert_eq!(nested.len(), 4);
    assert_eq!(
        nested[0].2["causal"]["effect_id"],
        nested[3].2["causal"]["effect_id"]
    );
    assert_eq!(
        nested[1].2["causal"]["parent"],
        nested[0].2["causal"]["effect_id"]
    );
    assert_eq!(nested[2].2["causal"], nested[1].2["causal"]);
    assert_eq!(nested[3].1, Some(nested[2].0));
    assert_ne!(nested[3].1, Some(nested[0].0));
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
#[cfg(target_arch = "x86_64")]
fn causal_stack_records_have_bounded_exact_layout() {
    assert_eq!(std::mem::size_of::<EffectIdentity>(), 52);
    assert_eq!(std::mem::size_of::<ChildInvocation>(), 80);
    assert_eq!(std::mem::size_of::<ToolEffectContext<'_>>(), 48);
}

struct RecursiveChildren;
impl ToolDispatcher for RecursiveChildren {
    fn invoke(
        &mut self,
        _: &str,
        _: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        fn descend(effects: &mut ToolEffectContext<'_>, remaining: u16) -> Result<String> {
            if remaining == 0 {
                assert!(
                    effects
                        .with_child("write", "", None, |_| panic!(
                            "count bound before child entry"
                        ))
                        .is_err()
                );
                return Ok("bounded".into());
            }
            let parent = effects.invocation_id();
            let output = effects.with_child("write", "", None, |child| {
                assert!(child.invocation_id().is_some());
                assert_ne!(child.invocation_id(), parent);
                descend(child, remaining - 1)
            })?;
            assert_eq!(effects.invocation_id(), parent);
            Ok(output)
        }
        descend(effects, NESTED_EFFECTS_MAX)
    }
}

#[test]
fn synchronous_child_stack_reaches_count_bound_then_unwinds() {
    let mut tools = ToolSession::new(std::env::temp_dir());
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(RecursiveChildren));
    tools.register(smith::tool::ToolMetadata::new(
        "fixture",
        "recursive children",
    ));
    let mut tools = tools.with_completion_boundary(submission, |_| Ok(()));
    assert!(
        tools
            .invoke("fixture", &ToolArguments::empty_object())
            .is_err()
    );
}

struct CatchingChildFailure;
impl ToolDispatcher for CatchingChildFailure {
    fn invoke(
        &mut self,
        _: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        let _caught = effects.with_child("write", "", None, |child| {
            CatchingWrites.invoke("write", input, child)
        });
        let _caught_again =
            effects.with_child("write", "", None, |_| panic!("poison forbids child entry"));
        Ok("guest caught child failure".into())
    }
}

#[test]
fn caught_child_recording_failure_is_terminal_with_applied_evidence() {
    let dir = std::env::temp_dir().join(format!(
        "smith-causal-poison-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&dir).unwrap();
    let mut tools = ToolSession::new(&dir);
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(CatchingChildFailure));
    let mut tools = tools.with_completion_boundary(submission, |frame| {
        if matches!(frame, Frame::Known { .. }) {
            return Ok(());
        }
        assert!(matches!(frame, Frame::NestedCommit { .. }));
        Err(SmithError::Cancelled)
    });
    let arguments =
        ToolArguments::from_serializable(&serde_json::json!({"path":"first.txt","content":"once"}))
            .unwrap();
    assert!(matches!(
        tools.invoke("write", &arguments),
        Err(SmithError::RecordFailed {
            mutation_state: MutationState::Applied,
            ..
        })
    ));
    assert_eq!(
        std::fs::read_to_string(dir.join("first.txt")).unwrap(),
        "once"
    );
    assert!(!dir.join("second.txt").exists());
    assert!(tools.cancel_handle().is_cancelled());
    assert!(tools.invoke("write", &arguments).is_err());
    std::fs::remove_dir_all(dir).unwrap();
}

struct CancellingAfterWrite;
impl ToolDispatcher for CancellingAfterWrite {
    fn invoke(
        &mut self,
        _: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        effects.invoke("write", input)?;
        effects.stop(InvocationStop::Cancelled);
        Ok("guest caught cancellation".into())
    }
}

#[test]
fn caught_cancellation_cannot_become_a_model_recoverable_outcome() {
    let dir = std::env::temp_dir().join(format!(
        "smith-caught-cancellation-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&dir).unwrap();
    let mut tools = ToolSession::new(&dir);
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(CancellingAfterWrite));
    let mut tools = tools.with_completion_boundary(submission, |_| Ok(()));
    let input = ToolArguments::from_serializable(
        &serde_json::json!({"path":"completed.txt","content":"retained"}),
    )
    .unwrap();
    let call_id = ToolCallId::new();
    let result = tools.invoke_recorded(
        call_id,
        "write",
        &input,
        &input,
        str::to_string,
        EffectFailure::ReturnOutcome,
    );
    assert!(matches!(result, Err(SmithError::Cancelled)), "{result:?}");
    assert_eq!(
        std::fs::read_to_string(dir.join("completed.txt")).unwrap(),
        "retained"
    );
    let contents: Vec<_> = tools
        .session
        .active_branch()
        .entries()
        .iter()
        .map(|entry| tools.session.content(entry).unwrap())
        .collect();
    assert!(contents.iter().any(|content| matches!(content,
        EntryContent::ToolResult { call_id: recorded, ok: false, .. } if *recorded == call_id
    )));
    assert!(tools.invoke("write", &input).is_err());
    std::fs::remove_dir_all(dir).unwrap();
}

struct StoppingAfterWrite(InvocationStop);
impl ToolDispatcher for StoppingAfterWrite {
    fn invoke(
        &mut self,
        _: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        effects.invoke("write", input)?;
        let result = effects.with_child("fixture:child/run", "{}", None, |child| {
            child.stop(self.0);
            child.stop(InvocationStop::Sandbox);
            assert_eq!(child.stop_reason(), Some(self.0));
            Ok("caught hard stop".into())
        });
        assert!(result.is_err());
        assert!(effects.invoke("write", input).is_err());
        Ok("caught child failure".into())
    }
}

#[test]
fn typed_hard_stop_survives_child_catch_and_model_outcome_conversion() {
    for reason in [
        InvocationStop::Deadline,
        InvocationStop::Fuel,
        InvocationStop::Memory,
        InvocationStop::Table,
        InvocationStop::HostAllocation,
        InvocationStop::Conversion,
        InvocationStop::Log,
        InvocationStop::Output,
        InvocationStop::Sandbox,
    ] {
        let dir =
            std::env::temp_dir().join(format!("smith-hard-stop-{}", smith::id::SessionId::new()));
        std::fs::create_dir(&dir).unwrap();
        let mut tools = ToolSession::new(&dir);
        let submission = root(&mut tools);
        tools.set_dispatcher(Box::new(StoppingAfterWrite(reason)));
        let mut tools = tools.with_completion_boundary(submission, |_| Ok(()));
        let input = ToolArguments::from_serializable(
            &serde_json::json!({"path":"completed.txt","content":"retained"}),
        )
        .unwrap();
        let result = tools.invoke_recorded(
            ToolCallId::new(),
            "write",
            &input,
            &input,
            str::to_string,
            EffectFailure::ReturnOutcome,
        );
        assert!(result.is_err(), "{reason:?}: {result:?}");
        assert!(
            !tools.recording_failed,
            "a hard stop must not fabricate recording uncertainty"
        );
        assert!(tools.cancel_handle().is_cancelled());
        assert_eq!(
            std::fs::read_to_string(dir.join("completed.txt")).unwrap(),
            "retained"
        );
        assert!(tools.invoke("write", &input).is_err());
        std::fs::remove_dir_all(dir).unwrap();
    }
}

struct ScopedWrites;
impl ToolDispatcher for ScopedWrites {
    fn invoke(
        &mut self,
        _: &str,
        _: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        effects.confine_workspace()?;
        effects.with_workspace_subdirectory("A", |effects| {
            let write = |path: &str| {
                ToolArguments::from_serializable(
                    &serde_json::json!({"path":path,"content":"delegated"}),
                )
                .unwrap()
            };
            effects.invoke_redacted("write", &write("allowed.txt"), str::to_string)?;
            let command =
                ToolArguments::from_serializable(&serde_json::json!({"command":"printf never"}))
                    .unwrap();
            assert!(
                effects
                    .invoke_redacted("bash", &command, str::to_string)
                    .is_err()
            );

            assert!(
                effects
                    .invoke_redacted("write", &write("../B/denied.txt"), str::to_string)
                    .is_err()
            );
            assert!(
                effects
                    .with_workspace_subdirectory("../B", |_| Ok("never".into()))
                    .is_err()
            );
            Ok("narrowed".into())
        })?;
        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = effects.with_workspace_subdirectory("A", |_| -> Result<String> {
                panic!("scope unwind");
            });
        }));
        assert!(caught.is_err());
        let parent = ToolArguments::from_serializable(
            &serde_json::json!({"path":"parent.txt","content":"restored"}),
        )
        .unwrap();
        effects.invoke_redacted("write", &parent, str::to_string)
    }
}

#[test]
fn descriptor_scopes_reject_escape_and_restore_parent_after_unwind() {
    let dir = std::env::temp_dir().join(format!(
        "smith-workspace-scopes-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir_all(dir.join("A")).unwrap();
    std::fs::create_dir_all(dir.join("B")).unwrap();
    let mut tools = ToolSession::new(&dir);
    let submission = root(&mut tools);
    tools.register(smith::tool::ToolMetadata::new("fixture", "scoped writes"));
    tools.set_dispatcher(Box::new(ScopedWrites));
    let mut tools = tools.with_completion_boundary(submission, |_| Ok(()));
    assert!(
        tools
            .invoke("fixture", &ToolArguments::empty_object())
            .unwrap()
            .ok
    );
    assert_eq!(
        std::fs::read_to_string(dir.join("A/allowed.txt")).unwrap(),
        "delegated"
    );
    assert!(!dir.join("B/denied.txt").exists());
    assert_eq!(
        std::fs::read_to_string(dir.join("parent.txt")).unwrap(),
        "restored"
    );
    assert!(!dir.join("A/parent.txt").exists());
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn invocation_allocation_report_is_a_fixed_resident_snapshot() {
    assert_eq!(std::mem::size_of::<InvocationAllocationReport>(), 56);
}

struct AcknowledgedAllocation(Arc<AtomicUsize>);
impl InvocationAllocationObserver for AcknowledgedAllocation {
    fn report(&self) -> Result<InvocationAllocationReport> {
        let actual_bytes = self.0.load(Ordering::SeqCst) as u64;
        if actual_bytes == u64::MAX {
            return Err(SmithError::Cancelled);
        }
        Ok(InvocationAllocationReport {
            threshold_bytes: 100,
            actual_bytes,
            cleanup_bytes: 0,
            excess_bytes: actual_bytes.saturating_sub(100),
            allocations: 3,
            stopped_bytes: None,
        })
    }
}
impl ToolDispatcher for AcknowledgedAllocation {
    fn invoke(
        &mut self,
        _: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        assert!(
            effects
                .hold_allocation_observer(Box::new(Self(Arc::clone(&self.0))))
                .is_none()
        );
        effects.report_allocation(100, 50, 1);
        effects.invoke("write", input)
    }
}

#[test]
fn terminal_recording_crossing_preserves_completed_effect_then_persists_causal_stop() {
    let dir = std::env::temp_dir().join(format!("smith-late-stop-{}", smith::id::SessionId::new()));
    std::fs::create_dir(&dir).unwrap();
    let usage = Arc::new(AtomicUsize::new(50));
    let persisted = Arc::new(std::sync::Mutex::new(Vec::new()));
    let seen = Arc::clone(&persisted);
    let mut tools = ToolSession::with_persist(&dir, Session::new(), move |entry, bytes| {
        seen.lock()
            .unwrap()
            .push((entry.id, EntryContent::decode(bytes)?));
        Ok(())
    });
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(AcknowledgedAllocation(Arc::clone(&usage))));
    let acknowledged = Arc::clone(&usage);
    let mut tools = tools.with_completion_boundary(submission, move |frame| {
        if matches!(frame, Frame::Commit { .. }) {
            acknowledged.store(125, Ordering::SeqCst);
        }
        Ok(())
    });
    let input = ToolArguments::from_serializable(
        &serde_json::json!({"path":"done.txt","content":"retained"}),
    )
    .unwrap();
    let call_id = ToolCallId::new();
    let error = tools
        .invoke_recorded(
            call_id,
            "write",
            &input,
            &input,
            str::to_string,
            EffectFailure::ReturnOutcome,
        )
        .unwrap_err();
    assert!(error.to_string().contains("HostAllocation"));
    assert!(tools.cancel_handle().is_cancelled());
    let entries = tools.session.active_branch().entries();
    assert!(entries.iter().any(|entry| matches!(tools.session.content(entry).unwrap(), EntryContent::ToolResult { call_id: id, ok: true, .. } if id == call_id)));
    let recorded = persisted.lock().unwrap();
    let (_, EntryContent::Meta { kind, detail }) = recorded.last().unwrap() else {
        panic!("missing durable stop")
    };
    assert_eq!(kind, "invocation-terminal-stop");
    let detail = serde_json::to_value(detail).unwrap();
    assert_eq!(detail["call_id"], call_id.to_string());
    assert_eq!(detail["submission_id"], submission.to_string());
    assert_eq!(detail["reason"], "HostAllocation");
    assert_eq!(detail["allocation"]["actual_bytes"], 125);
    assert_eq!(detail["allocation"]["cleanup_bytes"], 75);
    drop(recorded);
    let count = tools.session.active_branch().entries().len();
    assert!(tools.invoke("write", &input).is_err());
    assert_eq!(tools.session.active_branch().entries().len(), count);
    assert_eq!(
        std::fs::read_to_string(dir.join("done.txt")).unwrap(),
        "retained"
    );
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn recording_failure_remains_primary_when_allocation_observation_also_fails() {
    let dir = std::env::temp_dir().join(format!(
        "smith-poison-observer-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&dir).unwrap();
    let usage = Arc::new(AtomicUsize::new(50));
    let mut tools = ToolSession::new(&dir);
    let submission = root(&mut tools);
    tools.set_dispatcher(Box::new(AcknowledgedAllocation(Arc::clone(&usage))));
    let mut tools = tools.with_completion_boundary(submission, move |_| {
        usage.store(usize::MAX, Ordering::SeqCst);
        Err(tool_error(
            smith::error::ToolCode::Validation,
            "injected storage primary",
        ))
    });
    let input = ToolArguments::from_serializable(
        &serde_json::json!({"path":"done.txt","content":"retained"}),
    )
    .unwrap();
    let error = tools.invoke("write", &input).unwrap_err();
    assert!(
        matches!(error, SmithError::RecordFailed { .. }),
        "{error:?}"
    );
    assert!(
        error.to_string().contains("injected storage primary"),
        "{error}"
    );
    assert!(error.to_string().contains("allocation="));
    assert!(tools.cancel_handle().is_cancelled());
    std::fs::remove_dir_all(dir).unwrap();
}