Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix: clean up post-refactor regressions
AkitaOnRails2251cee72357
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 34079fa4..c1663de6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- Hook spool batch drains now scale the `/hook/batch` request timeout with the+ number of events in the chunk, reducing false timeout retries after a slow+ server has successfully committed the batch.+- Hook spool filenames now include a per-process monotonic suffix so tight loops+ or long-lived helper processes cannot overwrite events created in the same+ millisecond.+- Contamination audits now treat `%` and `_` in stored `repo_path` values as+ literal path bytes, matching runtime cwd-prefix resolution.+- Auto-improve telemetry rejection aggregates now exclude rejected maintenance+ report proposals (`curator_report` and `auto_improve_report`) from learning+ rejection signals.+- Auto-improve eval stdout capping now reads only `MAX+1` bytes before failing+ closed, avoiding a flaky oversized-output test path while preserving the cap.+- Updated `quinn-proto` to clear the new RustSec memory-exhaustion advisory.+## [1.2.0] - 2026-06-23### Addeddiff --git a/Cargo.lock b/Cargo.lockindex ad00c525..7d8d99c1 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2056,9 +2056,9 @@ dependencies = [[[package]]name = "quinn-proto"-version = "0.11.14"+version = "0.11.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"+checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"dependencies = ["bytes","getrandom 0.3.4",diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rsindex 2facff88..13c4f85b 100644--- a/crates/ai-memory-cli/src/commands/hook_spool.rs+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs@@ -19,6 +19,7 @@//! renewed rather than rejected).use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};use ai_memory_llm::{OidcToken, refresh_access_token};@@ -49,6 +50,8 @@ const MAX_BATCH_ITEMS: usize = 256;/// least one event even if that event alone exceeds this.const MAX_BATCH_BYTES: usize = 8 * 1024 * 1024;+static ENQUEUE_SEQ: AtomicU64 = AtomicU64::new(0);+/// How a spooled event authenticates to the server when drained.#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]pub enum AuthMode {@@ -108,14 +111,20 @@ fn now_ms() -> u64 {}/// Append an event to the spool, atomically (temp file + rename) and 0600 on-/// Unix. Never touches the network. Each hook invocation enqueues exactly one-/// event, so the `<ms>-<pid>` name is unique.+/// Unix. Never touches the network. File names include a per-process monotonic+/// suffix so tight loops or helper processes can enqueue several events in the+/// same millisecond without clobbering an earlier event.////// # Errors/// Returns an error only when the spool file cannot be written.pub fn enqueue(spool: &Path, entry: &SpoolEntry) -> std::io::Result<()> {std::fs::create_dir_all(spool)?;- let name = format!("{:013}-{}.json", entry.created_ms, std::process::id());+ let seq = ENQUEUE_SEQ.fetch_add(1, Ordering::Relaxed);+ let name = format!(+ "{:013}-{}-{seq:016x}.json",+ entry.created_ms,+ std::process::id()+ );let tmp = spool.join(format!("{name}.tmp"));let final_path = spool.join(&name);let bytes = serde_json::to_vec(entry)?;@@ -276,19 +285,13 @@ pub async fn drain(result.remaining += chunk.len().saturating_sub(1) + files.len().saturating_sub(idx);break;};- if started.elapsed() >= total_budget {+ let Some(remaining_budget) = total_budget.checked_sub(started.elapsed()) else {result.remaining += chunk.len() + files.len().saturating_sub(idx);break;- }- match post_batch(- &client,- &base,- &payload,- bearer.as_deref(),- per_event_timeout,- )- .await- {+ };+ let batch_timeout =+ batch_request_timeout(per_event_timeout, remaining_budget, chunk.len());+ match post_batch(&client, &base, &payload, bearer.as_deref(), batch_timeout).await {BatchOutcome::Accepted(k) => {let k = k.min(chunk.len());for (path, _) in &chunk[..k] {@@ -389,6 +392,18 @@ pub async fn drain(result}+fn batch_request_timeout(+ per_event_timeout: Duration,+ remaining_budget: Duration,+ item_count: usize,+) -> Duration {+ let item_count = u32::try_from(item_count.max(1)).unwrap_or(u32::MAX);+ per_event_timeout+ .checked_mul(item_count)+ .unwrap_or(Duration::MAX)+ .min(remaining_budget)+}+fn load_live_entry(path: &Path, result: &mut DrainResult) -> Option<SpoolEntry> {let Ok(bytes) = std::fs::read(path) else {result.remaining += 1;@@ -606,6 +621,25 @@ mod tests {assert_eq!(loaded.token.as_deref(), Some("tok"));}+ #[test]+ fn enqueue_names_are_unique_in_tight_loop() {+ let tmp = tempfile::tempdir().unwrap();+ let spool = spool_dir(tmp.path());+ for i in 0..MAX_SPOOL_FILES {+ let mut entry = entry_for(+ format!("https://x/hook?event=e{i}"),+ "{}".into(),+ None,+ false,+ );+ entry.created_ms = 42;+ enqueue(&spool, &entry).unwrap();+ }++ let files = list_entries(&spool).unwrap();+ assert_eq!(files.len(), MAX_SPOOL_FILES);+ }+#[test]fn enqueue_prunes_oldest_files_when_spool_exceeds_limit() {let tmp = tempfile::tempdir().unwrap();@@ -643,13 +677,7 @@ mod tests {None,false,);- // Distinct filenames: enqueue uses ms+pid, so space them out.enqueue(&spool, &e).unwrap();- std::fs::rename(- spool.join(format!("{:013}-{}.json", e.created_ms, std::process::id())),- spool.join(format!("evt-{i}.json")),- )- .unwrap();}let r = drain(&spool,@@ -842,6 +870,39 @@ mod tests {addr.to_string()}+ async fn serve_delayed_batch_hook(+ req_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,+ delay: Duration,+ ) -> String {+ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ while let Ok((mut s, _)) = listener.accept().await {+ let rc = req_count.clone();+ tokio::spawn(async move {+ let mut buf = vec![0_u8; 65536];+ let n = s.read(&mut buf).await.unwrap_or(0);+ rc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ let req = String::from_utf8_lossy(&buf[..n]);+ let payload = req.split("\r\n\r\n").nth(1).unwrap_or("");+ let accepted = serde_json::from_str::<serde_json::Value>(payload)+ .ok()+ .and_then(|v| v.as_array().map(Vec::len))+ .unwrap_or(0);+ tokio::time::sleep(delay).await;+ let body = format!("{{\"accepted\":{accepted}}}");+ let resp = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = s.write_all(resp.as_bytes()).await;+ });+ }+ });+ addr.to_string()+ }+fn write_spool_entry(spool: &Path, name: &str, url: String) {write_spool_entry_with_body(spool, name, url, "{}".into());}@@ -924,6 +985,47 @@ mod tests {);}+ #[tokio::test]+ async fn slow_batch_success_uses_chunk_scaled_timeout_and_deletes_once() {+ let req_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let addr = serve_delayed_batch_hook(req_count.clone(), Duration::from_millis(200)).await;+ let tmp = tempfile::tempdir().unwrap();+ let spool = spool_dir(tmp.path());+ for i in 0..3 {+ write_spool_entry(+ &spool,+ &format!("evt-{i}.json"),+ format!("http://{addr}/hook?event=e{i}"),+ );+ }++ let r = drain(+ &spool,+ tmp.path(),+ Duration::from_secs(2),+ Duration::from_millis(100),+ )+ .await;++ assert_eq!(r.sent, 3);+ assert_eq!(r.remaining, 0);+ assert!(list_entries(&spool).unwrap().is_empty());++ let second = drain(+ &spool,+ tmp.path(),+ Duration::from_secs(2),+ Duration::from_millis(100),+ )+ .await;+ assert_eq!(second, DrainResult::default());+ assert_eq!(+ req_count.load(std::sync::atomic::Ordering::SeqCst),+ 1,+ "a slow successful batch is not retried after the response lands"+ );+ }+#[tokio::test]async fn drain_falls_back_to_per_event_when_batch_unsupported() {// Pre-upgrade server: /hook/batch is 404, per-event /hook is 202.diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.tomlindex a3a94913..73070cd3 100644--- a/crates/ai-memory-cli/templates/config.default.toml+++ b/crates/ai-memory-cli/templates/config.default.toml@@ -100,8 +100,9 @@ pending_path = "_pending/auto-improve"# Optional executable evaluation gate for selected proposal targets. Disabled by# default; operators supply the command and scoring policy. The command is run-# directly (not through a shell) with JSON on stdin and must print JSON such as-# { "score_before": 0.72, "score_after": 0.76, "passed": true }.+# directly (not through a shell), split on whitespace, with JSON on stdin. Use a+# wrapper script for paths with spaces, custom environment, or multiple commands.+# It must print JSON such as { "score_before": 0.72, "score_after": 0.76, "passed": true }.[auto_improve.eval]enabled = falsecommand = ""diff --git a/crates/ai-memory-consolidate/src/auto_improve.rs b/crates/ai-memory-consolidate/src/auto_improve.rsindex 544f3f2f..456b101f 100644--- a/crates/ai-memory-consolidate/src/auto_improve.rs+++ b/crates/ai-memory-consolidate/src/auto_improve.rs@@ -739,23 +739,21 @@ whereuse tokio::io::AsyncReadExt;let mut out = Vec::new();- let mut buf = [0_u8; 8192];- loop {- let n = reader- .read(&mut buf)- .await- .map_err(|e| EvalRunError::Error(format!("failed to read eval stdout: {e}")))?;- if n == 0 {- return Ok(out);- }- if out.len().saturating_add(n) > MAX_EVAL_STDOUT_BYTES {- return Err(EvalRunError::Error(format!(- "eval stdout exceeded {} bytes",- MAX_EVAL_STDOUT_BYTES- )));- }- out.extend_from_slice(&buf[..n]);+ let cap = u64::try_from(MAX_EVAL_STDOUT_BYTES)+ .unwrap_or(u64::MAX)+ .saturating_add(1);+ reader+ .take(cap)+ .read_to_end(&mut out)+ .await+ .map_err(|e| EvalRunError::Error(format!("failed to read eval stdout: {e}")))?;+ if out.len() > MAX_EVAL_STDOUT_BYTES {+ return Err(EvalRunError::Error(format!(+ "eval stdout exceeded {} bytes",+ MAX_EVAL_STDOUT_BYTES+ )));}+ Ok(out)}fn format_eval_evidence(outcome: &AutoImproveEvalResponse, delta: Option<f64>) -> String {diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 569fe756..18628574 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -313,9 +313,8 @@ async fn handle_hook_batch(/// Parse the `?event=…&agent=…` query of a spooled hook URL into [`HookQuery`],/// mirroring axum's `Query` extractor (both use `serde_urlencoded`). A URL with-/// no query, or an unparseable one, yields the default (empty `event`) — which-/// `from_query_and_body` maps to an unknown event that `process` skips, so a-/// malformed item can't error the whole batch.+/// no query, or an unparseable one, yields the default query; downstream+/// fail-fast batch handling decides whether that default envelope can be stored.fn parse_hook_query(url: &str) -> HookQuery {let qs = url.split_once('?').map_or("", |(_, q)| q);serde_urlencoded::from_str(qs).unwrap_or_default()diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 92bafb74..8a3af5c8 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -1561,7 +1561,7 @@ fn auto_improve_error_response(}// ----------------------------------------------------------------------// curator report+// auto-improve telemetry report// ---------------------------------------------------------------------async fn handle_auto_improve_report(diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex b87cdb89..922e3660 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -866,7 +866,7 @@ mod tests {"telemetry",);telemetry_report.kind = "auto_improve_report".into();- store+ let maintenance_staged = store.writer.stage_auto_improve_run(stage_input(ws,@@ -875,6 +875,20 @@ mod tests {)).await.unwrap();+ for id in maintenance_staged.proposal_ids {+ store+ .writer+ .reject_auto_improve_proposal(RejectAutoImproveProposal {+ workspace_id: ws,+ project_id: proj,+ proposal_id: id,+ reason: "maintenance rejected".into(),+ actor: actor.clone(),+ author_id: None,+ })+ .await+ .unwrap();+ }let mut eval_rejections = stage_input(ws, proj, Vec::new());eval_rejections.rejected_candidates_json = serde_json::json!([@@ -1009,10 +1023,19 @@ mod tests {telemetry_count(&aggregate.rejections_by_reason, "eval_gate_error"),1);+ assert_eq!(+ telemetry_count(&aggregate.rejections_by_reason, "maintenance rejected"),+ 0,+ "maintenance/report proposal rejections must not pollute learning telemetry"+ );assert_eq!(telemetry_count(&aggregate.rejected_targets, "eval/repeat.md"),2);+ assert_eq!(+ telemetry_count(&aggregate.rejected_targets, "reports/curator.md"),+ 0+ );assert!(aggregate.repeated_rejection_fingerprintsdiff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex c688f258..5615ca7a 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -3367,7 +3367,7 @@ impl ReaderPool {.collect(),rejections_by_reason: auto_improve_rejection_group_counts(conn,- "reason",+ "r.reason",workspace_id,project_id,since_created_at,@@ -3382,7 +3382,7 @@ impl ReaderPool {)?,rejected_targets: auto_improve_rejection_group_counts(conn,- "COALESCE(target_path, '(none)')",+ "COALESCE(r.target_path, '(none)')",workspace_id,project_id,since_created_at,@@ -3666,9 +3666,7 @@ impl ReaderPool {FROM projects \WHERE repo_path IS NOT NULL \AND length(repo_path) > 1 \- AND repo_path NOT LIKE '%/' \- AND repo_path NOT LIKE '%\\%%' ESCAPE '\\' \- AND repo_path NOT LIKE '%\\_%' ESCAPE '\\'",+ AND repo_path NOT LIKE '%/'",);if scoped {p_sql.push_str(" AND workspace_id = ?");@@ -4285,8 +4283,10 @@ fn auto_improve_rejection_group_counts() -> rusqlite::Result<Vec<AutoImproveTelemetryCount>> {let sql = format!("SELECT {expr} AS key, COUNT(*) AS count- FROM auto_improve_rejections- WHERE workspace_id = ?1 AND project_id = ?2 AND created_at >= ?3+ FROM auto_improve_rejections r+ LEFT JOIN auto_improve_proposals p ON p.id = r.source_proposal_id+ WHERE r.workspace_id = ?1 AND r.project_id = ?2 AND r.created_at >= ?3+ AND (r.source_proposal_id IS NULL OR COALESCE(p.kind, '') NOT IN ('curator_report', 'auto_improve_report'))GROUP BY key ORDER BY count DESC, key ASC LIMIT ?4");let mut stmt = conn.prepare(&sql)?;@@ -4314,9 +4314,11 @@ fn auto_improve_repeated_rejection_fingerprints(limit: i64,) -> rusqlite::Result<Vec<AutoImproveTelemetryCount>> {let mut stmt = conn.prepare(- "SELECT normalized_fingerprint AS key, COUNT(*) AS count- FROM auto_improve_rejections- WHERE workspace_id = ?1 AND project_id = ?2 AND created_at >= ?3+ "SELECT r.normalized_fingerprint AS key, COUNT(*) AS count+ FROM auto_improve_rejections r+ LEFT JOIN auto_improve_proposals p ON p.id = r.source_proposal_id+ WHERE r.workspace_id = ?1 AND r.project_id = ?2 AND r.created_at >= ?3+ AND (r.source_proposal_id IS NULL OR COALESCE(p.kind, '') NOT IN ('curator_report', 'auto_improve_report'))GROUP BY normalized_fingerprint HAVING count > 1ORDER BY count DESC, key ASC LIMIT ?4",)?;diff --git a/crates/ai-memory-store/tests/audit_contamination.rs b/crates/ai-memory-store/tests/audit_contamination.rsindex 9d616f8b..c8b97192 100644--- a/crates/ai-memory-store/tests/audit_contamination.rs+++ b/crates/ai-memory-store/tests/audit_contamination.rs@@ -188,6 +188,83 @@ async fn audit_ignores_home_repo_path_when_home_is_provided() {assert!(with_home.findings.is_empty());}+#[tokio::test]+async fn audit_prefix_paths_treat_percent_and_underscore_literally() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let conn = Connection::open(store.db_path()).unwrap();+ let now = 1_700_000_000_000_i64;+ let (ws, underscore, percent, sibling, wrong_session, clean_session, sibling_session) =+ (id(1), id(2), id(3), id(4), id(5), id(6), id(7));++ conn.execute(+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'w', ?2)",+ params![&ws[..], now],+ )+ .unwrap();+ for (pid, name, repo_path) in [+ (&underscore, "under_score", "/w/a_b"),+ (&percent, "per_cent", "/w/a%b"),+ (&sibling, "sibling", "/w/axb"),+ ] {+ conn.execute(+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \+ VALUES (?1, ?2, ?3, ?4, ?5)",+ params![&pid[..], &ws[..], name, repo_path, now],+ )+ .unwrap();+ }+ conn.execute(+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \+ VALUES (?1, ?2, ?3, 'claude-code', ?4, ?5)",+ params![+ &wrong_session[..],+ &ws[..],+ &underscore[..],+ "/w/a%b/sub",+ now+ ],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \+ VALUES (?1, ?2, ?3, 'claude-code', ?4, ?5)",+ params![+ &clean_session[..],+ &ws[..],+ &underscore[..],+ "/w/a_b/sub",+ now+ ],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \+ VALUES (?1, ?2, ?3, 'claude-code', ?4, ?5)",+ params![+ &sibling_session[..],+ &ws[..],+ &sibling[..],+ "/w/axb/sub",+ now+ ],+ )+ .unwrap();+ drop(conn);++ let report = store.reader.audit_contamination(None, None).await.unwrap();++ assert_eq!(report.summary.sessions_misbucketed, 1);+ let finding = report+ .findings+ .iter()+ .find(|f| f.check == "session_wrong_bucket")+ .expect("percent repo_path mismatch should be visible to audit");+ assert_eq!(finding.landed_project, "under_score");+ assert_eq!(finding.expected_project.as_deref(), Some("per_cent"));+ assert_eq!(finding.cwd.as_deref(), Some("/w/a%b/sub"));+}+#[tokio::test]async fn audit_scope_restricts_to_landed_bucket() {let tmp = tempfile::tempdir().unwrap();