merry-tools 0.1.3

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
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! 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");
}

#[derive(Debug)]
struct TestExternalTreePolicy {
    root: PathBuf,
    read_paths: std::sync::Mutex<Vec<PathBuf>>,
    committed_paths: std::sync::Mutex<Vec<PathBuf>>,
}

impl TestExternalTreePolicy {
    fn new(root: PathBuf) -> Self {
        Self {
            root,
            read_paths: std::sync::Mutex::new(Vec::new()),
            committed_paths: std::sync::Mutex::new(Vec::new()),
        }
    }
}

impl crate::ExternalTreePolicy for TestExternalTreePolicy {
    fn root(&self) -> &Path {
        &self.root
    }

    fn governs_path(&self, path: &Path) -> bool {
        path.starts_with(&self.root)
    }

    fn on_text_read(&self, path: &Path) -> Result<(), String> {
        if self.governs_path(path) {
            self.read_paths
                .lock()
                .expect("read lock")
                .push(path.to_path_buf());
        }
        Ok(())
    }

    fn authorize_write(
        &self,
        kind: crate::ExternalWriteKind,
        path: &Path,
        _byte_len: usize,
    ) -> Result<(), String> {
        if !self.governs_path(path) {
            return Ok(());
        }
        if matches!(
            kind,
            crate::ExternalWriteKind::Update | crate::ExternalWriteKind::Delete
        ) && !self
            .read_paths
            .lock()
            .expect("read lock")
            .iter()
            .any(|seen| seen == path)
        {
            return Err("external tree requires reading a file before updating it".to_owned());
        }
        Ok(())
    }

    fn on_writes_committed(&self, paths: &[PathBuf]) -> Result<(), String> {
        self.committed_paths
            .lock()
            .expect("committed lock")
            .extend(paths.iter().cloned());
        Ok(())
    }
}

#[test]
fn read_only_write_scope_still_allows_governed_external_tree_writes() {
    let temp = TempWorkspace::new("path-memory-write-scope");
    let root = canonical_root(&temp);
    let external_root = sibling_of(&root, "-memory");
    fs::create_dir_all(&external_root).expect("external root should be created");
    let external_root = fs::canonicalize(&external_root).expect("canonical external root");
    let tree_policy = std::sync::Arc::new(TestExternalTreePolicy::new(external_root.clone()));
    let note = external_root.join("observations/_inbox/note.md");
    let tools = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf())
            .with_patch_write_scope(Some(Vec::new()))
            .with_external_tree_policy(tree_policy.clone()),
    )
    .expect("workspace tools should construct");
    let note_text = note.to_str().expect("external 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");
    assert_eq!(
        tree_policy.committed_paths.lock().expect("committed").len(),
        1
    );

    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(&external_root).expect("external root should be removable");
}

#[test]
fn write_forbidden_paths_block_patches_without_blocking_reads() {
    let temp = TempWorkspace::new("path-write-forbidden");
    temp.write_text(".git/config", "[core]\n");
    let tools = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf())
            .with_write_forbidden_paths(vec![PathBuf::from(".git")]),
    )
    .expect("workspace tools should construct");

    let read = read_outcome(&tools, ".git/config");
    assert_eq!(read.status(), ToolCallResultStatus::Succeeded);

    let patch = patch_text_outcome(&tools, &update_patch(".git/config", "[core]", "[changed]"));
    assert_eq!(patch.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        patch.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );
}

#[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 host_path_policy_blocks_credentials_and_allows_readonly_state_dir() {
    let temp = TempWorkspace::new("path-denied-absolute");
    let root = canonical_root(&temp);
    let state_dir = sibling_of(&root, "-private-state");
    let providers_dir = sibling_of(&root, "-providers");
    let trust_file = state_dir.join("workspace-trust.json");
    let input_history_file = state_dir.join("input-history/workspace.jsonl");
    let log_file = state_dir.join("logs/merry.jsonl");
    let journal_file = state_dir.join("sessions/sess-1/journal.jsonl");
    let secret_file = providers_dir.join("secrets/openai.key");
    let nested_secret = state_dir.join("external.key");
    fs::create_dir_all(journal_file.parent().expect("journal parent"))
        .expect("journal dir should be created");
    fs::create_dir_all(input_history_file.parent().expect("input history parent"))
        .expect("input history dir should be created");
    fs::create_dir_all(log_file.parent().expect("log parent")).expect("log dir should be created");
    fs::create_dir_all(secret_file.parent().expect("secret parent"))
        .expect("providers dir should be created");
    fs::write(&trust_file, "{}\n").expect("trust file should write");
    fs::write(&input_history_file, "\"hello\"\n").expect("input history should write");
    fs::write(&log_file, "{\"level\":\"INFO\"}\n").expect("log file should write");
    fs::write(&journal_file, "{\"event\":\"started\"}\n").expect("journal file should write");
    fs::write(&secret_file, "sk-top-secret\n").expect("secret file should write");
    fs::write(&nested_secret, "sk-nested-secret\n").expect("nested secret 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 policy =
        merry_core::HostPathPolicy::from_merry_dirs(state_dir.clone(), providers_dir.clone())
            .extend_denied([nested_secret.clone()]);
    let tools = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf()).with_host_path_policy(policy),
    )
    .expect("workspace tools should construct");

    // Provider credentials and explicitly denied secrets stay unreadable and unwritable.
    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 nested_secret_text = nested_secret
        .to_str()
        .expect("nested secret path should be utf8");
    let nested_secret_read_denied = read_outcome(&tools, nested_secret_text);
    assert_eq!(
        nested_secret_read_denied.status(),
        ToolCallResultStatus::Failed
    );
    assert_eq!(
        nested_secret_read_denied
            .diagnostic()
            .expect("diagnostic")
            .code(),
        ERROR_PATH_DENIED
    );

    let climbed = format!(
        "../{}/secrets/openai.key",
        providers_dir
            .file_name()
            .expect("providers 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 = providers_dir.join("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");

    // Merry's entire state directory (sessions, input history, logs, trust/prefs)
    // is readable by default, while remaining strictly non-writable.
    for (path, expected) in [
        (&journal_file, "{\"event\":\"started\"}\n"),
        (&input_history_file, "\"hello\"\n"),
        (&log_file, "{\"level\":\"INFO\"}\n"),
        (&trust_file, "{}\n"),
    ] {
        let path_text = path.to_str().expect("state path should be utf8");
        let read = read_outcome(&tools, path_text);
        assert_eq!(read.status(), ToolCallResultStatus::Succeeded);
        assert_eq!(json_content(&read)["content"], expected);
    }

    let journal_text = journal_file.to_str().expect("journal path should be utf8");
    let journal_update_denied = patch_text_outcome(
        &tools,
        &update_patch(
            journal_text,
            "{\"event\":\"started\"}",
            "{\"event\":\"tampered\"}",
        ),
    );
    assert_eq!(journal_update_denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        journal_update_denied
            .diagnostic()
            .expect("diagnostic")
            .code(),
        ERROR_PATH_DENIED
    );
    let trust_text = trust_file.to_str().expect("trust path should be utf8");
    let trust_update_denied =
        patch_text_outcome(&tools, &update_patch(trust_text, "{}", "{\"t\":1}"));
    assert_eq!(trust_update_denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        trust_update_denied.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );
    let journal_delete_denied = patch_text_outcome(&tools, &delete_patch(journal_text));
    assert_eq!(journal_delete_denied.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        journal_delete_denied
            .diagnostic()
            .expect("diagnostic")
            .code(),
        ERROR_PATH_DENIED
    );
    assert_eq!(read_text(&journal_file), "{\"event\":\"started\"}\n");
    assert_eq!(read_text(&trust_file), "{}\n");

    // Paths outside denied/readonly product trees 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(&state_dir).expect("state dir should be removable");
    fs::remove_dir_all(&providers_dir).expect("providers dir should be removable");
    fs::remove_dir_all(&allowed_dir).expect("allowed dir should be removable");
}

#[test]
fn host_path_policy_allows_nested_memory_writes_and_denies_nested_providers_under_state_dir() {
    let temp = TempWorkspace::new("path-shared-state-data");
    let root = canonical_root(&temp);
    let shared_merry_dir = sibling_of(&root, "-localappdata-merry");
    let providers_dir = shared_merry_dir.join("providers");
    let memory_root = shared_merry_dir.join("memory");
    let journal_file = shared_merry_dir.join("sessions/s1/journal.jsonl");
    let secret_file = providers_dir.join("secrets/openai.key");
    fs::create_dir_all(journal_file.parent().expect("journal parent")).expect("journal dir");
    fs::create_dir_all(secret_file.parent().expect("secret parent")).expect("providers dir");
    fs::create_dir_all(&memory_root).expect("memory dir");
    fs::write(&journal_file, "{\"event\":\"ok\"}\n").expect("journal write");
    fs::write(&secret_file, "sk-shared-secret\n").expect("secret write");

    let memory_root = fs::canonicalize(&memory_root).expect("canonical memory dir");
    let tree_policy = std::sync::Arc::new(TestExternalTreePolicy::new(memory_root.clone()));
    let memory_note = memory_root.join("topics/sandbox.md");
    fs::create_dir_all(memory_note.parent().expect("topics dir")).expect("topics dir");
    fs::write(&memory_note, "# Sandbox\n\nOld note.\n").expect("memory note write");

    let policy = merry_core::HostPathPolicy::from_merry_dirs(
        shared_merry_dir.clone(),
        providers_dir.clone(),
    )
    .with_durable_memory_root(Some(memory_root));
    let tools = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf())
            .with_host_path_policy(policy)
            .with_external_tree_policy(tree_policy),
    )
    .expect("workspace tools should construct");

    let journal_text = journal_file.to_str().expect("utf8 journal");
    let read_journal = read_outcome(&tools, journal_text);
    assert_eq!(read_journal.status(), ToolCallResultStatus::Succeeded);
    let patch_journal = patch_text_outcome(
        &tools,
        &update_patch(journal_text, "{\"event\":\"ok\"}", "{\"event\":\"bad\"}"),
    );
    assert_eq!(patch_journal.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        patch_journal.diagnostic().expect("diagnostic").code(),
        ERROR_PATH_DENIED
    );

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

    let note_text = memory_note.to_str().expect("utf8 note");
    let read_note = read_outcome(&tools, note_text);
    assert_eq!(read_note.status(), ToolCallResultStatus::Succeeded);
    let patch_note = patch_text_outcome(&tools, &update_patch(note_text, "Old note.", "New note."));
    assert_eq!(patch_note.status(), ToolCallResultStatus::Succeeded);
    assert_eq!(read_text(&memory_note), "# Sandbox\n\nNew note.\n");

    fs::remove_dir_all(&shared_merry_dir).expect("shared dir should be removable");
}