merry-coding 0.1.0

Coding prompts, project rules, tool catalog, permission policy, and subagent orchestration for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use crate::{
    CodingAutoFallback, CodingModelRoleConfig, CodingPermissionMode, CodingPermissionPolicy,
    CodingPermissionPolicyError, CodingRuntimeBuilder, CodingRuntimeInput, CodingSubagentsConfig,
    tests::process_backend,
};
use futures_util::stream;
use merry_core::{ProviderName, SessionId, SubagentActivityPhase, ToolName};
use merry_llm::{
    FinishReason, ModelCapabilities, ModelError, ModelEvent, ModelEventStream, ModelName,
    ModelOutput, ModelProvider, ModelProviderFuture, ModelRequest, ModelResponse, ModelRetryPolicy,
    ModelStreamContext, ModelToolCall, ModelToolCallId, ProviderErrorKind, ToolArguments,
    testing::FakeModelProvider,
};
use merry_runtime::{
    AgentLoopConfig, AgentLoopStatus, PermissionAdmissionContext, PermissionAdmissionDecision,
    PermissionAdmissionFuture, PermissionAdmissionSource, RuntimeModelRole, StepContext, StepInput,
    SubagentConfig,
};
use serde_json::json;
use std::{
    sync::{
        Arc, Mutex,
        atomic::{AtomicUsize, Ordering},
    },
    time::Duration,
};

#[derive(Clone)]
struct ParentChildProvider {
    name: ProviderName,
    capabilities: ModelCapabilities,
    state: Arc<Mutex<ParentChildProviderState>>,
}

struct ParentChildProviderState {
    parent_turns: usize,
    child_turns: usize,
    requests: Vec<ModelRequest>,
}

impl ParentChildProvider {
    fn new() -> Self {
        Self {
            name: ProviderName::new("parent-child-provider")
                .expect("provider name should be valid"),
            capabilities: ModelCapabilities::new(true, true, false, true, None, None)
                .expect("provider capabilities should be valid"),
            state: Arc::new(Mutex::new(ParentChildProviderState {
                parent_turns: 0,
                child_turns: 0,
                requests: Vec::new(),
            })),
        }
    }

    fn recorded_requests(&self) -> Vec<ModelRequest> {
        self.state
            .lock()
            .expect("provider state should not be poisoned")
            .requests
            .clone()
    }
}

impl ModelProvider for ParentChildProvider {
    fn name(&self) -> &ProviderName {
        &self.name
    }

    fn capabilities(&self) -> &ModelCapabilities {
        &self.capabilities
    }

    fn stream_model<'a>(
        &'a self,
        request: ModelRequest,
        _context: ModelStreamContext,
    ) -> ModelProviderFuture<'a, Result<ModelEventStream, ModelError>> {
        Box::pin(async move {
            let is_child = request.messages().iter().any(|message| {
                message
                    .content()
                    .as_text()
                    .contains("Run the child permission task.")
            });
            let event = {
                let mut state = self
                    .state
                    .lock()
                    .expect("provider state should not be poisoned");
                state.requests.push(request);
                if is_child {
                    let event = if state.child_turns == 0 {
                        permission_call_event()
                    } else {
                        completed_text("child done")
                    };
                    state.child_turns += 1;
                    event
                } else {
                    let event = if state.parent_turns == 0 {
                        spawn_child_event()
                    } else {
                        completed_text("parent done")
                    };
                    state.parent_turns += 1;
                    event
                }
            };
            Ok(Box::pin(stream::iter(vec![Ok(event)])) as ModelEventStream)
        })
    }
}

fn completed_text(text: &str) -> ModelEvent {
    ModelEvent::Completed {
        response: ModelResponse::new(vec![ModelOutput::text(text)], FinishReason::Stop, None),
    }
}

fn spawn_child_event() -> ModelEvent {
    let call = ModelToolCall::new(
        ModelToolCallId::new("parent-spawn-child").expect("call id should be valid"),
        ToolName::new("spawn_subagents").expect("tool name should be valid"),
        ToolArguments::try_from(json!({
            "tasks": [{
                "task": "Run the child permission task.",
                "max_model_turns": 2048,
                "allowed_tools": ["request_permissions"],
                "write_scope": []
            }]
        }))
        .expect("spawn arguments should be valid"),
    );
    ModelEvent::Completed {
        response: ModelResponse::new(
            vec![ModelOutput::tool_call(call)],
            FinishReason::ToolCalls,
            None,
        ),
    }
}

fn permission_call_event() -> ModelEvent {
    let call = ModelToolCall::new(
        ModelToolCallId::new("child-permission-call").expect("call id should be valid"),
        ToolName::new("request_permissions").expect("tool name should be valid"),
        ToolArguments::try_from(json!({
            "reason": "Run the exact child command.",
            "requested": {"network": true},
            "for_action": {
                "command": "printf child-permission",
                "cwd": "."
            }
        }))
        .expect("permission arguments should be valid"),
    );
    ModelEvent::Completed {
        response: ModelResponse::new(
            vec![ModelOutput::tool_call(call)],
            FinishReason::ToolCalls,
            None,
        ),
    }
}

fn approval_event() -> ModelEvent {
    completed_text(
        r#"{"schema_version":"permission_review.v1","decision":"approve","risk":"low","user_authorization":"high","rationale":"The child task authorizes this exact command."}"#,
    )
}

#[derive(Clone)]
struct CountingAdmission {
    calls: Arc<AtomicUsize>,
}

impl CountingAdmission {
    fn approving() -> Self {
        Self {
            calls: Arc::new(AtomicUsize::new(0)),
        }
    }

    fn calls(&self) -> usize {
        self.calls.load(Ordering::SeqCst)
    }
}

impl PermissionAdmissionSource for CountingAdmission {
    fn review<'a>(
        &'a self,
        _request: merry_runtime::PermissionRequest,
        _context: PermissionAdmissionContext,
    ) -> PermissionAdmissionFuture<'a> {
        Box::pin(async move {
            self.calls.fetch_add(1, Ordering::SeqCst);
            Ok(PermissionAdmissionDecision::approved("host approved"))
        })
    }
}

async fn run_parent_child_policy(
    session_id: &str,
    permission: CodingPermissionPolicy,
    model_roles: Vec<CodingModelRoleConfig>,
) -> Arc<ParentChildProvider> {
    let temp = tempfile::tempdir().expect("tempdir should be created");
    let primary = Arc::new(ParentChildProvider::new());
    let input = CodingRuntimeInput::new(
        SessionId::new(session_id).expect("session id should be valid"),
        temp.path(),
        primary.clone(),
        ModelName::new("parent-primary").expect("primary model should be valid"),
        process_backend(),
    )
    .with_automatic_compaction(merry_runtime::CompactionConfig::disabled())
    .with_retry_policy(ModelRetryPolicy::disabled())
    .with_model_roles(model_roles)
    .with_subagents(CodingSubagentsConfig::enabled(
        SubagentConfig::new(1, 1)
            .expect("subagent limits should be valid")
            .with_model_turn_bounds(2048, 2048)
            .expect("coding subagent bounds should be valid"),
    ));
    let coding_runtime = CodingRuntimeBuilder::new(input)
        .permission_policy(permission)
        .build()
        .expect("parent coding runtime should build");
    let mut activity = coding_runtime.runtime().subscribe_subagent_activity();

    let result = coding_runtime
        .runtime()
        .run_agent_loop(
            StepInput::user_text("Delegate the child permission task.")
                .expect("input should be valid"),
            StepContext::default(),
            AgentLoopConfig::new(3).expect("loop config should be valid"),
        )
        .await
        .expect("parent loop should complete");
    assert_eq!(result.status(), &AgentLoopStatus::Completed);

    let snapshots = tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            let snapshots = activity.borrow_and_update().clone();
            if snapshots
                .iter()
                .any(|snapshot| matches!(snapshot.phase, SubagentActivityPhase::Completed))
            {
                break snapshots;
            }
            assert!(
                !snapshots.iter().any(|snapshot| {
                    matches!(
                        snapshot.phase,
                        SubagentActivityPhase::Failed | SubagentActivityPhase::Cancelled
                    )
                }),
                "child runtime should not terminate unsuccessfully: {snapshots:?}"
            );
            activity
                .changed()
                .await
                .expect("subagent activity stream should remain open");
        }
    })
    .await
    .expect("child runtime should complete before timeout");
    assert!(
        snapshots
            .iter()
            .any(|snapshot| matches!(snapshot.phase, SubagentActivityPhase::Completed))
    );
    primary
}

#[tokio::test(flavor = "current_thread")]
async fn parent_builder_passes_policy_to_a_real_child_runtime() {
    let approval = Arc::new(FakeModelProvider::new(vec![Ok(approval_event())]));
    let approval_role = CodingModelRoleConfig::new(
        RuntimeModelRole::ApprovalReview,
        approval.clone(),
        ModelName::new("child-approval").expect("approval model should be valid"),
    )
    .expect("approval role should be valid");
    let primary = run_parent_child_policy(
        "coding-parent-child-policy",
        CodingPermissionPolicy::model_only(),
        vec![approval_role],
    )
    .await;
    assert_eq!(approval.recorded_requests().len(), 1);
    assert_eq!(
        approval.recorded_requests()[0].model().as_str(),
        "child-approval"
    );
    assert!(primary.recorded_requests().len() >= 3);
}

#[test]
fn host_reviewed_modes_reject_missing_host_admission() {
    for mode in [CodingPermissionMode::Auto, CodingPermissionMode::Ask] {
        let error = match CodingPermissionPolicy::for_permission_mode(
            mode,
            CodingAutoFallback::Ask,
            None,
        ) {
            Ok(_) => panic!("{mode:?} needs a host source"),
            Err(error) => error,
        };
        assert!(
            matches!(
                error,
                CodingPermissionPolicyError::HostAdmissionUnavailable { mode: found }
                    if found == mode
            ),
            "{mode:?}"
        );
    }
}

#[test]
fn auto_ask_fallback_uses_host_fallback() {
    let policy = CodingPermissionPolicy::for_permission_mode(
        CodingPermissionMode::Auto,
        CodingAutoFallback::Ask,
        Some(Arc::new(CountingAdmission::approving())),
    )
    .expect("host fallback policy should build");

    assert!(matches!(
        policy,
        CodingPermissionPolicy::ModelThenHostFallback { .. }
    ));
}

#[test]
fn ask_mode_uses_host_decision() {
    let policy = CodingPermissionPolicy::for_permission_mode(
        CodingPermissionMode::Ask,
        CodingAutoFallback::Ask,
        Some(Arc::new(CountingAdmission::approving())),
    )
    .expect("host review policy should build");

    assert!(matches!(
        policy,
        CodingPermissionPolicy::HostDecisionOnly { .. }
    ));
}

#[test]
fn reviewer_free_modes_do_not_need_a_host_admission_source() {
    let auto_deny = CodingPermissionPolicy::for_permission_mode(
        CodingPermissionMode::Auto,
        CodingAutoFallback::Deny,
        None,
    )
    .expect("auto deny fallback should not need a host");
    assert!(matches!(auto_deny, CodingPermissionPolicy::Required));

    let always = CodingPermissionPolicy::for_permission_mode(
        CodingPermissionMode::AlwaysApprove,
        CodingAutoFallback::Ask,
        None,
    )
    .expect("always-approve should not need a host");
    assert!(matches!(always, CodingPermissionPolicy::FullyTrusted));

    let deny = CodingPermissionPolicy::for_permission_mode(
        CodingPermissionMode::Deny,
        CodingAutoFallback::Ask,
        None,
    )
    .expect("deny should not need a host");
    assert!(matches!(deny, CodingPermissionPolicy::DenyAll));
}

#[test]
fn default_permission_mode_is_auto_with_ask_fallback() {
    assert_eq!(CodingPermissionMode::default(), CodingPermissionMode::Auto);
    assert_eq!(CodingAutoFallback::default(), CodingAutoFallback::Ask);
}

#[tokio::test(flavor = "current_thread")]
async fn parent_builder_passes_host_admission_to_a_real_child_runtime() {
    let host = CountingAdmission::approving();
    let primary = run_parent_child_policy(
        "coding-parent-child-host-policy",
        CodingPermissionPolicy::host_decision_only(Arc::new(host.clone())),
        Vec::new(),
    )
    .await;
    assert_eq!(host.calls(), 1);
    assert!(primary.recorded_requests().len() >= 3);
}

#[tokio::test(flavor = "current_thread")]
async fn parent_builder_passes_model_fallback_to_a_real_child_runtime() {
    let approval = Arc::new(FakeModelProvider::new(vec![Err(ModelError::provider(
        ProviderErrorKind::Unavailable,
        "approval provider unavailable",
    ))]));
    let approval_role = CodingModelRoleConfig::new(
        RuntimeModelRole::ApprovalReview,
        approval.clone(),
        ModelName::new("child-approval-fallback").expect("approval fallback model should be valid"),
    )
    .expect("approval role should be valid");
    let host = CountingAdmission::approving();
    let primary = run_parent_child_policy(
        "coding-parent-child-fallback-policy",
        CodingPermissionPolicy::model_then_host_fallback(Arc::new(host.clone())),
        vec![approval_role],
    )
    .await;

    assert_eq!(approval.recorded_requests().len(), 1);
    assert_eq!(host.calls(), 1);
    assert!(primary.recorded_requests().len() >= 3);
}

#[tokio::test(flavor = "current_thread")]
async fn parent_builder_passes_fully_trusted_to_a_real_child_runtime() {
    let approval = Arc::new(FakeModelProvider::new(vec![Err(ModelError::provider(
        ProviderErrorKind::Unavailable,
        "approval provider must not be called",
    ))]));
    let approval_role = CodingModelRoleConfig::new(
        RuntimeModelRole::ApprovalReview,
        approval.clone(),
        ModelName::new("child-approval-trusted").expect("trusted approval model should be valid"),
    )
    .expect("approval role should be valid");
    let primary = run_parent_child_policy(
        "coding-parent-child-trusted-policy",
        CodingPermissionPolicy::fully_trusted(),
        vec![approval_role],
    )
    .await;

    assert!(approval.recorded_requests().is_empty());
    assert!(primary.recorded_requests().len() >= 3);
}