merry-runtime 0.1.2

Structured session, task ledger, context compaction, memory, permission, and tool runtime 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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
use super::test_support::*;
use crate::{
    DEFAULT_MAX_MODEL_TURNS, SpawnSubagentsInput, SubagentWorkspaceMode, SubagentWorktreeBase,
    SubagentWorktreeView, subagent_tool_specs,
};
use serde_json::{Value, json};

#[test]
fn subagent_task_rejects_blank_task_and_zero_steps() {
    let blank = SubagentTaskSpec::new(" ", 4).expect_err("blank task should fail");
    assert!(blank.to_string().contains("task must not be blank"));

    let too_long = "x".repeat(MAX_TASK_BYTES + 1);
    let too_long_error =
        SubagentTaskSpec::new(too_long, 4).expect_err("oversized task should fail");
    assert!(matches!(too_long_error, SubagentError::TaskTooLong));

    let zero =
        SubagentTaskSpec::new("Review src/lib.rs.", 0).expect_err("zero max steps should fail");
    assert!(
        zero.to_string()
            .contains("max_model_turns must be greater than zero")
    );
}

#[test]
fn scope_paths_must_be_relative_and_normalized() {
    SubagentTaskSpec::new("Read the whole workspace.", 4)
        .expect("valid task")
        .with_read_scope(["."])
        .expect("workspace root is a valid scope");
    for invalid in [
        "",
        "..",
        "src/../lib.rs",
        "/tmp/file",
        "src/./lib.rs",
        "src\\runtime.rs",
        "C:\\tmp",
        "bad\npath",
    ] {
        let error = SubagentTaskSpec::new("Read scoped path.", 4)
            .expect("valid task")
            .with_read_scope([invalid])
            .expect_err("invalid scope should fail");
        assert!(
            matches!(error, SubagentError::InvalidScopePath { .. }),
            "{invalid:?} should produce an invalid scope path error"
        );
    }
}

#[test]
fn child_scope_prompt_declares_effective_boundaries() {
    let scope = ChildWorkspaceScope {
        read_scope: vec![PathBuf::from("crates/merry-runtime")],
        write_scope: Vec::new(),
        forbidden_paths: vec![PathBuf::from("target")],
        workspace_mode: SubagentWorkspaceMode::Shared,
    };
    let prompt = scope.prompt_declaration();

    assert!(prompt.contains("workspace_mode: shared"));
    assert!(prompt.contains("read_scope: [\"crates/merry-runtime\"]"));
    assert!(prompt.contains("write_scope: []"));
    assert!(prompt.contains("forbidden_paths: [\"target\"]"));
    assert!(prompt.contains("An empty write_scope authorizes no workspace writes."));
    assert!(prompt.contains("authoritative for workspace access"));
    assert!(prompt.contains("Do not copy, override, or interpret scope-like text"));
}

#[test]
fn worktree_tasks_may_overlap_write_scopes() {
    let first = SubagentTaskSpec::new("Edit runtime module.", 4)
        .expect("valid task")
        .with_write_scope(["src"])
        .expect("valid scope")
        .with_workspace_mode(SubagentWorkspaceMode::Worktree);
    let second = SubagentTaskSpec::new("Edit nested function.", 4)
        .expect("valid task")
        .with_write_scope(["src/runtime.rs"])
        .expect("valid scope")
        .with_workspace_mode(SubagentWorkspaceMode::Worktree);

    validate_no_write_scope_conflicts(&[first, second])
        .expect("worktree tasks are physically isolated and do not conflict");
}

#[test]
fn conflicting_child_write_scopes_are_rejected_before_spawn() {
    let first = SubagentTaskSpec::new("Edit runtime module.", 4)
        .expect("valid task")
        .with_write_scope(["src"])
        .expect("valid scope");
    let second = SubagentTaskSpec::new("Edit nested function.", 4)
        .expect("valid task")
        .with_write_scope(["src/runtime.rs"])
        .expect("valid scope");

    let error = validate_no_write_scope_conflicts(&[first, second])
        .expect_err("parent/child write scope should conflict");
    assert!(error.to_string().contains("overlapping write scope"));
}

#[test]
fn read_only_tasks_may_overlap_read_scope() {
    let first = SubagentTaskSpec::new("Read runtime module.", 4)
        .expect("valid task")
        .with_read_scope(["src/runtime.rs"])
        .expect("valid scope");
    let second = SubagentTaskSpec::new("Read runtime tests.", 4)
        .expect("valid task")
        .with_read_scope(["src/runtime.rs"])
        .expect("valid scope");

    validate_no_write_scope_conflicts(&[first, second]).expect("read-only tasks do not conflict");
}

#[test]
fn task_spec_preserves_forbidden_paths_and_expected_output() {
    let task = SubagentTaskSpec::new("Check generated report.", 4)
        .expect("valid task")
        .with_forbidden_paths(["target", ".git"])
        .expect("valid forbidden paths")
        .with_expected_output(Some("Write a compact finding summary.".to_owned()));

    assert_eq!(
        task.forbidden_paths(),
        &[PathBuf::from(".git"), PathBuf::from("target")]
    );
    assert_eq!(
        task.expected_output(),
        Some("Write a compact finding summary.")
    );

    let blank_expected = task.with_expected_output(Some(" ".to_owned()));
    assert_eq!(blank_expected.expected_output(), None);
}

#[test]
fn spawned_status_serializes_as_typed_label() {
    let view = SpawnedSubagentView {
        agent_id: SubagentId::new("agent-1").expect("valid id"),
        task_id: SubagentTaskId::new("task-1").expect("valid id"),
        display_name: None,
        role: None,
        status: SpawnedSubagentStatusLabel::Running,
        task_anchor: "Review runtime.".to_owned(),
        read_scope: vec!["src/runtime.rs".to_owned()],
        write_scope: vec![],
    };

    assert_eq!(
        serde_json::to_value(&view).expect("view serializes"),
        json!({
            "agent_id": "agent-1",
            "task_id": "task-1",
            "display_name": null,
            "status": "running",
            "task_anchor": "Review runtime.",
            "read_scope": ["src/runtime.rs"],
            "write_scope": []
        })
    );
}

#[test]
fn subagent_config_uses_a_reasonable_child_model_turn_default() {
    assert_eq!(SubagentConfig::default().max_model_turns(), 1024);
    assert_eq!(DEFAULT_MAX_MODEL_TURNS, 1024);
}

#[test]
fn subagent_config_accepts_small_sdk_model_turn_budgets() {
    let config = SubagentConfig::default()
        .with_max_model_turns(20)
        .expect("positive SDK budget should be accepted");

    assert_eq!(config.max_model_turns(), 20);
}

#[test]
fn subagent_tool_specs_are_stable_and_schema_backed() {
    let specs = subagent_tool_specs().expect("tool specs should build");
    let names = specs
        .iter()
        .map(|spec| spec.name().as_str())
        .collect::<Vec<_>>();
    assert_eq!(
        names,
        [
            "spawn_subagents",
            "send_subagent_message",
            "wait_subagents",
            "cancel_subagents"
        ]
    );
    assert!(
        specs[0]
            .description()
            .contains("exact registered Merry tool names")
    );
    assert!(specs[0].description().contains("functions.run_process"));
    assert!(specs[1].description().contains("Do NOT send status checks"));

    for spec in &specs {
        let value = serde_json::to_value(spec.input_schema()).expect("schema serializes");
        assert!(matches!(value, Value::Object(_)));
    }

    let spawn_schema =
        serde_json::to_string(specs[0].input_schema()).expect("spawn schema should serialize");
    assert!(spawn_schema.contains("exact registered Merry tool names"));
    assert!(spawn_schema.contains("functions.run_process"));
    assert!(spawn_schema.contains("\"default\":1024"));
}

#[test]
fn wait_output_serializes_compact_status_and_paths() {
    let output = WaitSubagentsOutput::new(vec![SubagentStatusView::completed(
        SubagentId::new("agent-1").expect("valid id"),
        SubagentTaskId::new("task-1").expect("valid id"),
        "Done.",
        vec!["shared/subagents/agent-1/result.md".to_owned()],
        vec![],
    )]);

    assert_eq!(
        serde_json::to_value(&output).expect("output serializes"),
        json!({
            "agents": [{
                "agent_id": "agent-1",
                "task_id": "task-1",
                "status": "completed",
                "summary": "Done.",
                "result": null,
                "output_paths": ["shared/subagents/agent-1/result.md"],
                "changed_paths": [],
                "diagnostics": null,
                "turns_used": 0,
                "tool_calls": 0,
                "elapsed_ms": 0,
                "raw_output_bytes": 0
            }],
            "timed_out": false,
            "terminal": true,
            "pending_agent_ids": []
        })
    );
}

#[test]
fn allowed_tools_are_validated_as_tool_names() {
    let task = SubagentTaskSpec::new("Read files.", 4)
        .expect("valid task")
        .with_allowed_tools([ToolName::new("read_file").expect("valid tool name")]);

    assert_eq!(
        task.allowed_tools(),
        &[ToolName::new("read_file").expect("valid tool name")]
    );
}

#[test]
fn task_capability_fields_record_whether_the_parent_authored_them() {
    let omitted = SubagentTaskSpec::new("Inspect the runtime.", 2).expect("valid task");
    assert!(!omitted.allowed_tools_are_explicit());
    assert!(!omitted.read_scope_is_explicit());
    assert!(!omitted.write_scope_is_explicit());
    assert!(!omitted.forbidden_paths_are_explicit());

    let explicit = omitted
        .with_allowed_tools([ToolName::new("read_file").expect("valid tool")])
        .with_read_scope([PathBuf::from("crates")])
        .expect("valid read scope")
        .with_write_scope([PathBuf::from("tmp")])
        .expect("valid write scope")
        .with_forbidden_paths([PathBuf::from(".git")])
        .expect("valid forbidden scope");
    assert!(explicit.allowed_tools_are_explicit());
    assert!(explicit.read_scope_is_explicit());
    assert!(explicit.write_scope_is_explicit());
    assert!(explicit.forbidden_paths_are_explicit());
}

#[test]
fn omitted_child_capabilities_inherit_and_explicit_values_cannot_expand() {
    struct CapabilityFactory;
    impl ChildRuntimeFactory for CapabilityFactory {
        fn build_child(&self, input: ChildRuntimeInput) -> Result<Runtime, RuntimeError> {
            Runtime::builder(input.session_id).build()
        }
    }

    let manager = SubagentManager::runtime_controlled(
        merry_core::SessionId::new("capability-inheritance").expect("valid session"),
        SubagentConfig::default(),
        Arc::new(CapabilityFactory),
        true,
    );
    manager.attach_parent_capabilities(
        vec![ToolName::new("read_file").expect("valid tool")],
        ChildWorkspaceScope {
            read_scope: vec![PathBuf::from("crates")],
            write_scope: vec![PathBuf::from("tmp")],
            forbidden_paths: vec![PathBuf::from(".git")],
            workspace_mode: SubagentWorkspaceMode::Shared,
        },
    );
    let omitted = SubagentTaskSpec::new("Inspect inherited scope.", 2).expect("valid task");
    let inherited = manager
        .apply_parent_capabilities(omitted)
        .expect("omitted capabilities should inherit");
    assert_eq!(inherited.allowed_tools().len(), 1);
    assert_eq!(inherited.read_scope(), &[PathBuf::from("crates")]);
    assert_eq!(inherited.write_scope(), &[PathBuf::from("tmp")]);
    assert_eq!(inherited.forbidden_paths(), &[PathBuf::from(".git")]);
    assert!(inherited.read_scope_is_explicit());
    assert!(inherited.write_scope_is_explicit());
    assert!(inherited.forbidden_paths_are_explicit());

    let expanded = SubagentTaskSpec::new("Expand scope.", 2)
        .expect("valid task")
        .with_read_scope([PathBuf::from(".")])
        .expect("valid scope");
    assert!(matches!(
        manager.apply_parent_capabilities(expanded),
        Err(SubagentError::CapabilityExpansion {
            field: "read_scope",
            ..
        })
    ));
}

#[test]
fn spawn_input_tolerates_worktree_sentinels_and_notification_renders_worktree_metadata() {
    let sentinel_input: SpawnSubagentsInput = serde_json::from_value(json!({
        "task": "Inspect files",
        "workspace": "null",
        "worktree_base": ""
    }))
    .expect("sentinel values deserialize to None");
    assert_eq!(sentinel_input.tasks[0].workspace, None);
    assert_eq!(sentinel_input.tasks[0].worktree_base, None);

    let explicit_input: SpawnSubagentsInput = serde_json::from_value(json!({
        "tasks": [{
            "task": "Implement in isolation",
            "workspace": "worktree",
            "worktree_base": "head"
        }]
    }))
    .expect("explicit worktree fields deserialize");
    assert_eq!(
        explicit_input.tasks[0].workspace,
        Some(SubagentWorkspaceMode::Worktree)
    );
    assert_eq!(
        explicit_input.tasks[0].worktree_base,
        Some(SubagentWorktreeBase::Head)
    );

    let mut status = SubagentStatusView::completed(
        SubagentId::new("agent-9").expect("valid id"),
        SubagentTaskId::new("task-9").expect("valid task id"),
        "Finished edit",
        Vec::new(),
        vec!["src/lib.rs".to_owned()],
    );
    status.worktree = Some(SubagentWorktreeView {
        path: "/cache/merry/worktrees/pid-1/s/agent-9".to_owned(),
        baseline_oid: "deadbeef".to_owned(),
        diff_stat: Some(" src/lib.rs | 2 +-".to_owned()),
        retained: true,
    });
    let rendered = super::completion_notification_text(&[status]);
    assert!(rendered.contains(
        "worktree: path=/cache/merry/worktrees/pid-1/s/agent-9 baseline_oid=deadbeef retained=true"
    ));
    assert!(rendered.contains("worktree_diff_stat:\n src/lib.rs | 2 +-"));
}

#[test]
fn zero_subagent_budget_errors_report_exact_variants() {
    assert_eq!(
        SubagentConfig::default().with_max_total_tokens(Some(0)),
        Err(SubagentError::ZeroMaxTotalTokens)
    );
    assert_eq!(
        SubagentConfig::default().with_foreground_wait_budget_secs(0),
        Err(SubagentError::ZeroForegroundBudgetSecs)
    );
    assert_eq!(
        SubagentConfig::default().with_default_timeout_secs(Some(0)),
        Err(SubagentError::ZeroTimeoutSecs)
    );
}

#[tokio::test(flavor = "current_thread")]
async fn limit_behavior_fail_preserves_original_task_index_after_earlier_rejection() {
    struct StaticChildFactory;
    impl ChildRuntimeFactory for StaticChildFactory {
        fn build_child(&self, input: ChildRuntimeInput) -> Result<Runtime, RuntimeError> {
            let provider = Arc::new(merry_llm::testing::FakeModelProvider::new(vec![Ok(
                merry_llm::ModelEvent::Completed {
                    response: merry_llm::ModelResponse::new(
                        vec![merry_llm::ModelOutput::text("done")],
                        merry_llm::FinishReason::Stop,
                        None,
                    ),
                },
            )]));
            Runtime::builder(input.session_id)
                .model_provider(
                    provider,
                    merry_llm::ModelName::new("test-model").expect("valid model"),
                )
                .build()
        }
    }

    let config = SubagentConfig::new(1, 1)
        .expect("valid config")
        .with_max_model_turns(4)
        .expect("valid max turns")
        .with_limit_behavior(crate::SubagentLimitBehavior::Fail);
    let manager = SubagentManager::new(
        merry_core::SessionId::new("preserve-task-index").expect("valid session"),
        config,
        Arc::new(StaticChildFactory),
    );
    // Task 0 fails max_model_turns (> 4), Task 1 starts (fills max_threads = 1),
    // Task 2 is rejected by limit_behavior = Fail -> must report task_index 2, not 1.
    let output = manager
        .spawn(
            vec![
                SubagentTaskSpec::new("Too many turns.", 10).expect("valid spec"),
                SubagentTaskSpec::new("Occupies slot.", 2).expect("valid spec"),
                SubagentTaskSpec::new("Exceeds max_threads.", 2).expect("valid spec"),
            ],
            None,
            CancellationToken::new(),
        )
        .await
        .expect("spawn succeeds");
    assert_eq!(output.spawned.len(), 1);
    assert_eq!(output.rejected.len(), 2);
    assert_eq!(output.rejected[0].task_index, 0);
    assert_eq!(output.rejected[1].task_index, 2);
    assert!(output.rejected[1].reason.contains("limit_behavior = fail"));
    manager.shutdown().await;
}

#[tokio::test(flavor = "current_thread")]
async fn mid_run_max_total_tokens_circuit_breaker_stops_child_before_next_turn() {
    use merry_core::{ToolInputSchema, ToolSpec};
    use merry_llm::{
        FinishReason, ModelEvent, ModelName, ModelOutput, ModelResponse, ModelToolCall,
        ModelToolCallId, ToolArguments, testing::FakeModelProvider,
    };

    let call = ModelToolCall::new(
        ModelToolCallId::new("tok-call-1").expect("valid id"),
        ToolName::new("noop_probe").expect("valid tool"),
        ToolArguments::try_from(json!({})).expect("valid args"),
    );
    let provider = Arc::new(FakeModelProvider::new_turns(vec![
        // Turn 1: calls tool and reports 50 tokens (> limit of 10).
        vec![Ok(ModelEvent::Completed {
            response: ModelResponse::new(
                vec![ModelOutput::tool_call(call)],
                FinishReason::ToolCalls,
                Some(merry_core::ModelUsage::new(30, 20)),
            ),
        })],
        // Turn 2: must NEVER be reached because circuit breaker fires after turn 1 usage!
        vec![Ok(ModelEvent::Completed {
            response: ModelResponse::new(
                vec![ModelOutput::text("should never run")],
                FinishReason::Stop,
                Some(merry_core::ModelUsage::new(10, 10)),
            ),
        })],
    ]));

    struct NoopExecutor;
    impl crate::ToolExecutor for NoopExecutor {
        fn execute<'a>(
            &'a self,
            _call: merry_core::PendingToolCall,
            _ctx: crate::ToolExecutionContext,
        ) -> crate::ToolExecutorFuture<'a> {
            Box::pin(async { Ok(crate::ToolExecutionOutcome::succeeded_text("ok")) })
        }
    }

    struct TokenLimitFactory {
        provider: Arc<FakeModelProvider>,
    }
    impl ChildRuntimeFactory for TokenLimitFactory {
        fn build_child(&self, input: ChildRuntimeInput) -> Result<Runtime, RuntimeError> {
            let schema = schemars::Schema::try_from(json!({ "type": "object" })).expect("schema");
            let spec = ToolSpec::new(
                ToolName::new("noop_probe").expect("valid name"),
                "Noop probe tool",
                ToolInputSchema::new(schema).expect("valid input schema"),
            )
            .expect("valid tool spec");
            Runtime::builder(input.session_id)
                .model_provider(
                    Arc::clone(&self.provider) as Arc<dyn merry_llm::ModelProvider>,
                    ModelName::new("test-model").expect("valid model"),
                )
                .register_tool(crate::RegisteredTool::read_only(
                    spec,
                    Arc::new(NoopExecutor),
                ))
                .build()
        }
    }

    let config = SubagentConfig::new(1, 1)
        .expect("valid config")
        .with_max_total_tokens(Some(10))
        .expect("valid token cap");
    let manager = SubagentManager::new(
        merry_core::SessionId::new("token-breaker").expect("valid session"),
        config,
        Arc::new(TokenLimitFactory {
            provider: Arc::clone(&provider),
        }),
    );
    let spawned = manager
        .spawn(
            vec![SubagentTaskSpec::new("Loop with tool.", 5).expect("valid task")],
            None,
            CancellationToken::new(),
        )
        .await
        .expect("spawn succeeds");
    let id = spawned.spawned[0].agent_id.clone();
    let waited = manager
        .wait(
            std::slice::from_ref(&id),
            WaitMode::All,
            Some(Duration::from_secs(5)),
        )
        .await
        .expect("wait succeeds");
    assert_eq!(waited.agents[0].status, SubagentStatusLabel::Blocked);
    assert_eq!(
        waited.agents[0].diagnostics.as_ref().map(|d| d.code()),
        Some("subagent_token_budget_exceeded")
    );
    assert_eq!(
        provider.recorded_requests().len(),
        1,
        "circuit breaker must stop child immediately before executing turn 2"
    );
}