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