minutes-cli 0.35.2

CLI for minutes — record, transcribe, and search conversation memory
//! Program Resume Protocol (OSC 7577) for read-only view panes.
//!
//! Lets terminals such as Rex and herdr restore read-only view panes (like
//! `minutes transcript --follow`) after a terminal restart.
//!
//! Capture commands (`minutes record`, `minutes live`, `minutes dictate`) MUST
//! NEVER register for resume — restarting capture automatically without the
//! user is a consent violation (RFC 0008). Minutes also never edits the user's
//! terminal configuration; [`rex_trust_rule_snippet`] prints an opt-in rule the
//! user can add to `~/.config/rex/init.lua` if they want automatic restore.

use crate::program_status::base64_standard;
use std::io::{IsTerminal, Write};
use std::time::{SystemTime, UNIX_EPOCH};

/// Environment variable supplied by terminals that implement OSC 7577.
pub const TOKEN_ENV: &str = "OSC7577_TOKEN";

/// Validate a terminal-provided OSC 7577 token per spec:
/// 22–64 ASCII characters in `[A-Za-z0-9_-]`.
pub fn is_valid_token(token: &str) -> bool {
    (22..=64).contains(&token.len())
        && token
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// Validate a resume command argument list per OSC 7577:
/// - non-empty
/// - `argv[0]` is a bare command name (not starting with `-`, no path separator)
///   or an absolute path (no relative paths like `./minutes`)
/// - no element contains C0/DEL/C1 control characters
pub fn validate_argv(argv: &[&str]) -> bool {
    let Some((first, _)) = argv.split_first() else {
        return false;
    };
    if first.is_empty() {
        return false;
    }
    let has_sep = first.contains('/') || first.contains('\\');
    if has_sep {
        // Must be absolute, never relative.
        let is_unix_abs = first.starts_with('/');
        let is_win_abs = first.len() >= 3
            && first.as_bytes()[0].is_ascii_alphabetic()
            && first.as_bytes()[1] == b':'
            && (first.as_bytes()[2] == b'\\' || first.as_bytes()[2] == b'/');
        if !is_unix_abs && !is_win_abs {
            return false;
        }
    } else if first.starts_with('-') {
        return false;
    }

    argv.iter().all(|arg| !contains_osc7577_control(arg))
}

fn contains_osc7577_control(text: &str) -> bool {
    text.chars().any(|ch| {
        let code = ch as u32;
        code <= 0x1F || code == 0x7F || (0x80..=0x9F).contains(&code)
    })
}

/// Format an OSC 7577 resume registration sequence, returning `None` if the
/// inputs violate protocol rules.
pub fn format_resume_report(
    pid: u32,
    unix_secs: u64,
    argv: &[&str],
    token: &str,
) -> Option<String> {
    if pid == 0 || unix_secs == 0 || !is_valid_token(token) || !validate_argv(argv) {
        return None;
    }
    let encoded_argv: Vec<String> = argv
        .iter()
        .map(|arg| base64_standard(arg.as_bytes()))
        .collect();
    let body = format!("pid={pid}:time={unix_secs}:argv={}", encoded_argv.join(","));
    let mac = compute_mac(&body, token);
    Some(format!("\x1b]7577;{body}:mac={mac}\x1b\\"))
}

/// Format an OSC 7577 clear sequence for `pid`.
pub fn format_clear_report(pid: u32, unix_secs: u64, token: &str) -> Option<String> {
    if pid == 0 || unix_secs == 0 || !is_valid_token(token) {
        return None;
    }
    let body = format!("pid={pid}:time={unix_secs}:clear=1");
    let mac = compute_mac(&body, token);
    Some(format!("\x1b]7577;{body}:mac={mac}\x1b\\"))
}

/// Compute the OSC 7577 `mac` field: lowercase hex SHA-256 of `<body_without_mac>:<token>`.
pub fn compute_mac(body: &str, token: &str) -> String {
    let mut input = Vec::with_capacity(body.len() + 1 + token.len());
    input.extend_from_slice(body.as_bytes());
    input.push(b':');
    input.extend_from_slice(token.as_bytes());
    let digest = sha256(&input);
    let mut hex = String::with_capacity(64);
    for byte in digest {
        hex.push_str(&format!("{byte:02x}"));
    }
    hex
}

/// Self-contained FIPS 180-4 SHA-256. Kept local so `crates/cli/Cargo.toml`
/// gains no dependency (preserving the graph-worker packaging boundary hash).
fn sha256(data: &[u8]) -> [u8; 32] {
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
        0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
        0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
        0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
        0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
        0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
        0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
        0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
        0xc67178f2,
    ];

    let mut h: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
        0x5be0cd19,
    ];

    let bit_len = (data.len() as u64).wrapping_mul(8);
    let mut padded = Vec::with_capacity((data.len() + 9).div_ceil(64) * 64);
    padded.extend_from_slice(data);
    padded.push(0x80);
    while (padded.len() % 64) != 56 {
        padded.push(0);
    }
    padded.extend_from_slice(&bit_len.to_be_bytes());

    for block in padded.chunks_exact(64) {
        let mut w = [0u32; 64];
        for (i, chunk) in block.chunks_exact(4).enumerate() {
            w[i] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
        }
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16]
                .wrapping_add(s0)
                .wrapping_add(w[i - 7])
                .wrapping_add(s1);
        }

        let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
        for i in 0..64 {
            let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
            let ch = (e & f) ^ ((!e) & g);
            let temp1 = hh
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
            let maj = (a & b) ^ (a & c) ^ (b & c);
            let temp2 = s0.wrapping_add(maj);

            hh = g;
            g = f;
            f = e;
            e = d.wrapping_add(temp1);
            d = c;
            c = b;
            b = a;
            a = temp1.wrapping_add(temp2);
        }

        h[0] = h[0].wrapping_add(a);
        h[1] = h[1].wrapping_add(b);
        h[2] = h[2].wrapping_add(c);
        h[3] = h[3].wrapping_add(d);
        h[4] = h[4].wrapping_add(e);
        h[5] = h[5].wrapping_add(f);
        h[6] = h[6].wrapping_add(g);
        h[7] = h[7].wrapping_add(hh);
    }

    let mut out = [0u8; 32];
    for (i, word) in h.iter().enumerate() {
        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

fn unix_timestamp_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// RAII registration for a read-only view pane's OSC 7577 resume record.
/// Emits `clear=1` on drop so the terminal drops the record on clean exit.
pub struct ResumeGuard {
    pid: u32,
    token: Option<String>,
}

impl ResumeGuard {
    /// Register a read-only view command when stderr is a terminal and
    /// `OSC7577_TOKEN` is set. Silently inert otherwise.
    pub fn register_view(argv: &[&str]) -> Self {
        if !std::io::stderr().is_terminal() {
            return Self::inert();
        }
        let Ok(token) = std::env::var(TOKEN_ENV) else {
            return Self::inert();
        };
        if !is_valid_token(&token) {
            return Self::inert();
        }
        let pid = std::process::id();
        let now = unix_timestamp_secs();
        let Some(seq) = format_resume_report(pid, now, argv, &token) else {
            return Self::inert();
        };
        let mut stderr = std::io::stderr();
        let _ = stderr.write_all(seq.as_bytes());
        let _ = stderr.flush();
        Self {
            pid,
            token: Some(token),
        }
    }

    fn inert() -> Self {
        Self {
            pid: 0,
            token: None,
        }
    }
}

impl Drop for ResumeGuard {
    fn drop(&mut self) {
        let Some(token) = self.token.take() else {
            return;
        };
        let now = unix_timestamp_secs();
        if let Some(seq) = format_clear_report(self.pid, now, &token) {
            let mut stderr = std::io::stderr();
            let _ = stderr.write_all(seq.as_bytes());
            let _ = stderr.flush();
        }
    }
}

/// Opt-in Rex `init.lua` rule trusting only read-only `minutes transcript`
/// follow panes. Minutes prints this for users and never edits `init.lua`.
pub fn rex_trust_rule_snippet() -> &'static str {
    r#"-- Optional: add to ~/.config/rex/init.lua to auto-resume Minutes transcript panes after a Rex restart.
-- Only read-only `minutes transcript --follow` panes are trusted; capture is never auto-resumed.
rex.set("resume.trust.minutes-transcript", {
  command = { "minutes", "transcript" },
  flags = {
    ["--follow"] = "keep",
    ["-f"] = "keep",
    ["--format"] = { "keep", values = 1 },
  },
})"#
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sha256_matches_fips_180_4_vectors() {
        let cases = [
            (
                "",
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            ),
            (
                "abc",
                "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
            ),
            (
                "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
                "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
            ),
        ];
        for (input, expected) in cases {
            let digest = sha256(input.as_bytes());
            let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
            assert_eq!(hex, expected, "input={input:?}");
        }
    }

    #[test]
    fn resume_report_matches_osc7577_spec_example_exactly() {
        // From the official Program Resume Protocol (OSC 7577) overview & mac section.
        let report = format_resume_report(
            74877,
            1795543200,
            &[
                "nvim",
                "-S",
                "/home/user/.local/state/nvim/sessions/8f2c1d.vim",
            ],
            "dummy-token-replace-me",
        )
        .unwrap();
        assert_eq!(
            report,
            "\x1b]7577;pid=74877:time=1795543200:argv=bnZpbQ==,LVM=,L2hvbWUvdXNlci8ubG9jYWwvc3RhdGUvbnZpbS9zZXNzaW9ucy84ZjJjMWQudmlt:mac=9dbb99bfb856749a87563839d7ce9062818d78cf25909db93f309e0cd3b1909b\x1b\\"
        );
    }

    #[test]
    fn clear_report_matches_osc7577_format() {
        let token = "dummy-token-replace-me";
        let report = format_clear_report(74877, 1795543200, token).unwrap();
        assert!(report.starts_with("\x1b]7577;pid=74877:time=1795543200:clear=1:mac="));
        assert!(report.ends_with("\x1b\\"));
        assert_eq!(
            report.len(),
            "\x1b]7577;pid=74877:time=1795543200:clear=1:mac=".len() + 64 + 2
        );
    }

    #[test]
    fn validates_tokens_and_rejects_unsafe_argv() {
        assert!(!is_valid_token("too-short"));
        assert!(!is_valid_token("has spaces in token 123456"));
        assert!(is_valid_token("dummy-token-replace-me"));

        assert!(validate_argv(&["minutes", "transcript", "--follow"]));
        assert!(validate_argv(&[
            "/usr/local/bin/minutes",
            "transcript",
            "--follow"
        ]));
        assert!(!validate_argv(&[]));
        assert!(!validate_argv(&["./minutes", "transcript", "--follow"]));
        assert!(!validate_argv(&["-minutes", "transcript"]));
        assert!(!validate_argv(&["minutes", "transcript\n--follow"]));
    }

    #[test]
    fn trust_rule_snippet_only_trusts_transcript_follow_never_capture() {
        let snippet = rex_trust_rule_snippet();
        assert!(snippet.contains("resume.trust.minutes-transcript"));
        assert!(snippet.contains("\"minutes\", \"transcript\""));
        assert!(!snippet.contains("\"record\""));
        assert!(!snippet.contains("\"live\""));
    }
}