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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#[cfg(windows)]
use crate::process::classification::windows_shell::{
    analyze_powershell_script, parse_plain_powershell_command_sequence,
};
use crate::process::{
    classification::shell::{
        ShellKind, command_words_have_env_injection, executable_name, executable_token_is,
        parse_bash_security_analysis, parse_plain_shell_command_sequence,
        shell_like_process_input_from_argv, shell_process_input_from_argv,
    },
    contracts::{
        AcceptedLocalWorkspaceProcessAdmission, ProcessActionIntent, ProcessEnvPolicy,
        ProcessPermissionProfileId,
    },
};
pub use shell::shell_command_for_argv;
pub(crate) use shell::{shell_command_argv, shell_process_input, stable_process_input_fingerprint};
use std::path::Path;
pub use windows_shell::{
    host_shell_chain_separator, host_shell_has_unix_utilities, host_shell_name,
};

#[cfg(feature = "bash-ast")]
mod bash_ast;
mod git;
mod shell;
mod triggers;
mod windows_shell;

pub use triggers::{
    ActionReviewTrigger, classify_process_action_review_triggers, summarize_action_review_triggers,
};

use git::{git_invocation_is_forbidden, is_read_only_git_command};

impl AcceptedLocalWorkspaceProcessAdmission {
    pub(crate) fn matches_intent(self, intent: &ProcessActionIntent) -> bool {
        let required = required_process_permission_profile_id(intent);
        (self.sandbox_profile() == super::contracts::LocalWorkspaceProcessSandboxProfile::Host
            && required.is_some())
            || required == Some(self.permission_profile_id())
            || (self.permission_profile_id() == ProcessPermissionProfileId::LOCAL_WORKSPACE_HOST
                && required == Some(ProcessPermissionProfileId::LOCAL_WORKSPACE))
    }
}

/// Coarse runtime-owned classification for a proposed process argv.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessIntentClass {
    /// Read-only inspection and navigation commands with no workspace effect.
    Informational,
    /// Bounded local commands expected to read/write build artifacts.
    LocalWorkspaceEffect,
    /// No specific policy class is known.
    Unknown,
    /// The argv is blocked by hard process policy.
    Forbidden,
}

/// Classifies a process intent using validated argv only.
#[must_use]
pub fn classify_process_intent(intent: &ProcessActionIntent) -> ProcessIntentClass {
    classify_process_argv(intent.argv())
}

fn classify_process_argv(argv: &[String]) -> ProcessIntentClass {
    if is_forbidden_process_argv(argv) {
        return ProcessIntentClass::Forbidden;
    }
    if is_informational_process_argv(argv) {
        return ProcessIntentClass::Informational;
    }
    if is_local_workspace_effect_process_argv(argv) {
        return ProcessIntentClass::LocalWorkspaceEffect;
    }
    ProcessIntentClass::Unknown
}

fn is_informational_process_argv(argv: &[String]) -> bool {
    if is_read_only_direct_process_argv(argv) {
        return true;
    }

    is_read_only_plain_shell_process_argv(argv)
}

pub(super) fn is_read_only_direct_process_argv(argv: &[String]) -> bool {
    match argv {
        [executable, version]
            if executable_token_is(executable, "rustc") && version.as_str() == "--version" =>
        {
            true
        }
        [executable, rg_arg] if executable_token_is(executable, "rg") => {
            is_read_only_rg_single_argument(rg_arg)
        }
        [executable, print_flag, range, file]
            if executable_token_is(executable, "sed")
                && print_flag.as_str() == "-n"
                && is_read_only_sed_print_range(range)
                && is_workspace_relative_file_argument(file) =>
        {
            true
        }
        [executable, subcommand, args @ ..] if executable_token_is(executable, "git") => {
            is_read_only_git_command(subcommand, args)
        }
        [executable, version]
            if executable_token_is(executable, "git") && version.as_str() == "--version" =>
        {
            true
        }
        [executable] if executable_token_is(executable, "pwd") => true,
        [executable] if executable_token_is(executable, "true") => true,
        [executable] if executable_token_is(executable, "false") => true,
        [executable, args @ ..] if executable_token_is(executable, "echo") => {
            is_read_only_echo_args(args)
        }
        [executable, args @ ..] if executable_token_is(executable, "wc") => {
            is_read_only_wc_args(args)
        }
        [executable, args @ ..] if executable_token_is(executable, "head") => {
            is_read_only_head_or_tail_args(args)
        }
        [executable, args @ ..] if executable_token_is(executable, "tail") => {
            is_read_only_head_or_tail_args(args)
        }
        [executable, args @ ..] if executable_token_is(executable, "cargo") => {
            is_read_only_cargo_fmt_check_args(args)
        }
        [executable] if executable_token_is(executable, "ls") => true,
        [executable, file] if executable_token_is(executable, "ls") => {
            is_workspace_relative_file_argument(file)
        }
        [executable, file] if executable_token_is(executable, "cat") => {
            is_workspace_relative_file_argument(file)
        }
        [executable] if executable.eq_ignore_ascii_case("get-location") => true,
        [executable] if executable.eq_ignore_ascii_case("get-childitem") => true,
        [executable, file] if executable.eq_ignore_ascii_case("get-childitem") => {
            is_workspace_relative_file_argument(file)
        }
        [executable, file] if executable.eq_ignore_ascii_case("get-content") => {
            is_workspace_relative_file_argument(file)
        }
        _ => false,
    }
}

fn is_read_only_cargo_fmt_check_args(args: &[String]) -> bool {
    let mut saw_fmt = false;
    let mut saw_check = false;
    for argument in args {
        match argument.as_str() {
            "fmt" if !saw_fmt => saw_fmt = true,
            "--all" | "--check" if !saw_check || argument == "--all" => {
                if argument == "--check" {
                    saw_check = true;
                }
            }
            _ => return false,
        }
    }
    saw_fmt && saw_check
}

fn is_read_only_plain_shell_process_argv(argv: &[String]) -> bool {
    let Some(shell_input) = shell_process_input_from_argv(argv) else {
        return false;
    };

    let commands = match shell_input.kind() {
        ShellKind::Bash => parse_plain_shell_command_sequence(shell_input.script()),
        #[cfg(windows)]
        ShellKind::PowerShell => parse_plain_powershell_command_sequence(shell_input.script()),
        #[cfg(windows)]
        ShellKind::Cmd => None,
    };

    commands.is_some_and(|commands| {
        !commands.is_empty()
            && commands
                .iter()
                .all(|command| is_read_only_direct_process_argv(command))
    })
}

fn is_read_only_echo_args(args: &[String]) -> bool {
    !args.iter().any(|arg| arg.starts_with('-'))
}

fn is_read_only_wc_args(args: &[String]) -> bool {
    match args {
        [] => true,
        [flag_or_file] => {
            is_read_only_wc_flag(flag_or_file) || is_workspace_relative_file_argument(flag_or_file)
        }
        [flag, file] => is_read_only_wc_flag(flag) && is_workspace_relative_file_argument(file),
        _ => false,
    }
}

fn is_read_only_wc_flag(flag: &str) -> bool {
    matches!(flag, "-l" | "-w" | "-c" | "-m")
}

fn is_read_only_head_or_tail_args(args: &[String]) -> bool {
    match args {
        [] => true,
        [file] => is_workspace_relative_file_argument(file),
        [count_flag, count] if count_flag.as_str() == "-n" => is_positive_decimal(count),
        [count_flag, count, file] if count_flag.as_str() == "-n" => {
            is_positive_decimal(count) && is_workspace_relative_file_argument(file)
        }
        _ => false,
    }
}

fn is_read_only_rg_single_argument(argument: &str) -> bool {
    argument == "--version" || argument == "--files" || is_simple_rg_literal_pattern(argument)
}

fn is_simple_rg_literal_pattern(pattern: &str) -> bool {
    !pattern.starts_with('-') && !pattern.chars().any(is_rg_regex_metacharacter)
}

fn is_rg_regex_metacharacter(character: char) -> bool {
    matches!(
        character,
        '\\' | '.' | '^' | '$' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|'
    )
}

fn is_read_only_sed_print_range(range: &str) -> bool {
    let Some(line_range) = range.strip_suffix('p') else {
        return false;
    };
    if line_range.is_empty() {
        return false;
    }
    let mut parts = line_range.split(',');
    let Some(start) = parts.next() else {
        return false;
    };
    if !is_positive_decimal(start) {
        return false;
    }
    match (parts.next(), parts.next()) {
        (None, None) => true,
        (Some(end), None) => is_positive_decimal(end),
        _ => false,
    }
}

pub(super) fn is_positive_decimal(value: &str) -> bool {
    !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) && value != "0"
}

pub(super) fn is_workspace_relative_file_argument(argument: &str) -> bool {
    if argument.starts_with('-')
        || Path::new(argument).is_absolute()
        || has_windows_drive_prefix(argument)
    {
        return false;
    }
    #[cfg(windows)]
    {
        !argument.starts_with(['/', '\\'])
            && !argument
                .split(['/', '\\'])
                .any(|segment| segment.is_empty() || segment == "." || segment == "..")
    }
    #[cfg(not(windows))]
    {
        !argument.split('/').any(|segment| {
            segment.is_empty() || segment == "." || segment == ".." || segment.contains('\\')
        })
    }
}

fn is_local_workspace_effect_process_argv(argv: &[String]) -> bool {
    matches!(
        argv,
        [cargo, command, package_flag, package]
            if executable_token_is(cargo, "cargo")
                && matches!(command.as_str(), "test" | "check")
                && (package_flag.as_str() == "-p" || package_flag.as_str() == "--package")
                && is_safe_cargo_package_token(package)
    )
}

pub(crate) fn is_safe_cargo_package_token(package: &str) -> bool {
    !package.is_empty()
        && !package.starts_with('-')
        && package
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
}

fn is_forbidden_process_argv(argv: &[String]) -> bool {
    if let Some(shell_input) = shell_like_process_input_from_argv(argv) {
        return shell_script_contains_forbidden_process(shell_input.kind(), shell_input.script());
    }

    is_forbidden_direct_process_argv(argv)
}

fn is_forbidden_direct_process_argv(argv: &[String]) -> bool {
    if command_words_have_env_injection(argv) {
        return true;
    }
    let argv = strip_shell_command_prefixes(argv);
    let Some(executable) = argv.first().map(|argument| executable_name(argument)) else {
        return false;
    };

    if executable == "rm" {
        return rm_invocation_requires_review(argv);
    }

    if FORBIDDEN_PROCESS_EXECUTABLES.contains(&executable.as_str()) {
        return true;
    }

    if executable == "git" {
        return git_invocation_is_forbidden(argv);
    }

    false
}

/// Peels common command wrappers (`env`, `timeout`, `command`, `exec`, `nohup`,
/// `time`, `builtin`, `!`) so forbidden executables behind them are still
/// detected.
pub(super) fn strip_shell_command_prefixes(mut argv: &[String]) -> &[String] {
    for _ in 0..8 {
        let Some(first) = argv.first() else {
            return argv;
        };
        if matches!(
            first.as_str(),
            "!" | "time" | "exec" | "command" | "builtin" | "nohup"
        ) {
            argv = &argv[1..];
            continue;
        }
        let head = executable_name(first);
        if head == "env" {
            let mut idx = 1;
            let mut options_done = false;
            while let Some(arg) = argv.get(idx) {
                if !options_done && arg == "--" {
                    options_done = true;
                    idx += 1;
                    continue;
                }
                if !options_done && arg.starts_with('-') {
                    idx += 1;
                    continue;
                }
                if arg.contains('=') && !arg.starts_with('=') {
                    idx += 1;
                    continue;
                }
                break;
            }
            argv = &argv[idx..];
            continue;
        }
        if head == "timeout" {
            let mut idx = 1;
            while let Some(arg) = argv.get(idx) {
                if matches!(arg.as_str(), "-k" | "--kill-after" | "-s" | "--signal") {
                    idx += 2;
                    continue;
                }
                if arg.starts_with('-') {
                    idx += 1;
                    continue;
                }
                // Consume the duration positional operand.
                idx += 1;
                break;
            }
            argv = argv.get(idx..).unwrap_or(&[]);
            continue;
        }
        break;
    }
    argv
}

fn shell_script_contains_forbidden_process(kind: ShellKind, script: &str) -> bool {
    match kind {
        ShellKind::Bash => {
            let Some(analysis) = parse_bash_security_analysis(script) else {
                // Syntax error or unparseable shell structure: fail closed.
                return true;
            };
            analysis.env_injection
                || analysis
                    .commands
                    .iter()
                    .any(|command| is_forbidden_direct_process_argv(command))
        }
        #[cfg(windows)]
        ShellKind::PowerShell => {
            let Some(analysis) = analyze_powershell_script(script) else {
                return true;
            };
            analysis.env_or_eval_injection
                || analysis.has_destructive_delete
                || analysis
                    .commands
                    .iter()
                    .any(|command| is_forbidden_direct_process_argv(command))
        }
        #[cfg(windows)]
        ShellKind::Cmd => true,
    }
}

const FORBIDDEN_PROCESS_EXECUTABLES: &[&str] = &[
    "bash",
    "cmd",
    "powershell",
    "pwsh",
    "sh",
    "su",
    "sudo",
    "zsh",
];

/// A plain `rm` of named files does not need a second review. Recursive deletes
/// and operands that wipe a tree still do. An unparsed shell mention of `rm`
/// stays under review because the flags are not reliable there.
fn rm_invocation_requires_review(argv: &[String]) -> bool {
    rm_review_target(argv).is_some()
}

/// Returns `Some(target_summary)` when an `rm` invocation requires review.
pub(super) fn rm_review_target(argv: &[String]) -> Option<Option<String>> {
    let mut operands = Vec::new();
    let mut end_of_flags = false;
    let mut recursive = false;
    for argument in argv.iter().skip(1) {
        if !end_of_flags && argument == "--" {
            end_of_flags = true;
            continue;
        }
        if !end_of_flags && argument.starts_with('-') {
            if rm_flag_requires_review(argument) {
                recursive = true;
            }
            continue;
        }
        operands.push(argument.as_str());
    }
    if recursive
        || operands.is_empty()
        || operands
            .iter()
            .any(|operand| rm_operand_requires_review(operand))
    {
        return Some(operands.first().map(|target| (*target).to_owned()));
    }
    None
}

fn rm_flag_requires_review(flag: &str) -> bool {
    if flag == "--recursive" || flag == "--dir" {
        return true;
    }
    let Some(cluster) = flag.strip_prefix('-') else {
        return false;
    };
    if cluster.starts_with('-') {
        return false;
    }
    cluster
        .chars()
        .any(|character| matches!(character, 'r' | 'R'))
}

fn rm_operand_requires_review(operand: &str) -> bool {
    operand.is_empty()
        || operand == "."
        || operand == ".."
        || operand == "/"
        || operand == "*"
        || operand == "~"
        || operand.ends_with("/*")
        || operand
            .chars()
            .any(|character| matches!(character, '*' | '?' | '[' | '{' | '$' | '`'))
}

/// Returns whether a process intent may enter the SP3-A low-risk process lane.
///
/// The first admitted lane is intentionally fail-closed. It is a small read-only
/// injected-runner allowset, not a general command risk model:
/// no inherited/supplied environment, no stdin text, and only deterministic
/// read-only argv shapes explicitly recognized by SP3-A. Future slices can
/// expand this predicate only with a real policy model and execution evidence
/// for the additional process inputs.
#[must_use]
pub fn is_low_risk_process_action_intent(intent: &ProcessActionIntent) -> bool {
    required_process_permission_profile_id(intent) == Some(ProcessPermissionProfileId::READ_ONLY)
}

/// Returns whether a process intent is a plain read-only shell-wrapper action.
///
/// This predicate is intentionally separate from the structured read-only
/// process lane. It recognizes only `bash`/`sh`/`zsh -c|-lc` scripts composed
/// of plain word commands joined by `|`, `&&`, `||`, or `;`, and it requires
/// each segment to match the direct read-only process classifier. It is not a
/// general shell parser and must be paired with an explicit shell runner
/// admission before execution.
#[must_use]
pub fn is_read_only_shell_process_action_intent(intent: &ProcessActionIntent) -> bool {
    required_process_permission_profile_id(intent)
        == Some(ProcessPermissionProfileId::SHELL_READ_ONLY)
}

pub(crate) fn required_process_permission_profile_id(
    intent: &ProcessActionIntent,
) -> Option<ProcessPermissionProfileId> {
    if intent.env_policy() != ProcessEnvPolicy::Empty || intent.stdin_text().is_some() {
        return Some(ProcessPermissionProfileId::LOCAL_WORKSPACE);
    }

    if is_read_only_plain_shell_process_argv(intent.argv()) {
        return Some(ProcessPermissionProfileId::SHELL_READ_ONLY);
    }

    match classify_process_intent(intent) {
        ProcessIntentClass::Informational => Some(ProcessPermissionProfileId::READ_ONLY),
        ProcessIntentClass::LocalWorkspaceEffect => {
            Some(ProcessPermissionProfileId::LOCAL_WORKSPACE)
        }
        ProcessIntentClass::Unknown => Some(ProcessPermissionProfileId::LOCAL_WORKSPACE),
        // Classification is a risk signal, not a command allowlist. The
        // selected runner remains the authority for capability enforcement.
        ProcessIntentClass::Forbidden => Some(ProcessPermissionProfileId::LOCAL_WORKSPACE),
    }
}

/// Returns whether the process classifier requires an independent action
/// review before execution.
///
/// Unknown commands are still admitted by the configured sandbox runner;
/// only the explicit high-risk classification triggers this second gate.
#[cfg(test)]
#[must_use]
pub(crate) fn requires_process_action_review(intent: &ProcessActionIntent) -> bool {
    matches!(
        classify_process_intent(intent),
        ProcessIntentClass::Forbidden
    )
}

fn has_windows_drive_prefix(value: &str) -> bool {
    let bytes = value.as_bytes();
    bytes.len() >= 2
        && bytes[0].is_ascii_alphabetic()
        && bytes[1] == b':'
        && (bytes.len() == 2 || matches!(bytes[2], b'\\' | b'/'))
}