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
use std::{
    collections::BTreeSet,
    fs,
    path::{Component, PathBuf},
    sync::Arc,
};

use merry_core::HostPathPolicy;
use merry_runtime::{
    LivePolicyHandle, PathAccess, PathAccessDecision, PathAccessRule, PathEvaluation,
    PermissionedAction, RequestedCapability, RequestedPathCapability, ToolPermissionRequirement,
    normalize_path_lexically, once_grants_cover_path, resolve_path_with_existing_ancestor,
};

use crate::{
    config::{WorkspaceToolConfigError, WorkspaceToolLimits, WorkspaceToolsConfig},
    errors::{DomainError, ERROR_PATH_DENIED},
    external_tree::ExternalTreePolicy,
    path::ValidatedToolPath,
};

#[derive(Debug)]
pub(crate) struct WorkspaceToolState {
    pub(crate) root: PathBuf,
    pub(crate) readonly_resource_roots: Vec<PathBuf>,
    pub(crate) limits: WorkspaceToolLimits,
    pub(crate) read_scope: Option<Vec<String>>,
    pub(crate) patch_write_scope: Option<Vec<String>>,
    pub(crate) read_forbidden_paths: Vec<String>,
    pub(crate) forbidden_paths: Vec<String>,
    pub(crate) host_path_policy: HostPathPolicy,
    pub(crate) access_policy: Option<LivePolicyHandle>,
    pub(crate) external_tree_policy: Option<Arc<dyn ExternalTreePolicy>>,
}

/// Outcome returned when `read_file` checks [`LivePolicyHandle`].
pub(crate) enum ReadAccessPolicyError {
    /// Hard-denied by a static policy ceiling or non-requestable path.
    Denied(DomainError),
    /// Outside current grants; runtime must review before retrying.
    PermissionRequired(Box<ToolPermissionRequirement>),
}

impl WorkspaceToolState {
    pub(crate) fn new(config: WorkspaceToolsConfig) -> Result<Self, WorkspaceToolConfigError> {
        validate_limits(&config.limits)?;

        let root = canonical_root(config.root)?;
        let mut readonly_resource_roots = Vec::with_capacity(config.readonly_resource_roots.len());
        for resource_root in config.readonly_resource_roots {
            if let Some(canonical) = canonical_optional_root(resource_root)?
                && canonical != root
            {
                readonly_resource_roots.push(canonical);
            }
        }

        let read_scope = match config.read_scope {
            Some(paths) => Some(normalize_scope_paths(paths)?),
            None => None,
        };
        let patch_write_scope = match config.patch_write_scope {
            Some(paths) => Some(normalize_scope_paths(paths)?),
            None => None,
        };
        let read_forbidden_paths = normalize_scope_paths(config.forbidden_paths)?;
        let mut forbidden_paths = read_forbidden_paths.clone();
        for path in normalize_scope_paths(config.write_forbidden_paths)? {
            if !forbidden_paths.iter().any(|existing| existing == &path) {
                forbidden_paths.push(path);
            }
        }
        let writable_product_roots = config
            .host_path_policy
            .product_writable_config()
            .iter()
            .cloned()
            .chain(
                config
                    .host_path_policy
                    .durable_memory_root()
                    .map(PathBuf::from),
            )
            .chain(
                config
                    .external_tree_policy
                    .as_ref()
                    .map(|policy| policy.root().to_path_buf()),
            );
        let host_path_policy = HostPathPolicy::new()
            .with_denied(normalize_host_paths(
                config.host_path_policy.denied().iter().cloned(),
            ))
            .with_product_readonly(normalize_host_paths(
                config.host_path_policy.product_readonly().iter().cloned(),
            ))
            .with_product_writable_config(normalize_host_paths(writable_product_roots));

        Ok(Self {
            root,
            readonly_resource_roots,
            limits: config.limits,
            read_scope,
            patch_write_scope,
            read_forbidden_paths,
            forbidden_paths,
            host_path_policy,
            access_policy: config.access_policy,
            external_tree_policy: config.external_tree_policy,
        })
    }

    /// Returns whether `path` is denied for reads by Merry's host path policy.
    ///
    /// Evaluates both the lexical spelling and the existing-ancestor canonical
    /// path against [`HostPathPolicy::is_denied_for_read`] so a symlink under a
    /// read-only product subtree cannot escape into a denied directory.
    pub(crate) fn is_denied_for_read(&self, path: &std::path::Path) -> bool {
        if self.host_path_policy.denied().is_empty() {
            return false;
        }
        let lexical = normalize_path_lexically(path);
        let resolved = resolve_path_with_existing_ancestor(&lexical);
        self.host_path_policy.is_denied_for_read(&lexical)
            || self.host_path_policy.is_denied_for_read(&resolved)
    }

    /// Returns whether Merry's `product_readonly` protection (`config.toml`,
    /// `state/`) is active.
    ///
    /// Active when running under a workspace sandbox (or standalone tools
    /// without a live access policy), and relaxed in unrestricted `--sandbox
    /// off` mode so users can edit `config.toml` directly while `providers/`
    /// secrets remain hard-denied.
    fn enforce_product_readonly(&self) -> bool {
        self.access_policy
            .as_ref()
            .is_none_or(LivePolicyHandle::is_restricted)
    }

    /// Returns whether `path` is denied for writes by Merry's host path policy.
    ///
    /// Denied secret paths (`providers/`, `MERRY_API_KEY_FILE`) are always
    /// non-writable; read-only product paths (`config.toml`, `state/`) are
    /// non-writable while workspace sandbox restrictions are active.
    pub(crate) fn is_denied_for_write(&self, path: &std::path::Path) -> bool {
        if !self.enforce_product_readonly() {
            return self.is_denied_for_read(path);
        }
        if self.host_path_policy.denied().is_empty()
            && self.host_path_policy.product_readonly().is_empty()
        {
            return false;
        }
        let lexical = normalize_path_lexically(path);
        let resolved = resolve_path_with_existing_ancestor(&lexical);
        self.host_path_policy.is_denied_for_write(&lexical)
            || self.host_path_policy.is_denied_for_write(&resolved)
    }

    /// Returns whether `path` falls inside an effective Merry-owned read-only
    /// product tree (such as `$XDG_STATE_HOME/merry`).
    pub(crate) fn is_readonly_product_path(&self, path: &std::path::Path) -> bool {
        if !self.enforce_product_readonly() || self.host_path_policy.product_readonly().is_empty() {
            return false;
        }
        let lexical = normalize_path_lexically(path);
        let resolved = resolve_path_with_existing_ancestor(&lexical);
        self.host_path_policy.is_product_readonly(&lexical)
            && self.host_path_policy.is_product_readonly(&resolved)
    }

    /// Returns the workspace root followed by every read-only resource root.
    ///
    /// A relative argument is looked up in this order, so the workspace stays
    /// the primary namespace and a skill's own relative `SKILL.md` path still
    /// resolves. An absolute argument names one path and ignores this order.
    pub(crate) fn read_roots(&self) -> impl Iterator<Item = &PathBuf> {
        std::iter::once(&self.root).chain(self.readonly_resource_roots.iter())
    }

    /// Returns whether this tool state is wired to a runtime permission review
    /// flow (versus standalone `WorkspaceTools` unit usage).
    pub(crate) fn has_runtime_permission_review(&self) -> bool {
        self.access_policy.is_some()
    }

    /// Returns whether any single-action grant in `once_grants` directly covers
    /// `path` with at least `requested` access.
    pub(crate) fn once_grants_cover(
        &self,
        once_grants: &[PathAccessRule],
        path: &std::path::Path,
        requested: PathAccess,
    ) -> bool {
        once_grants_cover_path(once_grants, path, requested)
    }

    /// Returns whether `path` is hard-denied for reads before touching the
    /// filesystem (avoiding existence probing on denied external paths).
    pub(crate) fn is_hard_denied_for_read(
        &self,
        path: &std::path::Path,
        once_grants: &[PathAccessRule],
    ) -> bool {
        if !self.has_runtime_permission_review() {
            return self.is_denied_for_read(path);
        }
        let Some(live) = self.access_policy.as_ref() else {
            return false;
        };
        live.evaluate_read(path, once_grants).decision == PathAccessDecision::Deny
    }

    /// Evaluates whether `resolved` is authorized for read access under the
    /// unified [`LivePolicyHandle`], returning either a hard denial or
    /// a [`ToolPermissionRequirement`] for runtime review.
    ///
    /// Hard user ceilings (`Deny`) are evaluated first so `HostPathPolicy`
    /// never shadows an explicit user `TrustedGlobalConfig` deny ceiling.
    pub(crate) fn authorize_read_access_policy(
        &self,
        resolved: &std::path::Path,
        once_grants: &[PathAccessRule],
    ) -> Result<(), ReadAccessPolicyError> {
        let Some(live) = self.access_policy.as_ref() else {
            return Ok(());
        };
        let eval = live.evaluate_read(resolved, once_grants);
        if eval.decision == PathAccessDecision::Deny {
            return Err(ReadAccessPolicyError::Denied(DomainError::new(
                ERROR_PATH_DENIED,
                "path is denied by configured workspace access policy",
            )));
        }
        if eval.protected_target || self.is_denied_for_read(resolved) {
            if eval.decision == PathAccessDecision::Allow
                && self.once_grants_cover(once_grants, resolved, PathAccess::ReadOnly)
            {
                return Ok(());
            }
            if !eval.protected_target
                && self.once_grants_cover(once_grants, resolved, PathAccess::ReadOnly)
            {
                return Ok(());
            }
            return Err(build_read_permission_requirement(
                resolved,
                "read_file targeted Merry protected credentials path",
                true,
            ));
        }
        if eval.decision == PathAccessDecision::Allow {
            return Ok(());
        }
        if self.is_readonly_product_path(resolved)
            || self
                .readonly_resource_roots
                .iter()
                .any(|root| resolved.starts_with(root))
            || self
                .external_tree_policy
                .as_ref()
                .is_some_and(|tree| tree.governs_path(resolved))
        {
            return Ok(());
        }
        Err(build_read_permission_requirement(
            resolved,
            "read_file targeted a path outside the active workspace access policy",
            false,
        ))
    }

    /// Evaluates whether `resolved` is authorized for write access under the
    /// unified [`LivePolicyHandle`].
    ///
    /// Hard user ceilings (`Deny`) and read-only workspace boundaries are
    /// evaluated first, followed by built-in protected paths (`protected_target`),
    /// then governed external trees and writable product config roots.
    pub(crate) fn evaluate_write_access_policy(
        &self,
        resolved: &std::path::Path,
        once_grants: &[PathAccessRule],
    ) -> PathEvaluation {
        let Some(live) = self.access_policy.as_ref() else {
            return PathEvaluation {
                decision: PathAccessDecision::Allow,
                protected_target: false,
                git_metadata: merry_runtime::is_git_metadata_path(resolved),
                denial_reason: None,
            };
        };
        let eval = live.evaluate_write(resolved, once_grants);
        if eval.decision == PathAccessDecision::Deny {
            return eval;
        }
        if eval.protected_target || self.is_denied_for_write(resolved) {
            let allowed = self.once_grants_cover(once_grants, resolved, PathAccess::ReadWrite);
            return PathEvaluation {
                decision: if allowed {
                    PathAccessDecision::Allow
                } else {
                    PathAccessDecision::RequireReview
                },
                protected_target: true,
                git_metadata: eval.git_metadata,
                denial_reason: None,
            };
        }
        if eval.decision == PathAccessDecision::Allow {
            return eval;
        }
        if self
            .external_tree_policy
            .as_ref()
            .is_some_and(|tree| tree.governs_path(resolved))
            || self
                .host_path_policy
                .product_writable_config()
                .iter()
                .any(|root| resolved.starts_with(root))
        {
            return PathEvaluation {
                decision: PathAccessDecision::Allow,
                protected_target: false,
                git_metadata: eval.git_metadata,
                denial_reason: None,
            };
        }
        eval
    }

    /// Validates that a resolved path is permitted by read security boundaries.
    pub(crate) fn validate_read_boundary(
        &self,
        path: &ValidatedToolPath,
        resolved: &std::path::Path,
    ) -> Result<(), DomainError> {
        if !self.has_runtime_permission_review() && self.is_denied_for_read(resolved) {
            return Err(DomainError::new(
                ERROR_PATH_DENIED,
                "path is denied by Merry security policy",
            ));
        }
        if self.is_readonly_product_path(resolved) {
            return Ok(());
        }
        if self
            .readonly_resource_roots
            .iter()
            .any(|root| resolved.starts_with(root))
        {
            return Ok(());
        }
        if let Some(policy) = &self.external_tree_policy
            && policy.governs_path(resolved)
        {
            return Ok(());
        }

        let scope_path = path.relative_spelling();
        if let Some(scope_path) = scope_path
            && matches_any_scope_path(scope_path, &self.read_forbidden_paths)
        {
            return Err(DomainError::new(
                ERROR_PATH_DENIED,
                "workspace read path is forbidden by the child workspace scope",
            ));
        }

        let Some(read_scope) = &self.read_scope else {
            return Ok(());
        };
        match scope_path {
            Some(scope_path) if matches_any_scope_path(scope_path, read_scope) => Ok(()),
            _ => {
                let message = if read_scope.is_empty() {
                    "workspace read path is outside the configured read scope; this read scope allows no workspace files"
                } else {
                    "workspace read path is outside the configured read scope"
                };
                Err(DomainError::new(ERROR_PATH_DENIED, message))
            }
        }
    }
}

/// Canonicalizes a required workspace root.
fn canonical_root(root: PathBuf) -> Result<PathBuf, WorkspaceToolConfigError> {
    if !root.exists() {
        return Err(WorkspaceToolConfigError::RootNotFound { root });
    }

    let canonical =
        fs::canonicalize(&root).map_err(|source| WorkspaceToolConfigError::RootCanonicalize {
            root: root.clone(),
            source,
        })?;

    if !canonical.is_dir() {
        return Err(WorkspaceToolConfigError::RootNotDirectory { root });
    }

    Ok(canonical)
}

/// Canonicalizes an optional read-only resource root.
///
/// Resource roots are optional configuration, so a missing or non-directory
/// entry is skipped instead of failing the whole tool set. A root that exists
/// but cannot be canonicalized is still an error.
fn canonical_optional_root(root: PathBuf) -> Result<Option<PathBuf>, WorkspaceToolConfigError> {
    match canonical_root(root) {
        Ok(canonical) => Ok(Some(canonical)),
        Err(WorkspaceToolConfigError::RootNotFound { .. })
        | Err(WorkspaceToolConfigError::RootNotDirectory { .. }) => Ok(None),
        Err(error) => Err(error),
    }
}

fn normalize_scope_paths(paths: Vec<PathBuf>) -> Result<Vec<String>, WorkspaceToolConfigError> {
    let paths = paths
        .into_iter()
        .map(normalize_scope_path)
        .collect::<Result<BTreeSet<_>, _>>()?;
    Ok(paths.into_iter().collect())
}

fn normalize_scope_path(path: PathBuf) -> Result<String, WorkspaceToolConfigError> {
    let Some(path_text) = path.to_str() else {
        return Err(WorkspaceToolConfigError::InvalidScopePath { path });
    };

    if path_text == "." {
        return Ok(String::new());
    }

    if path_text.is_empty()
        || path.is_absolute()
        || path_text.contains('\\')
        || path_text.chars().any(char::is_control)
        || path_text
            .split('/')
            .any(|segment| matches!(segment, "" | "." | ".."))
    {
        return Err(WorkspaceToolConfigError::InvalidScopePath { path });
    }

    let mut components = Vec::new();
    for component in path.components() {
        match component {
            Component::Normal(value) => {
                let Some(value) = value.to_str() else {
                    return Err(WorkspaceToolConfigError::InvalidScopePath { path });
                };
                components.push(value.to_owned());
            }
            Component::CurDir
            | Component::ParentDir
            | Component::RootDir
            | Component::Prefix(_) => {
                return Err(WorkspaceToolConfigError::InvalidScopePath { path });
            }
        }
    }

    if components.is_empty() {
        return Err(WorkspaceToolConfigError::InvalidScopePath { path });
    }

    Ok(components.join("/"))
}

pub(crate) fn matches_any_scope_path(relative: &str, scope_paths: &[String]) -> bool {
    scope_paths
        .iter()
        .any(|scope_path| matches_scope_path(relative, scope_path))
}

fn matches_scope_path(relative: &str, scope_path: &str) -> bool {
    scope_path.is_empty()
        || relative == scope_path
        || relative
            .strip_prefix(scope_path)
            .is_some_and(|suffix| suffix.starts_with('/'))
}

fn validate_limits(limits: &WorkspaceToolLimits) -> Result<(), WorkspaceToolConfigError> {
    for (name, value) in [
        ("max_read_bytes", limits.max_read_bytes),
        ("max_read_lines", limits.max_read_lines),
        ("max_write_bytes", limits.max_write_bytes),
        ("max_patch_bytes", limits.max_patch_bytes),
    ] {
        if value == 0 {
            return Err(WorkspaceToolConfigError::InvalidLimit { name });
        }
    }

    Ok(())
}

fn normalize_host_paths(paths: impl IntoIterator<Item = PathBuf>) -> Vec<PathBuf> {
    let mut normalized = BTreeSet::new();
    for path in paths {
        if !path.is_absolute() {
            continue;
        }
        let lexical = normalize_path_lexically(&path);
        let resolved = resolve_path_with_existing_ancestor(&lexical);
        normalized.insert(lexical);
        normalized.insert(resolved);
    }
    normalized.into_iter().collect()
}

fn build_read_permission_requirement(
    resolved: &std::path::Path,
    reason: &str,
    protected_target: bool,
) -> ReadAccessPolicyError {
    let target = resolved.to_string_lossy().into_owned();
    let capability = match RequestedPathCapability::new(target.clone(), PathAccess::ReadOnly) {
        Ok(cap) => RequestedCapability::Path(cap),
        Err(error) => {
            return ReadAccessPolicyError::Denied(DomainError::new(
                ERROR_PATH_DENIED,
                format!(
                    "external read target `{target}` is outside the active workspace access policy and cannot be requested for approval: {error}"
                ),
            ));
        }
    };
    let mut requirement = ToolPermissionRequirement::new(
        PermissionedAction::FileRead { path: target },
        vec![capability],
        Some(reason.to_owned()),
    );
    if protected_target {
        requirement = requirement.with_protected_target();
    }
    ReadAccessPolicyError::PermissionRequired(Box::new(requirement))
}