diff --git a/README.md b/README.md index eea0165..53a3ce8 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ set as `PROOFLINE_TOKEN`. A token that works in one organization needs no To register MCP without a prompt, run `proofline agent install CLIENT --yes`. Supported clients include `claude-code` (or `claude`), `cursor`, `codex`, `gemini`, and `kiro`. Without `--yes`, the command previews the entry and asks for confirmation, while `--print` previews without writing. Existing Proofline entries remain unchanged. New entries use this executable's absolute path and store no credentials. Claude Code uses the top-level `mcpServers` in `~/.claude.json`; a custom `CLAUDE_CONFIG_DIR` requires manual configuration with `--print`. +To unregister, run `proofline agent remove CLIENT`. It previews the `proofline` entry and its file, asks for confirmation, and removes only that server; `--yes` skips the prompt, and `--print` prints the entry without writing. Every other byte of a JSON file stays as it was, and a Codex file keeps its comments and layout. An emptied `mcpServers` object or `mcp_servers` table stays in place. With no entry, the command says so and exits 0. It refuses a file it cannot parse and leaves it unchanged, and it uses the same file checks and lock as `install`. A custom `CLAUDE_CONFIG_DIR` or `CODEX_HOME` requires removing the entry manually. When `install` finds an entry that starts a different executable, such as one from an earlier installation, it names that path and suggests `proofline agent remove CLIENT` followed by `proofline agent install CLIENT`. + Native knowledge, plan, fix and configuration commands send the selected organization as `organization_id` in each MCP tool call. With a `PROOFLINE_TOKEN` that works in more than one organization, select an authorized UUID using `--org ORGANIZATION_ID` or `PROOFLINE_ORGANIZATION_ID`; the flag takes precedence. A token that works in exactly one, such as a personal token, needs neither. A stored device sign-in uses its approved organization and refuses a different selection. For example, `proofline --org ORGANIZATION_ID wiki list --repo owner/name` and `proofline --org ORGANIZATION_ID config get` target that organization with a shared MCP OAuth credential. Selection grants no authority: the server checks each call, and a foreign target returns its refusal with a nonzero exit. MCP OAuth credentials remain limited to MCP and cannot use REST commands. The raw `proofline mcp` bridge preserves the caller's messages and per-call target unchanged. ## Reviews, history, and reruns diff --git a/src/agent.rs b/src/agent.rs index c9629d2..31442ef 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -25,6 +25,8 @@ pub(crate) struct AgentArgs { enum AgentCommand { /// Add Proofline to a coding agent's user configuration after confirmation. Install(InstallArgs), + /// Remove Proofline from a coding agent's user configuration after confirmation. + Remove(RemoveArgs), } #[derive(Debug, Args)] @@ -40,6 +42,19 @@ struct InstallArgs { yes: bool, } +#[derive(Debug, Args)] +struct RemoveArgs { + /// Coding agent whose user configuration loses the MCP server. + #[arg(value_enum)] + client: Client, + /// Print the server entry that would be removed without writing any file. + #[arg(long)] + print: bool, + /// Remove the previewed entry without an interactive confirmation. + #[arg(long, conflicts_with = "print")] + yes: bool, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] enum Client { #[value(alias = "claude")] @@ -60,6 +75,16 @@ impl Client { Self::Kiro => ".kiro/settings/mcp.json", } } + + const fn argument(self) -> &'static str { + match self { + Self::ClaudeCode => "claude-code", + Self::Codex => "codex", + Self::Cursor => "cursor", + Self::Gemini => "gemini", + Self::Kiro => "kiro", + } + } } impl fmt::Display for Client { @@ -90,6 +115,22 @@ enum InstallError { "CODEX_HOME selects a different directory; use --print and add the entry to that user configuration manually" )] CustomCodexHome, + #[error( + "CLAUDE_CONFIG_DIR selects custom configuration; remove the proofline server from that Claude Code configuration manually" + )] + RemoveCustomClaudeHome, + #[error( + "CODEX_HOME selects a different directory; remove the proofline server from that user configuration manually" + )] + RemoveCustomCodexHome, + #[error( + "could not parse the {0} configuration; it stays unchanged, so remove the proofline server manually" + )] + RemoveInvalidConfig(Client), + #[error( + "the configuration exceeds the 1 MiB installer limit; it stays unchanged, so remove the proofline server manually" + )] + RemoveTooLarge, #[error( "could not parse the {0} configuration; leave it unchanged and use --print for the server entry" )] @@ -156,6 +197,15 @@ impl InstallError { const fn console(operation: &'static str, source: io::Error) -> Self { Self::Console { operation, source } } + + /// Replace install advice that does not apply to a removal. + fn for_removal(self) -> Self { + match self { + Self::InvalidConfig(client) => Self::RemoveInvalidConfig(client), + Self::TooLarge => Self::RemoveTooLarge, + other => other, + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -164,31 +214,49 @@ enum Outcome { Cancelled, Existing, Installed, + Absent, + Removed, } pub(crate) async fn run(args: AgentArgs, origin: Origin) -> anyhow::Result<()> { tokio::task::spawn_blocking(move || { - let AgentCommand::Install(args) = args.command; let home = std::env::home_dir().ok_or(InstallError::Home)?; let codex_home = std::env::var_os("CODEX_HOME"); - if args.client == Client::ClaudeCode - && !args.print - && std::env::var_os("CLAUDE_CONFIG_DIR").is_some() - { - return Err(InstallError::CustomClaudeHome); - } + let custom_claude = std::env::var_os("CLAUDE_CONFIG_DIR").is_some(); let stdin = io::stdin(); let stdout = io::stdout(); let stderr = io::stderr(); - install( - &home, - codex_home.as_deref(), - &args, - &origin, - &mut stdin.lock(), - &mut stdout.lock(), - &mut stderr.lock(), - ) + match args.command { + AgentCommand::Install(args) => { + if args.client == Client::ClaudeCode && !args.print && custom_claude { + return Err(InstallError::CustomClaudeHome); + } + install( + &home, + codex_home.as_deref(), + &args, + &origin, + &mut stdin.lock(), + &mut stdout.lock(), + &mut stderr.lock(), + ) + } + AgentCommand::Remove(args) => { + // Even the preview reads ~/.claude.json, which Claude Code + // ignores while CLAUDE_CONFIG_DIR is set. + if args.client == Client::ClaudeCode && custom_claude { + return Err(InstallError::RemoveCustomClaudeHome); + } + remove( + &home, + codex_home.as_deref(), + &args, + &mut stdin.lock(), + &mut stdout.lock(), + &mut stderr.lock(), + ) + } + } }) .await .map_err(InstallError::Task)??; @@ -223,7 +291,7 @@ fn install( let before = layout.read()?; let config::Update::Change(bytes) = config::prepare(args.client, before.bytes(), origin)? else { - existing(&layout, diagnostics)?; + existing(&layout, args.client, before.bytes(), diagnostics)?; return Ok(Outcome::Existing); }; layout.writable(&before)?; @@ -234,28 +302,18 @@ fn install( layout.target() ) .map_err(|error| InstallError::console("show the proposed server entry", error))?; - if !args.yes { - write!(diagnostics, "Write this entry? [y/N] ") - .and_then(|()| diagnostics.flush()) - .map_err(|error| InstallError::console("ask for confirmation", error))?; - let mut answer = String::new(); - input - .take(65) - .read_line(&mut answer) - .map_err(|error| InstallError::console("read confirmation", error))?; - if answer.len() > 64 - || !answer.ends_with('\n') - || !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") - { - writeln!(diagnostics, "No configuration was written.").map_err(|error| { - InstallError::console("report the unchanged configuration", error) - })?; - return Ok(Outcome::Cancelled); - } + if !args.yes && !confirm("Write this entry?", input, diagnostics)? { + return Ok(Outcome::Cancelled); } match layout.save(&before, &bytes, origin)? { store::Saved::Existing => { - existing(&layout, diagnostics)?; + let current = layout.read().ok(); + existing( + &layout, + args.client, + current.as_ref().and_then(store::Snapshot::bytes), + diagnostics, + )?; Ok(Outcome::Existing) } store::Saved::Installed => { @@ -266,11 +324,129 @@ fn install( } } -fn existing(layout: &store::Layout, diagnostics: &mut impl Write) -> Result<(), InstallError> { +fn remove( + home: &Path, + codex_home: Option<&OsStr>, + args: &RemoveArgs, + input: &mut impl BufRead, + output: &mut impl Write, + diagnostics: &mut impl Write, +) -> Result { + if !home.is_absolute() { + return Err(InstallError::Home); + } + if args.client == Client::Codex + && codex_home.is_some_and(|selected| Path::new(selected) != home.join(".codex")) + { + return Err(InstallError::RemoveCustomCodexHome); + } + let layout = store::Layout::new(home, args.client)?; + let before = layout.read().map_err(InstallError::for_removal)?; + let Some(removal) = + config::remove(args.client, before.bytes()).map_err(InstallError::for_removal)? + else { + writeln!( + diagnostics, + "No proofline entry in {:?}; nothing to remove.", + layout.target() + ) + .map_err(|error| InstallError::console("report the missing entry", error))?; + return Ok(Outcome::Absent); + }; + if args.print { + output + .write_all(removal.entry.as_bytes()) + .map_err(|error| InstallError::console("print the server entry", error))?; + writeln!( + diagnostics, + "This entry would be removed from {:?}. No configuration was written.", + layout.target() + ) + .map_err(|error| InstallError::console("name the configuration", error))?; + return Ok(Outcome::Printed); + } + layout.writable(&before)?; + writeln!( + diagnostics, + "Remove this {0} server from {1:?}:\n{2}", + args.client, + layout.target(), + removal.entry + ) + .map_err(|error| InstallError::console("show the server entry", error))?; + if !args.yes && !confirm("Remove this entry?", input, diagnostics)? { + return Ok(Outcome::Cancelled); + } + layout + .replace(&before, &removal.bytes) + .map_err(InstallError::for_removal)?; + writeln!( + diagnostics, + "Removed the proofline server from {:?}. Sessions that already started may keep it until they restart.", + layout.target() + ) + .map_err(|error| InstallError::console("report the saved configuration", error))?; + Ok(Outcome::Removed) +} + +/// Ask a yes/no question; anything but a complete `y` or `yes` line declines. +fn confirm( + question: &str, + input: &mut impl BufRead, + diagnostics: &mut impl Write, +) -> Result { + write!(diagnostics, "{question} [y/N] ") + .and_then(|()| diagnostics.flush()) + .map_err(|error| InstallError::console("ask for confirmation", error))?; + let mut answer = String::new(); + input + .take(65) + .read_line(&mut answer) + .map_err(|error| InstallError::console("read confirmation", error))?; + if answer.len() > 64 + || !answer.ends_with('\n') + || !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") + { + writeln!(diagnostics, "No configuration was written.") + .map_err(|error| InstallError::console("report the unchanged configuration", error))?; + return Ok(false); + } + Ok(true) +} + +fn existing( + layout: &store::Layout, + client: Client, + bytes: Option<&[u8]>, + diagnostics: &mut impl Write, +) -> Result<(), InstallError> { writeln!( diagnostics, "A proofline entry already exists in {:?}; it stays unchanged.", layout.target() ) - .map_err(|error| InstallError::console("report the existing entry", error)) + .map_err(|error| InstallError::console("report the existing entry", error))?; + let Some(recorded) = bytes.and_then(|bytes| config::recorded_command(client, bytes)) else { + return Ok(()); + }; + if !other_executable(&recorded) { + return Ok(()); + } + writeln!( + diagnostics, + "It starts {recorded:?}, not this executable. To use this one, run `proofline agent remove {0}` and then `proofline agent install {0}`.", + client.argument() + ) + .map_err(|error| InstallError::console("suggest replacing the existing entry", error)) +} + +/// Whether a recorded command names a different file than the running one. +/// Paths are compared after resolving symlinks, so a symlinked launch path +/// such as macOS `/var` and `/private/var` still counts as the same file. +fn other_executable(recorded: &str) -> bool { + let Ok(current) = std::env::current_exe() else { + return false; + }; + let recorded = Path::new(recorded); + recorded != current && recorded.canonicalize().ok() != current.canonicalize().ok() } diff --git a/src/agent/config.rs b/src/agent/config.rs index 43b20c6..5ef215e 100644 --- a/src/agent/config.rs +++ b/src/agent/config.rs @@ -166,6 +166,211 @@ fn json(client: Client, original: Option<&[u8]>, origin: &Origin) -> Result, +} + +impl fmt::Debug for Removal { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("Removal") + .field("entry", &self.entry.len()) + .field("bytes", &self.bytes.len()) + .finish() + } +} + +/// Remove only the proofline server. `None` means there is nothing to remove. +pub(super) fn remove( + client: Client, + original: Option<&[u8]>, +) -> Result, InstallError> { + let Some(original) = original else { + return Ok(None); + }; + match client { + Client::Codex => codex_remove(original), + Client::ClaudeCode | Client::Cursor | Client::Gemini | Client::Kiro => { + json_remove(client, original) + } + } +} + +/// The `command` of an existing proofline server, when it has a string one. +pub(super) fn recorded_command(client: Client, original: &[u8]) -> Option { + let raw = std::str::from_utf8(original).ok()?; + match client { + Client::Codex => { + let document: DocumentMut = raw.parse().ok()?; + document + .get("mcp_servers")? + .get("proofline")? + .get("command")? + .as_str() + .map(str::to_owned) + } + Client::ClaudeCode | Client::Cursor | Client::Gemini | Client::Kiro => { + let document: BorrowedObject<'_> = serde_json::from_str(raw).ok()?; + let servers: BorrowedObject<'_> = + serde_json::from_str(document.member("mcpServers")?.get()).ok()?; + let server: Value = serde_json::from_str(servers.member("proofline")?.get()).ok()?; + server.get("command")?.as_str().map(str::to_owned) + } + } +} + +fn codex_remove(original: &[u8]) -> Result, InstallError> { + let raw = + std::str::from_utf8(original).map_err(|_| InstallError::InvalidConfig(Client::Codex))?; + // TOML diagnostics quote private configuration lines. Keep them out of errors. + let mut document: DocumentMut = raw + .parse() + .map_err(|_| InstallError::InvalidConfig(Client::Codex))?; + let removed = match document.get_mut("mcp_servers") { + None => None, + Some(Item::Table(servers)) => servers.remove("proofline"), + Some(Item::Value(toml_edit::Value::InlineTable(servers))) => { + let last = servers + .iter() + .last() + .is_some_and(|(key, _)| key == "proofline"); + let removed = servers.remove("proofline"); + // The space before `}` belongs to the last value; keep it. + if last + && let Some(suffix) = removed + .as_ref() + .and_then(|server| server.decor().suffix().cloned()) + && let Some((_, value)) = servers.iter_mut().last() + { + value.decor_mut().set_suffix(suffix); + } + removed.map(Item::Value) + } + Some(_) => { + return Err(InstallError::ConfigShape { + client: Client::Codex, + member: "mcp_servers", + }); + } + }; + let Some(server) = removed else { + return Ok(None); + }; + let mut servers = Table::new(); + servers.set_implicit(true); + servers.insert("proofline", server); + let mut entry = DocumentMut::new(); + entry.insert("mcp_servers", Item::Table(servers)); + Ok(Some(Removal { + entry: entry.to_string().trim_start().to_owned(), + bytes: document.to_string().into_bytes(), + })) +} + +/// Cut the proofline member's bytes out of `mcpServers` and keep every other +/// byte, so formatting, key order and number spelling stay as they were. +fn json_remove(client: Client, original: &[u8]) -> Result, InstallError> { + let raw = std::str::from_utf8(original).map_err(|_| InstallError::InvalidConfig(client))?; + serde_json::from_str::(raw).map_err(|_| InstallError::InvalidConfig(client))?; + let document: BorrowedObject<'_> = + serde_json::from_str(raw).map_err(|_| InstallError::ConfigShape { + client, + member: "root", + })?; + let Some(object) = document.member("mcpServers") else { + return Ok(None); + }; + let servers: BorrowedObject<'_> = + serde_json::from_str(object.get()).map_err(|_| InstallError::ConfigShape { + client, + member: "mcpServers", + })?; + let Some(index) = servers.0.iter().position(|(key, _)| key == "proofline") else { + return Ok(None); + }; + let server = servers.0[index].1; + // Both values borrow from `raw`, so their addresses locate them in it. + let start = |value: &RawValue| value.get().as_ptr().addr() - raw.as_ptr().addr(); + let end = |value: &RawValue| start(value) + value.get().len(); + let (cut_from, cut_to) = match (index.checked_sub(1), servers.0.get(index + 1)) { + // `"a": 1, "proofline": {…}` loses its separator and member. + (Some(previous), _) => (end(servers.0[previous].1), end(server)), + // `{"proofline": {…}, "b": 2` keeps the layout after the comma. + (None, Some(_)) => { + let comma = original[end(server)..] + .iter() + .position(|byte| *byte == b',') + .ok_or(InstallError::InvalidConfig(client))?; + (start(object) + 1, end(server) + comma + 1) + } + // The only member leaves `{}`. + (None, None) => (start(object) + 1, end(object) - 1), + }; + let entry = RawObject(vec![( + "mcpServers".to_owned(), + to_raw_value(&RawObject(vec![( + "proofline".to_owned(), + server.to_owned(), + )])) + .map_err(|_| InstallError::InvalidConfig(client))?, + )]); + let mut entry = + serde_json::to_string_pretty(&entry).map_err(|_| InstallError::InvalidConfig(client))?; + entry.push('\n'); + Ok(Some(Removal { + entry, + bytes: [&original[..cut_from], &original[cut_to..]].concat(), + })) +} + +/// Object members that borrow their raw values from the parsed text. +struct BorrowedObject<'a>(Vec<(String, &'a RawValue)>); + +impl<'a> BorrowedObject<'a> { + fn member(&self, name: &str) -> Option<&'a RawValue> { + self.0 + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| *value) + } +} + +impl fmt::Debug for BorrowedObject<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BorrowedObject") + .field("members", &self.0.len()) + .finish() + } +} + +impl<'de> Deserialize<'de> for BorrowedObject<'de> { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_map(BorrowedObjectVisitor) + } +} + +#[derive(Debug)] +struct BorrowedObjectVisitor; + +impl<'de> Visitor<'de> for BorrowedObjectVisitor { + type Value = BorrowedObject<'de>; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a JSON object") + } + + fn visit_map>(self, mut values: A) -> Result { + let mut object = Vec::new(); + while let Some(entry) = values.next_entry::()? { + object.push(entry); + } + Ok(BorrowedObject(object)) + } +} + struct RawObject(Vec<(String, Box)>); impl fmt::Debug for RawObject { diff --git a/src/agent/store.rs b/src/agent/store.rs index 91a607e..53d5072 100644 --- a/src/agent/store.rs +++ b/src/agent/store.rs @@ -223,6 +223,34 @@ impl Layout { Ok(Saved::Installed) } + /// Replace an existing configuration with `bytes` while it still matches + /// the snapshot the user confirmed, keeping its permissions. + pub(super) fn replace(&self, before: &Snapshot, bytes: &[u8]) -> Result<(), InstallError> { + let lease = self.acquire_lock()?; + let current = self.read()?; + self.writable(¤t)?; + if before.file.is_none() + || before.directories != current.directories + || !before.same_file(¤t) + { + return Err(InstallError::Changed(self.target.clone())); + } + let temporary = self.temporary(bytes, current.file.as_ref())?; + let check = self.read().and_then(|latest| { + if current.directories != latest.directories || !current.same_file(&latest) { + return Err(InstallError::Changed(self.target.clone())); + } + self.check_lock(&lease) + }); + if let Err(error) = check { + temporary.close().map_err(|error| { + InstallError::io("remove the temporary configuration", &self.parent, error) + })?; + return Err(error); + } + self.persist(temporary, true) + } + fn original_directories(&self, before: &Snapshot, current: &Snapshot) -> bool { before.directories.iter().all(|(path, identity)| { identity.as_ref().is_none_or(|identity| { diff --git a/src/agent/tests.rs b/src/agent/tests.rs index 8a67e1d..879b551 100644 --- a/src/agent/tests.rs +++ b/src/agent/tests.rs @@ -14,7 +14,7 @@ use clap::Parser as _; use serde_json::{Value, json}; use tempfile::TempDir; -use super::{Client, InstallArgs, InstallError, Outcome, install}; +use super::{Client, InstallArgs, InstallError, Outcome, RemoveArgs, install, remove}; use crate::origin::Origin; use crate::{Cli, Command as CliCommand}; @@ -27,6 +27,9 @@ const CLIENTS: [Client; 5] = [ Client::Kiro, ]; +/// `mcpServers` members in file order. +type Servers<'a> = Vec<(&'a str, &'a Value)>; + #[derive(Debug)] struct Invocation { result: Result, @@ -817,3 +820,402 @@ fn an_overlong_answer_and_unknown_client_or_output_flag_cannot_write() { assert!(Origin::parse(invalid).is_err()); } } + +fn removal( + home: &Path, + client: Client, + print: bool, + input: &mut impl BufRead, + codex_home: Option<&Path>, +) -> Invocation { + let mut output = Vec::new(); + let mut diagnostics = Vec::new(); + let result = remove( + home, + codex_home.map(Path::as_os_str), + &RemoveArgs { + client, + print, + yes: false, + }, + input, + &mut output, + &mut diagnostics, + ); + Invocation { + result, + output: String::from_utf8(output).unwrap(), + diagnostics: String::from_utf8(diagnostics).unwrap(), + } +} + +fn confirmed_removal(home: &Path, client: Client) -> Invocation { + removal(home, client, false, &mut Cursor::new(b"yes\n"), None) +} + +#[test] +fn install_then_remove_restores_each_client_configuration() { + for client in CLIENTS { + let home = TempDir::new().unwrap(); + let original = configuration(client); + let path = seed(home.path(), client, &original); + #[cfg(unix)] + fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap(); + assert_eq!( + confirmed(home.path(), client).result.unwrap(), + Outcome::Installed + ); + let removed = confirmed_removal(home.path(), client); + assert_eq!(removed.result.unwrap(), Outcome::Removed); + assert!(removed.output.is_empty()); + assert!(removed.diagnostics.contains("Remove this entry? [y/N]")); + assert!( + removed + .diagnostics + .contains(std::env::current_exe().unwrap().to_str().unwrap()) + ); + assert!(!removed.diagnostics.contains(PRIVATE)); + let actual = fs::read(&path).unwrap(); + match client { + // toml_edit keeps comments and layout, so the file is byte-identical. + Client::Codex => assert_eq!(actual, original), + // Install compacts `mcpServers`; every other member keeps its bytes. + Client::ClaudeCode | Client::Cursor | Client::Gemini | Client::Kiro => { + let expected: Value = serde_json::from_slice(&original).unwrap(); + let parsed: Value = serde_json::from_slice(&actual).unwrap(); + assert_eq!(parsed, expected); + assert_eq!( + parsed.as_object().unwrap().keys().collect::>(), + expected.as_object().unwrap().keys().collect::>() + ); + } + } + #[cfg(unix)] + assert_eq!(fs::metadata(&path).unwrap().mode() & 0o777, 0o640); + assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 2); + let again = confirmed_removal(home.path(), client); + assert_eq!(again.result.unwrap(), Outcome::Absent); + assert!(again.diagnostics.contains("nothing to remove")); + assert!(!again.diagnostics.contains("Remove this entry?")); + assert_eq!(fs::read(&path).unwrap(), actual); + } +} + +#[test] +fn json_removal_cuts_only_the_member_bytes_in_any_position() { + let server = json!({"type": "stdio", "command": "/old/proofline", "args": ["mcp"]}); + let other = json!({"command": "other-server", "value": 1}); + let layouts: [(Servers<'_>, Servers<'_>); 4] = [ + ( + vec![("proofline", &server), ("a", &other)], + vec![("a", &other)], + ), + ( + vec![("a", &other), ("proofline", &server), ("b", &other)], + vec![("a", &other), ("b", &other)], + ), + ( + vec![("a", &other), ("proofline", &server)], + vec![("a", &other)], + ), + (vec![("proofline", &server)], vec![]), + ]; + for client in [ + Client::ClaudeCode, + Client::Cursor, + Client::Gemini, + Client::Kiro, + ] { + for (with, without) in &layouts { + let document = |servers: &[(&str, &Value)]| { + let servers: serde_json::Map = servers + .iter() + .map(|(key, value)| ((*key).to_owned(), (*value).clone())) + .collect(); + let mut bytes = serde_json::to_vec_pretty(&json!({ + "theme": "chosen-theme", + "mcpServers": servers, + "precision": 1.5, + "privateSetting": PRIVATE + })) + .unwrap(); + bytes.push(b'\n'); + bytes + }; + let home = TempDir::new().unwrap(); + let path = seed(home.path(), client, &document(with)); + let removed = confirmed_removal(home.path(), client); + assert_eq!(removed.result.unwrap(), Outcome::Removed); + assert!(removed.diagnostics.contains("/old/proofline")); + assert!(!removed.diagnostics.contains(PRIVATE)); + assert_eq!( + String::from_utf8(fs::read(&path).unwrap()).unwrap(), + String::from_utf8(document(without)).unwrap() + ); + } + } + let home = TempDir::new().unwrap(); + let precise = "{\"big\":184467440737095516170,\"mcpServers\":{\"proofline\":{\"command\":\"x\"},\"other\":{\"value\":1.2345678901234567890123456789}}}"; + let path = seed(home.path(), Client::Gemini, precise.as_bytes()); + assert_eq!( + confirmed_removal(home.path(), Client::Gemini) + .result + .unwrap(), + Outcome::Removed + ); + assert_eq!( + fs::read_to_string(path).unwrap(), + "{\"big\":184467440737095516170,\"mcpServers\":{\"other\":{\"value\":1.2345678901234567890123456789}}}" + ); +} + +#[test] +fn toml_removal_keeps_comments_inline_tables_and_subtables() { + let cases = [ + ( + "# keep\n[mcp_servers.other]\ncommand = 'other' # trailing\n\n[mcp_servers.proofline]\ncommand = '/old/proofline'\nargs = ['mcp']\n\n[mcp_servers.proofline.env]\nKEY = 'value'\n\n[profile]\nname = 'kept'\n", + "# keep\n[mcp_servers.other]\ncommand = 'other' # trailing\n\n[profile]\nname = 'kept'\n", + ), + ( + "# inline\nmcp_servers = { other = { command = 'other' }, proofline = { command = '/old/proofline' } }\n", + "# inline\nmcp_servers = { other = { command = 'other' } }\n", + ), + ( + "model = 'kept'\nmcp_servers.proofline = { command = '/old/proofline' }\n", + "model = 'kept'\n", + ), + ]; + for (with, without) in cases { + let home = TempDir::new().unwrap(); + let path = seed(home.path(), Client::Codex, with.as_bytes()); + let printed = removal( + home.path(), + Client::Codex, + true, + &mut Cursor::new(b""), + None, + ); + assert_eq!(printed.result.unwrap(), Outcome::Printed); + let entry: toml::Value = toml::from_str(&printed.output).unwrap(); + assert_eq!( + entry["mcp_servers"]["proofline"]["command"].as_str(), + Some("/old/proofline") + ); + assert_eq!(fs::read_to_string(&path).unwrap(), with); + let removed = confirmed_removal(home.path(), Client::Codex); + assert_eq!(removed.result.unwrap(), Outcome::Removed); + assert_eq!(fs::read_to_string(&path).unwrap(), without); + } +} + +#[test] +fn removal_print_decline_and_absence_never_write() { + for client in CLIENTS { + let home = TempDir::new().unwrap(); + let missing = confirmed_removal(home.path(), client); + assert_eq!(missing.result.unwrap(), Outcome::Absent); + assert!(entries(home.path()).is_empty()); + let path = seed(home.path(), client, &configuration(client)); + let before = entries(home.path()); + assert_eq!( + confirmed_removal(home.path(), client).result.unwrap(), + Outcome::Absent + ); + assert_eq!(entries(home.path()), before); + assert_eq!( + confirmed(home.path(), client).result.unwrap(), + Outcome::Installed + ); + let installed = entries(home.path()); + let modified = fs::metadata(&path).unwrap().modified().unwrap(); + let printed = removal(home.path(), client, true, &mut Cursor::new(b"yes\n"), None); + assert_eq!(printed.result.unwrap(), Outcome::Printed); + assert!(printed.output.contains("proofline")); + assert!(!printed.output.contains(PRIVATE) && !printed.output.contains("other-server")); + assert!( + printed + .diagnostics + .contains("No configuration was written.") + ); + assert_eq!(entries(home.path()), installed); + for answer in [b"".as_slice(), b"\n", b"no\n", b"yes please\n", b"yes"] { + let declined = removal(home.path(), client, false, &mut Cursor::new(answer), None); + assert_eq!(declined.result.unwrap(), Outcome::Cancelled); + assert_eq!(entries(home.path()), installed); + } + assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), modified); + } +} + +#[test] +fn removal_refusals_leave_the_configuration_intact() { + for client in CLIENTS { + let home = TempDir::new().unwrap(); + let invalid = match client { + Client::Codex => vec![ + format!("private = '{PRIVATE}'\ninvalid = ["), + "mcp_servers = 42\n".to_owned(), + ], + Client::ClaudeCode | Client::Cursor | Client::Gemini | Client::Kiro => vec![ + format!("{{\"private\":\"{PRIVATE}\", \"unfinished\": "), + "{\"mcpServers\": []}".to_owned(), + format!( + "{{\"private\":\"{PRIVATE}\",\"mcpServers\":{{\"proofline\":1,\"proofline\":2}}}}" + ), + ], + }; + for document in invalid { + let path = seed(home.path(), client, document.as_bytes()); + let before = entries(home.path()); + let refused = confirmed_removal(home.path(), client); + assert!(matches!( + refused.result, + Err(InstallError::RemoveInvalidConfig(_) | InstallError::ConfigShape { .. }) + )); + let error = refused.result.unwrap_err(); + assert!(!format!("{error:?} {error}").contains(PRIVATE)); + assert!(!format!("{error}").contains("--print")); + assert_eq!(entries(home.path()), before); + assert_eq!(fs::read(path).unwrap(), document.as_bytes()); + } + let path = seed(home.path(), client, &vec![b' '; 1024 * 1024 + 1]); + assert!(matches!( + confirmed_removal(home.path(), client).result, + Err(InstallError::RemoveTooLarge) + )); + fs::write(&path, configuration(client)).unwrap(); + assert_eq!( + confirmed(home.path(), client).result.unwrap(), + Outcome::Installed + ); + let mut readonly = fs::metadata(&path).unwrap().permissions(); + readonly.set_readonly(true); + fs::set_permissions(&path, readonly).unwrap(); + let before = entries(home.path()); + assert!(matches!( + confirmed_removal(home.path(), client).result, + Err(InstallError::ReadOnly(_)) + )); + assert_eq!(entries(home.path()), before); + #[cfg(unix)] + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + #[cfg(not(unix))] + { + let mut permissions = fs::metadata(&path).unwrap().permissions(); + permissions.set_readonly(false); + fs::set_permissions(&path, permissions).unwrap(); + } + } + let home = TempDir::new().unwrap(); + seed(home.path(), Client::Codex, &configuration(Client::Codex)); + assert_eq!( + confirmed(home.path(), Client::Codex).result.unwrap(), + Outcome::Installed + ); + let before = entries(home.path()); + let custom = home.path().join("custom-codex"); + let refused = removal( + home.path(), + Client::Codex, + false, + &mut Cursor::new(b"yes\n"), + Some(&custom), + ); + assert!(matches!( + refused.result, + Err(InstallError::RemoveCustomCodexHome) + )); + assert_eq!(entries(home.path()), before); + git(home.path(), &["init", "--quiet", "--template="]); + let refused = confirmed_removal(home.path(), Client::Codex); + assert!(matches!(refused.result, Err(InstallError::Repository(_)))); +} + +#[test] +fn removal_confirmation_drift_refuses_without_writing() { + let home = TempDir::new().unwrap(); + let path = seed(home.path(), Client::Kiro, &configuration(Client::Kiro)); + assert_eq!( + confirmed(home.path(), Client::Kiro).result.unwrap(), + Outcome::Installed + ); + let changed = fs::read_to_string(&path) + .unwrap() + .replace("chosen-theme", "edited-theme"); + let mut input = AtConfirmation::new(|| fs::write(&path, changed.as_bytes()).unwrap()); + let result = removal(home.path(), Client::Kiro, false, &mut input, None); + assert!(matches!(result.result, Err(InstallError::Changed(_)))); + assert_eq!(fs::read_to_string(&path).unwrap(), changed); + assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 2); +} + +#[cfg(unix)] +#[test] +fn removal_refuses_symlinked_configuration() { + let root = TempDir::new().unwrap(); + let foreign = root.path().join("foreign.json"); + let original = + format!("{{\"mcpServers\":{{\"proofline\":{{\"command\":\"x\"}}}},\"p\":\"{PRIVATE}\"}}"); + fs::write(&foreign, &original).unwrap(); + let home = root.path().join("home"); + fs::create_dir_all(home.join(".cursor")).unwrap(); + symlink(&foreign, target(&home, Client::Cursor)).unwrap(); + assert!(matches!( + confirmed_removal(&home, Client::Cursor).result, + Err(InstallError::File(_)) + )); + assert_eq!(fs::read_to_string(foreign).unwrap(), original); +} + +#[test] +fn an_existing_entry_for_another_executable_suggests_remove_then_install() { + for client in CLIENTS { + let home = TempDir::new().unwrap(); + let stale = match client { + Client::Codex => { + "[mcp_servers.proofline]\ncommand = '/old/bin/proofline'\nargs = ['mcp']\n" + .to_owned() + } + Client::ClaudeCode | Client::Cursor | Client::Gemini | Client::Kiro => { + "{\"mcpServers\":{\"proofline\":{\"command\":\"/old/bin/proofline\"}}}".to_owned() + } + }; + seed(home.path(), client, stale.as_bytes()); + let existing = confirmed(home.path(), client); + assert_eq!(existing.result.unwrap(), Outcome::Existing); + assert!(existing.diagnostics.contains("/old/bin/proofline")); + assert!(existing.diagnostics.contains(&format!( + "`proofline agent remove {0}` and then `proofline agent install {0}`", + client.argument() + ))); + assert_eq!( + confirmed_removal(home.path(), client).result.unwrap(), + Outcome::Removed + ); + assert_eq!( + confirmed(home.path(), client).result.unwrap(), + Outcome::Installed + ); + let current = confirmed(home.path(), client); + assert_eq!(current.result.unwrap(), Outcome::Existing); + assert!(!current.diagnostics.contains("agent remove")); + } +} + +#[test] +fn remove_arguments_parse_like_install() { + for args in [ + vec!["proofline", "agent", "remove", "unknown"], + vec!["proofline", "agent", "remove", "cursor", "--yes", "--print"], + vec!["proofline", "agent", "remove"], + ] { + assert!(Cli::try_parse_from(args).is_err()); + } + for args in [ + vec!["proofline", "agent", "remove", "claude", "--print"], + vec!["proofline", "agent", "remove", "codex", "--yes"], + ] { + let cli = Cli::try_parse_from(args).unwrap(); + assert!(matches!(cli.command, CliCommand::Agent(_))); + } +} diff --git a/tests/agent_remove.rs b/tests/agent_remove.rs new file mode 100644 index 0000000..7288b01 --- /dev/null +++ b/tests/agent_remove.rs @@ -0,0 +1,105 @@ +//! The noninteractive removal contract exercised through the shipped binary. + +use std::fs; +use std::path::Path; +use std::process::{Command, Output, Stdio}; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +fn command(binary: &Path, home: &Path) -> Command { + let mut command = Command::new(binary); + command + .env("HOME", home) + .env("USERPROFILE", home) + .env_remove("CODEX_HOME") + .env_remove("CLAUDE_CONFIG_DIR") + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .stdin(Stdio::null()); + command +} + +fn run(home: &Path, args: &[&str]) -> Output { + command(Path::new(env!("CARGO_BIN_EXE_proofline")), home) + .args(args) + .output() + .unwrap() +} + +#[test] +fn unattended_install_then_remove_leaves_other_settings() { + let home = TempDir::new().unwrap(); + for (client, relative) in [ + ("claude-code", ".claude.json"), + ("cursor", ".cursor/mcp.json"), + ("codex", ".codex/config.toml"), + ] { + let path = home.path().join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let original = if client == "codex" { + "# preserved\nmodel = 'chosen-model'\n\n[mcp_servers.other]\ncommand = 'other-server'\n" + .to_owned() + } else { + json!({"projects": {"private-project": {"hasTrustDialogAccepted": false}}, + "mcpServers": {"other": {"command": "other-server"}}}) + .to_string() + }; + fs::write(&path, &original).unwrap(); + let installed = run(home.path(), &["agent", "install", client, "--yes"]); + assert!(installed.status.success()); + let preview = run(home.path(), &["agent", "remove", client, "--print"]); + assert!(preview.status.success()); + assert!(String::from_utf8_lossy(&preview.stdout).contains("proofline")); + assert!(!String::from_utf8_lossy(&preview.stdout).contains("other-server")); + let removed = run(home.path(), &["agent", "remove", client, "--yes"]); + assert!( + removed.status.success(), + "{}", + String::from_utf8_lossy(&removed.stderr) + ); + let bytes = fs::read_to_string(&path).unwrap(); + if client == "codex" { + assert_eq!(bytes, original); + } else { + assert_eq!( + serde_json::from_str::(&bytes).unwrap(), + serde_json::from_str::(&original).unwrap() + ); + } + let again = run(home.path(), &["agent", "remove", client, "--yes"]); + assert!(again.status.success()); + assert!(String::from_utf8_lossy(&again.stderr).contains("nothing to remove")); + assert_eq!(fs::read_to_string(&path).unwrap(), bytes); + } +} + +#[test] +fn custom_configuration_directories_refuse_even_a_preview() { + let home = TempDir::new().unwrap(); + let path = home.path().join(".claude.json"); + let original = "{\"mcpServers\":{\"proofline\":{\"command\":\"x\"}}}"; + fs::write(&path, original).unwrap(); + for args in [ + ["agent", "remove", "claude-code", "--yes"], + ["agent", "remove", "claude", "--print"], + ] { + let refused = command(Path::new(env!("CARGO_BIN_EXE_proofline")), home.path()) + .env("CLAUDE_CONFIG_DIR", home.path().join("custom")) + .args(args) + .output() + .unwrap(); + assert!(!refused.status.success()); + assert!(String::from_utf8_lossy(&refused.stderr).contains("CLAUDE_CONFIG_DIR")); + assert!(refused.stdout.is_empty()); + } + assert_eq!(fs::read_to_string(&path).unwrap(), original); + let refused = command(Path::new(env!("CARGO_BIN_EXE_proofline")), home.path()) + .env("CODEX_HOME", home.path().join("custom-codex")) + .args(["agent", "remove", "codex", "--print"]) + .output() + .unwrap(); + assert!(!refused.status.success()); + assert!(String::from_utf8_lossy(&refused.stderr).contains("CODEX_HOME")); +}