Skip to main content

causa_kernel/context/material/
tool_results.rs

1//! Execution-specific tool-result append validation.
2
3use crate::context::block::{BlockContent, ContextBlock};
4use crate::context::ids::BlockId;
5use crate::context::tool_data::ToolResultPayload;
6use std::collections::HashSet;
7
8/// Why tool results cannot be appended to the supplied material scope.
9#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
10pub enum ToolResultError {
11    /// The reference does not identify a tool declaration in this scope.
12    #[error("missing tool declaration {call_block_id:?}")]
13    MissingDeclaration {
14        /// The declaration referenced by the rejected result.
15        call_block_id: BlockId,
16    },
17    /// This declaration already has a result in the supplied material.
18    #[error("tool declaration already completed: {call_block_id:?}")]
19    AlreadyCompleted {
20        /// The declaration referenced by the rejected result.
21        call_block_id: BlockId,
22    },
23    /// This append would complete the same declaration more than once.
24    #[error("duplicate tool result for declaration {call_block_id:?}")]
25    DuplicateResult {
26        /// The declaration referenced by the rejected result.
27        call_block_id: BlockId,
28    },
29}
30
31/// Validates this result append without mutating or consuming its inputs.
32///
33/// Checks references in input order. Other local tool material need not form
34/// complete exchanges. Result block identity remains the responsibility of
35/// [`super::Context::apply`].
36pub fn validate_tool_result_append(
37    context_blocks: &[ContextBlock],
38    results: &[(BlockId, ToolResultPayload)],
39) -> Result<(), ToolResultError> {
40    let declarations = context_blocks
41        .iter()
42        .filter_map(|block| {
43            matches!(block.content(), BlockContent::ToolCall(_)).then_some(block.id())
44        })
45        .collect::<HashSet<_>>();
46    let completed = context_blocks
47        .iter()
48        .filter_map(|block| match block.content() {
49            BlockContent::ToolResult(result) => Some(result.call_block_id),
50            _ => None,
51        })
52        .collect::<HashSet<_>>();
53    let mut batch = HashSet::with_capacity(results.len());
54    for (_, result) in results {
55        let call_block_id = result.call_block_id;
56        if !declarations.contains(&call_block_id) {
57            return Err(ToolResultError::MissingDeclaration { call_block_id });
58        }
59        if completed.contains(&call_block_id) {
60            return Err(ToolResultError::AlreadyCompleted { call_block_id });
61        }
62        if !batch.insert(call_block_id) {
63            return Err(ToolResultError::DuplicateResult { call_block_id });
64        }
65    }
66    Ok(())
67}