neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! A TOML array of tables whose elements are named by a `name` member
//! (Mistral Vibe's `[[mcp_servers]]`), edited as text (A1a). An element is
//! found by its name on every edit, never by its position. Every line outside
//! the edited element stays byte for byte: comments, blank lines, other
//! tables, other elements, quoting and key order. Comments inside a replaced
//! element are not kept. Each edit is checked by parsing the result against
//! the intended document, and any form this editor cannot place an element in
//! (an inline array, a header inside a multi-line string, a name given twice)
//! is refused before anything is written.

use toml::{Table, Value};

/// One element as line indices: its header line, and the end of its members
/// and its own subtables (`content`); the comment and blank lines after them
/// belong to what follows and are never part of an edit.
struct Element {
    start: usize,
    content: usize,
    name: Option<String>,
}

fn parse(text: &str) -> Result<Table, String> {
    text.parse::<Table>()
        .map_err(|_| "the file does not parse as TOML".to_owned())
}

/// A header line's dotted key, each segment unquoted, and whether it opens
/// an array element (`[[...]]`). A line of a multi-line array value such as
/// `["a"],` is not a header: only a comment may follow the closing bracket.
fn header(line: &str) -> Option<(bool, Vec<String>)> {
    let line = line.trim_start();
    let array = line.starts_with("[[");
    let inner = line.strip_prefix(if array { "[[" } else { "[" })?;
    let closing = if array { "]]" } else { "]" };
    let close = inner.find(closing)?;
    let after = inner[close + closing.len()..].trim_start();
    if !(after.is_empty() || after.starts_with('#')) || inner[..close].contains(',') {
        return None;
    }
    let segments = inner[..close]
        .split('.')
        .map(|s| s.trim().trim_matches(['"', '\'']).to_owned())
        .collect();
    Some((array, segments))
}

fn quiet(line: &str) -> bool {
    let line = line.trim();
    line.is_empty() || line.starts_with('#')
}

/// The elements of `array` in the order they stand, each named from its own
/// text; refused when the file holds the array in another form.
fn elements(lines: &[&str], document: &Table, array: &str) -> Result<Vec<Element>, String> {
    let mut found: Vec<(usize, usize)> = vec![];
    let mut open: Option<usize> = None;
    for (index, line) in lines.iter().enumerate() {
        let Some((is_array, segments)) = header(line) else {
            continue;
        };
        let own = segments.len() > 1 && segments[0] == array;
        if open.is_some() && own {
            continue;
        }
        if let Some(start) = open.take() {
            found.push((start, index));
        }
        if is_array && segments == [array] {
            open = Some(index);
        }
    }
    if let Some(start) = open {
        found.push((start, lines.len()));
    }
    let parsed = match document.get(array) {
        None => 0,
        Some(Value::Array(items)) if items.iter().all(Value::is_table) => items.len(),
        Some(_) => return Err(format!("{array} is not written as [[{array}]] tables")),
    };
    if parsed != found.len() {
        return Err(format!(
            "{array} is written in a form this release does not edit"
        ));
    }
    found
        .into_iter()
        .map(|(start, end)| {
            let own = parse(&lines[start..end].concat())?;
            let name = own[array][0].get("name").and_then(Value::as_str);
            let content = (start + 1..end)
                .rev()
                .find(|i| !quiet(lines[*i]))
                .map_or(start + 1, |i| i + 1);
            Ok(Element {
                start,
                content,
                name: name.map(str::to_owned),
            })
        })
        .collect()
}

/// The text, its document, its elements and the position of the one named
/// `name` (`None` when absent; refused when the name is given twice).
struct Found<'a> {
    lines: Vec<&'a str>,
    document: Table,
    elements: Vec<Element>,
    at: Option<usize>,
}

fn find<'a>(text: &'a str, array: &str, name: &str) -> Result<Found<'a>, String> {
    let document = parse(text)?;
    let lines: Vec<&str> = text.split_inclusive('\n').collect();
    let elements = elements(&lines, &document, array)?;
    let named: Vec<usize> = (0..elements.len())
        .filter(|i| elements[*i].name.as_deref() == Some(name))
        .collect();
    if named.len() > 1 {
        return Err(format!("two [[{array}]] entries are named {name}"));
    }
    Ok(Found {
        at: named.first().copied(),
        lines,
        document,
        elements,
    })
}

/// The parsed elements, taken out of the document so the intended result can
/// be built from what is left.
fn items(document: &mut Table, array: &str) -> Vec<Value> {
    match document.remove(array) {
        Some(Value::Array(items)) => items,
        _ => vec![],
    }
}

fn checked(
    text: String,
    mut intended: Table,
    array: &str,
    items: Vec<Value>,
) -> Result<String, String> {
    if !items.is_empty() {
        intended.insert(array.to_owned(), Value::Array(items));
    }
    let mut written = parse(&text)?;
    if written
        .get(array)
        .is_some_and(|v| v.as_array().is_some_and(Vec::is_empty))
    {
        written.remove(array);
    }
    if written != intended {
        return Err("the edit would change more than the one entry".into());
    }
    Ok(text)
}

/// `text` with the element named `name` set to `body` (a whole
/// `[[array]]` element): replaced where it stands, else placed after the last
/// element, or at the end of the file when there is none.
pub fn put(text: &str, array: &str, name: &str, body: &str) -> Result<String, String> {
    let Found {
        lines,
        mut document,
        elements,
        at,
    } = find(text, array, name)?;
    let element = items(&mut parse(body)?, array)
        .pop()
        .ok_or("the entry is not an element")?;
    let mut list = items(&mut document, array);
    let edited = match at {
        Some(i) => {
            list[i] = element;
            let Element { start, content, .. } = elements[i];
            [&lines[..start].concat(), body, &lines[content..].concat()].concat()
        }
        None => {
            list.push(element);
            let at = elements.last().map_or(lines.len(), |e| e.content);
            let before = lines[..at].concat();
            let gap = match before.as_str() {
                "" => "",
                b if b.ends_with('\n') => "\n",
                _ => "\n\n",
            };
            [&before, gap, body, &lines[at..].concat()].concat()
        }
    };
    checked(edited, document, array, list)
}

/// `text` without the element named `name` and one blank line beside it (the
/// one before it, else the one after it); `None` when no element has that name.
pub fn remove(text: &str, array: &str, name: &str) -> Result<Option<String>, String> {
    let Found {
        lines,
        mut document,
        elements,
        at,
    } = find(text, array, name)?;
    let Some(i) = at else {
        return Ok(None);
    };
    let mut list = items(&mut document, array);
    list.remove(i);
    let Element { start, content, .. } = elements[i];
    let blank = |i: usize| lines.get(i).is_some_and(|l| l.trim().is_empty());
    let (from, to) = if start > 0 && blank(start - 1) {
        (start - 1, content)
    } else if blank(content) {
        (start, content + 1)
    } else {
        (start, content)
    };
    let edited = lines[..from].concat() + &lines[to..].concat();
    checked(edited, document, array, list).map(Some)
}

/// `text` with `members` (`key = value` lines) added to the element named
/// `name`, right after its header line.
pub fn add(text: &str, array: &str, name: &str, members: &str) -> Result<String, String> {
    let Found {
        lines,
        mut document,
        elements,
        at,
    } = find(text, array, name)?;
    let i = at.ok_or_else(|| format!("no [[{array}]] entry is named {name}"))?;
    let mut list = items(&mut document, array);
    let added = parse(members)?;
    if let Some(Value::Table(element)) = list.get_mut(i) {
        for (key, value) in added {
            element.insert(key, value);
        }
    }
    let start = elements[i].start + 1;
    let edited = [&lines[..start].concat(), members, &lines[start..].concat()].concat();
    checked(edited, document, array, list)
}

#[cfg(test)]
#[path = "named_tests.rs"]
mod tests;