merry-runtime 0.1.3

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
use crate::{
    RuntimeError,
    process::stable_process_input_fingerprint,
    runtime::tests::support::{
        common::capture_traces_for,
        process::{FakeProcessRunner, ProcessProposingToolExecutor},
        tool_helpers::{
            event_kind_names_for_tool_execution, policy_tool_spec,
            register_policy_pending_registered_tool_with_builder, resolved_artifact_json,
            resolved_tool_result,
        },
    },
    tool::{RegisteredTool, ToolActionKind, ToolExecutionContext},
};
use serde_json::json;
use std::sync::Arc;

#[tokio::test(flavor = "current_thread")]
async fn read_only_shell_process_requires_explicit_shell_runner_opt_in() {
    let executor =
        ProcessProposingToolExecutor::with_argv(["bash", "-lc", "rg ProcessRunner | wc -l"]);
    let runner = FakeProcessRunner::succeeding();
    let tool = RegisteredTool::new(
        policy_tool_spec("policy_command_shell_read_only_without_shell_opt_in"),
        Arc::new(executor.clone()),
        ToolActionKind::CommandExec,
    )
    .with_action_proposal();
    let (runtime, pending) = register_policy_pending_registered_tool_with_builder(
        "runtime-policy-command-exec-shell-read-only-without-shell-opt-in",
        "policy_command_shell_read_only_without_shell_opt_in",
        "call-command-exec-shell-read-only-without-shell-opt-in",
        tool,
        |builder| {
            builder
                .allow_low_risk_process_actions(Arc::new(runner.clone()))
                .build()
        },
    )
    .await;

    let events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("shell process proposal should be denied without shell opt-in");

    assert_eq!(executor.propose_count(), 1);
    assert_eq!(executor.execute_count(), 0);
    assert_eq!(runner.call_count(), 0);
    assert_eq!(
        event_kind_names_for_tool_execution(&events),
        ["ToolCallResolved"]
    );
    assert_eq!(
        resolved_tool_result(&events).status(),
        merry_core::ToolCallResultStatus::Failed
    );
}

#[tokio::test(flavor = "current_thread")]
async fn read_only_shell_process_executes_under_shell_profile_when_opted_in() {
    let executor =
        ProcessProposingToolExecutor::with_argv(["bash", "-lc", "rg ProcessRunner | wc -l"]);
    let runner = FakeProcessRunner::succeeding();
    let tool = RegisteredTool::new(
        policy_tool_spec("policy_command_shell_read_only_opt_in"),
        Arc::new(executor.clone()),
        ToolActionKind::CommandExec,
    )
    .with_action_proposal();
    let (runtime, pending) = register_policy_pending_registered_tool_with_builder(
        "runtime-policy-command-exec-shell-read-only-opt-in",
        "policy_command_shell_read_only_opt_in",
        "call-command-exec-shell-read-only-opt-in",
        tool,
        |builder| {
            builder
                .allow_read_only_shell_process_actions(Arc::new(runner.clone()))
                .build()
        },
    )
    .await;

    let events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("opted-in read-only shell process action should execute through shell runner");

    assert_eq!(executor.propose_count(), 1);
    assert_eq!(executor.execute_count(), 0);
    assert_eq!(runner.call_count(), 1);
    assert_eq!(
        event_kind_names_for_tool_execution(&events),
        ["ToolCallResolved"]
    );
    let result = resolved_tool_result(&events);
    assert_eq!(result.status(), merry_core::ToolCallResultStatus::Succeeded);

    let payload = resolved_artifact_json(&runtime, result, "shell process result").await;
    assert_eq!(payload["permission_profile_id"], "process.shell.read_only");
    assert!(payload["intent"].get("argv").is_none());
    assert_eq!(payload["intent"]["command"], "rg ProcessRunner | wc -l");
    assert_eq!(
        payload["input_evidence"],
        json!({
            "kind": "shell_command_script",
            "shell": "bash",
            "flag": "-lc",
            "script": "rg ProcessRunner | wc -l",
            "script_bytes": "rg ProcessRunner | wc -l".len(),
            "script_fingerprint": stable_process_input_fingerprint(
                "rg ProcessRunner | wc -l".as_bytes()
            ),
        })
    );
    assert!(payload.get("input_artifact").is_none());
    assert!(payload.get("provider").is_none());
    assert!(payload.get("wire").is_none());
    assert_eq!(runner.observed_intents().len(), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn read_only_shell_process_traces_payload_free_input_metadata_when_opted_in() {
    let script = "rg ProcessRunner | wc -l";
    let executor = ProcessProposingToolExecutor::with_argv(["bash", "-lc", script]);
    let runner = FakeProcessRunner::succeeding();
    let tool = RegisteredTool::new(
        policy_tool_spec("policy_command_shell_read_only_trace"),
        Arc::new(executor.clone()),
        ToolActionKind::CommandExec,
    )
    .with_action_proposal();
    let (runtime, pending) = register_policy_pending_registered_tool_with_builder(
        "runtime-policy-command-exec-shell-read-only-trace",
        "policy_command_shell_read_only_trace",
        "call-command-exec-shell-read-only-trace",
        tool,
        |builder| {
            builder
                .allow_read_only_shell_process_actions(Arc::new(runner.clone()))
                .build()
        },
    )
    .await;

    let (events, logs) = capture_traces_for(
        "runtime-policy-command-exec-shell-read-only-trace",
        runtime.execute_tool_call(pending.id(), ToolExecutionContext::default()),
    )
    .await;
    let events = events.expect("opted-in read-only shell process action should execute");

    assert_eq!(
        event_kind_names_for_tool_execution(&events),
        ["ToolCallResolved"]
    );
    assert_eq!(runner.call_count(), 1);
    assert!(logs.contains("\"event\":\"runtime.process.execute.start\""));
    assert!(logs.contains("\"event\":\"runtime.process.execute.finish\""));
    assert!(logs.contains("\"permission_profile_id\":\"process.shell.read_only\""));
    assert!(logs.contains("\"shell\":\"bash\""));
    assert!(logs.contains("\"shell_flag\":\"-lc\""));
    assert!(logs.contains("\"shell_script_bytes\":24"));
    assert!(logs.contains(&format!(
        "\"shell_script_fingerprint\":\"{}\"",
        stable_process_input_fingerprint(script.as_bytes())
    )));
    assert!(!logs.contains("\"argv\""));
    assert!(!logs.contains(script));
}

#[tokio::test(flavor = "current_thread")]
async fn read_only_shell_process_denies_complex_or_mutating_shell_without_runner_call() {
    for (name, argv) in [
        ("redirect", ["bash", "-lc", "rg ProcessRunner > out.txt"]),
        ("substitution", ["bash", "-lc", "echo $(pwd)"]),
        (
            "mutating-segment",
            ["bash", "-lc", "rg ProcessRunner | rm -rf target"],
        ),
    ] {
        let executor = ProcessProposingToolExecutor::with_argv(argv);
        let runner = FakeProcessRunner::succeeding();
        let tool = RegisteredTool::new(
            policy_tool_spec(&format!("policy_command_shell_{name}")),
            Arc::new(executor.clone()),
            ToolActionKind::CommandExec,
        )
        .with_action_proposal();
        let (runtime, pending) = register_policy_pending_registered_tool_with_builder(
            &format!("runtime-policy-command-exec-shell-{name}"),
            &format!("policy_command_shell_{name}"),
            &format!("call-command-exec-shell-{name}"),
            tool,
            |builder| {
                builder
                    .allow_read_only_shell_process_actions(Arc::new(runner.clone()))
                    .build()
            },
        )
        .await;

        let events = runtime
            .execute_tool_call(pending.id(), ToolExecutionContext::default())
            .await
            .expect("non-read-only shell process proposal should be denied durably");

        assert_eq!(executor.propose_count(), 1);
        assert_eq!(executor.execute_count(), 0);
        assert_eq!(runner.call_count(), 0);
        assert_eq!(
            resolved_tool_result(&events).status(),
            merry_core::ToolCallResultStatus::Failed
        );
    }
}

#[tokio::test(flavor = "current_thread")]
async fn read_only_shell_process_runner_cancel_keeps_pending_without_output() {
    let script = "rg ProcessRunner | wc -l";
    let executor = ProcessProposingToolExecutor::with_argv(["bash", "-lc", script]);
    let runner = FakeProcessRunner::cancelling();
    let tool = RegisteredTool::new(
        policy_tool_spec("policy_command_shell_runner_cancel"),
        Arc::new(executor.clone()),
        ToolActionKind::CommandExec,
    )
    .with_action_proposal();
    let (runtime, pending) = register_policy_pending_registered_tool_with_builder(
        "runtime-policy-command-exec-shell-runner-cancel",
        "policy_command_shell_runner_cancel",
        "call-command-exec-shell-runner-cancel",
        tool,
        |builder| {
            builder
                .allow_read_only_shell_process_actions(Arc::new(runner.clone()))
                .build()
        },
    )
    .await;

    let err = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect_err("runner-cancelled shell process action should not resolve");

    assert!(matches!(
        err,
        RuntimeError::ToolExecutionCancelled { call_id, .. } if call_id == *pending.id()
    ));
    assert_eq!(executor.propose_count(), 1);
    assert_eq!(executor.execute_count(), 0);
    assert_eq!(runner.call_count(), 1);
    assert_eq!(runtime.pending_tool_calls().await, vec![pending.clone()]);
    assert!(
        runtime
            .read_tool_output(pending.id())
            .await
            .expect("tool output query succeeds")
            .is_none()
    );
}

#[tokio::test(flavor = "current_thread")]
async fn read_only_shell_process_runner_failure_keeps_pending_without_output() {
    let script = "rg ProcessRunner | wc -l";
    let executor = ProcessProposingToolExecutor::with_argv(["bash", "-lc", script]);
    let runner = FakeProcessRunner::infrastructure_failure("shell runner unavailable");
    let tool = RegisteredTool::new(
        policy_tool_spec("policy_command_shell_runner_failure"),
        Arc::new(executor.clone()),
        ToolActionKind::CommandExec,
    )
    .with_action_proposal();
    let (runtime, pending) = register_policy_pending_registered_tool_with_builder(
        "runtime-policy-command-exec-shell-runner-failure",
        "policy_command_shell_runner_failure",
        "call-command-exec-shell-runner-failure",
        tool,
        |builder| {
            builder
                .allow_read_only_shell_process_actions(Arc::new(runner.clone()))
                .build()
        },
    )
    .await;

    let err = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect_err("infrastructure-failed shell process action should not resolve");

    assert!(matches!(
        err,
        RuntimeError::ToolExecutionFailed { call_id, message, .. }
            if call_id == *pending.id() && message == "shell runner unavailable"
    ));
    assert_eq!(executor.propose_count(), 1);
    assert_eq!(executor.execute_count(), 0);
    assert_eq!(runner.call_count(), 1);
    assert_eq!(runtime.pending_tool_calls().await, vec![pending.clone()]);
    assert!(
        runtime
            .read_tool_output(pending.id())
            .await
            .expect("tool output query succeeds")
            .is_none()
    );
}