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
//! Narrow shell-wrapper recognition, tree-sitter-bash AST normalization, and
//! Windows PowerShell detection/analysis; policy stays in the classifier.

use crate::process::contracts::ProcessActionIntent;

#[cfg(windows)]
use super::windows_shell;

/// Shell grammar family represented by one recognized shell wrapper argv.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ShellKind {
    /// POSIX/Bash-compatible shell (`bash`, `sh`, `zsh`, Git Bash).
    Bash,
    /// PowerShell (`pwsh`, `powershell`, `powershell.exe`).
    #[cfg(windows)]
    PowerShell,
    /// Windows Command Prompt (`cmd`, `cmd.exe`).
    #[cfg(windows)]
    Cmd,
}

/// Exact shell-wrapper input plus payload-free metadata helpers.
///
/// This value recognizes only the validated wrapper shape used by the current
/// shell read-only lane. It does not authorize execution by itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ShellProcessInput<'a> {
    pub(super) kind: ShellKind,
    pub(super) shell: &'a str,
    pub(super) flag: &'a str,
    pub(super) script: &'a str,
}

impl<'a> ShellProcessInput<'a> {
    pub(crate) const fn kind(self) -> ShellKind {
        self.kind
    }

    pub(crate) const fn shell(self) -> &'a str {
        self.shell
    }

    pub(crate) const fn flag(self) -> &'a str {
        self.flag
    }

    pub(crate) const fn script(self) -> &'a str {
        self.script
    }

    pub(crate) const fn script_bytes(self) -> usize {
        self.script.len()
    }

    pub(crate) fn script_fingerprint(self) -> String {
        stable_process_input_fingerprint(self.script.as_bytes())
    }
}

pub(crate) fn shell_process_input(intent: &ProcessActionIntent) -> Option<ShellProcessInput<'_>> {
    shell_process_input_from_argv(intent.argv())
}

/// Converts one model-facing shell command into the platform process argv
/// consumed by runtime policy and process runners.
pub(crate) fn shell_command_argv(command: &str) -> Vec<String> {
    #[cfg(windows)]
    {
        windows_shell::detect_windows_shell().command_argv(command)
    }

    #[cfg(not(windows))]
    {
        vec!["bash".to_owned(), "-lc".to_owned(), command.to_owned()]
    }
}

/// Returns the command script represented by a platform shell argv wrapper.
pub(crate) fn shell_command_from_argv(argv: &[String]) -> Option<&str> {
    #[cfg(windows)]
    {
        match argv {
            [shell, no_profile, non_interactive, flag, command]
                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
                    && no_profile.eq_ignore_ascii_case("-NoProfile")
                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
                    && flag.eq_ignore_ascii_case("-Command") =>
            {
                Some(command)
            }
            [shell, no_profile, flag, command]
                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
                    && no_profile.eq_ignore_ascii_case("-NoProfile")
                    && flag.eq_ignore_ascii_case("-Command") =>
            {
                Some(command)
            }
            [shell, flag, command]
                if executable_name(shell) == "bash" && matches!(flag.as_str(), "-c" | "-lc") =>
            {
                Some(command)
            }
            [shell, flag, command]
                if executable_name(shell) == "cmd" && flag.eq_ignore_ascii_case("/C") =>
            {
                Some(command)
            }
            _ => None,
        }
    }

    #[cfg(not(windows))]
    {
        match argv {
            [shell, flag, command] if shell == "bash" && matches!(flag.as_str(), "-c" | "-lc") => {
                Some(command)
            }
            _ => None,
        }
    }
}

/// Converts an argv vector into one shell command string for a model-facing
/// command field. Existing platform shell wrappers are unwrapped so their
/// script is preserved; direct argv items are quoted for the host shell.
#[must_use]
pub fn shell_command_for_argv(argv: &[String]) -> String {
    if let Some(command) = shell_command_from_argv(argv) {
        return command.to_owned();
    }

    argv.iter()
        .map(|argument| shell_quote_argument(argument))
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(not(windows))]
pub(super) fn shell_quote_argument(argument: &str) -> String {
    if !argument.is_empty() && argument.bytes().all(is_safe_shell_word_byte) {
        return argument.to_owned();
    }
    format!("'{}'", argument.replace('\'', "'\\''"))
}

#[cfg(windows)]
pub(super) fn shell_quote_argument(argument: &str) -> String {
    if !argument.is_empty() && argument.bytes().all(is_safe_shell_word_byte) {
        return argument.to_owned();
    }
    format!("'{}'", argument.replace('\'', "''"))
}

pub(super) fn is_safe_shell_word_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric()
        || matches!(
            byte,
            b'_' | b'-' | b'.' | b'/' | b':' | b'=' | b'@' | b'%' | b'+'
        )
}

pub(super) fn shell_process_input_from_argv(argv: &[String]) -> Option<ShellProcessInput<'_>> {
    #[cfg(windows)]
    {
        match argv {
            [shell, no_profile, non_interactive, flag, script]
                if is_supported_plain_shell_token(shell)
                    && no_profile.eq_ignore_ascii_case("-NoProfile")
                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
                    && flag.eq_ignore_ascii_case("-Command") =>
            {
                Some(ShellProcessInput {
                    kind: ShellKind::PowerShell,
                    shell,
                    flag,
                    script,
                })
            }
            [shell, no_profile, flag, script]
                if is_supported_plain_shell_token(shell)
                    && no_profile.eq_ignore_ascii_case("-NoProfile")
                    && flag.eq_ignore_ascii_case("-Command") =>
            {
                Some(ShellProcessInput {
                    kind: ShellKind::PowerShell,
                    shell,
                    flag,
                    script,
                })
            }
            [shell, flag, script]
                if is_supported_plain_bash_token(shell)
                    && matches!(flag.as_str(), "-c" | "-lc") =>
            {
                Some(ShellProcessInput {
                    kind: ShellKind::Bash,
                    shell,
                    flag,
                    script,
                })
            }
            _ => None,
        }
    }

    #[cfg(not(windows))]
    {
        let [shell, flag, script] = argv else {
            return None;
        };
        if !is_supported_plain_shell_token(shell) || !matches!(flag.as_str(), "-c" | "-lc") {
            return None;
        }
        Some(ShellProcessInput {
            kind: ShellKind::Bash,
            shell,
            flag,
            script,
        })
    }
}

pub(super) fn is_supported_plain_shell_token(shell: &str) -> bool {
    #[cfg(windows)]
    {
        !shell.contains(['/', '\\'])
            && matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
    }

    #[cfg(not(windows))]
    matches!(shell, "bash" | "sh" | "zsh")
}

#[cfg(windows)]
fn is_supported_plain_bash_token(shell: &str) -> bool {
    if !shell.contains(['/', '\\']) {
        return matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh");
    }
    matches!(
        windows_shell::detect_windows_shell(),
        windows_shell::WindowsShell::GitBash(path)
            if path.to_string_lossy().eq_ignore_ascii_case(shell)
    )
}

pub(crate) fn stable_process_input_fingerprint(bytes: &[u8]) -> String {
    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    let hash = bytes.iter().fold(FNV_OFFSET_BASIS, |hash, byte| {
        (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
    });
    format!("fnv1a64:{hash:016x}")
}

pub(super) fn shell_like_process_input_from_argv(argv: &[String]) -> Option<ShellProcessInput<'_>> {
    #[cfg(windows)]
    {
        match argv {
            [shell, no_profile, non_interactive, flag, script]
                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
                    && no_profile.eq_ignore_ascii_case("-NoProfile")
                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
                    && flag.eq_ignore_ascii_case("-Command") =>
            {
                Some(ShellProcessInput {
                    kind: ShellKind::PowerShell,
                    shell,
                    flag,
                    script,
                })
            }
            [shell, no_profile, flag, script]
                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
                    && no_profile.eq_ignore_ascii_case("-NoProfile")
                    && flag.eq_ignore_ascii_case("-Command") =>
            {
                Some(ShellProcessInput {
                    kind: ShellKind::PowerShell,
                    shell,
                    flag,
                    script,
                })
            }
            [shell, flag, script]
                if matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh")
                    && matches!(flag.as_str(), "-c" | "-lc") =>
            {
                Some(ShellProcessInput {
                    kind: ShellKind::Bash,
                    shell,
                    flag,
                    script,
                })
            }
            [shell, flag, script]
                if executable_name(shell) == "cmd" && flag.eq_ignore_ascii_case("/C") =>
            {
                Some(ShellProcessInput {
                    kind: ShellKind::Cmd,
                    shell,
                    flag,
                    script,
                })
            }
            _ => None,
        }
    }

    #[cfg(not(windows))]
    {
        let [shell, flag, script] = argv else {
            return None;
        };
        if !is_supported_shell_executable_name(shell) || !matches!(flag.as_str(), "-c" | "-lc") {
            return None;
        }
        Some(ShellProcessInput {
            kind: ShellKind::Bash,
            shell,
            flag,
            script,
        })
    }
}

#[cfg(not(windows))]
pub(super) fn is_supported_shell_executable_name(shell: &str) -> bool {
    matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh")
}

/// AST-derived security summary of one parsed bash script.
pub(super) struct BashSecurityAnalysis {
    /// Every command node found anywhere in the AST (including inside control
    /// flow, subshells, and `$(...)`/backtick substitutions), in source order.
    pub(super) commands: Vec<Vec<String>>,
    /// True if any inline assignment, `export`/`declare`, or `env` invocation
    /// sets an execution-injecting environment variable or uses `env -S`.
    pub(super) env_injection: bool,
}

const INJECTION_ENV_KEYS: &[&str] = &[
    "LD_PRELOAD",
    "LD_AUDIT",
    "BASH_ENV",
    "ENV",
    "IFS",
    "PATH",
    "GIT_EXTERNAL_DIFF",
    "GIT_PROXY_COMMAND",
    "PROMPT_COMMAND",
];

const INJECTION_ENV_KEY_PREFIXES: &[&str] = &["DYLD_", "GIT_CONFIG"];

pub(super) fn is_injection_env_key(key: &str) -> bool {
    INJECTION_ENV_KEYS.contains(&key)
        || INJECTION_ENV_KEY_PREFIXES
            .iter()
            .any(|prefix| key.starts_with(prefix))
}

/// Parses a strictly plain, expansion-free, redirect-free command sequence
/// joined only by `;`, `|`, `||`, or `&&` (used by the narrow SP3-A shell
/// read-only lane). Fails closed when the `bash-ast` feature is disabled.
pub(super) fn parse_plain_shell_command_sequence(script: &str) -> Option<Vec<Vec<String>>> {
    #[cfg(feature = "bash-ast")]
    {
        super::bash_ast::parse_plain_shell_command_sequence(script)
    }
    #[cfg(not(feature = "bash-ast"))]
    {
        let _ = script;
        None
    }
}

/// Parses a bash script into an AST security summary. Returns `None` on syntax
/// errors or when `bash-ast` is disabled so callers fail closed.
pub(super) fn parse_bash_security_analysis(script: &str) -> Option<BashSecurityAnalysis> {
    #[cfg(feature = "bash-ast")]
    {
        super::bash_ast::parse_bash_security_analysis(script)
    }
    #[cfg(not(feature = "bash-ast"))]
    {
        let _ = script;
        None
    }
}

/// Detects dangerous `env` invocations (`env -S`, `env LD_PRELOAD=...`, etc.)
/// even behind wrapper chains such as `timeout 5 env ...`.
pub(super) fn command_words_have_env_injection(words: &[String]) -> bool {
    let mut index = 0;
    while let Some(head) = words.get(index) {
        let name = executable_name(head);
        if name == "env" {
            let mut options_done = false;
            for arg in &words[index + 1..] {
                if !options_done && arg == "--" {
                    options_done = true;
                    continue;
                }
                if !options_done && arg.starts_with('-') {
                    // `-S` / `--split-string` rewrites argv and can smuggle commands.
                    if arg == "-S"
                        || arg.starts_with("-S")
                        || arg == "--split-string"
                        || arg.starts_with("--split-string=")
                        || (!arg.starts_with("--") && arg.contains('S'))
                    {
                        return true;
                    }
                    continue;
                }
                if let Some((key, _)) = arg.split_once('=') {
                    if is_injection_env_key(key) {
                        return true;
                    }
                    continue;
                }
                break;
            }
            return false;
        }
        if matches!(
            head.as_str(),
            "!" | "time" | "exec" | "command" | "builtin" | "nohup"
        ) {
            index += 1;
            continue;
        }
        if name == "timeout" {
            index += 1;
            while let Some(arg) = words.get(index) {
                if matches!(arg.as_str(), "-k" | "--kill-after" | "-s" | "--signal") {
                    index += 2;
                    continue;
                }
                if arg.starts_with('-') {
                    index += 1;
                    continue;
                }
                index += 1;
                break;
            }
            continue;
        }
        break;
    }
    false
}

pub(super) fn executable_name(argument: &str) -> String {
    let base = argument
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(argument)
        .to_ascii_lowercase();
    for suffix in [".exe", ".cmd", ".bat", ".com"] {
        if let Some(stripped) = base.strip_suffix(suffix)
            && !stripped.is_empty()
        {
            return stripped.to_owned();
        }
    }
    base
}

pub(super) fn executable_token_is(argument: &str, expected: &str) -> bool {
    #[cfg(windows)]
    {
        argument.eq_ignore_ascii_case(expected)
            || argument
                .strip_suffix(".exe")
                .or_else(|| argument.strip_suffix(".EXE"))
                .is_some_and(|stripped| stripped.eq_ignore_ascii_case(expected))
    }
    #[cfg(not(windows))]
    {
        argument == expected
    }
}