merry-runtime 0.1.4

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Atomic single-lock live policy baseline and per-session evaluation handle.
//!
//! `LivePolicyHandle` replaces the previously separate `RwLock`s for workspace
//! filesystem access, network/domain admission, sandbox mode, and protected
//! product paths with a single atomic `Arc<LivePolicyBaseline>` swap.
//!
//! Child subagent sessions derive from their parent handle via
//! [`LivePolicyHandle::for_child`]: they share the parent's live baseline lock
//! (tracking sandbox/config/workspace-permission reloads automatically) while
//! evaluating session-scoped grants strictly against their own
//! [`ProcessSessionPermissionView`] and pre-resolved child overrides.

use crate::{
    NetworkAccessDecision, NetworkAccessPolicy, PathAccess, PathAccessDecision, PathAccessRule,
    PathDenialReason, PathEvaluation, ProcessSessionPermissionSnapshot,
    ProcessSessionPermissionView, WorkspaceAccessPolicy,
    access_policy::{ResolvedPathRule, resolve_rule_path},
    is_protected_in_unrestricted_mode,
};
use std::{
    path::{Path, PathBuf},
    sync::{Arc, RwLock},
};

/// Immutable point-in-time policy baseline shared atomically across file tools,
/// web/browser tools, host-process backends, and child sessions.
#[derive(Debug, Clone)]
pub struct LivePolicyBaseline {
    restricted: bool,
    workspace_access: Option<WorkspaceAccessPolicy>,
    product_private_paths: Vec<PathBuf>,
    network_access: NetworkAccessPolicy,
}

impl LivePolicyBaseline {
    /// Constructs a new immutable policy baseline.
    #[must_use]
    pub fn new(
        restricted: bool,
        workspace_access: Option<WorkspaceAccessPolicy>,
        product_private_paths: Vec<PathBuf>,
        network_access: NetworkAccessPolicy,
    ) -> Self {
        Self {
            restricted,
            workspace_access,
            product_private_paths,
            network_access,
        }
    }

    /// Returns whether workspace sandbox restrictions are active (`--sandbox workspace`).
    #[must_use]
    pub const fn is_restricted(&self) -> bool {
        self.restricted
    }

    /// Returns the workspace access policy active under `--sandbox workspace`,
    /// or `None` under `--sandbox off`.
    #[must_use]
    pub fn workspace_access(&self) -> Option<&WorkspaceAccessPolicy> {
        self.workspace_access.as_ref()
    }

    /// Returns built-in Merry protected credential paths (`providers/`,
    /// `MERRY_API_KEY_FILE`) guarded by approval even in `--sandbox off`.
    #[must_use]
    pub fn product_private_paths(&self) -> &[PathBuf] {
        &self.product_private_paths
    }

    /// Returns the outbound network and domain policy baseline.
    #[must_use]
    pub fn network_access(&self) -> &NetworkAccessPolicy {
        &self.network_access
    }
}

/// Child-session workspace overrides layered purely on top of the parent's
/// live baseline without disconnecting live reload propagation.
#[derive(Debug, Clone)]
pub struct ChildWorkspacePolicyOverride {
    workspace_root_canonical: Option<PathBuf>,
    workspace_writable: bool,
    extra_resolved_rules: Vec<ResolvedPathRule>,
}

impl ChildWorkspacePolicyOverride {
    /// Creates a child override intersecting `workspace_writable`.
    #[must_use]
    pub fn new(workspace_writable: bool) -> Self {
        Self {
            workspace_root_canonical: None,
            workspace_writable,
            extra_resolved_rules: Vec::new(),
        }
    }

    /// Overrides the effective workspace root (used by worktree-isolated subagents),
    /// canonicalizing the root path once up front.
    #[must_use]
    pub fn with_workspace_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.workspace_root_canonical = Some(resolve_rule_path(&root.into()));
        self
    }

    /// Appends child-specific static path rules (such as worktree `.git` baseline
    /// rules), canonicalizing each path once up front.
    #[must_use]
    pub fn with_extra_path_rules(
        mut self,
        rules: impl IntoIterator<Item = PathAccessRule>,
    ) -> Self {
        self.extra_resolved_rules = rules
            .into_iter()
            .map(|rule| ResolvedPathRule::from_rule(&rule))
            .collect();
        self
    }

    #[must_use]
    pub(crate) fn workspace_root_canonical(&self) -> Option<&Path> {
        self.workspace_root_canonical.as_deref()
    }

    /// Returns whether the child session is permitted to write to its workspace.
    #[must_use]
    pub const fn workspace_writable(&self) -> bool {
        self.workspace_writable
    }

    #[must_use]
    pub(crate) fn extra_resolved_rules(&self) -> &[ResolvedPathRule] {
        &self.extra_resolved_rules
    }
}

/// Single-lock live policy handle coordinating filesystem, network, sandbox
/// mode, and protected-path evaluation across parent and child sessions.
#[derive(Debug, Clone)]
pub struct LivePolicyHandle {
    baseline: Arc<RwLock<Arc<LivePolicyBaseline>>>,
    session_permissions: Option<ProcessSessionPermissionView>,
    child_override: Option<Arc<ChildWorkspacePolicyOverride>>,
}

impl LivePolicyHandle {
    /// Creates a live handle initialized with `baseline`.
    #[must_use]
    pub fn new(baseline: LivePolicyBaseline) -> Self {
        Self {
            baseline: Arc::new(RwLock::new(Arc::new(baseline))),
            session_permissions: None,
            child_override: None,
        }
    }

    /// Creates a standalone handle initialized from an optional
    /// [`WorkspaceAccessPolicy`] (primarily for standalone tools and tests).
    #[must_use]
    pub fn for_workspace(policy: Option<WorkspaceAccessPolicy>) -> Self {
        let product_private_paths = policy
            .as_ref()
            .map(WorkspaceAccessPolicy::product_private_paths)
            .unwrap_or_default();
        Self::new(LivePolicyBaseline::new(
            policy.is_some(),
            policy,
            product_private_paths,
            NetworkAccessPolicy::default(),
        ))
    }

    /// Creates a standalone handle initialized from a [`NetworkAccessPolicy`]
    /// (preserving any attached session permission view).
    #[must_use]
    pub fn for_network(policy: NetworkAccessPolicy) -> Self {
        let session_view = policy.session_permissions_view();
        let mut handle = Self::new(LivePolicyBaseline::new(false, None, Vec::new(), policy));
        if let Some(view) = session_view {
            handle = handle.with_session_permissions(view);
        }
        handle
    }

    /// Attaches a live read-only view of session-scoped permission grants.
    #[must_use]
    pub fn with_session_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
        self.session_permissions = Some(view);
        self
    }

    /// Derives a child handle sharing the same atomic baseline lock while
    /// binding session grant evaluation strictly to the child's own
    /// `session_permissions` and optional workspace/worktree overrides.
    #[must_use]
    pub fn for_child(
        &self,
        session_permissions: Option<ProcessSessionPermissionView>,
        child_override: Option<ChildWorkspacePolicyOverride>,
    ) -> Self {
        Self {
            baseline: Arc::clone(&self.baseline),
            session_permissions,
            child_override: child_override.map(Arc::new),
        }
    }

    /// Returns a point-in-time `Arc` snapshot of the shared policy baseline.
    #[must_use]
    pub fn baseline_snapshot(&self) -> Arc<LivePolicyBaseline> {
        Arc::clone(
            &self
                .baseline
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        )
    }

    /// Atomically replaces the shared policy baseline under a single lock.
    pub fn replace_baseline(&self, next: LivePolicyBaseline) {
        *self
            .baseline
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::new(next);
    }

    /// Returns whether workspace sandbox restrictions are currently active.
    #[must_use]
    pub fn is_restricted(&self) -> bool {
        self.baseline_snapshot().restricted
    }

    /// Returns whether writes inside the workspace are currently allowed.
    #[must_use]
    pub fn workspace_writable(&self) -> bool {
        let baseline = self.baseline_snapshot();
        let child_writable = self
            .child_override
            .as_ref()
            .is_none_or(|override_cfg| override_cfg.workspace_writable);
        if !baseline.restricted {
            return child_writable;
        }
        let parent_writable = baseline
            .workspace_access
            .as_ref()
            .is_none_or(WorkspaceAccessPolicy::workspace_writable);
        parent_writable && child_writable
    }

    /// Returns whether the active network baseline allows local loopback targets.
    #[must_use]
    pub fn network_allow_local(&self) -> bool {
        self.baseline_snapshot().network_access.allow_local()
    }

    /// Returns the currently active `ProductPrivate` protected credential paths.
    #[must_use]
    pub fn product_private_paths(&self) -> Vec<PathBuf> {
        self.baseline_snapshot().product_private_paths.clone()
    }

    /// Evaluates filesystem read access for `path` against the active baseline,
    /// this session's grants, and optional single-action `once_grants`.
    #[must_use]
    pub fn evaluate_read(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathEvaluation {
        self.evaluate_path(path, PathAccess::ReadOnly, once_grants)
    }

    /// Evaluates filesystem write access for `path` against the active baseline,
    /// this session's grants, and optional single-action `once_grants`.
    #[must_use]
    pub fn evaluate_write(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathEvaluation {
        self.evaluate_path(path, PathAccess::ReadWrite, once_grants)
    }

    /// Evaluates filesystem access for `path` in either `--sandbox workspace`
    /// or `--sandbox off` mode using a single authoritative evaluation pass.
    #[must_use]
    pub fn evaluate_path(
        &self,
        path: &Path,
        requested: PathAccess,
        once_grants: &[PathAccessRule],
    ) -> PathEvaluation {
        let baseline = self.baseline_snapshot();
        if !baseline.restricted {
            let git_metadata = crate::is_git_metadata_path(path);
            if is_protected_in_unrestricted_mode(&baseline.product_private_paths, path) {
                let decision =
                    if crate::access_policy::once_grants_cover_path(once_grants, path, requested) {
                        PathAccessDecision::Allow
                    } else {
                        PathAccessDecision::RequireReview
                    };
                return PathEvaluation::protected(decision, git_metadata);
            }
            if requested == PathAccess::ReadWrite
                && self
                    .child_override
                    .as_ref()
                    .is_some_and(|override_cfg| !override_cfg.workspace_writable)
            {
                return PathEvaluation::deny(PathDenialReason::ReadOnlyWorkspace, git_metadata);
            }
            return PathEvaluation::allow(git_metadata);
        }

        let Some(base_policy) = baseline.workspace_access.as_ref() else {
            return PathEvaluation::allow(crate::is_git_metadata_path(path));
        };
        let session = self.session_snapshot();
        base_policy.evaluate_with_child_override(
            self.child_override.as_deref(),
            path,
            requested,
            session.as_ref(),
            once_grants,
        )
    }

    /// Evaluates outbound HTTP(S) access to `host` against the active baseline,
    /// this session's grants, and optional single-action `once_domains`.
    #[must_use]
    pub fn evaluate_network_host(
        &self,
        host: &str,
        once_domains: &[String],
    ) -> NetworkAccessDecision {
        let baseline = self.baseline_snapshot();
        let session = self.session_snapshot();
        baseline
            .network_access
            .evaluate_host_with_session(host, session.as_ref(), once_domains)
    }

    /// Evaluates access to a browser `data:` document against the active baseline.
    #[must_use]
    pub fn evaluate_data_url(&self) -> NetworkAccessDecision {
        self.baseline_snapshot().network_access.evaluate_data_url()
    }

    fn session_snapshot(&self) -> Option<ProcessSessionPermissionSnapshot> {
        self.session_permissions
            .as_ref()
            .and_then(|view| view.snapshot().ok())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{PathAccessRuleSource, ProcessSessionPermissions};
    use merry_core::CapabilityPolicy;

    #[test]
    fn child_handle_tracks_live_baseline_while_isolating_session_grants() {
        let temp = tempfile::tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        let external = temp.path().join("external.txt");
        let secret_dir = temp.path().join("providers");
        std::fs::create_dir_all(&workspace).expect("workspace");
        std::fs::create_dir_all(&secret_dir).expect("secret dir");
        std::fs::write(&external, "hello").expect("external");

        let parent_session = ProcessSessionPermissions::new();
        let child_session = ProcessSessionPermissions::new();

        let initial = LivePolicyBaseline::new(
            true,
            Some(WorkspaceAccessPolicy::new(&workspace, true)),
            vec![secret_dir.clone()],
            NetworkAccessPolicy::new(CapabilityPolicy::Ask, true),
        );
        let parent = LivePolicyHandle::new(initial).with_session_permissions(parent_session.view());
        let child = parent.for_child(
            Some(child_session.view()),
            Some(ChildWorkspacePolicyOverride::new(false)),
        );

        // Child approves a session domain grant; parent does NOT inherit it.
        child_session
            .retain_domain_grants(["docs.rs".to_owned()])
            .expect("retain domain");
        assert_eq!(
            child.evaluate_network_host("docs.rs", &[]),
            NetworkAccessDecision::Allow
        );
        assert_eq!(
            parent.evaluate_network_host("docs.rs", &[]),
            NetworkAccessDecision::RequireReview
        );

        // Child is read-only inside workspace even when parent is writable.
        let ws_file = workspace.join("src.rs");
        assert_eq!(
            parent.evaluate_write(&ws_file, &[]).decision,
            PathAccessDecision::Allow
        );
        assert_eq!(
            child.evaluate_write(&ws_file, &[]).decision,
            PathAccessDecision::Deny
        );

        // Parent flips baseline to unrestricted (`--sandbox off`) + `network = deny`.
        parent.replace_baseline(LivePolicyBaseline::new(
            false,
            None,
            vec![secret_dir.clone()],
            NetworkAccessPolicy::new(CapabilityPolicy::Deny, true),
        ));
        assert!(!child.is_restricted());
        assert_eq!(
            child.evaluate_read(&external, &[]).decision,
            PathAccessDecision::Allow
        );
        assert_eq!(
            child.evaluate_network_host("docs.rs", &[]),
            NetworkAccessDecision::Deny
        );
        // Built-in ProductPrivate remains approval-gated with protected_target=true in off mode.
        let secret_eval = child.evaluate_read(&secret_dir.join("key.json"), &[]);
        assert_eq!(secret_eval.decision, PathAccessDecision::RequireReview);
        assert!(secret_eval.protected_target);

        // Adding a saved workspace path rule under workspace mode flows immediately to child.
        parent.replace_baseline(LivePolicyBaseline::new(
            true,
            Some(
                WorkspaceAccessPolicy::new(&workspace, true).with_static_rules([
                    PathAccessRule::new(
                        &external,
                        PathAccess::ReadOnly,
                        PathAccessRuleSource::WorkspacePermissions,
                    ),
                ]),
            ),
            vec![secret_dir],
            NetworkAccessPolicy::new(CapabilityPolicy::Ask, true),
        ));
        assert!(child.is_restricted());
        assert_eq!(
            child.evaluate_read(&external, &[]).decision,
            PathAccessDecision::Allow
        );
    }
}