Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-core/src/tools/lifecycle.rs

Raw
//! Durable lifecycle roots without model tool attribution (SMH-SPEC-PLUG0001).
use super::{
    EffectIdentity, Entry, EntryContentRef, InvocationCause, MutationState, Persistence, Result,
    SmithError, StructuredData, ToolComponentProvenance, ToolEffectContext, aggregate_mutation,
    tool_error,
};
use crate::metadata::lifecycle as evidence;

impl ToolEffectContext<'_> {
    /// Mask a bounded leaf value without altering its enclosing canonical schema.
    ///
    /// # Errors
    /// Rejects input or expanded redaction beyond inline evidence limits.
    pub fn redact_lifecycle_bytes(&self, mut bytes: &[u8]) -> Result<Vec<u8>> {
        if bytes.len() > evidence::BYTES_MAX {
            return Err(tool_error(
                smith::error::ToolCode::Validation,
                "lifecycle redaction input exceeds bound",
            ));
        }
        let scope = self.scope.as_ref().ok_or_else(|| {
            tool_error(
                smith::error::ToolCode::Validation,
                "redaction requires scope",
            )
        })?;
        let mut output = Vec::new();
        while !bytes.is_empty() {
            match std::str::from_utf8(bytes) {
                Ok(text) => {
                    output.extend_from_slice((scope.redact)(text).as_bytes());
                    break;
                }
                Err(error) => {
                    let valid = &bytes[..error.valid_up_to()];
                    let text = std::str::from_utf8(valid).map_err(|_| {
                        tool_error(smith::error::ToolCode::Validation, "invalid UTF-8 prefix")
                    })?;
                    output.extend_from_slice((scope.redact)(text).as_bytes());
                    let remaining = &bytes[error.valid_up_to()..];
                    let invalid = error.error_len().unwrap_or(remaining.len());
                    output.extend_from_slice(&remaining[..invalid]);
                    bytes = &remaining[invalid..];
                }
            }
            if output.len() > evidence::BYTES_MAX {
                break;
            }
        }
        if output.len() > evidence::BYTES_MAX {
            return Err(tool_error(
                smith::error::ToolCode::Validation,
                "lifecycle redaction output exceeds bound",
            ));
        }
        Ok(output)
    }

    /// Durable origin, when the host attached a scoped invocation.
    #[must_use]
    pub fn cause(&self) -> Option<InvocationCause> {
        self.scope.as_ref().and_then(|scope| scope.cause)
    }

    /// Whether model-only primitives must reject this context.
    #[must_use]
    pub fn is_lifecycle(&self) -> bool {
        self.scope
            .as_ref()
            .is_some_and(|scope| scope.lifecycle_root.is_some())
    }

    fn lifecycle_identity(&self) -> Result<(smith::id::EntryId, smith::id::EntryId)> {
        let scope = self.scope.as_ref().ok_or_else(|| {
            tool_error(
                smith::error::ToolCode::Validation,
                "lifecycle requires attached scope",
            )
        })?;
        match (scope.lifecycle_root, scope.cause) {
            (Some(root), Some(InvocationCause::Lifecycle(invocation))) => Ok((root, invocation)),
            _ => Err(tool_error(
                smith::error::ToolCode::Validation,
                "lifecycle requires typed cause",
            )),
        }
    }

    fn record_lifecycle(
        &mut self,
        id: smith::id::EntryId,
        kind: &str,
        detail: &StructuredData,
    ) -> Result<()> {
        self.session.ensure_recording()?;
        let mut entry = crate::session::EntryFrame::from_content(
            self.session.session.selected_id().as_ref(),
            &EntryContentRef::Meta { kind, detail },
        )?;
        entry.id = id;
        let result = if let Some(boundary) = self.session.completion.as_mut() {
            self.session
                .session
                .append_effect_with(entry, false, &mut boundary.persist)
        } else {
            match &mut self.session.persistence {
                Persistence::Direct(writer) => {
                    self.session
                        .session
                        .append_effect_with(entry, false, |frame| writer.append_frame(&frame))
                }
                Persistence::Worker(persist) => {
                    self.session
                        .session
                        .append_effect_with(entry, false, |frame| {
                            let crate::frame::Frame::Known { entry } = frame else {
                                return Err(tool_error(
                                    smith::error::ToolCode::Validation,
                                    "lifecycle requires metadata frame",
                                ));
                            };
                            let record = Entry {
                                id: entry.id,
                                parent: entry.parent,
                                timestamp_ms: entry.timestamp_ms,
                                kind: entry.kind,
                                content: crate::session::Span { offset: 0, len: 0 },
                            };
                            persist(&record, &entry.content)
                        })
                }
                Persistence::None => Err(tool_error(
                    smith::error::ToolCode::Validation,
                    "lifecycle effects require durable writer authority",
                )),
            }
        };
        if let Err(error) = result {
            self.session.recording_failed = true;
            self.session.cancel.cancel();
            return Err(SmithError::RecordFailed {
                tool: "lifecycle".into(),
                mutation_state: self.mutation_state,
                message: error.to_string(),
            });
        }
        Ok(())
    }

    /// Acknowledge handler intent before entering its component generation.
    ///
    /// # Errors
    /// Rejects overlapping handlers, wrong roots, or uncertain persistence.
    pub fn begin_lifecycle_invocation(
        &mut self,
        event: &smith::lifecycle::LifecycleEvent,
        handler: &str,
        component: ToolComponentProvenance,
    ) -> Result<()> {
        let root = self
            .scope
            .as_ref()
            .and_then(|scope| scope.lifecycle_root)
            .ok_or_else(|| {
                tool_error(
                    smith::error::ToolCode::Validation,
                    "lifecycle requires durable root",
                )
            })?;
        if root != event.root_entry_id
            || self.active
            || self
                .scope
                .as_ref()
                .is_some_and(|scope| scope.component.is_some())
        {
            return Err(tool_error(
                smith::error::ToolCode::Validation,
                "invalid lifecycle handler ownership",
            ));
        }
        let id = smith::id::EntryId::new();
        let detail = crate::metadata::encode(&evidence::InvocationIntent {
            root_entry_id: root,
            invocation_id: id,
            boundary: event.boundary,
            round_index: event.round_index,
            handler,
            component: &component,
        })?;
        self.record_lifecycle(id, evidence::INVOCATION_INTENT, &detail)?;
        if let Some(scope) = &mut self.scope {
            scope.cause = Some(InvocationCause::Lifecycle(id));
            scope.component = Some(component);
            scope.stop = None;
        }
        self.next_index = 0;
        Ok(())
    }

    /// Acknowledge the nonmutating handler outcome before publishing actions.
    ///
    /// # Errors
    /// Open primitives remain unknown; recording failure poisons the root.
    pub fn finish_lifecycle_invocation(&mut self, ok: bool, output: &str) -> Result<()> {
        let result = self.finish_lifecycle_invocation_record(ok, output);
        if let Err(error) = result {
            self.session.recording_failed = true;
            self.session.cancel.cancel();
            return Err(SmithError::RecordFailed {
                tool: "lifecycle".into(),
                mutation_state: self.mutation_state,
                message: error.to_string(),
            });
        }
        Ok(())
    }

    fn finish_lifecycle_invocation_record(&mut self, ok: bool, output: &str) -> Result<()> {
        self.session.ensure_recording()?;
        if self.active {
            self.session.recording_failed = true;
            self.session.cancel.cancel();
            return Err(SmithError::RecordFailed {
                tool: "lifecycle".into(),
                mutation_state: MutationState::Unknown,
                message: "unresolved lifecycle effect".into(),
            });
        }
        let (root, invocation) = self.lifecycle_identity()?;
        let scope = self.scope.as_ref().ok_or_else(|| {
            tool_error(
                smith::error::ToolCode::Validation,
                "lifecycle requires scope",
            )
        })?;
        let output = (scope.redact)(output);
        let detail = crate::metadata::encode(&evidence::InvocationCompletion {
            root_entry_id: root,
            invocation_id: invocation,
            ok,
            output: &output,
        })?;
        self.record_lifecycle(
            smith::id::EntryId::new(),
            evidence::INVOCATION_COMPLETION,
            &detail,
        )?;
        if let Some(scope) = &mut self.scope {
            scope.component = None;
            scope.cause = None;
        }
        Ok(())
    }

    pub(super) fn begin_lifecycle_effect(
        &mut self,
        operation: &str,
        input: &str,
        redact: bool,
    ) -> Result<()> {
        self.session.ensure_recording()?;
        let (root, invocation) = self.lifecycle_identity()?;
        let scope = self.scope.as_ref().ok_or_else(|| {
            tool_error(
                smith::error::ToolCode::Validation,
                "lifecycle requires scope",
            )
        })?;
        if self.active
            || scope.component.is_none()
            || scope.stop.is_some()
            || self.next_index >= crate::metadata::NESTED_EFFECTS_MAX
            || input.len() > evidence::BYTES_MAX
            || operation != "http"
        {
            return Err(tool_error(
                smith::error::ToolCode::Validation,
                "lifecycle primitive unavailable or exceeds inline bounds",
            ));
        }
        if self.cancel_handle().is_cancelled() {
            return Err(SmithError::Cancelled);
        }
        let input = if redact {
            (scope.redact)(input)
        } else {
            input.to_owned()
        };
        let id = smith::id::EntryId::new();
        let detail = crate::metadata::encode(&evidence::EffectIntent {
            root_entry_id: root,
            invocation_id: invocation,
            effect_id: id,
            ordinal: self.next_index,
            operation,
            input: &input,
        })?;
        self.record_lifecycle(id, evidence::EFFECT_INTENT, &detail)?;
        if let Some(scope) = &mut self.scope {
            scope.pending = Some(EffectIdentity {
                id,
                index: self.next_index,
                causal: None,
            });
        }
        self.active = true;
        self.next_index += 1;
        Ok(())
    }

    pub(super) fn finish_lifecycle_effect(
        &mut self,
        ok: bool,
        mutation: MutationState,
        output: &str,
        redact: bool,
    ) -> Result<()> {
        self.mutation_state = aggregate_mutation(self.mutation_state, mutation);
        let result = (|| {
            self.session.ensure_recording()?;
            let (root, invocation) = self.lifecycle_identity()?;
            let scope = self.scope.as_ref().ok_or_else(|| {
                tool_error(
                    smith::error::ToolCode::Validation,
                    "lifecycle requires scope",
                )
            })?;
            let pending = scope.pending.filter(|_| self.active).ok_or_else(|| {
                tool_error(
                    smith::error::ToolCode::Validation,
                    "lifecycle completion requires pending effect",
                )
            })?;
            let output = if redact {
                (scope.redact)(output)
            } else {
                output.to_owned()
            };
            let detail = crate::metadata::encode(&evidence::EffectCompletion {
                root_entry_id: root,
                invocation_id: invocation,
                effect_id: pending.id,
                ordinal: pending.index,
                ok,
                mutation_state: mutation,
                output: &output,
            })?;
            self.record_lifecycle(
                smith::id::EntryId::new(),
                evidence::EFFECT_COMPLETION,
                &detail,
            )
        })();
        if let Err(error) = result {
            self.session.recording_failed = true;
            self.session.cancel.cancel();
            return Err(SmithError::RecordFailed {
                tool: "lifecycle".into(),
                mutation_state: mutation,
                message: error.to_string(),
            });
        }
        if let Some(scope) = &mut self.scope {
            scope.pending = None;
        }
        self.active = false;
        Ok(())
    }
}

// SMH-SPEC-PLUG0001: acknowledgement failures cannot become handler success.
#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::{ToolArguments, ToolDispatcher, ToolSession};
    use smith::lifecycle::{Boundary, LifecycleBatch, LifecycleEvent};
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };
    struct Handler {
        calls: Arc<AtomicUsize>,
        returns: Arc<AtomicUsize>,
    }
    fn component() -> ToolComponentProvenance {
        ToolComponentProvenance {
            source_id: "example:lifecycle".into(),
            manifest_sha256: "0".repeat(64),
            component_sha256: "1".repeat(64),
        }
    }
    impl ToolDispatcher for Handler {
        fn has_lifecycle_handlers(&self, _: smith::lifecycle::Boundary) -> bool {
            true
        }

        fn invoke(
            &mut self,
            _: &str,
            _: &ToolArguments,
            _: &mut ToolEffectContext<'_>,
        ) -> Result<String> {
            unreachable!()
        }
        fn lifecycle_effects(
            &mut self,
            event: &LifecycleEvent,
            effects: &mut ToolEffectContext<'_>,
        ) -> Result<LifecycleBatch> {
            effects.begin_lifecycle_invocation(event, "fixture", component())?;
            assert!(matches!(
                effects.cause(),
                Some(InvocationCause::Lifecycle(_))
            ));
            assert!(effects.call_id().is_none());
            effects.begin_nested("http", "private-input")?;
            self.calls.fetch_add(1, Ordering::Relaxed);
            // A malicious guest catches the primitive completion failure.
            let _caught = effects.finish_nested(true, MutationState::Applied, "private-output");
            effects.finish_lifecycle_invocation(true, "[]")?;
            self.returns.fetch_add(1, Ordering::Relaxed);
            Ok(LifecycleBatch::default())
        }
    }
    #[test]
    fn failed_intent_and_completion_acknowledgements_poison_lifecycle_without_fabricated_tool_messages()
     {
        for failure in [
            evidence::INVOCATION_INTENT,
            evidence::EFFECT_INTENT,
            evidence::EFFECT_COMPLETION,
            evidence::INVOCATION_COMPLETION,
        ] {
            let calls = Arc::new(AtomicUsize::new(0));
            let returns = Arc::new(AtomicUsize::new(0));
            let mut tools = ToolSession::new(std::env::temp_dir());
            let root = tools
                .session
                .append(EntryContentRef::Message(
                    &smith::message::Message::with_text(smith::message::Role::User, "root"),
                ))
                .unwrap()
                .id;
            tools.set_dispatcher(Box::new(Handler {
                calls: calls.clone(),
                returns: returns.clone(),
            }));
            let mut tools = tools.with_completion_boundary(root, move |frame| {
                let crate::frame::Frame::Known { entry } = frame else {
                    panic!("lifecycle uses one typed metadata frame");
                };
                if let crate::session::EntryContent::Meta { kind, .. } =
                    crate::session::EntryContent::decode(&entry.content).unwrap()
                    && kind == failure
                {
                    return Err(tool_error(
                        smith::error::ToolCode::Validation,
                        "injected acknowledgement failure",
                    ));
                }
                Ok(())
            });
            let event = LifecycleEvent {
                root_entry_id: root,
                boundary: Boundary::PreSettlement,
                round_index: 0,
                last_stop: smith::StopReason::EndTurn,
                continuation_eligible: true,
            };
            assert!(
                tools
                    .lifecycle(&event, &|text| text.replace("private", "<redacted>"))
                    .is_err()
            );
            assert_eq!(
                calls.load(Ordering::Relaxed),
                usize::from(matches!(
                    failure,
                    evidence::EFFECT_COMPLETION | evidence::INVOCATION_COMPLETION
                ))
            );
            assert_eq!(returns.load(Ordering::Relaxed), 0);
            assert!(tools.lifecycle(&event, &str::to_string).is_err());
            assert!(tools.cancel.is_cancelled());
            for entry in tools.session.active_branch().entries() {
                assert!(!matches!(
                    entry.kind,
                    crate::session::EntryKind::ToolCall { .. }
                        | crate::session::EntryKind::ToolResult { .. }
                ));
                let content = tools.session.content(entry).unwrap();
                assert!(!format!("{content:?}").contains("private"));
            }
        }
    }
    #[test]
    fn invocation_cause_layout_is_bounded() {
        assert_eq!(std::mem::size_of::<InvocationCause>(), 17);
    }
}