merry-tools 0.1.0

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
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
//! Tests for tool path form, normalization, and scope boundaries.
//!
//! A relative tool path is resolved under the workspace root first and then
//! under each read-only resource root, so `dir/note.txt` and the absolute path
//! to that file address the same target and report the same workspace-relative
//! path. An absolute path that is not below the workspace root is the caller's
//! own way to name a file, so it is used exactly as written instead of being
//! matched against another anchor, and it is never denied by a second path
//! policy inside the tool. What remains the tools' own business is that a
//! relative path resolves below the root it was joined against, that a symlink
//! component below the workspace root is denied, and that a child agent cannot
//! leave the scope its parent gave it.

use super::*;

/// Returns the canonical workspace root, which is what the tools resolve against.
fn canonical_root(temp: &TempWorkspace) -> PathBuf {
    fs::canonicalize(temp.path()).expect("workspace root should canonicalize")
}

/// Returns a sibling path outside the workspace root for this test.
///
/// The name derives from the unique temp workspace name so parallel test runs
/// cannot collide, and the caller removes what it created.
fn sibling_of(root: &Path, suffix: &str) -> PathBuf {
    let name = root
        .file_name()
        .expect("workspace root should have a file name")
        .to_string_lossy();
    root.parent()
        .expect("workspace root should have a parent")
        .join(format!("{name}{suffix}"))
}

#[test]
fn read_file_absolute_resource_path_is_not_shadowed_by_a_workspace_file() {
    let temp = TempWorkspace::new("path-resource-anchor");
    let tools = tools_for(temp.path());
    let root = canonical_root(&temp);
    let resource = sibling_of(&root, "-resource");
    temp.write_text("demo/SKILL.md", "workspace copy\n");
    fs::create_dir_all(resource.join("demo")).expect("resource directory should be creatable");
    fs::write(resource.join("demo/SKILL.md"), "resource copy\n")
        .expect("resource file should be writable");
    let absolute = resource.join("demo/SKILL.md");
    let absolute_text = absolute.to_str().expect("resource path should be utf8");

    // The resource root is its own directory tree, so it holds a file with the
    // same relative path as the workspace copy. Naming the resource file must
    // read that file: resolving the components below a different root would
    // silently answer with the workspace file instead.
    let outcome = read_outcome(&tools, absolute_text);

    assert_eq!(outcome.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(
        json_content(&outcome)["content"],
        "resource copy\n",
        "an absolute path must name the file it was written for, not a same-named file below another root"
    );
    assert_eq!(
        json_content(&outcome)["path"],
        absolute_text,
        "a file outside the workspace root keeps its absolute spelling"
    );
    fs::remove_dir_all(&resource).expect("resource tree should be removable");
}

#[test]
fn apply_patch_absolute_path_edits_outside_file_and_not_the_workspace_copy() {
    let temp = TempWorkspace::new("path-absolute-anchor");
    let tools = tools_for(temp.path());
    let root = canonical_root(&temp);
    let outside = sibling_of(&root, "-outside.txt");
    temp.write_text("note.txt", "alpha\nold\nomega\n");
    fs::write(&outside, "alpha\nold\nomega\n").expect("outside file should be writable");
    let outside_text = outside.to_str().expect("outside path should be utf8");

    // Both files share a name, so an anchored patch must touch the sibling the
    // caller named and leave the same-named workspace file alone.
    let outcome = patch_text_outcome(&tools, &update_patch(outside_text, "old", "new"));

    assert_eq!(outcome.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(read_text(&outside), "alpha\nnew\nomega\n");
    assert_eq!(
        read_text(&temp.path().join("note.txt")),
        "alpha\nold\nomega\n",
        "a same-named workspace file must not receive the outside write"
    );
    fs::remove_file(&outside).expect("outside file should be removable");
}

#[test]
fn read_file_accepts_absolute_path_inside_the_workspace() {
    let temp = TempWorkspace::new("path-absolute-read");
    temp.write_text("dir/note.txt", "one\ntwo\n");
    let tools = tools_for(temp.path());
    let absolute = canonical_root(&temp).join("dir/note.txt");

    let outcome = read_outcome(
        &tools,
        absolute.to_str().expect("absolute path should be utf8"),
    );

    assert_eq!(outcome.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(
        json_content(&outcome)["path"],
        "dir/note.txt",
        "an absolute argument must be reported as a workspace-relative path"
    );
    assert!(
        !outcome
            .content()
            .as_str()
            .contains(canonical_root(&temp).to_str().expect("root utf8")),
        "tool output must not include absolute host roots"
    );
}

#[test]
fn apply_patch_accepts_absolute_path_inside_the_workspace() {
    let temp = TempWorkspace::new("path-absolute-patch");
    temp.write_text("dir/note.txt", "alpha\nold\nomega\n");
    let tools = tools_for(temp.path());
    let absolute = canonical_root(&temp).join("dir/note.txt");
    let patch = update_patch(
        absolute.to_str().expect("absolute path should be utf8"),
        "old",
        "new",
    );

    let outcome = patch_text_outcome(&tools, &patch);

    assert_eq!(outcome.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(
        json_content(&outcome)["changes"][0]["path"],
        "dir/note.txt",
        "the change must be reported relative to the workspace root"
    );
    assert_eq!(
        read_text(&temp.path().join("dir/note.txt")),
        "alpha\nnew\nomega\n"
    );
}

#[test]
fn read_file_reads_absolute_path_outside_the_workspace() {
    let temp = TempWorkspace::new("path-absolute-outside");
    let tools = tools_for(temp.path());
    let root = canonical_root(&temp);
    let outside = sibling_of(&root, "-outside.txt");
    fs::write(&outside, "outside\n").expect("outside file should be writable");
    let outside_text = outside.to_str().expect("outside path should be utf8");

    let outcome = read_outcome(&tools, outside_text);

    assert_eq!(
        outcome.status(),
        ToolCallResultStatus::Succeeded,
        "an absolute path outside the workspace is the caller's own reference, not a tool denial"
    );
    assert_eq!(json_content(&outcome)["content"], "outside\n");
    assert_eq!(
        json_content(&outcome)["path"],
        outside_text,
        "a target outside the workspace root has no workspace-relative spelling to report"
    );
    fs::remove_file(&outside).expect("outside file should be removable");
}

#[test]
fn apply_patch_edits_files_outside_the_workspace() {
    let temp = TempWorkspace::new("path-absolute-patch-outside");
    let tools = tools_for(temp.path());
    let root = canonical_root(&temp);
    let outside_dir = sibling_of(&root, "-outside");
    fs::create_dir_all(&outside_dir).expect("outside directory should be creatable");
    let existing = outside_dir.join("note.txt");
    fs::write(&existing, "alpha\nold\nomega\n").expect("outside file should be writable");
    let existing_text = existing.to_str().expect("outside path should be utf8");

    let update = patch_text_outcome(&tools, &update_patch(existing_text, "old", "new"));
    assert_eq!(update.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(read_text(&existing), "alpha\nnew\nomega\n");

    let created = outside_dir.join("dir/created.txt");
    let created_text = created.to_str().expect("outside path should be utf8");
    let add = patch_text_outcome(&tools, &add_patch(created_text, &["one", "two"]));
    assert_eq!(add.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(read_text(&created), "one\ntwo\n");

    let delete = patch_text_outcome(&tools, &delete_patch(existing_text));
    assert_eq!(delete.status(), ToolCallResultStatus::Succeeded);
    assert!(
        !existing.exists(),
        "a delete section must remove the file it names"
    );
    fs::remove_dir_all(&outside_dir).expect("outside directory should be removable");
}

#[test]
fn child_write_scope_denies_absolute_paths_outside_the_workspace() {
    let temp = TempWorkspace::new("path-child-write-scope");
    let scoped = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf())
            .with_patch_write_scope(Some(vec![PathBuf::from("allowed")])),
    )
    .expect("workspace tools should construct");
    let unscoped = tools_for(temp.path());
    let root = canonical_root(&temp);
    let outside = sibling_of(&root, "-outside.txt");
    fs::write(&outside, "alpha\nold\nomega\n").expect("outside file should be writable");
    let outside_text = outside.to_str().expect("outside path should be utf8");

    // The target is reachable and editable here, so the denial below is about the
    // child scope rather than about a path the tool refuses for its own reasons.
    let allowed = patch_text_outcome(&unscoped, &update_patch(outside_text, "old", "new"));
    assert_eq!(allowed.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(read_text(&outside), "alpha\nnew\nomega\n");
    fs::write(&outside, "alpha\nold\nomega\n").expect("outside file should be restored");

    let denied = patch_text_outcome(&scoped, &update_patch(outside_text, "old", "new"));

    assert_eq!(denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        denied.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );
    assert!(
        json_content(&denied)["error"]["message"]
            .as_str()
            .expect("message should be text")
            .contains("outside the configured write scope"),
        "a child agent must not leave its write scope by naming an absolute path"
    );
    assert_eq!(read_text(&outside), "alpha\nold\nomega\n");
    fs::remove_file(&outside).expect("outside file should be removable");
}

#[test]
fn read_only_write_scope_still_allows_durable_memory_observations() {
    let temp = TempWorkspace::new("path-memory-write-scope");
    let root = canonical_root(&temp);
    let memory_root = sibling_of(&root, "-memory");
    fs::create_dir_all(&memory_root).expect("memory root should be created");
    let memory = merry_runtime::DurableMemory::open(
        merry_runtime::MemoryLayout::at(&memory_root, temp.path())
            .expect("memory layout should resolve"),
    )
    .expect("memory store should open");
    let note = memory
        .layout()
        .workspace_dir()
        .join("observations/_inbox/note.md");
    let tools = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf())
            .with_patch_write_scope(Some(Vec::new()))
            .with_durable_memory(memory),
    )
    .expect("workspace tools should construct");
    let note_text = note.to_str().expect("memory note path should be utf8");

    let created = patch_text_outcome(&tools, &add_patch(note_text, &["# Note", "", "A fact."]));
    assert_eq!(created.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(read_text(&note), "# Note\n\nA fact.\n");

    let outside = sibling_of(&root, "-nope.txt");
    let outside_text = outside.to_str().expect("outside path should be utf8");
    let denied = patch_text_outcome(&tools, &add_patch(outside_text, &["no"]));
    assert_eq!(denied.status(), ToolCallResultStatus::Failed);
    assert!(
        json_content(&denied)["error"]["message"]
            .as_str()
            .expect("message should be text")
            .contains("this write scope allows no workspace files")
    );
    assert!(
        !outside.exists(),
        "a read-only scope must not create workspace files"
    );
    fs::remove_dir_all(&memory_root).expect("memory root should be removable");
}

#[cfg(unix)]
#[test]
fn read_file_follows_platform_symlinks_outside_the_workspace() {
    let temp = TempWorkspace::new("path-outside-symlink");
    let tools = tools_for(temp.path());
    let root = canonical_root(&temp);
    let target_dir = sibling_of(&root, "-linked");
    let link_dir = sibling_of(&root, "-link");
    fs::create_dir_all(&target_dir).expect("linked directory should be creatable");
    fs::write(target_dir.join("note.txt"), "linked\n").expect("linked file should be writable");
    symlink(&target_dir, &link_dir).expect("directory symlink should be created");

    // Platform layout routinely exposes a real directory through a link, so a
    // target outside the workspace is resolved as the caller named it instead of
    // being denied for a component the sandbox already allows.
    let linked = link_dir.join("note.txt");
    let outcome = read_outcome(&tools, linked.to_str().expect("linked path should be utf8"));

    assert_eq!(outcome.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(json_content(&outcome)["content"], "linked\n");
    fs::remove_file(link_dir.as_path()).expect("directory symlink should be removable");
    fs::remove_dir_all(&target_dir).expect("linked directory should be removable");
}

#[test]
fn workspace_path_normalizes_dot_segments_and_resolves_escapes() {
    let temp = TempWorkspace::new("path-dot-segments");
    temp.write_text("dir/note.txt", "one\ntwo\n");
    let tools = tools_for(temp.path());
    let root = canonical_root(&temp);

    let inside = read_outcome(&tools, "./dir/../dir/note.txt");
    assert_eq!(
        inside.status(),
        ToolCallResultStatus::Succeeded,
        "redundant dot segments name the same file and must not be rejected"
    );
    assert_eq!(json_content(&inside)["path"], "dir/note.txt");

    // A relative argument may climb above its root: the target is the caller's
    // own reference, and the reported path keeps the `..` so the escape stays
    // visible instead of being silently rewritten as an in-root path.
    let sibling = sibling_of(&root, "-climbed.txt");
    fs::write(&sibling, "climbed\n").expect("sibling file should be writable");
    let named = sibling
        .strip_prefix(root.parent().expect("root parent"))
        .expect("sibling is below the shared parent");
    let climbed = read_outcome(&tools, &format!("../{}", named.display()));
    assert_eq!(
        climbed.status(),
        ToolCallResultStatus::Succeeded,
        "a relative path that climbs above the root names a real file"
    );
    assert_eq!(json_content(&climbed)["content"], "climbed\n");
    assert_eq!(
        json_content(&climbed)["path"],
        format!("../{}", named.display()),
        "the reported path keeps the escape visible"
    );
    fs::remove_file(&sibling).expect("sibling file should be removable");
}

#[test]
fn workspace_path_denies_the_root_itself_and_reads_prefix_lookalikes() {
    let temp = TempWorkspace::new("path-root-lookalike");
    temp.write_text("dir/note.txt", "one\ntwo\n");
    let tools = tools_for(temp.path());
    let root = canonical_root(&temp);
    let root_text = root.to_str().expect("root path should be utf8");

    let as_root = read_outcome(&tools, root_text);
    assert_failed_json(&as_root, ERROR_PATH_DENIED, None, root.as_path());
    assert!(
        json_content(&as_root)["error"]["message"]
            .as_str()
            .expect("message should be text")
            .contains("not the root itself"),
        "the root is a directory to browse, never a file to read"
    );

    // A sibling directory that merely shares the root's name prefix is not
    // inside the workspace, so prefix matching must compare whole components
    // rather than treat the sibling as part of the root.
    let lookalike_dir = sibling_of(&root, "-lookalike");
    fs::create_dir_all(lookalike_dir.join("dir")).expect("lookalike tree should be creatable");
    fs::write(lookalike_dir.join("dir/note.txt"), "sibling\n")
        .expect("lookalike file should be writable");
    let lookalike = lookalike_dir.join("dir/note.txt");
    let lookalike_text = lookalike.to_str().expect("lookalike path should be utf8");

    let sibling = read_outcome(&tools, lookalike_text);
    assert_eq!(
        sibling.status(),
        ToolCallResultStatus::Succeeded,
        "a sibling that shares the root's name prefix is its own target"
    );
    assert_eq!(json_content(&sibling)["content"], "sibling\n");
    assert_eq!(
        json_content(&sibling)["path"],
        lookalike_text,
        "the sibling is not inside the workspace root, so it is reported absolute"
    );
    fs::remove_dir_all(&lookalike_dir).expect("lookalike tree should be removable");
}

#[test]
fn workspace_path_reads_hidden_components_after_normalization() {
    let temp = TempWorkspace::new("path-hidden-after-normalization");
    temp.write_text(".git/config", "[core]\n");
    let tools = tools_for(temp.path());

    let outcome = read_outcome(&tools, "dir/../.git/config");
    assert_eq!(
        outcome.status(),
        ToolCallResultStatus::Succeeded,
        "a leading dot is ordinary spelling and must survive normalization"
    );
    assert_eq!(
        json_content(&outcome)["path"],
        ".git/config",
        "the reported path is the normalized workspace-relative form"
    );
    assert_eq!(json_content(&outcome)["content"], "[core]\n");
}

#[test]
fn denied_absolute_paths_block_read_file_and_apply_patch() {
    let temp = TempWorkspace::new("path-denied-absolute");
    let root = canonical_root(&temp);
    let private_dir = sibling_of(&root, "-private-state");
    let secret_file = private_dir.join("managed/secrets/openai.key");
    fs::create_dir_all(secret_file.parent().expect("secret parent"))
        .expect("private dir should be created");
    fs::write(&secret_file, "sk-top-secret\n").expect("secret file should write");

    let allowed_dir = sibling_of(&root, "-config-dir");
    let allowed_file = allowed_dir.join("config.toml");
    fs::create_dir_all(&allowed_dir).expect("allowed dir should be created");
    fs::write(&allowed_file, "profile = 'coding'\n").expect("allowed file should write");

    let tools = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf())
            .with_denied_absolute_paths(vec![private_dir.clone()]),
    )
    .expect("workspace tools should construct");

    let secret_text = secret_file.to_str().expect("secret path should be utf8");
    let read_denied = read_outcome(&tools, secret_text);
    assert_eq!(read_denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        read_denied.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );

    let climbed = format!(
        "../{}/managed/secrets/openai.key",
        private_dir
            .file_name()
            .expect("private dir name")
            .to_str()
            .expect("utf8")
    );
    let climbed_read_denied = read_outcome(&tools, &climbed);
    assert_eq!(climbed_read_denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        climbed_read_denied.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );

    let update_denied = patch_text_outcome(
        &tools,
        &update_patch(secret_text, "sk-top-secret", "sk-tampered"),
    );
    assert_eq!(update_denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        update_denied.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );

    let added_secret = private_dir.join("managed/secrets/new.key");
    let add_denied = patch_text_outcome(
        &tools,
        &add_patch(added_secret.to_str().expect("utf8"), &["sk-new"]),
    );
    assert_eq!(add_denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        add_denied.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );
    assert!(!added_secret.exists());

    let delete_denied = patch_text_outcome(&tools, &delete_patch(secret_text));
    assert_eq!(delete_denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        delete_denied.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );
    assert_eq!(read_text(&secret_file), "sk-top-secret\n");

    // Paths outside denied_absolute_paths remain readable and editable.
    let allowed_text = allowed_file.to_str().expect("allowed path should be utf8");
    let read_allowed = read_outcome(&tools, allowed_text);
    assert_eq!(read_allowed.status(), ToolCallResultStatus::Succeeded);
    let update_allowed = patch_text_outcome(
        &tools,
        &update_patch(allowed_text, "profile = 'coding'", "profile = 'updated'"),
    );
    assert_eq!(update_allowed.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(read_text(&allowed_file), "profile = 'updated'\n");

    fs::remove_dir_all(&private_dir).expect("private dir should be removable");
    fs::remove_dir_all(&allowed_dir).expect("allowed dir should be removable");
}