Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(backfill): report import failures with a nonzero exit status

Samir Hanna Verza37aafdd169c0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aedb30ba..1a2ea487 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
server and the opt-in was a silent no-op for OpenCode. Root sessions (no
`parentID`) stay unmarked (#755).
+- `backfill` returned success even when imports failed, and `--quiet` hid
+ their diagnostics. It now reports errors on stderr, includes failure counts
+ in the human summary, and exits nonzero after emitting its report (#786).
+
## [2.3.1] - 2026-09-17
### Added
diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rs
index 2529c094..f45707b8 100644
--- a/crates/ai-memory-cli/src/commands/backfill.rs
+++ b/crates/ai-memory-cli/src/commands/backfill.rs
@@ -149,7 +149,9 @@ fn write_sentinel(data_dir: &Path, cwd: &Path) {
///
/// # Errors
/// Returns an error when the scope cannot be resolved, the working directory
-/// cannot be read, or the server is unreachable for the emptiness check.
+/// cannot be read, the server is unreachable for the emptiness check, or any
+/// selected session fails to import. The report is emitted before import errors
+/// are returned, including in JSON mode.
pub async fn run(config: &Config, args: crate::cli::BackfillArgs) -> Result<()> {
let cwd = std::env::current_dir().context("resolving the current working directory")?;
@@ -209,19 +211,27 @@ pub async fn run(config: &Config, args: crate::cli::BackfillArgs) -> Result<()>
}
Err(error) => {
report.failed_sessions += 1;
- if !args.quiet {
- eprintln!(
- "ai-memory: backfill of {} session {} failed: {error:#}",
- session.harness.as_str(),
- display_id(&session.native_session_id)
- );
- }
+ // Quiet suppresses the success summary, not failures: the
+ // detached worker's stderr is the operator's diagnostic log.
+ eprintln!(
+ "ai-memory: backfill of {} session {} failed: {error:#}",
+ session.harness.as_str(),
+ display_id(&session.native_session_id)
+ );
}
}
}
write_sentinel(&config.data_dir, &cwd);
- finish(&args, &report)
+ finish(&args, &report)?;
+ if report.failed_sessions > 0 {
+ bail!(
+ "backfill failed to import {} of {} selected session(s)",
+ report.failed_sessions,
+ report.selected
+ );
+ }
+ Ok(())
}
/// Sum the server's per-agent session counts for this scope; zero means empty.
@@ -552,6 +562,9 @@ fn finish(args: &crate::cli::BackfillArgs, report: &BackfillReport) -> Result<()
"📼 ai-memory imported {} prior local session(s) (~{} events) for {}/{}.",
report.imported_sessions, report.imported_events, report.workspace, report.project
);
+ if report.failed_sessions > 0 {
+ line.push_str(&format!(" {} session(s) failed.", report.failed_sessions));
+ }
if report.skipped_for_cap > 0 {
line.push_str(&format!(
" {} older session(s) skipped (import cap).",
diff --git a/crates/ai-memory-cli/tests/suite/backfill_failures.rs b/crates/ai-memory-cli/tests/suite/backfill_failures.rs
new file mode 100644
index 00000000..4cc8cd39
--- /dev/null
+++ b/crates/ai-memory-cli/tests/suite/backfill_failures.rs
@@ -0,0 +1,94 @@
+//! Real CLI exit status and output when the hook batch endpoint fails.
+#![cfg(unix)]
+use axum::{Json, Router, http::StatusCode, routing::post};
+use serde_json::{Value, json};
+
+#[tokio::test]
+async fn import_failures_are_errors_in_human_json_and_quiet_modes() {
+ for partial in [false, true] {
+ let home = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let cwd = std::fs::canonicalize(project.path()).unwrap();
+ let transcripts = home
+ .path()
+ .join(".claude/projects")
+ .join(cwd.to_string_lossy().replace('/', "-"));
+ std::fs::create_dir_all(&transcripts).unwrap();
+ for sid in [
+ "11111111-2222-3333-4444-555555555555",
+ "99999999-2222-3333-4444-555555555555",
+ ] {
+ crate::e2e_support::write_jsonl(
+ &transcripts.join(format!("{sid}.jsonl")),
+ &[
+ json!({"sessionId": sid, "cwd": cwd}),
+ json!({"type": "user", "message": {"role": "user", "content": [{"type":"text", "text":"fixture history"}]}}),
+ ],
+ );
+ }
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let app = Router::new().route(
+ "/hook/batch",
+ post(move |Json(items): Json<Vec<Value>>| async move {
+ if partial && items[0]["url"].as_str().unwrap().contains("99999999") {
+ (StatusCode::OK, Json(json!({"accepted": items.len()})))
+ } else {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({"error": "injected batch failure"})),
+ )
+ }
+ }),
+ );
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ for mode in ["human", "json", "quiet"] {
+ let data = tempfile::tempdir().unwrap();
+ let mut cmd = crate::e2e_support::hermetic(env!("CARGO_BIN_EXE_ai-memory"));
+ cmd.env_remove("CODEX_HOME");
+ cmd.current_dir(&cwd)
+ .env("AI_MEMORY_HOME", home.path())
+ .env("AI_MEMORY_DATA_DIR", data.path())
+ .env("AI_MEMORY_SERVER_URL", format!("http://{addr}"))
+ .args([
+ "backfill",
+ "--workspace",
+ "review",
+ "--project",
+ "fixture",
+ "--force",
+ ]);
+ if mode == "json" {
+ cmd.arg("--json");
+ }
+ if mode == "quiet" {
+ cmd.args(["--auto", "--quiet"]);
+ }
+ let output = tokio::process::Command::from(cmd).output().await.unwrap();
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ let stderr = String::from_utf8(output.stderr).unwrap();
+ assert!(
+ !output.status.success(),
+ "{mode}, partial={partial}: falsely succeeded: {stdout}"
+ );
+ assert!(
+ stderr.contains("injected batch failure"),
+ "failure detail lost: {stderr}"
+ );
+ if mode == "json" {
+ let report: Value = serde_json::from_str(&stdout).unwrap();
+ assert_eq!(report["selected"], 2);
+ assert_eq!(report["imported_sessions"], usize::from(partial));
+ assert_eq!(report["failed_sessions"], if partial { 1 } else { 2 });
+ } else if mode == "quiet" {
+ assert!(stdout.is_empty());
+ } else {
+ assert!(
+ stdout.contains("failed"),
+ "human summary must include failures: {stdout}"
+ );
+ }
+ }
+ server.abort();
+ }
+}
diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rs
index 15a6e194..1386b9a9 100644
--- a/crates/ai-memory-cli/tests/suite/main.rs
+++ b/crates/ai-memory-cli/tests/suite/main.rs
@@ -7,6 +7,7 @@
mod autoscope_env;
mod backfill_e2e;
+mod backfill_failures;
mod completions;
mod doctor_e2e;
mod e2e_support;
diff --git a/docs/design-boot-backfill.md b/docs/design-boot-backfill.md
index 1daa335f..b39dfd04 100644
--- a/docs/design-boot-backfill.md
+++ b/docs/design-boot-backfill.md
@@ -25,6 +25,12 @@ behavior and touches the trust boundary (retroactive untrusted text enters the s
The automatic path runs detached and silent (like Claude Code's own auto-memory); the
`📼 imported N session(s)` summary is shown on a **manual** `ai-memory backfill` only.
+Failed imports are always written to stderr (the detached worker's
+`logs/backfill.log`), including with `--quiet`. Any failed session makes the
+command exit nonzero after emitting its report; `--json` still produces the
+complete report on stdout. Other selected sessions are still attempted, and
+the one-attempt sentinel policy is unchanged.
+
Surfacing the count in the next session's on-start context is a possible follow-up
(§ "Notice delivery" describes the delivery path it would reuse).