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
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
//! Pre-execution action policy and process-lane admission evaluator.
//!
//! This module is the pure, synchronous decision layer sitting strictly ahead
//! of tool dispatch: given snapshotted policy/lane inputs and an optional
//! preflight [`ActionProposal`], it returns a deterministic
//! [`ToolAdmissionOutcome`] without locking session state or performing I/O.

use std::sync::Arc;

use super::{process_execution::ProcessExecutionAdmission, state::ProcessExecutionLanes};
use crate::{
    ActionProposal, ActionReviewTrigger, ProcessActionIntent, ProcessPermissionProfileId,
    ToolActionKind,
    action_policy::{
        ActionPolicyDecision, DefaultActionPolicy, classify_tool_action_risk,
        is_local_workspace_effect_process_action_proposal, is_low_risk_apply_patch_proposal,
        is_low_risk_process_action_proposal, is_read_only_shell_process_action_proposal,
    },
    process_tool::process_call_requests_permission,
    tool::ActionProposalEvidence,
};
use merry_core::PendingToolCall;

/// Read-only runtime policy inputs snapshotted before evaluating one tool call.
pub(super) struct ToolAdmissionInput<'a> {
    pub(super) pending: &'a PendingToolCall,
    pub(super) action_kind: ToolActionKind,
    pub(super) low_risk_workspace_patch_lane: bool,
    pub(super) allow_low_risk_workspace_patches: bool,
    pub(super) permissioned_network_lane: bool,
    pub(super) allow_permissioned_network_tools: bool,
    pub(super) plan_mode_active: bool,
    pub(super) fully_trusted: bool,
    pub(super) process_lanes: &'a ProcessExecutionLanes,
}

/// Deterministic admission outcome consumed by tool execution dispatch.
pub(super) enum ToolAdmissionOutcome {
    /// Blocked by the Plan Mode read-only edit gate.
    DenyPlanModeReadOnly,
    /// Blocked by default action policy with no matching admitted lane.
    DenyActionPolicy,
    /// Admitted to the generic registered [`crate::ToolExecutor`].
    ExecuteGeneric {
        decision: ActionPolicyDecision,
        approved_proposal: Option<ActionProposal>,
    },
    /// Admitted to a concrete process runner lane, optionally requiring a
    /// structured high-risk action review round before execution.
    ExecuteProcess {
        proposal: ActionProposal,
        admission: ProcessExecutionAdmission,
        review_triggers: Vec<ActionReviewTrigger>,
    },
    /// Routed to the permissioned process review and execution service.
    RequireProcessPermissionRequest { intent: ProcessActionIntent },
}

/// Returns whether the runtime must request a read-only [`ActionProposal`]
/// preflight from the tool executor before evaluating admission.
pub(super) fn requires_action_preflight(
    action_kind: ToolActionKind,
    proposals_enabled: bool,
    plan_mode_active: bool,
    fully_trusted: bool,
) -> bool {
    if action_kind == ToolActionKind::WorkspaceWrite && plan_mode_active {
        return false;
    }
    if !action_kind.is_mutating() || !proposals_enabled {
        return false;
    }
    let default_allowed = DefaultActionPolicy.decide(action_kind).is_allowed();
    !default_allowed || (fully_trusted && action_kind != ToolActionKind::Network)
}

/// Evaluates hard policy, Plan Mode edit gating, and configured execution lanes.
pub(super) fn evaluate_tool_admission(
    input: &ToolAdmissionInput<'_>,
    proposal: Option<ActionProposal>,
) -> ToolAdmissionOutcome {
    // Plan Mode read-only edit gate: block workspace file mutations even under
    // fully-trusted permission mode so design remains separate from coding.
    if input.action_kind == ToolActionKind::WorkspaceWrite && input.plan_mode_active {
        return ToolAdmissionOutcome::DenyPlanModeReadOnly;
    }

    let default_decision = DefaultActionPolicy.decide(input.action_kind);
    if default_decision.is_allowed()
        && (!input.fully_trusted
            || !input.action_kind.is_mutating()
            || input.action_kind == ToolActionKind::Network
            || proposal.is_none())
    {
        let decision = if input.fully_trusted {
            ActionPolicyDecision::allow_fully_trusted_action(input.action_kind)
        } else {
            default_decision
        };
        return ToolAdmissionOutcome::ExecuteGeneric {
            decision,
            approved_proposal: None,
        };
    }

    // Unified permissioned network lane (`web_fetch`, `browser_tab`,
    // `browser_network`): executors enforce SSRF + `LivePolicyHandle`
    // and escalate unapproved external domains through runtime review.
    if input.action_kind == ToolActionKind::Network
        && input.permissioned_network_lane
        && input.allow_permissioned_network_tools
    {
        return ToolAdmissionOutcome::ExecuteGeneric {
            decision: ActionPolicyDecision::allow_permissioned_network_action(),
            approved_proposal: None,
        };
    }

    let Some(proposal) = proposal else {
        if input.plan_mode_active && input.action_kind == ToolActionKind::CommandExec {
            return ToolAdmissionOutcome::DenyPlanModeReadOnly;
        }
        return if input.fully_trusted {
            ToolAdmissionOutcome::ExecuteGeneric {
                decision: ActionPolicyDecision::allow_fully_trusted_action(input.action_kind),
                approved_proposal: None,
            }
        } else {
            ToolAdmissionOutcome::DenyActionPolicy
        };
    };

    if let ActionProposalEvidence::ProcessAction(intent) = proposal.evidence()
        && process_call_requests_permission(input.pending)
    {
        if input.plan_mode_active {
            return ToolAdmissionOutcome::DenyPlanModeReadOnly;
        }
        return ToolAdmissionOutcome::RequireProcessPermissionRequest {
            intent: intent.clone(),
        };
    }

    if input.allow_low_risk_workspace_patches
        && input.low_risk_workspace_patch_lane
        && is_low_risk_apply_patch_proposal(input.action_kind, &proposal)
    {
        return ToolAdmissionOutcome::ExecuteGeneric {
            decision: ActionPolicyDecision::allow_low_risk_apply_patch(),
            approved_proposal: Some(proposal),
        };
    }

    if let Some(runner) = input.process_lanes.low_risk_runner.as_ref()
        && is_low_risk_process_action_proposal(input.action_kind, &proposal)
    {
        return ToolAdmissionOutcome::ExecuteProcess {
            proposal,
            admission: ProcessExecutionAdmission::new(
                ActionPolicyDecision::allow_low_risk_process_action(),
                ProcessPermissionProfileId::READ_ONLY,
                Arc::clone(runner),
                false,
            ),
            review_triggers: Vec::new(),
        };
    }

    if let Some(runner) = input.process_lanes.read_only_shell_runner.as_ref()
        && is_read_only_shell_process_action_proposal(input.action_kind, &proposal)
    {
        return ToolAdmissionOutcome::ExecuteProcess {
            proposal,
            admission: ProcessExecutionAdmission::new(
                ActionPolicyDecision::allow_read_only_shell_process_action(),
                ProcessPermissionProfileId::SHELL_READ_ONLY,
                Arc::clone(runner),
                false,
            ),
            review_triggers: Vec::new(),
        };
    }

    // Plan Mode read-only gate for shell commands: read-only inspection
    // commands admitted above may proceed, while mutating or unclassified
    // commands stay blocked even under fully-trusted permission mode.
    if input.plan_mode_active && input.action_kind == ToolActionKind::CommandExec {
        return ToolAdmissionOutcome::DenyPlanModeReadOnly;
    }

    if let Some(accepted) = input.process_lanes.accepted_local_workspace_runner.as_ref()
        && is_local_workspace_effect_process_action_proposal(
            input.action_kind,
            &proposal,
            accepted.admission,
        )
    {
        return ToolAdmissionOutcome::ExecuteProcess {
            proposal,
            admission: ProcessExecutionAdmission::new(
                ActionPolicyDecision::allow_accepted_local_workspace_process_action(),
                accepted.admission.permission_profile_id(),
                Arc::clone(&accepted.runner),
                false,
            ),
            review_triggers: Vec::new(),
        };
    }

    if let Some(accepted) = input.process_lanes.accepted_local_workspace_runner.as_ref()
        && input.action_kind == ToolActionKind::CommandExec
        && proposal.action_kind() == ToolActionKind::CommandExec
        && let ActionProposalEvidence::ProcessAction(intent) = proposal.evidence()
        && accepted.admission.matches_intent(intent)
    {
        // The classifier is an audit/risk signal. The configured runner
        // boundary, rather than a command allowlist, decides which capabilities
        // the process actually receives.
        let risk_tier = classify_tool_action_risk(input.action_kind, Some(&proposal));
        let policy_decision = if input.fully_trusted {
            ActionPolicyDecision::allow_fully_trusted_action(input.action_kind)
                .with_risk_tier(risk_tier)
        } else {
            ActionPolicyDecision::allow_configured_process_action().with_risk_tier(risk_tier)
        };
        let review_triggers = if input.fully_trusted {
            Vec::new()
        } else {
            crate::process::classify_process_action_review_triggers(intent)
        };
        return ToolAdmissionOutcome::ExecuteProcess {
            proposal,
            admission: ProcessExecutionAdmission::new(
                policy_decision,
                accepted.admission.permission_profile_id(),
                Arc::clone(&accepted.runner),
                false,
            ),
            review_triggers,
        };
    }

    if input.fully_trusted {
        let decision =
            ActionPolicyDecision::allow_fully_trusted_action(input.action_kind).with_risk_tier(
                classify_tool_action_risk(input.action_kind, Some(&proposal)),
            );
        return ToolAdmissionOutcome::ExecuteGeneric {
            decision,
            approved_proposal: Some(proposal),
        };
    }

    ToolAdmissionOutcome::DenyActionPolicy
}

#[cfg(test)]
mod tests {
    use super::{ToolAdmissionInput, ToolAdmissionOutcome, evaluate_tool_admission};
    use crate::{
        AcceptedLocalWorkspaceProcessAdmission, ActionProposal, ActionProposalEvidence,
        ProcessActionIntent, ProcessEnvPolicy, ProcessRunner, ProcessRunnerContext,
        ProcessRunnerError, ProcessRunnerFuture, ToolActionKind, WorkspacePatchProposal,
        runtime::state::{AcceptedLocalWorkspaceProcessRunner, ProcessExecutionLanes},
    };
    use merry_core::{PendingToolCall, ToolCallArguments, ToolCallId, ToolName};
    use serde_json::json;
    use std::sync::Arc;

    struct NoopRunner;

    impl ProcessRunner for NoopRunner {
        fn run<'a>(
            &'a self,
            _intent: ProcessActionIntent,
            _context: ProcessRunnerContext,
        ) -> ProcessRunnerFuture<'a> {
            Box::pin(async { Err(ProcessRunnerError::infrastructure("unused in pure test")) })
        }
    }

    fn call(name: &str, args: serde_json::Value) -> PendingToolCall {
        PendingToolCall::new(
            ToolCallId::new("call-1").expect("valid call id"),
            ToolName::new(name).expect("valid tool name"),
            ToolCallArguments::try_from(args).expect("valid args"),
        )
    }

    fn patch_proposal(pending: &PendingToolCall) -> ActionProposal {
        let patch = WorkspacePatchProposal::new(
            "src/lib.rs",
            1,
            1,
            10,
            10,
            "fnv1a64:0000000000000001",
            "fnv1a64:0000000000000002",
        )
        .expect("patch proposal");
        ActionProposal::new(
            pending,
            ToolActionKind::WorkspaceWrite,
            "workspace patch",
            "src/lib.rs",
            "Edit src/lib.rs",
            ActionProposalEvidence::WorkspacePatch(patch),
        )
        .expect("action proposal")
    }

    fn process_proposal(pending: &PendingToolCall, argv: &[&str]) -> ActionProposal {
        let intent = ProcessActionIntent::new(
            argv.iter().map(|part| (*part).to_owned()).collect(),
            Some(".".to_owned()),
            ProcessEnvPolicy::empty(),
            None,
            1024,
            1024,
        )
        .expect("intent");
        ActionProposal::new(
            pending,
            ToolActionKind::CommandExec,
            "process",
            argv.join(" "),
            "Run command",
            ActionProposalEvidence::ProcessAction(intent),
        )
        .expect("proposal")
    }

    #[test]
    fn plan_mode_blocks_workspace_write_even_when_fully_trusted() {
        let pending = call("apply_patch", json!({ "patch": "*** Begin Patch" }));
        let lanes = ProcessExecutionLanes::default();
        let outcome = evaluate_tool_admission(
            &ToolAdmissionInput {
                pending: &pending,
                action_kind: ToolActionKind::WorkspaceWrite,
                low_risk_workspace_patch_lane: true,
                allow_low_risk_workspace_patches: true,
                permissioned_network_lane: false,
                allow_permissioned_network_tools: false,
                plan_mode_active: true,
                fully_trusted: true,
                process_lanes: &lanes,
            },
            Some(patch_proposal(&pending)),
        );
        assert!(matches!(
            outcome,
            ToolAdmissionOutcome::DenyPlanModeReadOnly
        ));
    }

    #[test]
    fn process_call_with_permissions_routes_to_permission_request_service() {
        let pending = call(
            "run_process",
            json!({ "command": "curl https://example.com", "permissions": { "network": true } }),
        );
        let lanes = ProcessExecutionLanes::default();
        let outcome = evaluate_tool_admission(
            &ToolAdmissionInput {
                pending: &pending,
                action_kind: ToolActionKind::CommandExec,
                low_risk_workspace_patch_lane: false,
                allow_low_risk_workspace_patches: false,
                permissioned_network_lane: false,
                allow_permissioned_network_tools: false,
                plan_mode_active: false,
                fully_trusted: false,
                process_lanes: &lanes,
            },
            Some(process_proposal(
                &pending,
                &["sh", "-c", "curl https://example.com"],
            )),
        );
        assert!(matches!(
            outcome,
            ToolAdmissionOutcome::RequireProcessPermissionRequest { .. }
        ));
    }

    #[test]
    fn high_risk_process_requests_review_unless_fully_trusted() {
        let pending = call("run_process", json!({ "command": "rm -rf target" }));
        let runner: Arc<dyn ProcessRunner> = Arc::new(NoopRunner);
        let lanes = ProcessExecutionLanes {
            accepted_local_workspace_runner: Some(AcceptedLocalWorkspaceProcessRunner {
                admission: AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
                runner,
            }),
            ..ProcessExecutionLanes::default()
        };

        let reviewed = evaluate_tool_admission(
            &ToolAdmissionInput {
                pending: &pending,
                action_kind: ToolActionKind::CommandExec,
                low_risk_workspace_patch_lane: false,
                allow_low_risk_workspace_patches: false,
                permissioned_network_lane: false,
                allow_permissioned_network_tools: false,
                plan_mode_active: false,
                fully_trusted: false,
                process_lanes: &lanes,
            },
            Some(process_proposal(&pending, &["sh", "-c", "rm -rf target"])),
        );
        assert!(matches!(
            reviewed,
            ToolAdmissionOutcome::ExecuteProcess {
                review_triggers,
                ..
            } if !review_triggers.is_empty()
        ));

        let trusted = evaluate_tool_admission(
            &ToolAdmissionInput {
                pending: &pending,
                action_kind: ToolActionKind::CommandExec,
                low_risk_workspace_patch_lane: false,
                allow_low_risk_workspace_patches: false,
                permissioned_network_lane: false,
                allow_permissioned_network_tools: false,
                plan_mode_active: false,
                fully_trusted: true,
                process_lanes: &lanes,
            },
            Some(process_proposal(&pending, &["sh", "-c", "rm -rf target"])),
        );
        assert!(matches!(
            trusted,
            ToolAdmissionOutcome::ExecuteProcess {
                review_triggers,
                ..
            } if review_triggers.is_empty()
        ));
    }

    #[test]
    fn plan_mode_blocks_mutating_and_permissioned_commands_but_allows_read_only() {
        let runner: Arc<dyn ProcessRunner> = Arc::new(NoopRunner);
        let lanes = ProcessExecutionLanes {
            low_risk_runner: Some(Arc::clone(&runner)),
            read_only_shell_runner: Some(Arc::clone(&runner)),
            accepted_local_workspace_runner: Some(AcceptedLocalWorkspaceProcessRunner {
                admission: AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
                runner,
            }),
            ..ProcessExecutionLanes::default()
        };

        let direct_read_only = call("run_process", json!({ "command": "git status" }));
        let direct_read_outcome = evaluate_tool_admission(
            &ToolAdmissionInput {
                pending: &direct_read_only,
                action_kind: ToolActionKind::CommandExec,
                low_risk_workspace_patch_lane: false,
                allow_low_risk_workspace_patches: false,
                permissioned_network_lane: false,
                allow_permissioned_network_tools: false,
                plan_mode_active: true,
                fully_trusted: true,
                process_lanes: &lanes,
            },
            Some(process_proposal(&direct_read_only, &["git", "status"])),
        );
        assert!(matches!(
            direct_read_outcome,
            ToolAdmissionOutcome::ExecuteProcess { .. }
        ));

        let shell_read_only = call("run_process", json!({ "command": "git status" }));
        let shell_read_outcome = evaluate_tool_admission(
            &ToolAdmissionInput {
                pending: &shell_read_only,
                action_kind: ToolActionKind::CommandExec,
                low_risk_workspace_patch_lane: false,
                allow_low_risk_workspace_patches: false,
                permissioned_network_lane: false,
                allow_permissioned_network_tools: false,
                plan_mode_active: true,
                fully_trusted: true,
                process_lanes: &lanes,
            },
            Some(process_proposal(
                &shell_read_only,
                &["sh", "-c", "git status"],
            )),
        );
        #[cfg(feature = "bash-ast")]
        assert!(matches!(
            shell_read_outcome,
            ToolAdmissionOutcome::ExecuteProcess { .. }
        ));
        #[cfg(not(feature = "bash-ast"))]
        assert!(matches!(
            shell_read_outcome,
            ToolAdmissionOutcome::DenyPlanModeReadOnly
        ));

        let mutating = call("run_process", json!({ "command": "rm -rf target" }));
        let mutating_outcome = evaluate_tool_admission(
            &ToolAdmissionInput {
                pending: &mutating,
                action_kind: ToolActionKind::CommandExec,
                low_risk_workspace_patch_lane: false,
                allow_low_risk_workspace_patches: false,
                permissioned_network_lane: false,
                allow_permissioned_network_tools: false,
                plan_mode_active: true,
                fully_trusted: true,
                process_lanes: &lanes,
            },
            Some(process_proposal(&mutating, &["sh", "-c", "rm -rf target"])),
        );
        assert!(matches!(
            mutating_outcome,
            ToolAdmissionOutcome::DenyPlanModeReadOnly
        ));

        let permissioned = call(
            "run_process",
            json!({ "command": "curl https://example.com", "permissions": { "network": true } }),
        );
        let perm_outcome = evaluate_tool_admission(
            &ToolAdmissionInput {
                pending: &permissioned,
                action_kind: ToolActionKind::CommandExec,
                low_risk_workspace_patch_lane: false,
                allow_low_risk_workspace_patches: false,
                permissioned_network_lane: false,
                allow_permissioned_network_tools: false,
                plan_mode_active: true,
                fully_trusted: true,
                process_lanes: &lanes,
            },
            Some(process_proposal(
                &permissioned,
                &["sh", "-c", "curl https://example.com"],
            )),
        );
        assert!(matches!(
            perm_outcome,
            ToolAdmissionOutcome::DenyPlanModeReadOnly
        ));
    }
}