merry-tools 0.1.2

Workspace file, search, patch, web fetch, and document tools for the Merry agent runtime.
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
use super::support::*;

#[tokio::test(flavor = "current_thread")]
async fn registered_apply_patch_tool_is_policy_denied_before_mutating_file() {
    let temp = TempWorkspace::new("patch-policy-denied");
    temp.write_text("note.txt", "alpha\nold\nomega\n");
    let runtime =
        runtime_with_apply_patch_tools(temp.path(), pending_patch_call("note.txt", "old", "new"));

    let pending_events = collect_step(&runtime, "patch note").await;
    assert_eq!(
        event_kind_names(&pending_events),
        ["SessionStarted", "StepStarted", "ToolCallPending"]
    );
    let pending = runtime
        .pending_tool_calls()
        .await
        .into_iter()
        .next()
        .expect("pending call should be stored");

    let execution_events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("runtime policy denial should resolve pending call");

    assert_eq!(event_kind_names(&execution_events), ["ToolCallResolved"]);
    let result = resolved_tool_result(&execution_events);
    assert_eq!(result.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        result
            .diagnostic()
            .expect("policy denial should include diagnostic")
            .code(),
        "action_policy_denied"
    );
    assert_eq!(
        fs::read_to_string(temp.path().join("note.txt")).expect("workspace file should read"),
        "alpha\nold\nomega\n"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn denied_apply_patch_leaves_file_unchanged_and_returns_sanitized_result() {
    let temp = TempWorkspace::new("patch-policy-proposed");
    temp.write_text("note.txt", "alpha\nold\nomega\n");
    let runtime =
        runtime_with_apply_patch_tools(temp.path(), pending_patch_call("note.txt", "old", "new"));
    let _pending_events = collect_step(&runtime, "patch note").await;
    let pending = runtime
        .pending_tool_calls()
        .await
        .into_iter()
        .next()
        .expect("pending call should be stored");

    let execution_events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("runtime policy denial should resolve pending call");

    assert_eq!(
        fs::read_to_string(temp.path().join("note.txt")).expect("workspace file should read"),
        "alpha\nold\nomega\n"
    );
    let result = resolved_tool_result(&execution_events);
    assert_eq!(result.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        result
            .diagnostic()
            .expect("policy denial should include diagnostic")
            .code(),
        "action_policy_denied"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn opt_in_apply_patch_tool_applies_patch_and_records_artifact_before_resolution() {
    let temp = TempWorkspace::new("patch-opt-in-success");
    temp.write_text("note.txt", "alpha\nold\nomega\n");
    let runtime = runtime_with_opt_in_apply_patch_tools(
        temp.path(),
        pending_patch_call("note.txt", "old", "new"),
    );

    let pending_events = collect_step(&runtime, "patch note").await;
    assert_eq!(
        event_kind_names(&pending_events),
        ["SessionStarted", "StepStarted", "ToolCallPending"]
    );
    let pending = runtime
        .pending_tool_calls()
        .await
        .into_iter()
        .next()
        .expect("pending call should be stored");

    let execution_events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("opted-in workspace patch should execute");

    assert_eq!(
        fs::read_to_string(temp.path().join("note.txt")).expect("workspace file should read"),
        "alpha\nnew\nomega\n"
    );
    assert_succeeded_json_result(&execution_events);
    assert!(runtime.pending_tool_calls().await.is_empty());
}

#[tokio::test(flavor = "current_thread")]
async fn opt_in_apply_patch_tool_adds_new_file_through_runtime() {
    let temp = TempWorkspace::new("patch-opt-in-add-success");
    fs::create_dir_all(temp.path().join("notes")).expect("parent directory should be created");
    let runtime = runtime_with_opt_in_apply_patch_tools(
        temp.path(),
        pending_add_patch_call("notes/new.txt", &["alpha", "beta"]),
    );

    let execution_events = execute_first_pending_call(&runtime, "add a new note").await;

    assert_eq!(
        fs::read_to_string(temp.path().join("notes/new.txt"))
            .expect("new workspace file should read"),
        "alpha\nbeta\n"
    );
    assert_succeeded_json_result(&execution_events);
}

#[tokio::test(flavor = "current_thread")]
async fn opt_in_apply_patch_preflight_failure_resolves_with_patch_diagnostic() {
    let temp = TempWorkspace::new("patch-opt-in-preflight-failure");
    temp.write_text("note.txt", "alpha\nold\nomega\n");
    let runtime = runtime_with_opt_in_apply_patch_tools(
        temp.path(),
        pending_patch_call("note.txt", "missing", "new"),
    );

    let _pending_events = collect_step(&runtime, "patch note").await;
    let pending = runtime
        .pending_tool_calls()
        .await
        .into_iter()
        .next()
        .expect("pending call should be stored");

    let execution_events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("patch preflight failure should resolve as a failed tool result");

    assert_eq!(
        fs::read_to_string(temp.path().join("note.txt")).expect("workspace file should read"),
        "alpha\nold\nomega\n"
    );
    assert_failed_json_result(&execution_events, "apply_patch_preimage_absent");
}

#[tokio::test(flavor = "current_thread")]
async fn opt_in_patch_success_continuation_does_not_leak_internal_evidence() {
    let temp = TempWorkspace::new("patch-opt-in-no-leak");
    temp.write_text("note.txt", "alpha\nold\nomega\n");
    let provider = ScriptedModelProvider::new(vec![
        vec![Ok(pending_patch_call("note.txt", "old", "new"))],
        vec![Ok(ModelEvent::Completed {
            response: ModelResponse::new(
                vec![ModelOutput::text("continued after patch")],
                FinishReason::Stop,
                None,
            ),
        })],
    ]);
    let provider_handle = provider.clone();
    let runtime = runtime_with_opt_in_apply_patch_tools_and_provider(temp.path(), provider);
    let _pending_events = collect_step(&runtime, "patch note").await;
    let pending = runtime
        .pending_tool_calls()
        .await
        .into_iter()
        .next()
        .expect("pending call should be stored");

    let execution_events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("opted-in workspace patch should execute");
    assert_succeeded_json_result(&execution_events);

    let _continuation_events = collect_step(&runtime, "continue after patch").await;
    let requests = provider_handle.recorded_requests();
    let continuation = requests[1]
        .continuations()
        .first()
        .expect("successful tool result should be compiled as continuation");
    assert_eq!(
        continuation.result().status(),
        ToolCallResultStatus::Succeeded
    );
    assert_eq!(
        continuation.result().content().as_text(),
        Some("Applied patch:\nupdated note.txt")
    );
    let result = resolved_tool_result(&execution_events);
    let full = runtime
        .read_tool_output(result.call_id())
        .await
        .expect("full patch output read")
        .expect("full patch output exists");
    assert_successful_patch_content_does_not_leak_internal_metadata(full.as_str());
}

#[tokio::test(flavor = "current_thread")]
async fn patch_proposal_and_audit_do_not_leak_into_sanitized_result_or_continuation() {
    let temp = TempWorkspace::new("patch-policy-no-leak");
    temp.write_text("note.txt", "alpha\nold\nomega\n");
    let tools = WorkspaceTools::new(WorkspaceToolsConfig::new(temp.path().to_path_buf()))
        .expect("workspace tools should construct");
    let provider = ScriptedModelProvider::new(vec![
        vec![Ok(pending_patch_call("note.txt", "old", "new"))],
        vec![Ok(ModelEvent::Completed {
            response: ModelResponse::new(
                vec![ModelOutput::text("continued after denial")],
                FinishReason::Stop,
                None,
            ),
        })],
    ]);
    let provider_handle = provider.clone();
    let mut builder =
        Runtime::builder(session_id()).model_provider(Arc::new(provider), model_name());
    for tool in tools.into_registered_tools_with_patch() {
        builder = builder.register_tool(tool);
    }
    let runtime = builder.build().expect("runtime should build");
    let _pending_events = collect_step(&runtime, "patch note").await;
    let pending = runtime
        .pending_tool_calls()
        .await
        .into_iter()
        .next()
        .expect("pending call should be stored");
    let execution_events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("runtime policy denial should resolve pending call");

    let result = resolved_tool_result(&execution_events);
    assert_eq!(result.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        result
            .diagnostic()
            .expect("policy denial should include diagnostic")
            .code(),
        "action_policy_denied"
    );

    let _continuation_events = collect_step(&runtime, "continue after denial").await;
    let requests = provider_handle.recorded_requests();
    let continuation = requests[1]
        .continuations()
        .first()
        .expect("denied tool result should be compiled as continuation");
    let ModelToolResultContent::Json(continuation_json) = continuation.result().content() else {
        panic!("denial continuation should be JSON");
    };
    assert_eq!(continuation.result().status(), ToolCallResultStatus::Failed);
    assert_eq!(
        continuation
            .result()
            .diagnostic()
            .expect("denial continuation should include diagnostic")
            .code(),
        "action_policy_denied"
    );
    assert_patch_denial_json_sanitized(continuation_json, APPLY_PATCH_TOOL);
}

#[tokio::test(flavor = "current_thread")]
async fn opt_in_apply_patch_tool_deletes_file_and_reports_the_operation() {
    let temp = TempWorkspace::new("patch-opt-in-delete-success");
    temp.write_text("dir/gone.txt", "alpha\nbeta\n");
    let provider = ScriptedModelProvider::new(vec![
        vec![Ok(pending_delete_patch_call("dir/gone.txt"))],
        vec![Ok(ModelEvent::Completed {
            response: ModelResponse::new(
                vec![ModelOutput::text("continued after delete")],
                FinishReason::Stop,
                None,
            ),
        })],
    ]);
    let provider_handle = provider.clone();
    let runtime = runtime_with_opt_in_apply_patch_tools_and_provider(temp.path(), provider);
    let _pending_events = collect_step(&runtime, "delete the old note").await;
    let pending = runtime
        .pending_tool_calls()
        .await
        .into_iter()
        .next()
        .expect("pending call should be stored");

    let execution_events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("opted-in delete should execute");

    assert_succeeded_json_result(&execution_events);
    assert!(
        !temp.path().join("dir/gone.txt").exists(),
        "an executed delete must remove the file"
    );
    assert!(
        temp.path().join("dir").is_dir(),
        "deleting a file must leave its parent directory in place"
    );

    // The provider-visible result is what the model sees, so it must name the
    // removal instead of leaving a delete and an emptied file indistinguishable.
    let _continuation_events = collect_step(&runtime, "continue after delete").await;
    let requests = provider_handle.recorded_requests();
    let continuation = requests[1]
        .continuations()
        .first()
        .expect("successful tool result should be compiled as continuation");
    assert_eq!(
        continuation.result().status(),
        ToolCallResultStatus::Succeeded
    );
    assert_eq!(
        continuation.result().content().as_text(),
        Some("Applied patch:\ndeleted dir/gone.txt")
    );
    let result = resolved_tool_result(&execution_events);
    let full = runtime
        .read_tool_output(result.call_id())
        .await
        .expect("full delete output read")
        .expect("full delete output exists");
    let envelope: Value =
        serde_json::from_str(full.as_str()).expect("delete result should be JSON");
    assert_eq!(envelope["ok"], true);
    assert_eq!(envelope["tool"], APPLY_PATCH_TOOL);
    assert_eq!(envelope["changes"][0]["path"], "dir/gone.txt");
    assert_eq!(envelope["changes"][0]["op"], "delete");
    assert_eq!(envelope["changes"][0]["lines_before"], 2);
    assert_eq!(envelope["changes"][0]["lines_after"], 0);
    assert_eq!(envelope["changes"][0]["bytes_after"], 0);
}

#[tokio::test(flavor = "current_thread")]
async fn policy_denied_delete_resolves_without_removing_the_file() {
    let temp = TempWorkspace::new("patch-delete-policy-denied");
    temp.write_text("note.txt", "alpha\n");
    let runtime =
        runtime_with_apply_patch_tools(temp.path(), pending_delete_patch_call("note.txt"));

    let _pending_events = collect_step(&runtime, "delete the note").await;
    let pending = runtime
        .pending_tool_calls()
        .await
        .into_iter()
        .next()
        .expect("pending call should be stored");

    let execution_events = runtime
        .execute_tool_call(pending.id(), ToolExecutionContext::default())
        .await
        .expect("runtime policy denial should resolve pending call");

    assert_failed_json_result(&execution_events, "action_policy_denied");
    assert_eq!(
        fs::read_to_string(temp.path().join("note.txt")).expect("workspace file should read"),
        "alpha\n",
        "a denied delete must leave the file unchanged"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn delete_outside_the_write_scope_is_denied_and_keeps_the_file() {
    let temp = TempWorkspace::new("patch-delete-scope-denied");
    temp.write_text("allowed/note.txt", "alpha\n");
    temp.write_text("denied/note.txt", "alpha\n");
    let tools = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf())
            .with_patch_write_scope(Some(vec![PathBuf::from("allowed")])),
    )
    .expect("workspace tools should construct");
    let provider = FakeModelProvider::new(vec![Ok(pending_delete_patch_call("denied/note.txt"))]);
    let mut builder = Runtime::builder(session_id())
        .model_provider(Arc::new(provider), model_name())
        .allow_low_risk_apply_patches();
    for tool in tools.into_registered_tools_with_patch() {
        builder = builder.register_tool(tool);
    }
    let runtime = builder.build().expect("runtime should build");

    let execution_events =
        execute_first_pending_call(&runtime, "delete a note outside scope").await;

    assert_failed_json_result(&execution_events, "workspace_path_denied");
    assert_eq!(
        fs::read_to_string(temp.path().join("denied/note.txt")).expect("denied file should read"),
        "alpha\n",
        "a delete outside the write scope must leave the file unchanged"
    );
    assert!(
        temp.path().join("allowed/note.txt").exists(),
        "a denied delete must not remove an unrelated file"
    );
}