Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(capture): inspect Codex transcript shell calls as the hook sees them
AkitaOnRailsa3354f2637e7
diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rsindex 950bcc10..289e01f7 100644--- a/crates/ai-memory-cli/src/commands/backfill.rs+++ b/crates/ai-memory-cli/src/commands/backfill.rs@@ -1399,6 +1399,127 @@ mod tests {server.abort();}+ /// Plant `lines` as one native session and backfill it from `repo`,+ /// returning everything posted to `/hook/batch` as one JSON string.+ #[cfg(unix)]+ async fn backfill_posted(+ harness: ManagedHarness,+ home: &Path,+ data_dir: &Path,+ repo: &Path,+ sid: &str,+ lines: &[serde_json::Value],+ ) -> String {+ use axum::{Router, routing::post};+ use std::sync::{Arc, Mutex};++ let session_file = match harness {+ ManagedHarness::Claude => home+ .join(".claude/projects")+ .join(repo.to_string_lossy().replace('/', "-"))+ .join(format!("{sid}.jsonl")),+ ManagedHarness::Codex => home+ .join(".codex/sessions/2026/09/01")+ .join(format!("rollout-2026-09-01T10-00-00-{sid}.jsonl")),+ other => panic!("no fixture layout for {}", other.as_str()),+ };+ std::fs::create_dir_all(session_file.parent().unwrap()).unwrap();+ let body: String = lines.iter().map(|line| format!("{line}\n")).collect();+ std::fs::write(&session_file, body).unwrap();++ let posted = Arc::new(Mutex::new(Vec::<serde_json::Value>::new()));+ let captured = posted.clone();+ let app = Router::new().route(+ "/hook/batch",+ post(+ move |axum::Json(items): axum::Json<Vec<serde_json::Value>>| {+ let captured = captured.clone();+ async move {+ let accepted = items.len();+ captured.lock().unwrap().extend(items);+ axum::Json(serde_json::json!({ "accepted": accepted }))+ }+ },+ ),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let endpoint = ServerEndpoint::for_hook_target(format!("http://{address}"), None);+ let session = SessionRef {+ harness,+ native_session_id: sid.into(),+ updated_at: SystemTime::now(),+ };+ let capture = TranscriptCapture::for_checkout(data_dir, repo);+ import_one(&endpoint, "ws", "proj", home, repo, &capture, &session)+ .await+ .unwrap();+ server.abort();+ serde_json::to_string(&*posted.lock().unwrap()).unwrap()+ }++ fn marked_checkout(marker: &str) -> tempfile::TempDir {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join(".ai-memory.toml"), marker).unwrap();+ dir+ }++ /// Codex records its shell tool as `exec_command` with `{cmd, workdir}`;+ /// the live hook receives it as `Bash`. A command whose `workdir`-relative+ /// argument names an ignored path never reaches `/hook/batch`, call or+ /// output; the same command run from a public directory does.+ #[cfg(unix)]+ #[tokio::test]+ async fn backfill_inspects_codex_exec_command_as_the_hook_shell_call() {+ let home = tempfile::tempdir().unwrap();+ let repo = marked_checkout("[capture]\nignore_paths = [\"docs/adr/**\"]\n");+ for dir in ["docs/adr", "src/adr"] {+ std::fs::create_dir_all(repo.path().join(dir)).unwrap();+ }+ let sid = "019a0000-0000-7000-8000-000000000001";+ let item = |payload: serde_json::Value| {+ serde_json::json!({+ "type": "response_item", "timestamp": "2026-09-01T10:00:00Z", "payload": payload,+ })+ };+ let exec = |id: &str, workdir: &str| {+ item(serde_json::json!({+ "type": "function_call", "name": "exec_command", "call_id": id,+ "arguments": serde_json::json!({+ "cmd": "cat adr/x.md", "workdir": repo.path().join(workdir),+ }).to_string(),+ }))+ };+ let output = |id: &str, text: &str| {+ item(serde_json::json!({"type": "function_call_output", "call_id": id, "output": text}))+ };+ let lines = [+ serde_json::json!({"type": "session_meta", "payload": {"id": sid, "cwd": repo.path()}}),+ item(serde_json::json!({+ "type": "message", "role": "user",+ "content": [{"type": "input_text", "text": "show both adr notes"}],+ })),+ exec("call_adr", "docs"),+ output("call_adr", "ADRSENTINEL private decision"),+ exec("call_pub", "src"),+ output("call_pub", "PUBLICCONTROL public note"),+ ];+ let posted = backfill_posted(+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ repo.path(),+ sid,+ &lines,+ )+ .await;+ assert!(!posted.contains("ADRSENTINEL"), "excluded output: {posted}");+ assert!(!posted.contains("/docs\\\""), "excluded call: {posted}");+ assert!(posted.contains("PUBLICCONTROL"), "public output: {posted}");+ assert!(posted.contains("/src"), "public call: {posted}");+ }+fn spawned_args(server_url: Option<&str>,server_profile: Option<&str>,diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 1ebe71f4..4c4e4703 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -8937,6 +8937,100 @@ mod tests {);}+ /// Codex records its shell tool as `exec_command` with `{cmd, workdir}`,+ /// which hooks receive as `Bash`. The ledger upload inspects it as that+ /// shell call: a command whose `workdir`-relative argument names an ignored+ /// path never reaches the finish request, while the same command run from+ /// a public directory does.+ #[tokio::test]+ async fn ledger_upload_inspects_codex_exec_command_as_the_hook_shell_call() {+ let requests = Arc::new(std::sync::Mutex::new(Vec::<FinishManagedRunRequest>::new()));+ let captured = requests.clone();+ let app = Router::new().route(+ "/workstream/runs/{id}/finish",+ post(+ move |axum::Json(request): axum::Json<FinishManagedRunRequest>| {+ let captured = captured.clone();+ async move {+ let imported_events = request.events.len();+ captured.lock().unwrap().push(request);+ axum::Json(FinishManagedRunResponse {+ imported_events,+ latest_sequence: 1,+ })+ }+ },+ ),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let home = tempfile::tempdir().unwrap();+ let config = launch_config(home.path(), home.path(), address);+ let endpoint = ServerEndpoint::from_config_resolving_auth(&config).await;+ let repo = tempfile::tempdir().unwrap();+ std::fs::write(+ repo.path().join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"docs/adr/**\"]\n",+ )+ .unwrap();+ let event = |kind, content: String, id: &str| ai_memory_core::NewWorkstreamEvent {+ event_id: format!("e-{id}-{}", content.len()),+ agent: AgentKind::Codex,+ native_session_id: "sid-1".into(),+ source_record_id: None,+ kind,+ role: None,+ content,+ occurred_at: None,+ metadata: serde_json::json!({"tool": "exec_command", "tool_use_id": id}),+ };+ let exec = |workdir: &str, id: &str| {+ event(+ ai_memory_core::WorkstreamEventKind::ToolCall,+ format!(+ "exec_command: {}",+ serde_json::json!({"cmd": "cat adr/x.md", "workdir": repo.path().join(workdir)})+ ),+ id,+ )+ };+ let output = |text: &str, id: &str| {+ event(+ ai_memory_core::WorkstreamEventKind::ToolResult,+ text.into(),+ id,+ )+ };+ let transcript = ExportedTranscript {+ native_session_id: "sid-1".into(),+ source_cursor: Some("cursor".into()),+ events: vec![+ exec("docs", "adr"),+ output("ADRSENTINEL private decision", "adr"),+ exec("src", "pub"),+ output("PUBLICCONTROL public note", "pub"),+ ],+ losses: Vec::new(),+ };+ let imported = import_batches(+ &endpoint,+ "/workstream/runs/test",+ transcript,+ Default::default(),+ Some(0),+ &Sanitizer::builtin(),+ &TranscriptCapture::for_checkout(home.path(), repo.path()),+ )+ .await+ .unwrap();+ server.abort();+ let posted = serde_json::to_string(&*requests.lock().unwrap()).unwrap();+ assert!(!posted.contains("ADRSENTINEL"), "excluded output: {posted}");+ assert!(posted.contains("PUBLICCONTROL"), "public output: {posted}");+ assert_eq!(imported, 2, "only the public call and its output: {posted}");+ }+/// Allowlist capture mode (#446): the live hook emits nothing from an/// unmarked checkout, so its run ledger upload carries no events — no/// prompt, no tool content — while still finishing the run. A markeddiff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex 620d24d8..cc0e8422 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -814,6 +814,11 @@ pub fn metadata_only_body(/// `ai-memory run` ledger — so the import applies the live decision table/// rather than a second matcher. `args: None` means the arguments could not be/// recovered, which a file tool treats as malformed.+///+/// A transcript can name a tool differently from the hook: Codex records its+/// shell tool as `exec_command` with `{cmd, workdir}`, which reaches hooks as+/// `Bash`. Such a call is rebuilt under the hook's name and fields, so the+/// import classifies it as the live hook does.#[must_use]pub fn tool_call_payload(agent: AgentKind,@@ -822,6 +827,7 @@ pub fn tool_call_payload(call_id: Option<&str>,) -> Value {let args = args.cloned().unwrap_or(Value::Null);+ let (name, args) = hook_tool_call(agent, name, args);let mut payload = match agent {AgentKind::AntigravityCli => json!({"toolCall": {"name": name, "args": args}}),AgentKind::Zero => json!({"toolName": name, "input": args}),@@ -836,6 +842,24 @@ pub fn tool_call_payload(payload}+/// The name and arguments the live hook receives for a call a transcript+/// records under its own name. Unreadable arguments stay unreadable.+fn hook_tool_call(agent: AgentKind, name: &str, args: Value) -> (&str, Value) {+ if agent == AgentKind::Codex && name.eq_ignore_ascii_case("exec_command") {+ let Value::Object(recorded) = args else {+ return ("Bash", args);+ };+ let mut input = Map::new();+ for (from, to) in [("cmd", "command"), ("workdir", "workdir")] {+ if let Some(value) = recorded.get(from) {+ input.insert(to.into(), value.clone());+ }+ }+ return ("Bash", Value::Object(input));+ }+ (name, args)+}+#[derive(Default)]struct Extracted<'a> {family: ToolFamily,@@ -2461,6 +2485,57 @@ mod tests {}}+ /// Codex transcripts record the shell tool as `exec_command` with+ /// `{cmd, workdir}`; hooks receive it as `Bash`. The rebuilt call must be a+ /// shell call resolved from its `workdir`, not an unknown tool whose output+ /// is kept.+ #[test]+ fn codex_transcript_exec_command_is_inspected_as_the_hook_bash_call() {+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["docs/adr/**".into()],+ }),+ "/repo",+ None,+ );+ let decide = |agent: AgentKind, args: Value| {+ let raw = tool_call_payload(agent, "exec_command", Some(&args), Some("call-1"));+ policy.inspect(agent, &raw, "/repo").protocol().clone()+ };+ for args in [+ json!({"cmd": "cat adr/x.md", "workdir": "/repo/docs"}),+ json!({"cmd": "cat adr/x.md", "workdir": "docs"}),+ json!({"cmd": "cat docs/adr/x.md"}),+ json!({"cmd": ["bash", "-lc", "cat docs/adr/x.md"], "yield_time_ms": 1000}),+ ] {+ let protocol = decide(AgentKind::Codex, args.clone());+ assert_eq!(protocol.tool_family(), ToolFamily::NonFile, "{args}");+ assert_eq!(protocol.disposition(), CaptureDisposition::Drop, "{args}");+ }+ let public = decide(+ AgentKind::Codex,+ json!({"cmd": "cat adr/x.md", "workdir": "/repo/src"}),+ );+ assert_eq!(public.tool_family(), ToolFamily::NonFile);+ assert_eq!(public.disposition(), CaptureDisposition::Keep);+ let raw = tool_call_payload(+ AgentKind::Codex,+ "exec_command",+ Some(&json!({"cmd": "ls", "workdir": "/other/repo"})),+ None,+ );+ assert_eq!(+ absolute_tool_location_paths(AgentKind::Codex, &raw, "/repo"),+ Some(vec!["/other/repo".to_owned()]),+ "the workdir locates the call like a live shell workdir"+ );+ // Only Codex records its shell under this name.+ assert_eq!(+ decide(AgentKind::ClaudeCode, json!({"cmd": "cat docs/adr/x.md"})).tool_family(),+ ToolFamily::Unknown+ );+ }+#[test]fn hermes_documented_tool_names_map_to_canonical_families() {for (tool, expected) in [