Skip to content

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

Rust

fix(capture): judge imported events by their record cwd and the hook's delivery checks

AkitaOnRailse8f1445ab8ad
diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rs
index 289e01f7..3b3ef097 100644
--- a/crates/ai-memory-cli/src/commands/backfill.rs
+++ b/crates/ai-memory-cli/src/commands/backfill.rs
@@ -1520,6 +1520,185 @@ mod tests {
assert!(posted.contains("/src"), "public call: {posted}");
}
+ /// A Claude Code transcript record: `content` is the message content.
+ fn claude_record(
+ sid: &str,
+ uuid: &str,
+ cwd: &Path,
+ role: &str,
+ content: serde_json::Value,
+ ) -> serde_json::Value {
+ serde_json::json!({
+ "type": role, "uuid": uuid, "sessionId": sid, "cwd": cwd,
+ "timestamp": "2026-09-01T10:00:00Z",
+ "message": {"role": role, "content": content},
+ })
+ }
+
+ fn claude_tool(name: &str, id: &str, input: serde_json::Value) -> serde_json::Value {
+ serde_json::json!({"type": "tool_use", "id": id, "name": name, "input": input})
+ }
+
+ fn claude_output(id: &str, text: &str) -> serde_json::Value {
+ serde_json::json!({"type": "tool_result", "tool_use_id": id, "content": text})
+ }
+
+ /// Claude Code records each line's `cwd`, which follows the session as it
+ /// moves. The live hook resolves a relative argument from that cwd, so an
+ /// import must too: `cat adr/x.md` run from `docs/` reads an ignored file
+ /// and is never posted, while the same command run from the checkout root
+ /// names a public path and is.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn backfill_resolves_each_call_from_its_record_cwd() {
+ let home = tempfile::tempdir().unwrap();
+ let repo = marked_checkout("[capture]\nignore_paths = [\"docs/adr/**\"]\n");
+ let docs = repo.path().join("docs");
+ std::fs::create_dir_all(docs.join("adr")).unwrap();
+ let sid = "11111111-2222-3333-4444-555555555556";
+ let cat = |id| claude_tool("Bash", id, serde_json::json!({"command": "cat adr/x.md"}));
+ let lines = [
+ claude_record(sid, "u1", repo.path(), "user", "read the adr".into()),
+ claude_record(
+ sid,
+ "a1",
+ &docs,
+ "assistant",
+ serde_json::json!([cat("toolu_docs")]),
+ ),
+ claude_record(
+ sid,
+ "u2",
+ &docs,
+ "user",
+ serde_json::json!([claude_output("toolu_docs", "ADRSENTINEL private decision")]),
+ ),
+ claude_record(
+ sid,
+ "a2",
+ repo.path(),
+ "assistant",
+ serde_json::json!([cat("toolu_root")]),
+ ),
+ claude_record(
+ sid,
+ "u3",
+ repo.path(),
+ "user",
+ serde_json::json!([claude_output("toolu_root", "PUBLICCONTROL root note")]),
+ ),
+ ];
+ let posted = backfill_posted(
+ ManagedHarness::Claude,
+ home.path(),
+ home.path(),
+ repo.path(),
+ sid,
+ &lines,
+ )
+ .await;
+ assert!(!posted.contains("ADRSENTINEL"), "excluded output: {posted}");
+ assert!(posted.contains("PUBLICCONTROL"), "control output: {posted}");
+ assert_eq!(
+ posted.matches("cat adr/x.md").count(),
+ 2,
+ "only the root call, as title and message: {posted}"
+ );
+ }
+
+ /// A call the live hook would reroute to another checkout must pass that
+ /// checkout's admission gate and reach the same server, or it is never
+ /// posted: under allowlist mode an unmarked repository admits nothing, a
+ /// marker selecting an unregistered profile emits nothing, and a marker
+ /// selecting a registered profile sends to another server. Control: a read
+ /// in a marked checkout with no server selection is posted.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn backfill_drops_reroutes_the_live_hook_would_not_deliver_here() {
+ let home = tempfile::tempdir().unwrap();
+ let data_dir = tempfile::tempdir().unwrap();
+ std::fs::write(
+ data_dir.path().join(super::super::hook::CAPTURE_MODE_FILE),
+ "allowlist\n",
+ )
+ .unwrap();
+ let name = crate::server_profiles::ProfileName::parse("team-e").unwrap();
+ crate::server_profiles::add(data_dir.path(), &name, "https://e.example", &[], Some("E"))
+ .unwrap();
+ let source = marked_checkout("[capture]\n");
+ let unmarked = tempfile::tempdir().unwrap();
+ let init = std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(unmarked.path())
+ .status()
+ .unwrap();
+ assert!(init.success());
+ let unknown_profile = marked_checkout("server = \"team-b\"\n");
+ let other_server = marked_checkout("server = \"team-e\"\n");
+ let same_server = marked_checkout("[capture]\n");
+ let sid = "11111111-2222-3333-4444-555555555557";
+ let reads = [
+ (&unmarked, "UNMARKEDSENTINEL"),
+ (&unknown_profile, "UNKNOWNPROFILESENTINEL"),
+ (&other_server, "OTHERSERVERSENTINEL"),
+ (&same_server, "SAMESERVERCONTROL"),
+ ];
+ let mut lines = vec![claude_record(
+ sid,
+ "u0",
+ source.path(),
+ "user",
+ "read the notes".into(),
+ )];
+ for (index, (repo, text)) in reads.iter().enumerate() {
+ let file = repo.path().join(format!("{text}.txt"));
+ std::fs::write(&file, text).unwrap();
+ let id = format!("toolu_{index}");
+ lines.push(claude_record(
+ sid,
+ &format!("a{index}"),
+ source.path(),
+ "assistant",
+ serde_json::json!([claude_tool(
+ "Read",
+ &id,
+ serde_json::json!({"file_path": file})
+ )]),
+ ));
+ lines.push(claude_record(
+ sid,
+ &format!("u{}", index + 1),
+ source.path(),
+ "user",
+ serde_json::json!([claude_output(&id, &format!("{text} content"))]),
+ ));
+ }
+ let posted = backfill_posted(
+ ManagedHarness::Claude,
+ home.path(),
+ data_dir.path(),
+ source.path(),
+ sid,
+ &lines,
+ )
+ .await;
+ for sentinel in [
+ "UNMARKEDSENTINEL",
+ "UNKNOWNPROFILESENTINEL",
+ "OTHERSERVERSENTINEL",
+ ] {
+ assert!(
+ !posted.contains(sentinel),
+ "{sentinel} was posted: {posted}"
+ );
+ }
+ assert!(
+ posted.contains("SAMESERVERCONTROL content"),
+ "control: {posted}"
+ );
+ assert!(posted.contains("read the notes"), "prompt kept: {posted}");
+ }
+
fn spawned_args(
server_url: Option<&str>,
server_profile: Option<&str>,
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index bec48478..494add12 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -1366,6 +1366,22 @@ fn resolve_hook_route(
}
}
+/// Whether the live hook would deliver events from `destination` to the same
+/// server as events from `source`, resolving each like [`resolve_hook_route`].
+/// A refused selection on either side delivers nowhere, so it never matches.
+/// A transcript import posts everything to one endpoint, so an event the hook
+/// would send elsewhere must not ride along.
+pub(crate) fn delivers_to_same_server(data_dir: &Path, source: &str, destination: &str) -> bool {
+ match (
+ resolve_hook_route(data_dir, Some(source), || None),
+ resolve_hook_route(data_dir, Some(destination), || None),
+ ) {
+ (HookRoute::InstallDefault, HookRoute::InstallDefault) => true,
+ (HookRoute::Profile(source), HookRoute::Profile(destination)) => source == destination,
+ _ => false,
+ }
+}
+
/// Normalize the raw hook `cwd` into the base `policy.inspect` joins a tool
/// event's relative candidate path onto — lexically, via
/// `marker::absolute_normalized`, NOT `fs::canonicalize` (#671).
diff --git a/crates/ai-memory-cli/src/commands/transcript_capture.rs b/crates/ai-memory-cli/src/commands/transcript_capture.rs
index 6230d6f9..7da6eba8 100644
--- a/crates/ai-memory-cli/src/commands/transcript_capture.rs
+++ b/crates/ai-memory-cli/src/commands/transcript_capture.rs
@@ -5,20 +5,25 @@
//! policy never saw those tool calls. This applies the same decision table
//! rather than a second matcher: each recorded tool call is rebuilt in its
//! agent's hook shape (`tool_call_payload`) and inspected by the checkout's
-//! `CapturePolicy`; a call the live hook would reroute to another checkout
-//! also answers to that checkout's policy; and each tool result inherits the
-//! decision of the call it answers.
+//! `CapturePolicy`, resolved from the working directory its own record names
+//! when the adapter keeps one; a call the live hook would reroute to another
+//! checkout also answers to that checkout's admission gate, server route and
+//! policy; and each tool result inherits the decision of the call it answers.
use std::collections::HashMap;
-use std::path::Path;
+use std::path::{Path, PathBuf};
-use ai_memory_core::{NewWorkstreamEvent, WorkstreamEventKind};
+use ai_memory_core::{AgentKind, NewWorkstreamEvent, WorkstreamEventKind};
use ai_memory_hooks::{
CaptureDecision, CaptureDisposition, CapturePolicy, PolicyState, ToolFamily, tool_call_payload,
};
+use ai_memory_workstream::RECORD_CWD_KEY;
use serde_json::Value;
-use super::hook::{checkout_admits_capture, lexical_capture_cwd, tool_location_routing_cwd};
+use super::hook::{
+ checkout_admits_capture, delivers_to_same_server, lexical_capture_cwd,
+ tool_location_routing_cwd,
+};
use super::hook_capture::capture_policy;
/// What an import does with one transcript event.
@@ -60,6 +65,7 @@ impl EventCapture {
/// The capture policy of the checkout a transcript was recorded in.
pub(crate) struct TranscriptCapture {
+ data_dir: PathBuf,
admitted: bool,
policy: CapturePolicy,
cwd: String,
@@ -73,6 +79,7 @@ impl TranscriptCapture {
pub(crate) fn for_checkout(data_dir: &Path, cwd: &Path) -> Self {
let cwd = cwd.to_string_lossy().into_owned();
Self {
+ data_dir: data_dir.to_path_buf(),
admitted: checkout_admits_capture(data_dir, &cwd),
policy: capture_policy(&cwd),
inspection_cwd: lexical_capture_cwd(&cwd),
@@ -91,6 +98,11 @@ impl TranscriptCapture {
/// live hook emits none. Otherwise messages are kept, as live prompt
/// capture keeps them.
///
+ /// An event whose record names its own working directory is judged from
+ /// there, as the live hook judges an event by its own `cwd`: that
+ /// directory must pass the same admission gate and deliver to the same
+ /// server as this checkout, or the event is dropped.
+ ///
/// A result answers the call with the same native id. Some adapters record
/// no id, so a result without a matching call takes the strictest decision
/// of every call since the last user message: parallel calls may answer
@@ -102,19 +114,27 @@ impl TranscriptCapture {
if !self.admitted {
return vec![EventCapture::Drop; events.len()];
}
+ let mut elsewhere = HashMap::new();
let mut by_id: HashMap<&str, EventCapture> = HashMap::new();
let mut turn: Vec<EventCapture> = Vec::new();
let mut out = Vec::with_capacity(events.len());
for event in events {
+ let cwd = record_cwd(event).unwrap_or(&self.cwd);
+ let admitted = cwd == self.cwd || self.admits_elsewhere(cwd, &mut elsewhere);
let capture = match event.kind {
WorkstreamEventKind::ToolCall => {
- let capture = self.decide_call(event);
+ let capture = if admitted {
+ self.decide_call(event, cwd, &mut elsewhere)
+ } else {
+ EventCapture::Drop
+ };
if let Some(id) = call_id(event) {
by_id.insert(id, capture.clone());
}
turn.push(capture.clone());
capture
}
+ WorkstreamEventKind::ToolResult if !admitted => EventCapture::Drop,
WorkstreamEventKind::ToolResult => {
match call_id(event).and_then(|id| by_id.get(id)) {
Some(capture) => capture.clone(),
@@ -129,7 +149,11 @@ impl TranscriptCapture {
if matches!(event.role.as_deref(), Some("user" | "human")) {
turn.clear();
}
- EventCapture::Keep
+ if admitted {
+ EventCapture::Keep
+ } else {
+ EventCapture::Drop
+ }
}
WorkstreamEventKind::Compaction
| WorkstreamEventKind::Checkpoint
@@ -155,6 +179,13 @@ impl TranscriptCapture {
EventCapture::Drop => None,
EventCapture::MetadataOnly(decision) => Some(withheld(event, &decision)),
})
+ .map(|mut event| {
+ // The record's cwd only steers the decision above.
+ if let Some(metadata) = event.metadata.as_object_mut() {
+ metadata.remove(RECORD_CWD_KEY);
+ }
+ event
+ })
.collect()
}
@@ -166,33 +197,89 @@ impl TranscriptCapture {
}
}
- fn decide_call(&self, event: &NewWorkstreamEvent) -> EventCapture {
+ /// Whether the live hook would deliver an event reported from `cwd`, a
+ /// directory other than this checkout's, to this import's server at all:
+ /// the hook's admission gate there (capture mode, marker opt-in, readable
+ /// routing marker) and the same server-profile route.
+ fn admits_elsewhere(&self, cwd: &str, seen: &mut HashMap<String, bool>) -> bool {
+ *seen.entry(cwd.to_owned()).or_insert_with(|| {
+ checkout_admits_capture(&self.data_dir, cwd)
+ && delivers_to_same_server(&self.data_dir, &self.cwd, cwd)
+ })
+ }
+
+ /// Judge one call as the live hook would for an event reporting `cwd`,
+ /// under this checkout's policy too, since the import stays in this scope.
+ fn decide_call(
+ &self,
+ event: &NewWorkstreamEvent,
+ cwd: &str,
+ elsewhere: &mut HashMap<String, bool>,
+ ) -> EventCapture {
let (name, args) = recorded_call(event);
+ let unreadable = args.is_none();
let raw = tool_call_payload(event.agent, name, args.as_ref(), call_id(event));
- let decision = self.policy.inspect(event.agent, &raw, &self.inspection_cwd);
- // A shell command cut by the adapter's size cap, or recorded as
- // unparseable text, cannot be matched, and its output may name any path.
- if args.is_none()
- && decision.protocol().tool_family() == ToolFamily::NonFile
- && self.policy.state() != PolicyState::Inactive
- {
- return EventCapture::Drop;
- }
- let capture = EventCapture::from_decision(decision);
- match tool_location_routing_cwd(event.agent, &raw, &self.cwd) {
- // The live hook would deliver this call to that checkout under its
- // policy. An import stays in this scope, so both policies apply.
- Some(destination) => {
- let destination_decision = capture_policy(&destination).inspect(
- event.agent,
- &raw,
- &lexical_capture_cwd(&destination),
- );
- capture.stricter(EventCapture::from_decision(destination_decision))
+ let inspect = |policy: &CapturePolicy, cwd: &str| {
+ inspect_call(
+ policy,
+ event.agent,
+ &raw,
+ &lexical_capture_cwd(cwd),
+ unreadable,
+ )
+ };
+ let mut capture = if cwd == self.cwd {
+ inspect_call(
+ &self.policy,
+ event.agent,
+ &raw,
+ &self.inspection_cwd,
+ unreadable,
+ )
+ } else {
+ inspect(&self.policy, cwd).stricter(inspect(&capture_policy(cwd), cwd))
+ };
+ // The live hook would deliver this call to that checkout under its
+ // admission gate, route and policy. An import stays in this scope, so
+ // both policies apply, and a destination the hook would refuse or send
+ // to another server drops the call.
+ if let Some(destination) = tool_location_routing_cwd(event.agent, &raw, cwd) {
+ if !self.admits_elsewhere(&destination, elsewhere) {
+ return EventCapture::Drop;
}
- None => capture,
+ capture = capture.stricter(inspect(&capture_policy(&destination), &destination));
}
+ capture
+ }
+}
+
+/// One policy's decision for a rebuilt call. A shell command cut by the
+/// adapter's size cap, or recorded as unparseable text, cannot be matched, and
+/// its output may name any path.
+fn inspect_call(
+ policy: &CapturePolicy,
+ agent: AgentKind,
+ raw: &Value,
+ inspection_cwd: &str,
+ unreadable: bool,
+) -> EventCapture {
+ let decision = policy.inspect(agent, raw, inspection_cwd);
+ if unreadable
+ && decision.protocol().tool_family() == ToolFamily::NonFile
+ && policy.state() != PolicyState::Inactive
+ {
+ return EventCapture::Drop;
}
+ EventCapture::from_decision(decision)
+}
+
+/// The absolute working directory the event's own record names, if any.
+fn record_cwd(event: &NewWorkstreamEvent) -> Option<&str> {
+ event
+ .metadata
+ .get(RECORD_CWD_KEY)
+ .and_then(Value::as_str)
+ .filter(|cwd| Path::new(cwd).is_absolute())
}
/// The native id linking a tool call and its result, when the adapter kept one.
@@ -255,7 +342,6 @@ fn withheld(mut event: NewWorkstreamEvent, decision: &CaptureDecision) -> NewWor
#[cfg(test)]
mod tests {
use super::*;
- use ai_memory_core::AgentKind;
use serde_json::json;
fn event(
@@ -470,6 +556,63 @@ mod tests {
);
}
+ fn at(mut event: NewWorkstreamEvent, cwd: &Path) -> NewWorkstreamEvent {
+ event.metadata[RECORD_CWD_KEY] = cwd.to_string_lossy().into_owned().into();
+ event
+ }
+
+ /// The live hook judges every event — prompts included — by its own
+ /// `cwd`. A record written after the session moved into a repository
+ /// the hook would not capture under allowlist mode is dropped; records in
+ /// a subdirectory of the opted-in checkout are kept, and the record cwd
+ /// never reaches the ledger.
+ #[test]
+ fn a_record_cwd_answers_to_the_hook_admission_gate_there() {
+ let data_dir = tempfile::tempdir().unwrap();
+ std::fs::write(
+ data_dir.path().join(super::super::hook::CAPTURE_MODE_FILE),
+ "allowlist\n",
+ )
+ .unwrap();
+ let marked = checkout(Some("docs/adr/**"));
+ // Outside `$HOME` a marker lookup stops at the git root.
+ let init = std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(marked.path())
+ .status()
+ .unwrap();
+ assert!(init.success());
+ let subdir = marked.path().join("src");
+ std::fs::create_dir_all(&subdir).unwrap();
+ let unmarked = checkout(None);
+ let capture = TranscriptCapture::for_checkout(data_dir.path(), marked.path());
+ let events = |cwd: &Path| {
+ vec![
+ at(
+ event(WorkstreamEventKind::Message, "user", "a prompt", json!({})),
+ cwd,
+ ),
+ at(read_call(&cwd.join("lib.rs"), Some("r")), cwd),
+ at(result("code", Some("r")), cwd),
+ ]
+ };
+ assert_eq!(
+ kinds(&capture.decide(&events(unmarked.path()))),
+ ["drop", "drop", "drop"]
+ );
+ assert_eq!(
+ kinds(&capture.decide(&events(&subdir))),
+ ["keep", "keep", "keep"]
+ );
+ let uploaded = capture.filter_ledger_events(events(&subdir));
+ assert!(
+ uploaded
+ .iter()
+ .all(|event| event.metadata.get(RECORD_CWD_KEY).is_none()),
+ "{uploaded:?}"
+ );
+ }
+
#[test]
fn ledger_events_are_dropped_or_stripped_before_upload() {
let repo = checkout(Some("docs/adr/**"));
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index b2d7ecff..be653988 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -26,9 +26,9 @@ pub use repository::{
};
pub use transcript::{
AmbiguousNativeSession, ClaudeContinuation, ExportedTranscript, NativeSessionCandidate,
- claude_continued_session, claude_live_background_attach_id, claude_session_ran_in_background,
- discover_native_session, export_transcript, kiro_harness_from_source_cursor,
- kiro_v3_resume_uses_default_store, list_native_sessions, native_memory_dir,
- native_session_exists, native_session_in_checkout, native_store_root,
+ RECORD_CWD_KEY, claude_continued_session, claude_live_background_attach_id,
+ claude_session_ran_in_background, discover_native_session, export_transcript,
+ kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store, list_native_sessions,
+ native_memory_dir, native_session_exists, native_session_in_checkout, native_store_root,
wait_for_transcript_flush,
};
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index db1bf8d8..aa0ebd23 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -29,6 +29,9 @@ const MAX_ANTIGRAVITY_HISTORY_LINE_BYTES: usize = 64 * 1024;
/// of its `.db` being created.
const ANTIGRAVITY_OPENING_PROMPT_WINDOW: Duration = Duration::from_secs(5);
const LEGACY_MANAGED_WORKSTREAM_PACKET_PREFIX: &str = "> **ai-memory managed workstream:";
+/// Event metadata key holding the working directory the event's own record
+/// was written in, when the harness records one per record.
+pub const RECORD_CWD_KEY: &str = "cwd";
/// Checkout-local native session that can seed an otherwise-empty workstream.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -668,6 +671,7 @@ fn export_jsonl(
let mut line = Vec::new();
let mut events = Vec::new();
let mut losses = Vec::new();
+ let mut codex_turn_cwd: Option<String> = None;
loop {
line.clear();
let read = reader.read_until(b'\n', &mut line)?;
@@ -706,6 +710,7 @@ fn export_jsonl(
} else {
source_id(&value).unwrap_or_else(|| format!("byte-{}", offset - read as u64))
};
+ let first_event = events.len();
match harness {
ManagedHarness::Claude => parse_claude(
&value,
@@ -774,6 +779,21 @@ fn export_jsonl(
));
}
}
+ let record_cwd = match harness {
+ ManagedHarness::Claude => value.get("cwd").and_then(Value::as_str),
+ ManagedHarness::Codex => {
+ if matches!(
+ value.get("type").and_then(Value::as_str),
+ Some("session_meta" | "turn_context")
+ ) && let Some(cwd) = value.pointer("/payload/cwd").and_then(Value::as_str)
+ {
+ codex_turn_cwd = Some(cwd.to_owned());
+ }
+ codex_turn_cwd.as_deref()
+ }
+ _ => None,
+ };
+ stamp_record_cwd(&mut events[first_event..], record_cwd);
}
if harness == ManagedHarness::Kimi {
annotate_kimi_subagents(path, &mut losses);
@@ -792,6 +812,23 @@ fn export_jsonl(
})
}
+/// Label each event with the working directory its record was written in.
+/// Claude Code records `cwd` on every line and Codex in each `turn_context`,
+/// and both follow the session as it moves, so the session's opening cwd can
+/// be the wrong base for a relative path. Imports resolve tool arguments and
+/// the capture policy from this label, as the live hook does from each event's
+/// own `cwd`.
+fn stamp_record_cwd(events: &mut [NewWorkstreamEvent], cwd: Option<&str>) {
+ let Some(cwd) = cwd.filter(|cwd| Path::new(cwd).is_absolute()) else {
+ return;
+ };
+ for event in events {
+ if let Some(metadata) = event.metadata.as_object_mut() {
+ metadata.insert(RECORD_CWD_KEY.into(), Value::String(cwd.to_owned()));
+ }
+ }
+}
+
fn hash_file_prefix(file: &mut File, len: u64) -> Result<Option<Sha256>> {
file.seek(SeekFrom::Start(0))?;
let mut hasher = Sha256::new();
@@ -5026,6 +5063,65 @@ mod tests {
assert_eq!(second.events[0].content, "ok");
}
+ /// Claude Code writes `cwd` on every record and Codex in each
+ /// `turn_context`; each event carries the cwd of the record it came from,
+ /// so an import resolves relative tool arguments from where the call ran.
+ #[test]
+ fn jsonl_events_carry_their_record_cwd() {
+ let temp = tempfile::tempdir().unwrap();
+ let root = temp.path().join("repo");
+ let docs = root.join("docs");
+ let claude = temp.path().join("claude.jsonl");
+ let record = |uuid: &str, cwd: &Path, content: Value| json!({"type":"assistant","uuid":uuid,"cwd":cwd,"message":{"role":"assistant","content":content}});
+ fs::write(
+ &claude,
+ [
+ record("one", &root, json!("at the root")),
+ record(
+ "two",
+ &docs,
+ json!([{"type":"tool_use","id":"t","name":"Bash","input":{"command":"ls"}}]),
+ ),
+ json!({"type":"assistant","uuid":"three","cwd":"relative","message":{"role":"assistant","content":"no usable cwd"}}),
+ ]
+ .map(|line| format!("{line}\n"))
+ .concat(),
+ )
+ .unwrap();
+ let events = export_jsonl(ManagedHarness::Claude, &claude, "s", None)
+ .unwrap()
+ .events;
+ let cwds: Vec<_> = events
+ .iter()
+ .map(|event| event.metadata.get(RECORD_CWD_KEY).and_then(Value::as_str))
+ .collect();
+ assert_eq!(cwds, [root.to_str(), docs.to_str(), None], "{events:?}");
+ assert_eq!(events[1].metadata["tool"], "Bash");
+
+ let codex = temp.path().join("codex.jsonl");
+ let item = |text: &str| json!({"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":text}]}});
+ fs::write(
+ &codex,
+ [
+ json!({"type":"session_meta","payload":{"id":"s","cwd":root}}),
+ item("first turn"),
+ json!({"type":"turn_context","payload":{"cwd":docs}}),
+ item("second turn"),
+ ]
+ .map(|line| format!("{line}\n"))
+ .concat(),
+ )
+ .unwrap();
+ let events = export_jsonl(ManagedHarness::Codex, &codex, "s", None)
+ .unwrap()
+ .events;
+ let cwds: Vec<_> = events
+ .iter()
+ .map(|event| event.metadata.get(RECORD_CWD_KEY).and_then(Value::as_str))
+ .collect();
+ assert_eq!(cwds, [root.to_str(), docs.to_str()], "{events:?}");
+ }
+
#[test]
fn incomplete_final_jsonl_record_does_not_advance_cursor() {
let temp = tempfile::tempdir().unwrap();