Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(serve): observe ctrl-c on the stdio transport (#699)
Samir Hanna Verza3dda84db518f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fa333692..02b6a245 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0now uses the import instead of a prose pointer (#680).### Fixed+- `serve --transport stdio` ignored Ctrl-C. The stdio arm awaited the MCP+ service without installing a signal handler, so the interrupt was left to the+ default disposition — which the kernel discards when the process is PID 1 in+ its namespace, as it is under the container entrypoint. The server stayed up+ with its watcher and scheduler still ticking, and only closing stdin stopped+ it. `serve` now watches for Ctrl-C from before the `initialize` handshake, so+ a server started by hand and never contacted by a client is interruptible+ too, and exits instead of parking on the uncancellable blocking read of+ stdin. The HTTP transport already had this (#699).- The from-source AUR `PKGBUILD` now builds and tests on constrained AURbuilders. Release LTO was disabled (`options=('!debug' '!lto')`) so thefinal link no longer gets OOM-killed on low-memory build hosts, and thediff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex f2b01fed..e047570c 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -905,8 +905,40 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {match args.transport {TransportKind::Stdio => {info!("MCP server ready on stdio (Ctrl-C to stop)");- let service = server.serve(stdio()).await?;- service.waiting().await?;+ // Ctrl-C has to be observed, and from before the transport is up.+ // Two things conspire otherwise (#699). The default disposition is+ // not enough: the container entrypoint runs this binary directly+ // (`ENTRYPOINT ["/usr/local/bin/ai-memory"]`, no init), so the+ // server is PID 1 in its namespace and the kernel drops a+ // default-disposition signal sent to a namespace's init. And a+ // handler installed *after* `serve()` would never be reached,+ // because `serve()` blocks on the MCP `initialize` handshake — a+ // server started by hand, with no client writing to stdin, sits+ // there while the watcher and scheduler keep ticking. Racing the+ // whole session covers both windows. The HTTP arm below has always+ // had this, through `with_graceful_shutdown`.+ let session = async {+ let service = server.serve(stdio()).await?;+ service.waiting().await?;+ anyhow::Ok(())+ };+ tokio::select! {+ result = session => result?,+ _ = tokio::signal::ctrl_c() => {+ info!("ctrl-c received; shutting down");+ // Returning through `run()` would park on runtime+ // shutdown instead of exiting: the stdio transport reads+ // stdin on a blocking thread that cannot be cancelled, and+ // dropping the runtime waits for blocking tasks, so the+ // process would sit there until the client closed the pipe.+ // Leaving here is exactly what the default disposition+ // already does for a server that is not PID 1 — the same+ // abruptness, now reachable inside the image too — and 0+ // matches the HTTP arm's exit for an operator-requested+ // stop.+ std::process::exit(0);+ }+ }}TransportKind::Http => {let bind = args.bind.unwrap_or_else(|| config.bind.clone());diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex 4a5cbdaa..5ac288d4 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -15,3 +15,4 @@ mod removal;mod repo_layout;mod routing_instructions;mod routing_skills;+mod serve_shutdown;diff --git a/crates/ai-memory-cli/tests/suite/serve_shutdown.rs b/crates/ai-memory-cli/tests/suite/serve_shutdown.rsnew file mode 100644index 00000000..99c45d99--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/serve_shutdown.rs@@ -0,0 +1,106 @@+//! `serve --transport stdio` must stop when the operator interrupts it (#699).++#![cfg(unix)]++/// Startup, one interrupt and one shutdown: seconds, not milliseconds.+mod slow {+ use std::io::{BufRead, BufReader};+ use std::process::{Child, Command, Stdio};+ use std::sync::mpsc;+ use std::thread;+ use std::time::{Duration, Instant};++ const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++ fn wait_for_exit(child: &mut Child, budget: Duration) -> Option<std::process::ExitStatus> {+ let deadline = Instant::now() + budget;+ while Instant::now() < deadline {+ match child.try_wait().expect("try_wait") {+ Some(status) => return Some(status),+ None => thread::sleep(Duration::from_millis(100)),+ }+ }+ None+ }++ /// A stdio server must shut down when it is interrupted, even when the+ /// disposition it inherited would discard the signal.+ ///+ /// What this covers: that `serve` installs a signal handler instead of+ /// relying on the default disposition, that it does so *before* the MCP+ /// `initialize` handshake (a server started by hand has no client writing+ /// to stdin and never gets past `serve()`), and that observing the+ /// interrupt actually ends the process rather than parking on runtime+ /// shutdown behind the uncancellable blocking read of stdin.+ ///+ /// What it does not cover: the reported environment itself. #699 is the+ /// container entrypoint running this binary as PID 1, where the kernel+ /// drops a default-disposition signal sent to a namespace's init. A test+ /// cannot portably become PID 1, so the child inherits `SIG_IGN` for+ /// SIGINT instead — `trap "" INT` before `exec`, which survives the exec.+ /// The mechanism that swallows the signal differs; the property under test+ /// is the same one that fixes both, and reverting the fix fails this test.+ #[test]+ fn stdio_serve_exits_when_interrupted() {+ let data_dir = tempfile::TempDir::new().expect("tempdir");++ let mut child = Command::new("sh")+ .arg("-c")+ .arg(r#"trap "" INT; exec "$1" serve"#)+ .arg("sh")+ .arg(BIN)+ .env("AI_MEMORY_DATA_DIR", data_dir.path())+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn serve");++ // Hold stdin open: closing it is the other way this server stops, and+ // it would hide whether the interrupt was observed at all.+ let _stdin = child.stdin.take().expect("stdin");++ let stderr = child.stderr.take().expect("stderr");+ let (tx, rx) = mpsc::channel();+ thread::spawn(move || {+ for line in BufReader::new(stderr).lines().map_while(Result::ok) {+ let ready = line.contains("ready on stdio");+ let _ = tx.send(line);+ if ready {+ break;+ }+ }+ });++ let deadline = Instant::now() + Duration::from_secs(60);+ let mut ready = false;+ while Instant::now() < deadline {+ match rx.recv_timeout(Duration::from_secs(1)) {+ Ok(line) if line.contains("ready on stdio") => {+ ready = true;+ break;+ }+ Ok(_) => {}+ Err(mpsc::RecvTimeoutError::Timeout) => {}+ Err(mpsc::RecvTimeoutError::Disconnected) => break,+ }+ }+ assert!(ready, "server never reported it was ready on stdio");++ let killed = Command::new("kill")+ .args(["-INT", &child.id().to_string()])+ .status()+ .expect("send SIGINT");+ assert!(killed.success(), "kill -INT failed");++ let status = wait_for_exit(&mut child, Duration::from_secs(20));+ let Some(status) = status else {+ let _ = child.kill();+ panic!("serve was still running 20s after SIGINT");+ };+ assert!(+ status.success(),+ "an operator-requested stop should exit 0, got {status:?}"+ );+ }+}