neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! `neosian setup --undo-rename [--client NAME]` (DESIGN ยง40.53 item 5): the
//! same move in the other direction for each client on `neosian` whose entry
//! is still ours, refusing where a person has since replaced it. The client
//! is then held: only `setup --refresh --rename` moves it again.

use super::{Plan, Step, backup::Backup, moves, places, report, text};
use crate::clients::{
    context::Context,
    naming::{self, NEW, OLD},
    receipt, targets,
};
use serde_json::{Value, json};
use std::io::{self, Write};

fn plan(client: &'static str, context: &Context) -> (Plan, Vec<String>) {
    let label = targets::mcp(client, context, "user").label;
    let mut plan = Plan {
        client,
        label,
        steps: vec![],
        stops: vec![],
        found: Default::default(),
        hosted: vec![],
    };
    let mut refused = vec![];
    if !super::installed(client, context) {
        return (plan, refused);
    }
    for container in places::containers(client, context) {
        let Ok(entries) = container.entries() else {
            continue;
        };
        let Some(new) = entries.new else {
            continue;
        };
        if !super::ours(&container, &new, context) || entries.old.is_some() {
            refused.push(format!(
                "{} {}",
                container.file.display(),
                container.pointer(NEW)
            ));
            continue;
        }
        plan.steps.push(Step {
            container,
            entry: new,
            remove_only: false,
        });
    }
    (plan, refused)
}

/// A client no release registered under the old key: its entry under
/// `neosian` has no move to put back, and is listed as staying.
fn fresh(client: &'static str, context: &Context) -> Option<Value> {
    let stays: Vec<String> = places::containers(client, context)
        .into_iter()
        .filter(|c| {
            let new = c.entries().ok().and_then(|e| e.new);
            new.is_some_and(|e| super::ours(c, &e, context))
        })
        .map(|c| format!("{} {}", c.file.display(), c.pointer(NEW)))
        .collect();
    let label = targets::mcp(client, context, "user").label;
    (super::installed(client, context) && !stays.is_empty())
        .then(|| json!({"client": client, "label": label, "refused": [], "stays": stays}))
}

pub fn run(
    context: &Context,
    only: Option<&str>,
    json_out: bool,
    out: &mut impl Write,
) -> io::Result<u8> {
    let mut rows = vec![];
    let mut backup = None;
    let mut ok = true;
    for client in naming::CLIENTS
        .into_iter()
        .filter(|c| only.is_none_or(|o| o == *c))
    {
        if !naming::shipped(client) {
            rows.extend(fresh(client, context));
            continue;
        }
        let (plan, refused) = plan(client, context);
        if plan.steps.is_empty() && refused.is_empty() {
            continue;
        }
        let mut row = json!({"client": client, "label": plan.label, "refused": refused});
        // Refusals are listed; only a failure while writing fails the command.
        if !plan.steps.is_empty() {
            let result = match &mut backup {
                Some(b) => Ok(b),
                None => Backup::begin(context).map(|b| backup.insert(b)),
            }
            .and_then(|b| moves::apply(context, &plan, NEW, OLD, b));
            match result {
                Ok(()) => {
                    let _ = receipt::settle(client, context, &[], Some(("undo", "held")));
                    row["back"] = json!(plan.steps.len());
                }
                Err(failure) => {
                    ok = false;
                    row["error"] = json!(failure.message);
                }
            }
        }
        rows.push(row);
    }
    if let Some(mut b) = backup {
        let _ = b.finish();
    }
    let report = json!({"success": ok, "clients": rows});
    if json_out {
        writeln!(out, "{report}")?;
    } else {
        report::undo_text(&report, out)?;
        if rows_empty(&report) {
            writeln!(out, "{}", text::get("undo_none"))?;
        }
    }
    Ok(u8::from(!ok))
}

fn rows_empty(report: &Value) -> bool {
    report["clients"].as_array().is_none_or(Vec::is_empty)
}