merry-runtime 0.1.4

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
//! Tree-sitter Bash AST parsing for read-only shell classification and
//! security-summary extraction.

use super::shell::{BashSecurityAnalysis, command_words_have_env_injection, is_injection_env_key};
use tree_sitter::{Node, Parser, Tree};
use tree_sitter_bash::LANGUAGE as BASH_LANGUAGE;

fn try_parse_bash(script: &str) -> Option<Tree> {
    let mut parser = Parser::new();
    parser.set_language(&BASH_LANGUAGE.into()).ok()?;
    parser.parse(script, None)
}

/// Parses a strictly plain, expansion-free, redirect-free command sequence
/// joined only by `;`, `|`, `||`, or `&&` (used by the narrow SP3-A shell
/// read-only lane).
pub(super) fn parse_plain_shell_command_sequence(script: &str) -> Option<Vec<Vec<String>>> {
    let tree = try_parse_bash(script)?;
    let root = tree.root_node();
    if root.has_error() {
        return None;
    }

    const ALLOWED_KINDS: &[&str] = &[
        "program",
        "list",
        "pipeline",
        "command",
        "command_name",
        "word",
        "string",
        "string_content",
        "raw_string",
        "number",
        "concatenation",
    ];
    const ALLOWED_PUNCT: &[&str] = &["&&", "||", ";", "|", "\"", "'"];

    let mut stack = vec![root];
    let mut command_nodes = Vec::new();
    while let Some(node) = stack.pop() {
        let kind = node.kind();
        if node.is_named() {
            if !ALLOWED_KINDS.contains(&kind) {
                return None;
            }
            if kind == "command" {
                command_nodes.push(node);
            }
        } else if !(ALLOWED_PUNCT.contains(&kind) || kind.trim().is_empty()) {
            return None;
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            stack.push(child);
        }
    }

    if command_nodes.is_empty() {
        return None;
    }
    command_nodes.sort_by_key(Node::start_byte);

    let mut commands = Vec::with_capacity(command_nodes.len());
    for command_node in command_nodes {
        let mut words = Vec::new();
        let mut cursor = command_node.walk();
        for child in command_node.children(&mut cursor) {
            if !child.is_named() {
                continue;
            }
            let word = decode_strict_plain_word(child, script)?;
            if word.is_empty() {
                return None;
            }
            words.push(word);
        }
        if words.is_empty() {
            return None;
        }
        commands.push(words);
    }
    Some(commands)
}

fn decode_strict_plain_word(node: Node<'_>, src: &str) -> Option<String> {
    match node.kind() {
        "command_name" => {
            let child = node.named_child(0)?;
            decode_strict_plain_word(child, src)
        }
        "word" | "number" => {
            let text = node.utf8_text(src.as_bytes()).ok()?;
            if text.chars().any(shell_word_character_is_disallowed) {
                return None;
            }
            Some(text.to_owned())
        }
        "raw_string" => {
            let text = node.utf8_text(src.as_bytes()).ok()?;
            text.strip_prefix('\'')
                .and_then(|rest| rest.strip_suffix('\''))
                .map(str::to_owned)
        }
        "string" => {
            let mut out = String::new();
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if !child.is_named() {
                    continue;
                }
                if child.kind() != "string_content" {
                    return None;
                }
                let text = child.utf8_text(src.as_bytes()).ok()?;
                if text.chars().any(|ch| matches!(ch, '$' | '`' | '\\' | '!')) {
                    return None;
                }
                out.push_str(text);
            }
            Some(out)
        }
        "concatenation" => {
            let mut out = String::new();
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.is_named() {
                    out.push_str(&decode_strict_plain_word(child, src)?);
                }
            }
            Some(out)
        }
        _ => None,
    }
}

fn shell_word_character_is_disallowed(character: char) -> bool {
    matches!(
        character,
        '$' | '`'
            | '\\'
            | '<'
            | '>'
            | '('
            | ')'
            | '{'
            | '}'
            | '['
            | ']'
            | '*'
            | '?'
            | '~'
            | '#'
            | '!'
    )
}

/// Parses a bash script into an AST security summary. Returns `None` on syntax
/// errors (such as unclosed quotes) so callers fail closed.
pub(super) fn parse_bash_security_analysis(script: &str) -> Option<BashSecurityAnalysis> {
    let tree = try_parse_bash(script)?;
    let root = tree.root_node();
    if root.has_error() {
        return None;
    }

    let mut stack = vec![root];
    let mut command_nodes = Vec::new();
    let mut env_injection = false;

    while let Some(node) = stack.pop() {
        match node.kind() {
            "command" => command_nodes.push(node),
            "variable_assignment" => {
                if let Some(key) = variable_assignment_key(node, script)
                    && is_injection_env_key(key)
                {
                    env_injection = true;
                }
            }
            _ => {}
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            stack.push(child);
        }
    }

    command_nodes.sort_by_key(Node::start_byte);

    let mut commands = Vec::with_capacity(command_nodes.len());
    for command_node in command_nodes {
        let mut words = Vec::new();
        let mut cursor = command_node.walk();
        for child in command_node.children(&mut cursor) {
            if !child.is_named() {
                continue;
            }
            if matches!(
                child.kind(),
                "variable_assignment" | "file_redirect" | "heredoc_redirect" | "comment"
            ) {
                continue;
            }
            let decoded = decode_security_word(child, script);
            if !decoded.is_empty() {
                words.push(decoded);
            }
        }
        if !words.is_empty() {
            if command_words_have_env_injection(&words) {
                env_injection = true;
            }
            commands.push(words);
        }
    }

    Some(BashSecurityAnalysis {
        commands,
        env_injection,
    })
}

fn variable_assignment_key<'a>(node: Node<'_>, src: &'a str) -> Option<&'a str> {
    if let Some(name_node) = node.child_by_field_name("name")
        && let Ok(text) = name_node.utf8_text(src.as_bytes())
    {
        return Some(text);
    }
    node.utf8_text(src.as_bytes())
        .ok()
        .and_then(|text| text.split('=').next())
}

/// Decodes a command word for security analysis. Expansion-free quotes are
/// unwrapped so `env "LD_PRELOAD=..."` or `"rm"` cannot hide behind quoting;
/// dynamic nodes keep their raw source text so `$VAR`/`$(...)` remain visible.
fn decode_security_word(node: Node<'_>, src: &str) -> String {
    match node.kind() {
        "command_name" => node
            .named_child(0)
            .map(|child| decode_security_word(child, src))
            .unwrap_or_default(),
        "raw_string" => node
            .utf8_text(src.as_bytes())
            .ok()
            .and_then(|text| {
                text.strip_prefix('\'')
                    .and_then(|rest| rest.strip_suffix('\''))
            })
            .unwrap_or_default()
            .to_owned(),
        "string" => {
            let mut out = String::new();
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if !child.is_named() {
                    continue;
                }
                if child.kind() == "string_content" {
                    if let Ok(text) = child.utf8_text(src.as_bytes()) {
                        out.push_str(text);
                    }
                } else if let Ok(text) = child.utf8_text(src.as_bytes()) {
                    out.push_str(text);
                }
            }
            out
        }
        "concatenation" => {
            let mut out = String::new();
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.is_named() {
                    out.push_str(&decode_security_word(child, src));
                }
            }
            out
        }
        _ => node.utf8_text(src.as_bytes()).unwrap_or("").to_owned(),
    }
}