merry-runtime 0.1.4

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
use crate::{
    memory::{
        ActivatedMemory, MemoryActivationContext, MemoryActivationFuture, MemoryActivationReason,
        MemoryActivationScore, MemoryActivationSource, MemoryActivationSourceKind, MemoryError,
        MemoryEvidence, MemoryId, MemoryItem, MemoryItemSelection, MemoryScope,
    },
    runtime::{
        Runtime,
        tests::support::{
            common::RuntimeSessionStateTestExt,
            model_provider::{NotifyOnDrop, RecordingModelProvider},
            runtime_factories::runtime_with_provider_and_memory_source,
        },
    },
};
use merry_core::{
    PendingToolCall, ToolCallArguments, ToolCallId, ToolCallResultStatus, ToolName, ToolOutput,
};
use std::sync::{
    Arc, Mutex as StdMutex,
    atomic::{AtomicUsize, Ordering},
};
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;

pub(in crate::runtime::tests) fn activated_memory(
    id: &str,
    text: &str,
    evidence_artifact: &str,
) -> ActivatedMemory {
    let item = memory_item(id, text, evidence_artifact, &["topic"]);
    let score = MemoryActivationScore::new(1, 1, 0.8).expect("valid memory score");
    ActivatedMemory::new(
        item,
        score,
        vec![
            MemoryActivationReason::ScopeAllowed,
            MemoryActivationReason::trigger_matched("topic").expect("valid trigger"),
            MemoryActivationReason::ranked(score),
        ],
        crate::memory::MemoryActivationProvenance::new(
            "topic",
            vec![MemoryScope::Session, MemoryScope::Task, MemoryScope::Step],
            MemoryActivationSourceKind::UserQuery,
            "test source",
        )
        .expect("valid provenance"),
    )
    .expect("valid activated memory")
}

pub(in crate::runtime::tests) fn memory_item(
    id: &str,
    text: &str,
    evidence_source: &str,
    triggers: &[&str],
) -> MemoryItem {
    MemoryItem::new(
        MemoryId::new(id).expect("valid memory id"),
        MemoryScope::Session,
        text,
        vec![
            MemoryEvidence::new("primary source", evidence_source).expect("valid memory evidence"),
        ],
        MemoryItemSelection::new(
            triggers
                .iter()
                .map(|trigger| (*trigger).to_owned())
                .collect(),
            0.8,
            1,
            None,
        )
        .expect("valid memory selection"),
    )
    .expect("valid memory item")
}

pub(in crate::runtime::tests) fn record_prior_failed_tool_result(runtime: &Runtime, content: &str) {
    let mut session = runtime
        .inner
        .session
        .try_lock()
        .expect("session lock is free");
    let call = PendingToolCall::new(
        ToolCallId::new("call-prior-process").expect("valid tool call id"),
        ToolName::new("process_command").expect("valid tool name"),
        ToolCallArguments::try_from(serde_json::json!({
            "command": "cargo test",
            "cwd": "."
        }))
        .expect("valid arguments"),
    );
    session
        .record_test_tool_call_pending(call.clone())
        .expect("prior pending call records");
    session
        .submit_tool_execution_outcome(
            call.id(),
            ToolCallResultStatus::Failed,
            ToolOutput::json(content.to_owned()),
            Some(
                merry_core::ErrorInfo::new("process_action_failed", "process action failed")
                    .expect("valid diagnostic"),
            ),
            None,
        )
        .expect("prior failed tool result records");
}

pub(in crate::runtime::tests) fn record_memory_item(runtime: &Runtime, item: MemoryItem) {
    let mut session = runtime
        .inner
        .session
        .try_lock()
        .expect("session lock is free");
    session
        .record_memory_item(item)
        .expect("memory item records");
}

pub(in crate::runtime::tests) fn runtime_with_provider_and_single_memory(
    session: &str,
    provider: RecordingModelProvider,
    memory_id: &str,
    memory_text: &str,
    memory_source: &str,
) -> (Runtime, ScriptedMemoryActivationSource) {
    let memory = activated_memory(memory_id, memory_text, memory_source);
    let source = ScriptedMemoryActivationSource::new(vec![vec![memory.clone()]]);
    let runtime = runtime_with_provider_and_memory_source(session, provider, source.clone());
    record_memory_item(&runtime, memory.item().clone());
    (runtime, source)
}

pub(in crate::runtime::tests) async fn compiled_context_snapshot(runtime: &Runtime) -> String {
    crate::ContextCompiler::new()
        .compile(&runtime.context_snapshot().await)
        .expect("context compiles")
        .to_snapshot()
}

pub(in crate::runtime::tests) async fn assert_activated_memory_projection_cleared(
    runtime: &Runtime,
) {
    assert_eq!(compiled_context_snapshot(runtime).await, "");
}

pub(in crate::runtime::tests) async fn assert_activated_memory_projection_retained(
    runtime: &Runtime,
    memory_id: &str,
    memory_text: &str,
) {
    let snapshot = compiled_context_snapshot(runtime).await;
    assert!(
        snapshot.contains(&format!("memory:{memory_id}")),
        "compiled context should retain memory id {memory_id}; snapshot:\n{snapshot}"
    );
    assert!(
        snapshot.contains(&format!("memory-text:{memory_text}")),
        "compiled context should retain memory text for {memory_id}; snapshot:\n{snapshot}"
    );
}

#[derive(Debug)]
pub(in crate::runtime::tests) enum ScriptedMemoryActivationResponse {
    Memories(Vec<ActivatedMemory>),
    Error(MemoryError),
    CancelThenMemories {
        token: CancellationToken,
        memories: Vec<ActivatedMemory>,
    },
    PendingUntilDropped {
        started: oneshot::Sender<()>,
        dropped: oneshot::Sender<()>,
    },
}

impl ScriptedMemoryActivationResponse {
    pub(in crate::runtime::tests) async fn into_result(
        self,
    ) -> Result<Vec<ActivatedMemory>, MemoryError> {
        match self {
            Self::Memories(memories) => Ok(memories),
            Self::Error(error) => Err(error),
            Self::CancelThenMemories { token, memories } => {
                token.cancel();
                Ok(memories)
            }
            Self::PendingUntilDropped { started, dropped } => {
                let _notify_on_drop = NotifyOnDrop::new(dropped);
                let _ = started.send(());
                std::future::pending::<Result<Vec<ActivatedMemory>, MemoryError>>().await
            }
        }
    }
}

#[derive(Debug, Clone)]
pub(in crate::runtime::tests) struct ScriptedMemoryActivationSource {
    pub(in crate::runtime::tests) responses: Arc<StdMutex<Vec<ScriptedMemoryActivationResponse>>>,
    pub(in crate::runtime::tests) calls: Arc<AtomicUsize>,
    pub(in crate::runtime::tests) observed_queries: Arc<StdMutex<Vec<String>>>,
}

impl ScriptedMemoryActivationSource {
    pub(in crate::runtime::tests) fn new(responses: Vec<Vec<ActivatedMemory>>) -> Self {
        Self::with_script(
            responses
                .into_iter()
                .map(ScriptedMemoryActivationResponse::Memories)
                .collect(),
        )
    }

    pub(in crate::runtime::tests) fn with_script(
        responses: Vec<ScriptedMemoryActivationResponse>,
    ) -> Self {
        Self {
            responses: Arc::new(StdMutex::new(responses.into_iter().rev().collect())),
            calls: Arc::new(AtomicUsize::new(0)),
            observed_queries: Arc::new(StdMutex::new(Vec::new())),
        }
    }

    pub(in crate::runtime::tests) fn call_count(&self) -> usize {
        self.calls.load(Ordering::SeqCst)
    }
}

impl MemoryActivationSource for ScriptedMemoryActivationSource {
    fn activate<'a>(
        &'a self,
        seed: crate::memory::MemoryActivationSeed,
        _candidates: Vec<MemoryItem>,
        context: MemoryActivationContext,
    ) -> MemoryActivationFuture<'a> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        self.observed_queries
            .lock()
            .expect("observed query mutex should not be poisoned")
            .push(seed.query().to_owned());
        let response = self
            .responses
            .lock()
            .expect("memory response mutex should not be poisoned")
            .pop();
        Box::pin(async move {
            if context.cancellation_token().is_cancelled() {
                return Ok(Vec::new());
            }

            match response {
                Some(response) => response.into_result().await,
                None => Ok(Vec::new()),
            }
        })
    }
}

pub(in crate::runtime::tests) fn pending_memory_activation_source() -> (
    ScriptedMemoryActivationSource,
    oneshot::Receiver<()>,
    oneshot::Receiver<()>,
) {
    let (started_tx, started_rx) = oneshot::channel();
    let (dropped_tx, dropped_rx) = oneshot::channel();
    let source = ScriptedMemoryActivationSource::with_script(vec![
        ScriptedMemoryActivationResponse::PendingUntilDropped {
            started: started_tx,
            dropped: dropped_tx,
        },
    ]);

    (source, started_rx, dropped_rx)
}