use crate::{
CODING_AGENT_POLICY_PROMPT, CodingAgentRunPolicy, CodingFinalReportPolicy, ProjectRules,
TaskAnchor, coding_agent,
tests::{bridge_tool, bridge_tool_with_description, process_session},
};
use merry_core::ToolName;
use merry_llm::ModelRetryPolicy;
use merry_process::TokioProcessRunner;
use merry_runtime::{AcceptedLocalWorkspaceProcessAdmission, DurableMemory, MemoryLayout};
use serde_json::json;
use std::sync::Arc;
#[test]
fn workspace_profile_builds_read_tools_and_coding_defaults() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let profile = coding_agent(temp.path())
.build()
.expect("workspace profile should build");
let tool_names = profile
.registered_tools()
.iter()
.map(|tool| tool.spec().name().as_str())
.collect::<Vec<_>>();
assert!(tool_names.contains(&"read_file"));
assert!(!tool_names.contains(&"apply_patch"));
assert!(profile.runtime_profile().progress_commentary());
assert_eq!(
profile.runtime_profile().model_retry_policy(),
Some(ModelRetryPolicy::coding_agent_default())
);
}
#[test]
fn coding_agent_profile_has_one_canonical_workspace_tool_order() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let profile = coding_agent(temp.path())
.build()
.expect("coding-agent profile should build");
let tool_names = profile
.tool_names()
.into_iter()
.map(ToolName::as_str)
.collect::<Vec<_>>();
assert_eq!(tool_names, vec!["read_file"]);
}
#[test]
fn coding_agent_profile_owns_process_permission_and_patch_order() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let runner: Arc<dyn merry_runtime::ProcessRunner> = Arc::new(TokioProcessRunner::new());
let profile = coding_agent(temp.path())
.patch_tool()
.accepted_process_session(process_session(
AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
runner,
))
.build()
.expect("coding-agent profile should build");
let tool_names = profile
.tool_names()
.into_iter()
.map(ToolName::as_str)
.collect::<Vec<_>>();
assert_eq!(
tool_names,
vec![
"run_process",
"request_permissions",
"read_background_process",
"stop_background_process",
"read_file",
"apply_patch",
]
);
let process = &profile.registered_tools()[0];
assert!(
process
.spec()
.description()
.contains("omit cwd for the current workspace directory")
);
assert!(
process
.spec()
.description()
.contains("runtime will review before running this exact command")
);
assert!(process.spec().description().contains(
"Paths and host integrations enabled by trusted global configuration are already available"
));
assert!(
process
.spec()
.description()
.contains("Network is never granted implicitly")
);
assert!(
process
.spec()
.description()
.contains("Set background to true")
);
assert!(
process
.spec()
.description()
.contains("read_background_process")
);
let schema = process.spec().input_schema().as_schema().as_value();
assert_eq!(schema["required"], json!(["command"]));
assert!(schema["properties"]["permissions"].is_object());
assert!(
schema["properties"]["permissions"]["properties"]["host_integrations"]["description"]
.as_str()
.expect("host integration description should be text")
.contains("Integrations enabled by trusted global configuration are already available")
);
assert!(
schema["properties"]["permissions"]["properties"]["network"]["description"]
.as_str()
.expect("network description should be text")
.contains("Network is never granted implicitly")
);
}
#[test]
fn coding_agent_profile_hash_is_deterministic_and_tracks_stable_material() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let first = coding_agent(temp.path())
.project_rules(
ProjectRules::new("AGENTS.md", "Use the project rules.")
.expect("project rules should be valid"),
)
.task_anchor(TaskAnchor::new("First task").expect("task anchor should be valid"))
.build()
.expect("coding-agent profile should build");
let dynamic_change = coding_agent(temp.path())
.project_rules(
ProjectRules::new("AGENTS.md", "Use the project rules.")
.expect("project rules should be valid"),
)
.task_anchor(TaskAnchor::new("Different task").expect("task anchor should be valid"))
.build()
.expect("coding-agent profile should build");
let stable_change = coding_agent(temp.path())
.project_rules(
ProjectRules::new("AGENTS.md", "Changed project rules.")
.expect("project rules should be valid"),
)
.task_anchor(TaskAnchor::new("First task").expect("task anchor should be valid"))
.build()
.expect("coding-agent profile should build");
let retry_change = coding_agent(temp.path())
.retry_policy(ModelRetryPolicy::disabled())
.project_rules(
ProjectRules::new("AGENTS.md", "Use the project rules.")
.expect("project rules should be valid"),
)
.task_anchor(TaskAnchor::new("First task").expect("task anchor should be valid"))
.build()
.expect("coding-agent profile should build");
assert_eq!(first.profile_hash(), dynamic_change.profile_hash());
assert_ne!(first.profile_hash(), stable_change.profile_hash());
assert_ne!(first.profile_hash(), retry_change.profile_hash());
assert!(first.profile_hash().as_str().starts_with("fnv1a64:"));
}
#[test]
fn coding_agent_profile_hash_includes_advertised_tool_order() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let first = coding_agent(temp.path())
.register_tools([bridge_tool("alpha"), bridge_tool("beta")])
.build()
.expect("coding-agent profile should build");
let reordered = coding_agent(temp.path())
.register_tools([bridge_tool("beta"), bridge_tool("alpha")])
.build()
.expect("coding-agent profile should build");
assert_ne!(first.profile_hash(), reordered.profile_hash());
assert_eq!(
first
.tool_names()
.into_iter()
.map(ToolName::as_str)
.collect::<Vec<_>>(),
vec!["read_file", "alpha", "beta"]
);
}
#[test]
fn coding_agent_profile_hash_tracks_tool_schema_and_coding_run_policy() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let base = coding_agent(temp.path())
.register_tool(bridge_tool("catalog_tool"))
.build()
.expect("base profile should build");
let changed_schema = coding_agent(temp.path())
.register_tool(bridge_tool_with_description(
"catalog_tool",
"Changed description",
))
.build()
.expect("changed schema profile should build");
let changed_policy = coding_agent(temp.path())
.run_policy(
CodingAgentRunPolicy::new(16, CodingFinalReportPolicy::EvidenceBackedSummary)
.expect("valid coding run policy"),
)
.build()
.expect("changed policy profile should build");
assert_ne!(base.profile_hash(), changed_schema.profile_hash());
assert_ne!(base.profile_hash(), changed_policy.profile_hash());
assert_eq!(base.run_policy().max_model_turns(), usize::MAX);
assert_eq!(
changed_policy
.loop_config()
.expect("loop config")
.max_model_turns(),
16
);
assert_eq!(
changed_policy.run_policy().final_report().as_str(),
"evidence_backed_summary"
);
}
#[test]
fn coding_agent_profile_owns_the_coding_prompt_and_hashes_its_exact_text() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let profile = coding_agent(temp.path())
.build()
.expect("coding-agent profile should build");
let runtime_profile = profile.runtime_profile();
let prompt = runtime_profile.prompt_profile();
assert_eq!(prompt.stable_blocks().len(), 1);
assert_eq!(prompt.stable_blocks()[0].tag(), "merry_coding_policy");
assert_eq!(prompt.stable_blocks()[0].text(), CODING_AGENT_POLICY_PROMPT);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("evidence-backed summary")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("same `run_process` call under `permissions`")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("discovered after a failed sandboxed attempt")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("already available to sandboxed commands")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("starts with no network access")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("preferring the installed modern search tools")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("Do not delete coverage, weaken an assertion")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("Commit, push, merge, or publish only when the user asks")
);
assert!(
prompt.stable_blocks()[0].text().contains(
"Subagent orchestration discipline (`spawn_subagents`, `send_subagent_message`"
)
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("Prefer editing an existing file")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("Set `background` to true")
);
assert!(
prompt.stable_blocks()[0]
.text()
.contains("`read_background_process`")
);
}
#[test]
fn coding_agent_profile_appends_memory_instructions_after_policy() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let workspace = temp.path().join("workspace");
std::fs::create_dir(&workspace).expect("workspace dir should be created");
let memory = DurableMemory::open(
MemoryLayout::at(&temp.path().join("memory"), &workspace)
.expect("memory layout should resolve"),
)
.expect("memory store should open");
let without = coding_agent(&workspace)
.build()
.expect("profile without memory should build");
let profile = coding_agent(&workspace)
.durable_memory(memory)
.build()
.expect("profile with memory should build");
let runtime_profile = profile.runtime_profile();
let blocks = runtime_profile.prompt_profile().stable_blocks();
assert_eq!(blocks.len(), 2);
assert_eq!(blocks[0].tag(), "merry_coding_policy");
assert_eq!(blocks[0].text(), CODING_AGENT_POLICY_PROMPT);
assert_eq!(blocks[1].tag(), "merry_memory");
assert!(blocks[1].text().contains("`read_file`"));
assert!(blocks[1].text().contains("`apply_patch`"));
assert!(blocks[1].text().contains("never read or edit MEMORY.md"));
assert_ne!(without.profile_hash(), profile.profile_hash());
}
#[test]
fn coding_agent_profile_hash_distinguishes_patch_scope_and_process_admission() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let runner: Arc<dyn merry_runtime::ProcessRunner> = Arc::new(TokioProcessRunner::new());
let unrestricted = coding_agent(temp.path())
.patch_tool()
.build()
.expect("unrestricted profile should build");
let read_only = coding_agent(temp.path())
.patch_tool()
.read_only_patch_scope()
.build()
.expect("read-only profile should build");
let isolated = coding_agent(temp.path())
.accepted_process_session(process_session(
AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
Arc::clone(&runner),
))
.build()
.expect("isolated profile should build");
let host = coding_agent(temp.path())
.accepted_process_session(process_session(
AcceptedLocalWorkspaceProcessAdmission::accept_host(),
runner,
))
.build()
.expect("host profile should build");
assert_ne!(unrestricted.profile_hash(), read_only.profile_hash());
assert_ne!(isolated.profile_hash(), host.profile_hash());
}
#[test]
fn workspace_profile_can_enable_patch_tool() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let profile = coding_agent(temp.path())
.patch_tool()
.read_only_patch_scope()
.build()
.expect("workspace profile should build");
assert!(
profile
.registered_tools()
.iter()
.any(|tool| tool.spec().name().as_str() == "apply_patch")
);
}
#[test]
fn workspace_profile_web_tools_registers_web_and_browser_tools_in_order() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let bare = coding_agent(temp.path())
.build()
.expect("bare profile should build");
let with_web = coding_agent(temp.path())
.web_tools()
.build()
.expect("web profile should build");
let names = with_web
.tool_names()
.into_iter()
.map(ToolName::as_str)
.collect::<Vec<_>>();
assert_eq!(
names,
vec!["read_file", "web_fetch", "browser_tab", "browser_network"]
);
for web_name in ["web_fetch", "browser_tab", "browser_network"] {
let tool = with_web
.registered_tools()
.iter()
.find(|tool| tool.spec().name().as_str() == web_name)
.expect("web tool registered");
assert_eq!(tool.action_kind(), merry_runtime::ToolActionKind::Network);
assert!(tool.permissioned_network_lane());
}
assert_ne!(bare.profile_hash(), with_web.profile_hash());
assert!(CODING_AGENT_POLICY_PROMPT.contains("browser_tab"));
assert!(CODING_AGENT_POLICY_PROMPT.contains("web_fetch"));
assert!(CODING_AGENT_POLICY_PROMPT.contains("data:text/html"));
assert!(CODING_AGENT_POLICY_PROMPT.contains("A failed open does not start a session"));
assert!(CODING_AGENT_POLICY_PROMPT.contains("policy refusal"));
}
#[test]
fn network_policy_and_allowed_domains_preserve_profile_hash_and_tool_specs_for_kv_cache() {
use merry_core::CapabilityPolicy;
use merry_process::{
LocalProcessBackend, ProcessBackend, ProcessBackendMode, ProcessBackendOptions,
};
let temp = tempfile::tempdir().expect("tempdir should be created");
let backend_ask = LocalProcessBackend::new(
temp.path(),
ProcessBackendMode::Host,
ProcessBackendOptions::new().with_network_policy(CapabilityPolicy::Ask),
)
.expect("host backend");
let backend_allow_domains = LocalProcessBackend::new(
temp.path(),
ProcessBackendMode::Host,
ProcessBackendOptions::new()
.with_network_policy(CapabilityPolicy::Deny)
.with_allowed_domains(["docs.rs", "crates.io"])
.with_browser_allow_local(false),
)
.expect("host backend");
let profile_ask = coding_agent(temp.path())
.web_tools()
.accepted_process_session(backend_ask.new_session())
.build()
.expect("ask profile");
let profile_deny = coding_agent(temp.path())
.web_tools()
.accepted_process_session(backend_allow_domains.new_session())
.build()
.expect("deny profile");
assert_eq!(profile_ask.profile_hash(), profile_deny.profile_hash());
assert_eq!(profile_ask.tool_names(), profile_deny.tool_names());
assert_eq!(
profile_ask
.registered_tools()
.iter()
.map(|t| t.spec().clone())
.collect::<Vec<_>>(),
profile_deny
.registered_tools()
.iter()
.map(|t| t.spec().clone())
.collect::<Vec<_>>()
);
}
#[tokio::test]
async fn web_fetch_session_domain_grant_can_be_inspected_and_revoked_live() {
use merry_core::{ApprovalScope, CapabilityPolicy, SessionId};
use merry_llm::{
FinishReason, ModelEvent, ModelName, ModelOutput, ModelResponse, ModelToolCall,
ModelToolCallId, ToolArguments, testing::FakeModelProvider,
};
use merry_process::{LocalProcessBackend, ProcessBackendMode, ProcessBackendOptions};
use merry_runtime::{
AgentLoopConfig, AgentLoopStatus, PermissionAdmissionContext, PermissionAdmissionDecision,
PermissionAdmissionFuture, PermissionAdmissionSource, PermissionedAction,
RequestedCapability, SessionPermissionGrantKind, StepContext, StepInput,
};
use std::sync::atomic::{AtomicUsize, Ordering};
struct DomainGrantAdmission {
prompts: Arc<AtomicUsize>,
}
impl PermissionAdmissionSource for DomainGrantAdmission {
fn review<'a>(
&'a self,
request: merry_runtime::PermissionRequest,
_context: PermissionAdmissionContext,
) -> PermissionAdmissionFuture<'a> {
Box::pin(async move {
let turn = self.prompts.fetch_add(1, Ordering::SeqCst);
assert_eq!(
request.requested(),
&[RequestedCapability::NetworkDomain("docs.rs".to_owned())]
);
assert!(matches!(
request.action(),
PermissionedAction::NetworkUrl { tool, host, .. }
if tool == "web_fetch" && host == "docs.rs"
));
if turn == 0 {
Ok(PermissionAdmissionDecision::approved_with_scope(
ApprovalScope::Session,
"session domain allow",
))
} else {
Ok(PermissionAdmissionDecision::denied("revoked domain"))
}
})
}
}
let make_web_fetch_turn = |call_id: &str| {
let call = ModelToolCall::new(
ModelToolCallId::new(call_id).expect("valid call id"),
ToolName::new("web_fetch").expect("valid tool name"),
ToolArguments::try_from(json!({ "url": "https://docs.rs/serde" })).expect("valid args"),
);
ModelEvent::Completed {
response: ModelResponse::new(
vec![ModelOutput::tool_call(call)],
FinishReason::ToolCalls,
None,
),
}
};
let done_turn = |text: &str| ModelEvent::Completed {
response: ModelResponse::new(vec![ModelOutput::text(text)], FinishReason::Stop, None),
};
let temp = tempfile::tempdir().expect("tempdir should be created");
let backend = Arc::new(
LocalProcessBackend::new(
temp.path(),
ProcessBackendMode::Host,
ProcessBackendOptions::new().with_network_policy(CapabilityPolicy::Ask),
)
.expect("host backend"),
);
let provider = Arc::new(FakeModelProvider::new_turns(vec![
vec![Ok(make_web_fetch_turn("call-1"))],
vec![Ok(done_turn("after first fetch"))],
vec![Ok(make_web_fetch_turn("call-2"))],
vec![Ok(done_turn("after cached fetch"))],
vec![Ok(make_web_fetch_turn("call-3"))],
vec![Ok(done_turn("after revoked fetch"))],
]));
let prompt_count = Arc::new(AtomicUsize::new(0));
let admission: Arc<dyn PermissionAdmissionSource> = Arc::new(DomainGrantAdmission {
prompts: Arc::clone(&prompt_count),
});
let coding = crate::CodingRuntimeBuilder::new(
crate::CodingRuntimeInput::new(
SessionId::new("session-web-domain-grant").expect("valid session id"),
temp.path(),
provider,
ModelName::new("test-model").expect("valid model"),
backend,
)
.with_automatic_compaction(merry_runtime::CompactionConfig::disabled())
.with_retry_policy(ModelRetryPolicy::disabled()),
)
.permission_policy(crate::CodingPermissionPolicy::host_decision_only(admission))
.build()
.expect("coding runtime builds");
let runtime = coding.runtime();
let turn1 = runtime
.run_agent_loop(
StepInput::user_text("Fetch docs 1").expect("input"),
StepContext::default(),
AgentLoopConfig::new(4).expect("loop config"),
)
.await
.expect("turn 1 finishes");
assert_eq!(turn1.status(), &AgentLoopStatus::Completed);
assert_eq!(prompt_count.load(Ordering::SeqCst), 1);
let active = runtime.active_permission_grants();
assert!(active.has_elevated_network());
let domain_grant = active
.grants()
.iter()
.find(|grant| {
matches!(
grant.kind(),
SessionPermissionGrantKind::NetworkDomain(host) if host == "docs.rs"
)
})
.expect("docs.rs session grant should be visible in active_permission_grants");
let grant_id = domain_grant.id();
let turn2 = runtime
.run_agent_loop(
StepInput::user_text("Fetch docs 2").expect("input"),
StepContext::default(),
AgentLoopConfig::new(4).expect("loop config"),
)
.await
.expect("turn 2 finishes");
assert_eq!(turn2.status(), &AgentLoopStatus::Completed);
assert_eq!(
prompt_count.load(Ordering::SeqCst),
1,
"session domain grant must bypass a second prompt"
);
assert!(
runtime
.revoke_session_grant(grant_id)
.expect("revoke session grant")
);
assert!(!runtime.active_permission_grants().has_elevated_network());
let turn3 = runtime
.run_agent_loop(
StepInput::user_text("Fetch docs 3").expect("input"),
StepContext::default(),
AgentLoopConfig::new(4).expect("loop config"),
)
.await
.expect("turn 3 finishes");
assert_eq!(turn3.status(), &AgentLoopStatus::Completed);
assert_eq!(
prompt_count.load(Ordering::SeqCst),
2,
"revoked domain grant must re-prompt on the very next web_fetch call"
);
}