From 0be4b52069d6b059b138b369040cd18acf619d43 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 19 Nov 2026 15:07:58 -0500 Subject: [PATCH 1/5] Extract an agent adapter boundary, and pin the bundle format MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Everything loch needs from one agent harness — hook events and hooks file, reading a turn from the transcript, the store key for a transcript, session discovery and metadata, a transcript's cwds, where a restore goes and how it resumes, finding a transcript and forking it — is now behind agent::Agent, in three tiers (attribution, transport, conversation) whose later tiers have declining defaults. Claude Code moves onto it with no change in behaviour. tests/bundle.rs now pins the packed JSON and ref of a bundle, and that repacking reproduces the bytes. save and list on 100 real sessions gave identical refs and output before and after. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 14 +- src/agent.rs | 164 +++++++++++++++++++ src/backfill.rs | 3 +- src/claude.rs | 409 +++++++++++++++++++++++++++++++++++++++++++++--- src/cli.rs | 123 +++++++++------ src/hook.rs | 151 +++++------------- src/lib.rs | 1 + src/rewrite.rs | 11 +- src/trace.rs | 250 +++++------------------------ tests/bundle.rs | 71 +++++++++ tests/claude.rs | 2 +- 11 files changed, 796 insertions(+), 403 deletions(-) create mode 100644 src/agent.rs diff --git a/CLAUDE.md b/CLAUDE.md index 5d051f3..7b42a74 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -218,7 +218,8 @@ src/ ├── main.rs # argv handling, dispatch, the two renderers' entry point ├── cli.rs # every command: list/save/restore/delete/reindex/ingest/install/ │ # blame/log/ask/backfill/gc/hook/help/version -├── claude.rs # Claude Code adapter: path encoding, session discovery, metadata +├── agent.rs # the adapter boundary: what loch needs from one agent harness +├── claude.rs # Claude Code adapter: path encoding, discovery, metadata, turns, fork ├── bundle.rs # bundle format, gzip, content-addressed ref ├── format.rs # loch format: turn and content ids, derived files ├── ingest.rs # Claude Code JSONL -> loch turns (the converter) @@ -830,10 +831,13 @@ field it wants is `foreignCwds`. Its shape is keyed on the origin deliberately (above) — it was `{"": }` briefly and was changed before anything consumed it. -Nothing currently pins the bundle format. The two constraints above — -compact separators and omitted-not-null metadata — are held by prose -rather than by a test, so a well-meaning refactor could change every -ref the format produces without failing the suite. Note that +The bundle format is pinned by `tests/bundle.rs`: the exact packed JSON +and ref of a two-session bundle (an absent branch and version, non-ASCII, +escapes), and that re-packing an unpacked bundle reproduces its bytes. A +failure there means every existing ref would stop reproducing, which needs +a decision, not a test update. The adapter extraction was also checked +against real data: `save` and `list` on three project directories (100 +sessions) gave identical refs and output before and after. Note that `SessionMeta.other_cwds` is deliberately *not* packed into the bundle: the transcript is the source of truth for what directories it names, and adding a field would change the ref of every bundle for a value the diff --git a/src/agent.rs b/src/agent.rs new file mode 100644 index 0000000..41a9b9d --- /dev/null +++ b/src/agent.rs @@ -0,0 +1,164 @@ +//! The agent adapter boundary: everything loch needs to know about one agent +//! harness, behind one trait, so the rest of loch — snapshots, attribution, +//! bundles, the store, the JSON contract — is written once. +//! +//! What an adapter has to provide comes in tiers, and each tier is useful on +//! its own: +//! +//! 1. **Attribution** — `id`, `hook_events`, `hooks_file`. Blame and log need +//! nothing else: a hook at a turn's start and end, carrying a session id +//! and a cwd. `current_turn` (what the transcript says the turn was) only +//! sharpens the record, and the default says nothing. +//! 2. **Transport** — `list_sessions`, `transcript_cwds`, `restore_path`, +//! `existing_transcript`, `resume_command`. `save`, `list` and `restore`. +//! 3. **Conversation** — `find_transcript`, `fork`. `ask`. +//! +//! Everything past tier 1 has a default that declines, so a harness with turn +//! hooks and nothing else is still an adapter. + +use crate::json::Map; +use crate::store::{Store, StoreError}; +use crate::trace::{Fork, ForkError}; + +#[derive(Clone, Debug)] +pub struct SessionMeta { + pub agent: &'static str, + pub session_id: String, + pub path: String, + pub cwd: String, + pub git_branch: Option, + /// The harness's own version, as its transcript records it. + pub version: Option, + pub bytes: u64, + pub modified_at: String, + pub summary: Option, + /// Directories the session also worked in before it moved. A restore has + /// one target cwd, so records naming these cannot be made correct on the + /// far side; surfacing them is the only honest option. + pub other_cwds: Vec, +} + +/// What the transcript says about a turn: the record that began it and the +/// last record written. Each id is whatever the agent's transcript uses to +/// name a position in itself — a record uuid for Claude Code, a turn id for +/// Codex — and only that agent's adapter ever interprets it. +#[derive(Default)] +pub struct TurnInfo { + pub prompt_uuid: Option, + pub prompt: Option, + pub started: Option, + pub end_uuid: Option, + pub ended: Option, +} + +/// A loch hook subcommand an agent event runs: `(event, name)`, e.g. +/// `("UserPromptSubmit", "prompt")`. +pub type HookEvent = (&'static str, &'static str); + +pub trait Agent: Sync { + /// Stable identifier: edit records, store keys, bundles, `--agent`. + fn id(&self) -> &'static str; + /// For prose. + fn name(&self) -> &'static str; + + // -- tier 1: attribution --------------------------------------------------- + + /// The events loch hooks, and the subcommand each runs. + fn hook_events(&self) -> &'static [HookEvent]; + /// The hooks file `install` writes, for a workspace root. + fn hooks_file(&self, root: &str, local: bool) -> String; + /// What `install` says after writing, beyond the file it wrote. + fn install_note(&self) -> &'static str; + /// Hooks this agent won't run until a person approves them. + fn hooks_need_review(&self) -> bool { + false + } + /// The turn `event` closes, as the transcript tells it. When the closing + /// hook belongs to the *next* prompt (`for_next`), that prompt may already + /// be written and is left out. + fn current_turn(&self, _transcript: &str, _event: &Map, _for_next: bool) -> TurnInfo { + TurnInfo::default() + } + /// Where the store keeps this session's transcript, under + /// `transcripts//`. `None` keeps none. + fn transcript_key(&self, _path: &str, _session_id: &str) -> Option { + None + } + + // -- tier 2: transport ------------------------------------------------------ + + /// Where this agent keeps transcripts, for messages. + fn sessions_dir(&self) -> String; + fn list_sessions( + &self, + _cwd: &str, + _branch: Option<&str>, + _session_id: Option<&str>, + ) -> Vec { + Vec::new() + } + fn read_session_meta(&self, _path: &str) -> Option { + None + } + /// Every working directory the transcript's records name, with how many + /// name it, in order of first appearance. + fn transcript_cwds(&self, _raw: &str) -> Vec<(String, usize)> { + Vec::new() + } + /// Where a restored transcript goes. `raw` is the rewritten transcript. + fn restore_path(&self, _raw: &str, _cwd: &str, _session_id: &str) -> Option { + None + } + /// A transcript this machine already holds for the session, which a + /// restore must not silently duplicate or overwrite. + fn existing_transcript(&self, _cwd: &str, _session_id: &str) -> Option { + None + } + /// argv that resumes the session. + fn resume_command(&self, _session_id: &str) -> Option> { + None + } + + // -- tier 3: conversation ----------------------------------------------------- + + /// The agent's own copy if it still exists, else the store's. + fn find_transcript( + &self, + _session_id: &str, + _store: Option<&dyn Store>, + ) -> Result, StoreError> { + Ok(None) + } + /// A new session holding the conversation up to `cut` (the end, if none), + /// filed under `target_cwd`. + fn fork( + &self, + _transcript: &str, + _target_cwd: &str, + _cut: Option<&str>, + _title: Option<&str>, + ) -> Result { + Err(ForkError::Unsupported(self.name())) + } +} + +static ALL: &[&dyn Agent] = &[&crate::claude::CLAUDE_CODE]; + +pub fn all() -> &'static [&'static dyn Agent] { + ALL +} + +pub fn by_id(id: &str) -> Option<&'static dyn Agent> { + all().iter().copied().find(|agent| agent.id() == id) +} + +/// The agents `--agent` names, or every one. +pub fn selected(id: Option<&str>) -> Result, String> { + match id.filter(|id| !id.is_empty()) { + None => Ok(all().to_vec()), + Some(id) => by_id(id).map(|agent| vec![agent]).ok_or_else(|| { + let known: Vec<&str> = all().iter().map(|a| a.id()).collect(); + format!("unknown agent {} (known: {})", id, known.join(", ")) + }), + } +} diff --git a/src/backfill.rs b/src/backfill.rs index bea6727..b100750 100644 --- a/src/backfill.rs +++ b/src/backfill.rs @@ -20,9 +20,8 @@ //! what an earlier backfill wrote. use crate::attribution::{self, EditRecord, FileChange, Hunk, TurnRecord}; -use crate::claude::{self, display_summary, AGENT}; +use crate::claude::{self, display_summary, is_human_prompt, prompt_text, AGENT}; use crate::git; -use crate::hook::{is_human_prompt, prompt_text}; use crate::json::{self, Map, Value}; use crate::snapshot; use crate::store::Store; diff --git a/src/claude.rs b/src/claude.rs index 5e298e6..f8bf0fd 100644 --- a/src/claude.rs +++ b/src/claude.rs @@ -1,32 +1,25 @@ -//! The Claude Code adapter: where sessions live, how -//! their directory is named, and what a session's metadata is. +//! The Claude Code adapter: where sessions live, how their directory is +//! named, what a session's metadata is, how a turn reads in the transcript, +//! and how a conversation is forked. -use crate::json::{self, Value}; +pub use crate::agent::SessionMeta; +use crate::agent::{Agent, HookEvent, TurnInfo}; +use crate::json::{self, Map, Value}; +use crate::object; use crate::py; use crate::redact; +use crate::rewrite::{rewrite_transcript, RewriteSpec}; +use crate::store::{Store, StoreError}; use crate::sys; +use crate::trace::{self, content, records_of, Fork, ForkError, TraceError}; +use std::collections::{HashMap, HashSet}; use std::fs; +use std::path::Path; pub const AGENT: &str = "claude-code"; pub const SUMMARY_LIMIT: usize = 120; -#[derive(Clone, Debug)] -pub struct SessionMeta { - pub session_id: String, - pub path: String, - pub cwd: String, - pub git_branch: Option, - pub claude_version: Option, - pub bytes: u64, - pub modified_at: String, - pub summary: Option, - /// Directories the session also worked in before it moved. A restore has - /// one target cwd, so records naming these cannot be made correct on the - /// far side; surfacing them is the only honest option. - pub other_cwds: Vec, -} - /// `Path.home()`: `HOME` on Unix, `USERPROFILE` on Windows. pub fn home_dir() -> String { let name = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; @@ -189,10 +182,11 @@ pub fn read_session_meta(path: &str) -> Option { let ordered: Vec = counts.keys().cloned().collect(); let cwd = cwd_for_directory(&ordered, &sys::basename(&sys::dirname(path))); Some(SessionMeta { + agent: AGENT, session_id, path: path.into(), git_branch: branches.get(&cwd).cloned(), - claude_version: versions + version: versions .get(&cwd) .or_else(|| versions.values().next()) .cloned(), @@ -239,3 +233,378 @@ pub fn list_sessions( metas.sort_by(|a, b| py::cmp(&b.modified_at, &a.modified_at)); metas } + +// -- reading a turn -------------------------------------------------------------- + +/// A record a person typed: a user message that is neither a tool's result +/// nor Claude Code's own bookkeeping. +pub fn is_human_prompt(record: &Map) -> bool { + if !record.get("type").is_some_and(|t| t.is_str("user")) { + return false; + } + if record.get("isMeta").is_some_and(Value::truthy) + || record.get("isCompactSummary").is_some_and(Value::truthy) + { + return false; + } + match record.get("message").and_then(|m| m.get("content")) { + Some(Value::Str(_)) => true, + Some(Value::Array(_)) => !content(record) + .iter() + .any(|b| b.get("type").is_some_and(|t| t.is_str("tool_result"))), + _ => false, + } +} + +pub fn prompt_text(record: &Map) -> Option { + match record.get("message")?.get("content")? { + Value::Str(text) => Some(text.clone()), + Value::Array(_) => content(record) + .iter() + .find_map(|block| match block.get("text") { + Some(Value::Str(text)) if !text.is_empty() => Some(text.clone()), + _ => None, + }), + _ => None, + } +} + +/// The turn the transcript ends with. When the hook closing it belongs to the +/// *next* prompt, that prompt may already be written; `excluding` names it, +/// and it and everything after are left out. +pub fn current_turn(transcript: &str, excluding: Option<&str>) -> TurnInfo { + let records: Vec = trace::read_records(transcript) + .into_iter() + .filter(|r| matches!(r.get("uuid"), Some(Value::Str(_)))) + .collect(); + let mut end = records.len(); + if let Some(next) = excluding { + if let Some(at) = records.iter().rposition(is_human_prompt) { + if prompt_text(&records[at]).as_deref() == Some(next) { + end = at; + } + } + } + let mut info = TurnInfo::default(); + for record in &records[..end] { + let uuid = record + .get("uuid") + .and_then(Value::as_str) + .map(str::to_string); + let stamp = record + .get("timestamp") + .and_then(Value::as_str) + .map(str::to_string); + if is_human_prompt(record) { + info.prompt_uuid = uuid.clone(); + info.prompt = display_summary(prompt_text(record).as_deref()); + info.started = stamp.clone(); + } + info.end_uuid = uuid; + info.ended = stamp; + } + info +} + +// -- finding a transcript ------------------------------------------------------------ + +fn list_dir(path: &str) -> Vec { + fs::read_dir(path) + .map(|entries| { + entries + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect() + }) + .unwrap_or_default() +} + +/// Claude's own copy if it still exists, else the store's snapshot, fetched +/// into a cache laid out like Claude's project directory so the session's cwd +/// is chosen the same way. +pub fn find_transcript( + session_id: &str, + store: Option<&dyn Store>, +) -> Result, StoreError> { + let root = projects_dir(None); + if Path::new(&root).is_dir() { + for project in list_dir(&root) { + let path = sys::join( + &sys::join(&root, &project), + &format!("{}.jsonl", session_id), + ); + if Path::new(&path).exists() { + return Ok(Some(path)); + } + } + } + let Some(store) = store else { + return Ok(None); + }; + let prefix = trace::transcripts_prefix(AGENT); + let Ok(keys) = store.list(&prefix) else { + return Ok(None); + }; + let suffix = format!("/{}.jsonl", session_id); + for key in keys { + if key.ends_with(&suffix) { + let project = key[prefix.len()..] + .split('/') + .next() + .unwrap_or("") + .to_string(); + let data = match store.get(&key) { + Ok(data) => data, + Err(StoreError::Missing(_)) => return Ok(None), + Err(error) => return Err(error), + }; + let cache = sys::join(&trace::cache_dir(), &project); + let cached = sys::join(&cache, &format!("{}.jsonl", session_id)); + let _ = fs::create_dir_all(&cache); + let _ = fs::write(&cached, data); + return Ok(Some(cached)); + } + } + Ok(None) +} + +// -- forking ------------------------------------------------------------------------- + +fn parent(record: &Map) -> Option { + let parent = match record.get("parentUuid") { + None | Some(Value::Null) => record.get("logicalParentUuid"), + other => other, + }; + parent.and_then(Value::as_str).map(str::to_string) +} + +fn uuid(record: &Map) -> &str { + record.get("uuid").and_then(Value::as_str).unwrap_or("") +} + +/// A new Claude session holding the conversation, filed under `target_cwd`. +/// With no `cut` it holds the conversation to its end — the last record +/// written, which after a rewind is the branch the session was left on. With +/// one, it ends at that record: the last of the turn being asked about. +pub fn fork_session( + transcript: &str, + target_cwd: &str, + cut: Option<&str>, + title: Option<&str>, +) -> Result { + let bytes = + fs::read(transcript).map_err(|e| ForkError::Internal(sys::os_error(&e, transcript)))?; + let raw = py::decode_surrogateescape(&bytes); + let records: Vec = records_of(&raw) + .into_iter() + .filter(|r| matches!(r.get("uuid"), Some(Value::Str(_)))) + .collect(); + if records.is_empty() { + return Err(ForkError::Trace(TraceError::new( + "turn-not-found", + "the transcript holds no records", + ))); + } + let leaf = match cut { + None => records.len() - 1, + Some(cut) => match records.iter().rposition(|r| uuid(r) == cut) { + Some(leaf) => leaf, + None => { + return Err(ForkError::Trace(TraceError::new( + "turn-not-found", + format!("the transcript has no record {}", cut), + ))) + } + }, + }; + write_fork(transcript, &raw, &records, leaf, target_cwd, title) +} + +fn write_fork( + transcript: &str, + raw: &str, + records: &[Map], + leaf: usize, + target_cwd: &str, + title: Option<&str>, +) -> Result { + let mut by_uuid: HashMap<&str, usize> = HashMap::new(); + for (index, record) in records.iter().enumerate() { + by_uuid.insert(uuid(record), index); + } + let mut keep: HashSet = HashSet::new(); + let mut walker = Some(leaf); + while let Some(index) = walker { + let id = uuid(&records[index]).to_string(); + if keep.contains(&id) { + break; + } + keep.insert(id); + walker = parent(&records[index]).and_then(|p| by_uuid.get(p.as_str()).copied()); + } + + let origin_cwd = match read_session_meta(transcript) { + Some(meta) => meta.cwd, + None => match transcript_cwds(raw).into_iter().next() { + Some((cwd, _)) => cwd, + None => return Err(ForkError::Internal("the transcript names no cwd".into())), + }, + }; + let file = sys::basename(transcript); + let origin_session = file[..file.len().saturating_sub(".jsonl".len())].to_string(); + let new_id = sys::uuid4(); + + let mut kept: Vec = records + .iter() + .filter(|r| keep.contains(uuid(r))) + .map(|r| json::dumps(&Value::Object(r.clone()), json::UNICODE)) + .collect(); + let default_title = format!("loch ask: {}", py::truncate(&origin_session, 8)); + kept.push(json::dumps( + &Value::Object(object! { + "type" => "custom-title", + "customTitle" => title.filter(|t| !t.is_empty()).unwrap_or(&default_title), + "sessionId" => origin_session.as_str(), + }), + json::DEFAULT, + )); + let home = home_dir(); + let spec = RewriteSpec { + origin_cwd, + origin_home: home.clone(), + target_cwd: target_cwd.into(), + target_home: home, + origin_session_id: Some(origin_session.clone()), + target_session_id: Some(new_id.clone()), + }; + let text = rewrite_transcript(&format!("{}\n", kept.join("\n")), &spec); + let path = transcript_path_for(target_cwd, &new_id, None); + let parent_dir = sys::dirname(&path); + fs::create_dir_all(&parent_dir) + .map_err(|e| ForkError::Internal(sys::os_error(&e, &parent_dir)))?; + let bytes = py::encode_surrogateescape(&text) + .map_err(|_| ForkError::Internal("the fork holds an unencodable surrogate".into()))?; + fs::write(&path, bytes).map_err(|e| ForkError::Internal(sys::os_error(&e, &path)))?; + Ok(Fork { + session_id: new_id, + path, + cwd: target_cwd.into(), + records: keep.len(), + origin_session, + }) +} + +// -- the adapter ----------------------------------------------------------------------- + +pub struct ClaudeCode; + +pub static CLAUDE_CODE: ClaudeCode = ClaudeCode; + +/// A turn's two moments, which is all attribution needs, and the session's +/// end, which closes a turn a cancel left open. +const HOOK_EVENTS: &[HookEvent] = &[ + ("UserPromptSubmit", "prompt"), + ("Stop", "stop"), + ("SessionEnd", "end"), +]; + +impl Agent for ClaudeCode { + fn id(&self) -> &'static str { + AGENT + } + + fn name(&self) -> &'static str { + "Claude Code" + } + + fn hook_events(&self) -> &'static [HookEvent] { + HOOK_EVENTS + } + + /// The project's settings file, or with `local` the uncommitted one, since + /// a `--local` command is a machine-specific path. + fn hooks_file(&self, root: &str, local: bool) -> String { + let name = if local { + "settings.local.json" + } else { + "settings.json" + }; + sys::join(&sys::join(root, ".claude"), name) + } + + fn install_note(&self) -> &'static str { + "restart Claude Code sessions here to pick them up" + } + + fn current_turn(&self, transcript: &str, event: &Map, for_next: bool) -> TurnInfo { + let next = match event.get("prompt") { + Some(Value::Str(text)) if for_next => Some(text.as_str()), + _ => None, + }; + current_turn(transcript, next) + } + + /// Keyed by Claude's project directory, so a fetched copy can be filed + /// back under it and its cwd chosen the same way. + fn transcript_key(&self, path: &str, session_id: &str) -> Option { + let project = sys::basename(&sys::dirname(path)); + Some(format!( + "{}{}/{}.jsonl", + trace::transcripts_prefix(AGENT), + project, + session_id + )) + } + + fn sessions_dir(&self) -> String { + projects_dir(None) + } + + fn list_sessions( + &self, + cwd: &str, + branch: Option<&str>, + session_id: Option<&str>, + ) -> Vec { + list_sessions(cwd, branch, session_id, None) + } + + fn read_session_meta(&self, path: &str) -> Option { + read_session_meta(path) + } + + fn transcript_cwds(&self, raw: &str) -> Vec<(String, usize)> { + transcript_cwds(raw) + } + + fn restore_path(&self, _raw: &str, cwd: &str, session_id: &str) -> Option { + Some(transcript_path_for(cwd, session_id, None)) + } + + fn existing_transcript(&self, cwd: &str, session_id: &str) -> Option { + let path = transcript_path_for(cwd, session_id, None); + Path::new(&path).exists().then_some(path) + } + + fn resume_command(&self, session_id: &str) -> Option> { + Some(vec!["claude".into(), "--resume".into(), session_id.into()]) + } + + fn find_transcript( + &self, + session_id: &str, + store: Option<&dyn Store>, + ) -> Result, StoreError> { + find_transcript(session_id, store) + } + + fn fork( + &self, + transcript: &str, + target_cwd: &str, + cut: Option<&str>, + title: Option<&str>, + ) -> Result { + fork_session(transcript, target_cwd, cut, title) + } +} diff --git a/src/cli.rs b/src/cli.rs index dbf906f..2eb0ffd 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,13 +1,12 @@ //! Every command: each builds one `Outcome` — payload //! and prose together — and `main` renders it. +use crate::agent::{self, Agent}; use crate::argparse::{Exit, Nargs, Parser}; use crate::attribution::{self, EditRecord}; use crate::blame_html; use crate::bundle::{self, Bundle, BundleOrigin, BundleSession, BUNDLE_VERSION}; -use crate::claude::{ - self, home_dir, list_sessions, resolve_cwd, transcript_path_for, SessionMeta, AGENT, -}; +use crate::claude::{self, home_dir, resolve_cwd, SessionMeta, AGENT}; use crate::format; use crate::index::{self, IndexEntry, IndexError, BRANCH}; use crate::ingest::{self, Origin}; @@ -188,7 +187,7 @@ fn collect( session: Option<&str>, ) -> (String, Vec) { let resolved = resolve_cwd(&cwd.map(str::to_string).unwrap_or_else(sys::getcwd)); - let sessions = list_sessions(&resolved, branch, session, None); + let sessions = claude::CLAUDE_CODE.list_sessions(&resolved, branch, session); (resolved, sessions) } @@ -207,7 +206,7 @@ fn session_payload(meta: &SessionMeta) -> Value { "cwd" => meta.cwd.as_str(), "otherCwds" => strings(&meta.other_cwds), "branch" => Value::opt_str(meta.git_branch.as_deref()), - "claudeVersion" => Value::opt_str(meta.claude_version.as_deref()), + "claudeVersion" => Value::opt_str(meta.version.as_deref()), "bytes" => meta.bytes as i64, "modifiedAt" => meta.modified_at.as_str(), "summary" => Value::opt_str(meta.summary.as_deref()), @@ -391,7 +390,7 @@ pub fn command_save(argv: &[String]) -> Run { session_id: meta.session_id.clone(), cwd: meta.cwd.clone(), git_branch: meta.git_branch.clone(), - claude_version: meta.claude_version.clone(), + claude_version: meta.version.clone(), modified_at: meta.modified_at.clone(), transcript: scrubbed.text, }); @@ -540,6 +539,7 @@ pub fn command_restore(argv: &[String]) -> Run { Err(error) => return err("bundle-unreadable", format!("{}: {}", described, error)), }; let target_cwd = resolve_cwd(&args.str("into").unwrap_or_else(sys::getcwd)); + let adapter: &dyn Agent = &claude::CLAUDE_CODE; let target_home = home_dir(); let mut restored = Vec::new(); for session in &bundle.sessions { @@ -557,20 +557,33 @@ pub fn command_restore(argv: &[String]) -> Run { target_session_id: Some(target_session_id.clone()), }; let transcript = rewrite::rewrite_transcript(&session.transcript, &spec); - let destination = transcript_path_for(&target_cwd, &target_session_id, None); - if Path::new(&destination).exists() && !args.flag("force") { + let Some(mut destination) = + adapter.restore_path(&transcript, &target_cwd, &target_session_id) + else { + return Err(Failure::Internal(format!( + "{} sessions can't be restored", + adapter.name() + ))); + }; + let existing = adapter.existing_transcript(&target_cwd, &target_session_id); + if existing.is_some() && !args.flag("force") { restored.push(Restored { session_id: target_session_id, origin_session_id: session.session_id.clone(), branch: session.git_branch.clone(), status: "skipped", - path: destination, + path: existing.unwrap_or(destination), residual: Vec::new(), resume_command: None, foreign: Vec::new(), }); continue; } + // Overwriting in place: a second copy of one session id is a + // transcript the agent may pick either of. + if let Some(existing) = existing { + destination = existing; + } let parent = sys::dirname(&destination); fs::create_dir_all(&parent).map_err(|e| Failure::Internal(sys::os_error(&e, &parent)))?; fs::write(&destination, transcript.as_bytes()) @@ -582,12 +595,11 @@ pub fn command_restore(argv: &[String]) -> Run { status: "restored", path: destination, residual: rewrite::residual_origin_paths(&transcript, &spec), - resume_command: Some(format!( - "cd {} && claude --resume {}", - target_cwd, target_session_id - )), + resume_command: adapter + .resume_command(&target_session_id) + .map(|argv| format!("cd {} && {}", target_cwd, argv.join(" "))), // Pre-rewrite: the origin path only exists losslessly here. - foreign: rewrite::foreign_cwds(&session.transcript, &spec), + foreign: rewrite::foreign_cwds_of(adapter.transcript_cwds(&session.transcript), &spec), }); } @@ -846,9 +858,17 @@ pub fn command_ingest(argv: &[String]) -> Run { pub fn command_hook(argv: &[String]) -> Run { use std::io::Read; let name = argv.first().map(String::as_str).unwrap_or(""); + // `hook [--agent ]`, read by hand: a hook must never fail on + // its arguments, and the lines earlier versions installed carry no flag. + let agent_id = argv + .iter() + .position(|a| a == "--agent") + .and_then(|i| argv.get(i + 1)) + .map(String::as_str) + .unwrap_or(AGENT); let mut stdin = Vec::new(); if std::io::stdin().read_to_end(&mut stdin).is_ok() { - crate::hook::run(name, &stdin); + crate::hook::run(name, agent_id, &stdin); } Ok(Outcome::new("hook")) } @@ -893,13 +913,9 @@ pub fn command_install(argv: &[String]) -> Run { .unwrap_or_else(|| sys::abspath(&std::env::args().next().unwrap_or_default())), None => "loch".into(), }; - let name = if args.flag("local") { - "settings.local.json" - } else { - "settings.json" - }; - let settings = sys::join(&sys::join(&root, ".claude"), name); - let installed = trace::install_hooks(&settings, &command) + let adapter: &dyn Agent = &claude::CLAUDE_CODE; + let settings = adapter.hooks_file(&root, args.flag("local")); + let installed = trace::install_hooks(&settings, &command, adapter) .map_err(|trace::InstallError::Internal(m)| Failure::Internal(m))?; let mut text = if installed.added.is_empty() { format!("loch hooks already installed in {}\n", settings) @@ -916,7 +932,7 @@ pub fn command_install(argv: &[String]) -> Run { installed.removed.join(", ") )); } - text.push_str("restart Claude Code sessions here to pick them up\n"); + text.push_str(&format!("{}\n", adapter.install_note())); Ok(Outcome::with( "install", object! { @@ -1389,13 +1405,22 @@ pub fn command_ask(argv: &[String]) -> Run { ); }; let link = blamed.links[owner].clone(); + let Some(adapter) = agent::by_id(&link.agent) else { + return err( + "transcript-missing", + format!( + "session {} wrote it, but this build doesn't know its agent, {}", + link.session_id, link.agent + ), + ); + }; let Some(transcript) = &link.transcript else { return err( "transcript-missing", format!( "session {} wrote it, but its transcript is neither in {} nor in the store", link.session_id, - claude::projects_dir(None) + adapter.sessions_dir() ), ); }; @@ -1408,26 +1433,32 @@ pub fn command_ask(argv: &[String]) -> Run { .map(|r| r.root.clone()) .filter(|root| Path::new(root).is_dir()) .unwrap_or_else(sys::getcwd); - let fork = trace::fork_session( - transcript, - &cwd, - if at_turn { - link.end_uuid.as_deref() - } else { - None - }, - Some(&format!("loch ask {}", target)), - ) - .map_err(|e| match e { - trace::ForkError::Trace(t) => Failure::from(t), - trace::ForkError::Internal(m) => Failure::Internal(m), - })?; + let fork = adapter + .fork( + transcript, + &cwd, + if at_turn { + link.end_uuid.as_deref() + } else { + None + }, + Some(&format!("loch ask {}", target)), + ) + .map_err(|e| match e { + trace::ForkError::Trace(t) => Failure::from(t), + trace::ForkError::Internal(m) => Failure::Internal(m), + trace::ForkError::Unsupported(name) => Failure::Error(CommandError::new( + "unsupported-agent", + format!("{} conversations can't be forked", name), + )), + })?; - let mut command = vec![ - "claude".to_string(), - "--resume".into(), - fork.session_id.clone(), - ]; + let Some(mut command) = adapter.resume_command(&fork.session_id) else { + return err( + "unsupported-agent", + format!("{} sessions can't be resumed", adapter.name()), + ); + }; if let Some(question) = args.str("question").filter(|q| !q.is_empty()) { command.push(question); } @@ -1468,11 +1499,11 @@ pub fn command_ask(argv: &[String]) -> Run { )); } eprint!("{}", text); - exec_claude(&fork.cwd, &command) + exec_agent(&fork.cwd, &command) } #[cfg(unix)] -fn exec_claude(root: &str, command: &[String]) -> Run { +fn exec_agent(root: &str, command: &[String]) -> Run { use std::os::unix::process::CommandExt; let _ = std::env::set_current_dir(root); let error = std::process::Command::new(&command[0]) @@ -1488,7 +1519,7 @@ fn exec_claude(root: &str, command: &[String]) -> Run { } #[cfg(not(unix))] -fn exec_claude(root: &str, command: &[String]) -> Run { +fn exec_agent(root: &str, command: &[String]) -> Run { let status = std::process::Command::new(&command[0]) .args(&command[1..]) .current_dir(root) diff --git a/src/hook.rs b/src/hook.rs index a842a6b..773f429 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -20,14 +20,13 @@ //! and nothing is written to stdout: a hook that breaks the agent gets //! uninstalled. +use crate::agent::{self, Agent, TurnInfo}; use crate::attribution::{self, EditRecord, TurnRecord}; -use crate::claude::{display_summary, AGENT}; use crate::json::{self, Map, Value}; use crate::object; use crate::snapshot; use crate::store::{self, Store}; use crate::sys; -use crate::trace::{self, content}; use std::fs; use std::path::PathBuf; @@ -114,94 +113,12 @@ fn write_state(session: &str, state: &State) -> Result<(), Stop> { Ok(()) } -// -- reading the transcript ------------------------------------------------------- - -/// What the transcript says about a turn: the prompt that began it and the -/// last record written. -#[derive(Default)] -pub struct TurnInfo { - pub prompt_uuid: Option, - pub prompt: Option, - pub started: Option, - pub end_uuid: Option, - pub ended: Option, -} - -/// A record a person typed: a user message that is neither a tool's result -/// nor Claude Code's own bookkeeping. -pub fn is_human_prompt(record: &Map) -> bool { - if !record.get("type").is_some_and(|t| t.is_str("user")) { - return false; - } - if record.get("isMeta").is_some_and(Value::truthy) - || record.get("isCompactSummary").is_some_and(Value::truthy) - { - return false; - } - match record.get("message").and_then(|m| m.get("content")) { - Some(Value::Str(_)) => true, - Some(Value::Array(_)) => !content(record) - .iter() - .any(|b| b.get("type").is_some_and(|t| t.is_str("tool_result"))), - _ => false, - } -} - -pub fn prompt_text(record: &Map) -> Option { - match record.get("message")?.get("content")? { - Value::Str(text) => Some(text.clone()), - Value::Array(_) => content(record) - .iter() - .find_map(|block| match block.get("text") { - Some(Value::Str(text)) if !text.is_empty() => Some(text.clone()), - _ => None, - }), - _ => None, - } -} - -/// The turn the transcript ends with. When the hook closing it belongs to the -/// *next* prompt, that prompt may already be written; `excluding` names it, -/// and it and everything after are left out. -pub fn current_turn(transcript: &str, excluding: Option<&str>) -> TurnInfo { - let records: Vec = trace::read_records(transcript) - .into_iter() - .filter(|r| matches!(r.get("uuid"), Some(Value::Str(_)))) - .collect(); - let mut end = records.len(); - if let Some(next) = excluding { - if let Some(at) = records.iter().rposition(is_human_prompt) { - if prompt_text(&records[at]).as_deref() == Some(next) { - end = at; - } - } - } - let mut info = TurnInfo::default(); - for record in &records[..end] { - let uuid = record - .get("uuid") - .and_then(Value::as_str) - .map(str::to_string); - let stamp = record - .get("timestamp") - .and_then(Value::as_str) - .map(str::to_string); - if is_human_prompt(record) { - info.prompt_uuid = uuid.clone(); - info.prompt = display_summary(prompt_text(record).as_deref()); - info.started = stamp.clone(); - } - info.end_uuid = uuid; - info.ended = stamp; - } - info -} - // -- closing a turn ------------------------------------------------------------------ /// Records the turn that began at `start` and ends now, in the session's edit /// record, and returns the snapshot it ended at. fn close_turn( + agent: &dyn Agent, session: &str, root: &str, start: Option<&str>, @@ -210,8 +127,8 @@ fn close_turn( store: Option<&dyn Store>, ) -> Result { let end = snapshot::snapshot(root)?; - let mut record = attribution::load_local(AGENT, session).unwrap_or_else(|| EditRecord { - agent: AGENT.into(), + let mut record = attribution::load_local(agent.id(), session).unwrap_or_else(|| EditRecord { + agent: agent.id().into(), session: session.into(), project: attribution::project_id(root), root: root.into(), @@ -248,8 +165,8 @@ fn close_turn( } /// The session's last closed turn's prompt, to recognise a repeated `Stop`. -fn last_prompt(session: &str) -> Option { - attribution::load_local(AGENT, session)? +fn last_prompt(agent: &dyn Agent, session: &str) -> Option { + attribution::load_local(agent.id(), session)? .turns .last()? .prompt_uuid @@ -259,19 +176,16 @@ fn last_prompt(session: &str) -> Option { /// A turn begins. A turn still open from before — cancelled, or a crash then /// `--resume` — is closed first, so its edits are its own and not this /// turn's baseline. -pub fn prompt(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { +pub fn prompt(agent: &dyn Agent, event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { let session = session_of(event)?; let root = snapshot::workspace_root(&event_cwd(event)); if let Some(state) = read_state(&session).filter(|s| s.open) { if snapshot::snapshottable(&state.root) { - let next = match event.get("prompt") { - Some(Value::Str(text)) => Some(text.as_str()), - _ => None, - }; let info = transcript_of(event) - .map(|t| current_turn(&t, next)) + .map(|t| agent.current_turn(&t, event, true)) .unwrap_or_default(); close_turn( + agent, &session, &state.root, Some(&state.turn_start), @@ -296,9 +210,9 @@ pub fn prompt(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { } /// The agent finished: record what the turn changed, and keep the transcript. -pub fn stop(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { +pub fn stop(agent: &dyn Agent, event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { if let Some(store) = store { - let _ = snapshot_transcript(event, store); + let _ = snapshot_transcript(agent, event, store); } let session = session_of(event)?; let state = read_state(&session); @@ -310,9 +224,9 @@ pub fn stop(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { return Ok(()); } let info = transcript_of(event) - .map(|t| current_turn(&t, None)) + .map(|t| agent.current_turn(&t, event, false)) .unwrap_or_default(); - let repeated = info.prompt_uuid.is_some() && last_prompt(&session) == info.prompt_uuid; + let repeated = info.prompt_uuid.is_some() && last_prompt(agent, &session) == info.prompt_uuid; // The turn's own start if it has one — an open turn, or a repeated stop of // the last one. Otherwise no prompt hook ran (installed mid-session, or a // harness without one), and the workspace's last snapshot is the best @@ -321,7 +235,7 @@ pub fn stop(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { Some(state) if state.open || repeated => Some(state.turn_start.clone()), _ => snapshot::latest(&root), }; - close_turn(&session, &root, start.as_deref(), info, false, store)?; + close_turn(agent, &session, &root, start.as_deref(), info, false, store)?; if let Some(start) = start { write_state( &session, @@ -337,14 +251,15 @@ pub fn stop(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { /// The session is over. A turn still open was cut short; close it, and let /// the session's state go, so nothing it held is kept any longer. -pub fn end(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { +pub fn end(agent: &dyn Agent, event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { let session = session_of(event)?; if let Some(state) = read_state(&session).filter(|s| s.open) { if snapshot::snapshottable(&state.root) { let info = transcript_of(event) - .map(|t| current_turn(&t, None)) + .map(|t| agent.current_turn(&t, event, false)) .unwrap_or_default(); close_turn( + agent, &session, &state.root, Some(&state.turn_start), @@ -355,7 +270,7 @@ pub fn end(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { } } if let Some(store) = store { - let _ = snapshot_transcript(event, store); + let _ = snapshot_transcript(agent, event, store); } let _ = fs::remove_file(state_path(&session)); Ok(()) @@ -400,28 +315,32 @@ pub fn collect() -> Result { /// Copies the live transcript into the store. The file is append-only, so the /// latest snapshot covers every earlier one and one key per session suffices. -pub fn snapshot_transcript(event: &Map, store: &dyn Store) -> Result, Stop> { +pub fn snapshot_transcript( + agent: &dyn Agent, + event: &Map, + store: &dyn Store, +) -> Result, Stop> { let (Some(Value::Str(path)), Some(Value::Str(session_id))) = (event.get("transcript_path"), event.get("session_id")) else { return Ok(None); }; + let Some(key) = agent.transcript_key(path, session_id) else { + return Ok(None); + }; let Ok(data) = fs::read(path) else { return Ok(None); }; - let project = sys::basename(&sys::dirname(path)); - let key = format!( - "{}{}/{}.jsonl", - trace::transcripts_prefix(), - project, - session_id - ); store.put(&key, &data).map_err(|_| Stop)?; Ok(Some(key)) } -/// Run by the harness with the event as JSON on stdin. -pub fn run(name: &str, stdin: &[u8]) { +/// Run by the harness with the event as JSON on stdin. An agent this build +/// doesn't know does nothing, like every other failure here. +pub fn run(name: &str, agent_id: &str, stdin: &[u8]) { + let Some(agent) = agent::by_id(agent_id) else { + return; + }; let Ok(text) = std::str::from_utf8(stdin) else { return; }; @@ -431,9 +350,9 @@ pub fn run(name: &str, stdin: &[u8]) { }; let store = || store::create_store(&store::resolve_store_uri(None)).ok(); let _ = match name { - "prompt" => prompt(&event, store().as_deref()), - "stop" => stop(&event, store().as_deref()), - "end" => end(&event, store().as_deref()), + "prompt" => prompt(agent, &event, store().as_deref()), + "stop" => stop(agent, &event, store().as_deref()), + "end" => end(agent, &event, store().as_deref()), // The tool-call hooks the git-notes design used. A settings file can // still name them until `install` is re-run; they do nothing. _ => return, diff --git a/src/lib.rs b/src/lib.rs index c2fd6f0..9d9a4f5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ // The error path is cold and runs once per process; boxing it buys nothing. #![allow(clippy::result_large_err)] +pub mod agent; pub mod argparse; pub mod attribution; pub mod backfill; diff --git a/src/rewrite.rs b/src/rewrite.rs index 1b72375..4dd0079 100644 --- a/src/rewrite.rs +++ b/src/rewrite.rs @@ -162,8 +162,15 @@ pub struct ForeignCwd { /// satisfy, keyed by their path on the *origin* machine. Takes the transcript /// before rewriting, the only place the origin path still exists losslessly. pub fn foreign_cwds(raw: &str, spec: &RewriteSpec) -> Vec<(String, ForeignCwd)> { - transcript_cwds(raw) - .into_iter() + foreign_cwds_of(transcript_cwds(raw), spec) +} + +/// `foreign_cwds` over the cwds an agent's adapter read from the transcript. +pub fn foreign_cwds_of( + cwds: Vec<(String, usize)>, + spec: &RewriteSpec, +) -> Vec<(String, ForeignCwd)> { + cwds.into_iter() .filter_map(|(cwd, count)| { let restored = rewrite_transcript(&cwd, spec); (restored != spec.target_cwd).then_some((cwd, ForeignCwd { count, restored })) diff --git a/src/trace.rs b/src/trace.rs index a0e46ba..9e9e9de 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -5,23 +5,22 @@ //! What a turn changed is recorded by the hooks (`hook.rs`) and matched by //! content (`attribution.rs`); nothing here reads or writes git history. +use crate::agent::{self, Agent}; use crate::attribution::{EditRecord, TurnRecord}; -use crate::claude::{self, home_dir, projects_dir, read_session_meta, AGENT}; +use crate::claude::{self, home_dir}; use crate::format::Turn; use crate::git as gitio; use crate::ingest::{self, Origin}; use crate::json::{self, Map, Value}; use crate::object; use crate::py; -use crate::rewrite::{rewrite_transcript, RewriteSpec}; -use crate::store::{Store, StoreError}; +use crate::store::Store; use crate::sys; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::fs; -use std::path::Path; -pub fn transcripts_prefix() -> String { - format!("transcripts/{}/", AGENT) +pub fn transcripts_prefix(agent: &str) -> String { + format!("transcripts/{}/", agent) } #[derive(Debug)] @@ -59,14 +58,6 @@ pub fn py_str(value: Option<&Value>) -> String { // -- install ------------------------------------------------------------------ -/// A turn's two moments, which is all attribution needs, and the session's -/// end, which closes a turn a cancel left open. -const HOOK_EVENTS: &[(&str, &str)] = &[ - ("UserPromptSubmit", "prompt"), - ("Stop", "stop"), - ("SessionEnd", "end"), -]; - /// What earlier versions of `install` wrote around every Bash call, for the /// git-notes design. Removed on install, so they stop costing a process each. const RETIRED: &[&str] = &["pre-tool", "post-tool"]; @@ -81,10 +72,17 @@ pub struct Installed { pub removed: Vec, } -fn hook_line(command: &str, name: &str) -> String { +/// The line a hook runs. `agent` is passed only for agents other than Claude +/// Code, so the lines earlier versions wrote for it still match. +pub fn hook_line(command: &str, name: &str, agent: &dyn Agent) -> String { + let flag = if agent.id() == claude::AGENT { + String::new() + } else { + format!(" --agent {}", agent.id()) + }; // A checkout whose machine lacks loch gets a silent no-op rather than an // error on every turn, since the settings file is committed. - format!("{} hook {} 2>/dev/null || true", command, name) + format!("{} hook {}{} 2>/dev/null || true", command, name, flag) } fn is_retired(line: &str) -> bool { @@ -93,12 +91,14 @@ fn is_retired(line: &str) -> bool { .any(|name| line.ends_with(&format!(" hook {} 2>/dev/null || true", name))) } -/// Adds loch's hooks to a Claude Code settings file, keeping whatever else is -/// there, and takes out the ones it no longer uses. Re-running changes -/// nothing. +/// Adds an agent's loch hooks to its hooks file, keeping whatever else is +/// there, and takes out the ones loch no longer uses. Re-running changes +/// nothing. Claude Code's settings and Codex's hooks.json share the shape +/// `{"hooks": {"": [{"hooks": [{"type": "command", "command": ...}]}]}}`. pub fn install_hooks( settings_path: &str, command: &str, + agent: &dyn Agent, ) -> std::result::Result { let mut settings = match fs::read(settings_path) { Ok(bytes) => { @@ -154,8 +154,8 @@ pub fn install_hooks( hooks.retain(|_, groups| groups.as_array().is_none_or(|g| !g.is_empty())); let mut added = Vec::new(); - for (event, name) in HOOK_EVENTS { - let line = hook_line(command, name); + for (event, name) in agent.hook_events() { + let line = hook_line(command, name, agent); let groups = hooks .entry(event.to_string()) .or_insert_with(|| Value::Array(Vec::new())); @@ -220,67 +220,9 @@ pub fn content(record: &Map) -> Vec<&Map> { } } -fn list_dir(path: &str) -> Vec { - fs::read_dir(path) - .map(|entries| { - entries - .flatten() - .map(|e| e.file_name().to_string_lossy().into_owned()) - .collect() - }) - .unwrap_or_default() -} - -/// Claude's own copy if it still exists, else the store's snapshot, fetched -/// into a cache laid out like Claude's project directory so the session's cwd -/// is chosen the same way. -pub fn find_transcript( - session_id: &str, - store: Option<&dyn Store>, -) -> std::result::Result, StoreError> { - let root = projects_dir(None); - if Path::new(&root).is_dir() { - for project in list_dir(&root) { - let path = sys::join( - &sys::join(&root, &project), - &format!("{}.jsonl", session_id), - ); - if Path::new(&path).exists() { - return Ok(Some(path)); - } - } - } - let Some(store) = store else { - return Ok(None); - }; - let prefix = transcripts_prefix(); - let Ok(keys) = store.list(&prefix) else { - return Ok(None); - }; - let suffix = format!("/{}.jsonl", session_id); - for key in keys { - if key.ends_with(&suffix) { - let project = key[prefix.len()..] - .split('/') - .next() - .unwrap_or("") - .to_string(); - let data = match store.get(&key) { - Ok(data) => data, - Err(StoreError::Missing(_)) => return Ok(None), - Err(error) => return Err(error), - }; - let cache = sys::join( - &sys::join(&sys::join(&home_dir(), ".loch"), "cache"), - &project, - ); - let cached = sys::join(&cache, &format!("{}.jsonl", session_id)); - let _ = fs::create_dir_all(&cache); - let _ = fs::write(&cached, data); - return Ok(Some(cached)); - } - } - Ok(None) +/// Where transcripts fetched from the store are kept. +pub fn cache_dir() -> String { + sys::join(&sys::join(&home_dir(), ".loch"), "cache") } // -- describing a turn ------------------------------------------------------------- @@ -338,14 +280,22 @@ impl<'a> Resolver<'a> { fn session( &mut self, + agent_id: &str, session_id: &str, ) -> std::result::Result<&(Option, Vec, Map), String> { if !self.sessions.contains_key(session_id) { - let path = find_transcript(session_id, self.store).map_err(|e| e.to_string())?; + let path = match agent::by_id(agent_id) { + Some(agent) => agent + .find_transcript(session_id, self.store) + .map_err(|e| e.to_string())?, + None => None, + }; let mut turns = Vec::new(); let mut header = Map::new(); - if let Some(path) = &path { - if let Some(meta) = read_session_meta(path) { + // The loch converter reads Claude Code's format alone; another + // agent's turns are described without loch ids. + if let (Some(path), true) = (&path, agent_id == claude::AGENT) { + if let Some(meta) = claude::read_session_meta(path) { let origin = Origin { cwd: meta.cwd, home: home_dir(), @@ -369,7 +319,7 @@ impl<'a> Resolver<'a> { index: usize, ) -> std::result::Result { let turn: &TurnRecord = &record.turns[index]; - let (path, turns, header) = self.session(&record.session)?; + let (path, turns, header) = self.session(&record.agent, &record.session)?; // The loch turn whose source record is the prompt that began this // turn — or that a resubmitted identical prompt folded into. let holds = |candidate: &&Turn, uuid: &str| { @@ -430,132 +380,10 @@ pub struct Fork { pub origin_session: String, } -fn parent(record: &Map) -> Option { - let parent = match record.get("parentUuid") { - None | Some(Value::Null) => record.get("logicalParentUuid"), - other => other, - }; - parent.and_then(Value::as_str).map(str::to_string) -} - -fn uuid(record: &Map) -> &str { - record.get("uuid").and_then(Value::as_str).unwrap_or("") -} - -/// A new Claude session holding the conversation, filed under `target_cwd`. -/// With no `cut` it holds the conversation to its end — the last record -/// written, which after a rewind is the branch the session was left on. With -/// one, it ends at that record: the last of the turn being asked about. -pub fn fork_session( - transcript: &str, - target_cwd: &str, - cut: Option<&str>, - title: Option<&str>, -) -> std::result::Result { - let bytes = - fs::read(transcript).map_err(|e| ForkError::Internal(sys::os_error(&e, transcript)))?; - let raw = py::decode_surrogateescape(&bytes); - let records: Vec = records_of(&raw) - .into_iter() - .filter(|r| matches!(r.get("uuid"), Some(Value::Str(_)))) - .collect(); - if records.is_empty() { - return Err(ForkError::Trace(TraceError::new( - "turn-not-found", - "the transcript holds no records", - ))); - } - let leaf = match cut { - None => records.len() - 1, - Some(cut) => match records.iter().rposition(|r| uuid(r) == cut) { - Some(leaf) => leaf, - None => { - return Err(ForkError::Trace(TraceError::new( - "turn-not-found", - format!("the transcript has no record {}", cut), - ))) - } - }, - }; - write_fork(transcript, &raw, &records, leaf, target_cwd, title) -} - #[derive(Debug)] pub enum ForkError { Trace(TraceError), Internal(String), -} - -fn write_fork( - transcript: &str, - raw: &str, - records: &[Map], - leaf: usize, - target_cwd: &str, - title: Option<&str>, -) -> std::result::Result { - let mut by_uuid: HashMap<&str, usize> = HashMap::new(); - for (index, record) in records.iter().enumerate() { - by_uuid.insert(uuid(record), index); - } - let mut keep: HashSet = HashSet::new(); - let mut walker = Some(leaf); - while let Some(index) = walker { - let id = uuid(&records[index]).to_string(); - if keep.contains(&id) { - break; - } - keep.insert(id); - walker = parent(&records[index]).and_then(|p| by_uuid.get(p.as_str()).copied()); - } - - let origin_cwd = match read_session_meta(transcript) { - Some(meta) => meta.cwd, - None => match claude::transcript_cwds(raw).into_iter().next() { - Some((cwd, _)) => cwd, - None => return Err(ForkError::Internal("the transcript names no cwd".into())), - }, - }; - let file = sys::basename(transcript); - let origin_session = file[..file.len().saturating_sub(".jsonl".len())].to_string(); - let new_id = sys::uuid4(); - - let mut kept: Vec = records - .iter() - .filter(|r| keep.contains(uuid(r))) - .map(|r| json::dumps(&Value::Object(r.clone()), json::UNICODE)) - .collect(); - let default_title = format!("loch ask: {}", py::truncate(&origin_session, 8)); - kept.push(json::dumps( - &Value::Object(object! { - "type" => "custom-title", - "customTitle" => title.filter(|t| !t.is_empty()).unwrap_or(&default_title), - "sessionId" => origin_session.as_str(), - }), - json::DEFAULT, - )); - let home = home_dir(); - let spec = RewriteSpec { - origin_cwd, - origin_home: home.clone(), - target_cwd: target_cwd.into(), - target_home: home, - origin_session_id: Some(origin_session.clone()), - target_session_id: Some(new_id.clone()), - }; - let text = rewrite_transcript(&format!("{}\n", kept.join("\n")), &spec); - let path = claude::transcript_path_for(target_cwd, &new_id, None); - let parent_dir = sys::dirname(&path); - fs::create_dir_all(&parent_dir) - .map_err(|e| ForkError::Internal(sys::os_error(&e, &parent_dir)))?; - let bytes = py::encode_surrogateescape(&text) - .map_err(|_| ForkError::Internal("the fork holds an unencodable surrogate".into()))?; - fs::write(&path, bytes).map_err(|e| ForkError::Internal(sys::os_error(&e, &path)))?; - Ok(Fork { - session_id: new_id, - path, - cwd: target_cwd.into(), - records: keep.len(), - origin_session, - }) + /// The agent's adapter can't fork a conversation. + Unsupported(&'static str), } diff --git a/tests/bundle.rs b/tests/bundle.rs index f45fdfc..6afbd05 100644 --- a/tests/bundle.rs +++ b/tests/bundle.rs @@ -128,3 +128,74 @@ fn packing_matches_python_310_on_every_platform() { assert_eq!(&sha256_hex(&packed)[..16], "405552bff938ef58"); assert_eq!(gunzip(&packed), data); } + +// -- format pins ---------------------------------------------------------------- +// +// The ref is a hash of the packed bytes, so anything that changes them — +// separators, key order, a null where a key was omitted, a field added to +// every session — changes the identity of every bundle ever made. These pin +// the bytes of today's format; a failure here means existing refs would no +// longer reproduce, which needs a deliberate decision, not a test update. + +fn pinned_bundle() -> Bundle { + Bundle { + version: 1, + agent: "claude-code".into(), + created_at: "2026-08-14T13:27:07.373Z".into(), + origin: BundleOrigin { + home: "/home/mike".into(), + platform: "linux".into(), + hostname: "box".into(), + }, + sessions: vec![ + BundleSession { + session_id: "11111111-2222-4333-8444-555555555555".into(), + cwd: "/home/mike/proj".into(), + git_branch: Some("feature/é".into()), + claude_version: Some("1.0.99".into()), + modified_at: "2026-08-14T13:00:00.000Z".into(), + transcript: concat!( + "{\"type\":\"user\",\"cwd\":\"/home/mike/proj\",\"message\":", + "{\"content\":\"quote \\\" newline \\n tab \\t snowman ☃\"}}\n" + ) + .into(), + }, + BundleSession { + session_id: "66666666-7777-4888-9999-000000000000".into(), + cwd: "/home/mike/proj".into(), + git_branch: None, + claude_version: None, + modified_at: "2026-08-14T12:00:00.000Z".into(), + transcript: "{\"cwd\":\"/home/mike/proj\"}\n".into(), + }, + ], + } +} + +#[test] +fn the_packed_json_is_pinned() { + let packed = pack_bundle(&pinned_bundle()).unwrap(); + let json = String::from_utf8(gunzip(&packed)).unwrap(); + assert_eq!( + json, + r##"{"version":1,"agent":"claude-code","createdAt":"2026-08-14T13:27:07.373Z","origin":{"home":"/home/mike","platform":"linux","hostname":"box"},"sessions":[{"sessionId":"11111111-2222-4333-8444-555555555555","cwd":"/home/mike/proj","gitBranch":"feature/é","claudeVersion":"1.0.99","modifiedAt":"2026-08-14T13:00:00.000Z","transcript":"{\"type\":\"user\",\"cwd\":\"/home/mike/proj\",\"message\":{\"content\":\"quote \\\" newline \\n tab \\t snowman ☃\"}}\n"},{"sessionId":"66666666-7777-4888-9999-000000000000","cwd":"/home/mike/proj","modifiedAt":"2026-08-14T12:00:00.000Z","transcript":"{\"cwd\":\"/home/mike/proj\"}\n"}]}"## + ); +} + +#[test] +fn the_ref_is_pinned() { + let packed = pack_bundle(&pinned_bundle()).unwrap(); + assert_eq!( + bundle_ref(&packed), + "3069348d032085727a057739310cef4cb14ab8dba1fe838f865e46bf90235dad" + ); +} + +#[test] +fn repacking_an_unpacked_bundle_reproduces_its_bytes() { + let packed = pack_bundle(&pinned_bundle()).unwrap(); + assert_eq!( + pack_bundle(&unpack_bundle(&packed).unwrap()).unwrap(), + packed + ); +} diff --git a/tests/claude.rs b/tests/claude.rs index a6d9b31..0779e78 100644 --- a/tests/claude.rs +++ b/tests/claude.rs @@ -114,7 +114,7 @@ fn reads_metadata_from_a_transcript() { assert_eq!(meta.session_id, "abc"); assert_eq!(meta.cwd, "/Users/mike/proj"); assert_eq!(meta.git_branch.as_deref(), Some("main")); - assert_eq!(meta.claude_version.as_deref(), Some("1.0.99")); + assert_eq!(meta.version.as_deref(), Some("1.0.99")); assert_eq!(meta.summary.as_deref(), Some("do the thing")); assert!(meta.modified_at.ends_with('Z')); } From ae54071e21dc649a48bb2c2603652e83009a00cd Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 19 Nov 2026 15:30:24 -0500 Subject: [PATCH 2/5] Add the Codex CLI adapter codex.rs implements every tier of agent::Agent for codex-cli: rollout discovery under $CODEX_HOME/sessions, the live cwd from the last turn_context (compared symlink-resolved, since Codex stores -C as given), session_meta's branch only where the session hasn't moved, turns bounded by the records naming their turn_id, restore filed by start date, and ask's fork as a byte-for-byte prefix of the rollout resumed with codex resume. install writes .codex/hooks.json (or with --local the user's) beside whatever is there, appending groups so the trust Codex keys by position stays valid, and reports needsReview: loch never writes Codex's hook trust. list, save and install take --agent; sessions, bundles and restores carry agent and agentVersion. A bundle's sessions name their agent only where it differs from the bundle's, so every Claude-only bundle keeps its ref. Verified end to end on real Codex sessions (CLAUDE.md, State): hooks and blame, a cancelled TUI turn, ask at a turn and to the end, and a cross-machine restore that resumed. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 226 ++++++++++++- src/agent.rs | 7 +- src/bundle.rs | 33 +- src/cli.rs | 205 ++++++++---- src/codex.rs | 587 ++++++++++++++++++++++++++++++++++ src/index.rs | 11 +- src/lib.rs | 1 + src/trace.rs | 5 +- src/usage.txt | 26 +- tests/backfill.rs | 1 + tests/bundle.rs | 6 + tests/cli.rs | 9 +- tests/codex.rs | 787 ++++++++++++++++++++++++++++++++++++++++++++++ tests/index.rs | 2 + tests/trace.rs | 1 + 15 files changed, 1826 insertions(+), 81 deletions(-) create mode 100644 src/codex.rs create mode 100644 tests/codex.rs diff --git a/CLAUDE.md b/CLAUDE.md index 7b42a74..6e72f23 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,8 +9,8 @@ laptop that produced it. `loch` packs those transcripts into a content-addressed bundle, stores it anywhere S3-compatible, and unpacks it elsewhere with paths rewritten so the session actually resumes. -Currently supports Claude Code. Codex and Cursor are the intended next -adapters. +Supports Claude Code and Codex, behind one adapter boundary (`agent.rs`, +below). Cursor is the obvious next one. It is also becoming the **conversation format**: `loch ingest` turns a session into a content-addressed graph of turns that can be forked, shared @@ -208,6 +208,159 @@ public API. Re-verify if something breaks. bigger window is a bet on a bound that the worst cases are the likeliest to break. +## Empirical findings about Codex's storage + +Verified on codex-cli 0.166.0 by experiment (scratch repositories, real +`codex exec` and TUI runs), against the 70 rollouts on one machine +(versions 0.46, 0.121, 0.165, 0.166). Not stable public API: re-verify if +something breaks. Claude's rules above do **not** carry over; each was +re-derived. + +- **Where sessions live:** `$CODEX_HOME/sessions/YYYY/MM/DD/rollout--.jsonl`, `$CODEX_HOME` defaulting to `~/.codex`. Filed by date, + not by directory, so there is no directory to look in and discovery reads + every rollout (`codex.rs`). That costs ~50ms for 70 rollouts (10MB) and is + linear in total bytes. +- **`codex resume ` needs the rollout file and nothing else.** A copy + under a fresh id, with no row in any sqlite file, resumed and recalled its + conversation, and Codex inserted the `threads` row itself afterwards. The + sqlite files are projections: `state_5.sqlite`'s `threads` holds + `rollout_path` and summary columns, and `thread_history_1.sqlite` is keyed + by rollout byte offset (`thread_history_projection_state`). Lookup is by + the id the file name ends with. The date directory and the time in the + name don't matter (a copy under `2025/03/01` resumed), so `restore` files + a session under the day its `session_meta` says it began. + `session_index.jsonl` holds thread names alone (appended, last wins), so + loch reads it for blame's title and never writes it. +- **Records** are `{"timestamp", "type", "payload"}`, newer ones with an + `ordinal`. `session_meta` comes first: `id` and `session_id`, `cwd`, + `cli_version`, `originator`, `git: {commit_hash, branch}`, + `history_mode` (`paginated` from 0.165, absent before). The id also + appears in `thread_settings_applied.thread_id`, `item_completed.thread_id` + and `token_usage_record.session_id`, so, as with Claude, minting an id + means rewriting every occurrence (the rewrite's session pair does), and + the file name too. +- **A turn is named by id.** `task_started`, `turn_context`, + `item_completed`, `token_usage_record` and `task_complete` carry + `payload.turn_id`, and response items carry it in + `internal_chat_message_metadata_passthrough.turn_id`. But a `resume` + writes `thread_settings_applied`, which names no turn, *before* the next + `task_started`, so "the last turn seen" puts it in the previous turn. A + turn therefore runs from the first to the last record **naming** it, + which is where `ask --at-turn` cuts. +- **What a person typed** is `event_msg` `item_completed` with a + `UserMessage` item (0.165+), or `event_msg` `user_message` (older). + `response_item` user messages are not it: Codex injects + `` and AGENTS.md as user messages. +- **The live cwd is the last `turn_context`'s.** `resume -C ` + appends a `turn_context` naming the new directory, and `session_meta` + keeps naming where the session began. Nothing else marks which is live, + and there is no directory-name disambiguator as there is for Claude. The + last turn is where the session most recently ran, which is what a + restore wants. Cwds are counted from `session_meta` and `turn_context` + only. `world_state` and tool calls name directories too, so a substring + count would cry wolf, as it would for Claude. +- **Codex does not resolve symlinks in `-C`.** A session begun in `/tmp/x` + recorded `/private/tmp/x` (the process's resolved cwd), and the same + session resumed with `-C /tmp/y` recorded `/tmp/y`. Discovery compares + cwds resolved. +- **The branch is recorded once,** in `session_meta.git.branch`, for the + directory the session began in. No turn records one, and neither does + `world_state`. A moved session's branch is unknowable from its rollout, so + it is reported as none (`[no branch]`, `%00` in the index) rather than + the old directory's, which is Claude's stale-branch defect. A session + begun through a symlink to where it is now has not moved. None of the 70 + local rollouts had moved, so this is the rare case, and it is the honest + answer. +- **Hooks** use Claude's file shape, + `{"hooks": {"": [{"hooks": [{"type": "command", "command", "timeout"}]}]}}`, + from `$CODEX_HOME/hooks.json` and `/.codex/hooks.json` (plus + plugins and config layers). 0.166 knows `PreToolUse`, + `PermissionRequest`, `PostToolUse`, `PreCompact`, `PostCompact`, + `SessionStart`, `SessionEnd`, `UserPromptSubmit`, `SubagentStart`, + `SubagentStop`, `Stop`, `Interrupt` and `PreModelRequest`. They're enabled + by `[features] hooks` (stable and on here; `codex_hooks` is its deprecated + alias). It clamps the `SessionEnd` and `Interrupt` timeouts to 3s. Captured + payloads: every event carries `session_id`, `transcript_path`, `cwd` and + `hook_event_name`. `UserPromptSubmit` and `Stop` add `turn_id`, `model` + and `permission_mode`; `UserPromptSubmit` adds `prompt`, and `Stop` adds + `stop_hook_active` and `last_assistant_message`. `SessionEnd` adds + `reason` and **no `turn_id`**. So `hook.rs` is unchanged; only reading the + turn back from the transcript differs. +- **New hooks don't run until a person trusts them.** Trust lives in + `config.toml` as `[hooks.state.":::"] + trusted_hash = "sha256:…"`. An untrusted hook is skipped silently in + `exec`, and the TUI opens with "Hooks need review: N hooks are new or + changed" (*Review hooks* / *Trust all and continue* / *Continue without + trusting*), with `/hooks` to manage them. The hash is not a plain SHA-256 + of the entry. **loch never writes trust**: it is the user's review of a + command that runs outside the sandbox, and forging it would defeat the + point. `install` reports `needsReview` and says to open `/hooks`. Trust is + keyed by position, so loch appends its hooks as new groups and leaves + every existing entry's position, and so its trust, alone. That is what + keeps Ness's user-level hooks trusted after a `--local` install. + `--dangerously-bypass-hook-trust` exists for automation. The tests used + it, and loch never passes it. +- **A cancelled turn gets no `Stop`.** Esc mid-turn writes `turn_aborted` + (`reason: "interrupted"`) and runs no `Stop`, exactly like Claude Code, + so the next prompt's hook closes it as `interrupted`, keeping its edits. + Verified in the TUI. `SessionEnd` runs on `/quit` and at the end of every + `exec`, so quitting mid-turn is closed the same way. The `Interrupt` event + would close a cancelled turn sooner, but no payload was captured and + nothing needs it, so it isn't installed. +- **`codex fork` can't cut at a turn** (no `--at-turn`), and needs a session + Codex can already find. `ask` writes its own fork instead: a prefix of the + rollout's lines, kept byte for byte, under a new id, rewritten into the + target cwd. It resumes with `codex resume `. It has no title, since + titles live in `session_index.jsonl`. +- **Tool calls changed shape across versions:** 0.166's are + `custom_tool_call`s named `exec` whose input is JavaScript calling + `tools.exec_command`, and older ones are `function_call`s. So backfill's + approach (the text an `Edit`/`Write` call carries) doesn't carry over, and + `backfill` stays Claude-only. + +## The adapter boundary, and what a third harness costs + +`agent.rs` is everything loch needs from one harness, in three tiers. Each +later tier's methods have defaults that decline, so an adapter is as big as +what the harness supports: + +1. **Attribution** (`blame`, `log`). Required: an `id`, the hook events + (a turn's start, its end, and ideally the session's end) and the hooks + file `install` writes. That is the whole requirement, because snapshots, + diffs, edit records and matching are harness-agnostic, and `hook.rs` + only needs a payload with `session_id` and `cwd` (Claude-shaped field + names; an adapter for differently named fields would add a payload + mapping). Optional: `current_turn` (which transcript record a turn began + and ended at, and its prompt) and `transcript_key` (keeping the + transcript in the store). Without them blame still works and says + nothing about what was asked. +2. **Transport** (`save`, `list`, `restore`): `list_sessions` with the + live-cwd/branch/version choice, `transcript_cwds`, `restore_path`, + `existing_transcript` and `resume_command`. The rewrite itself is shared + and needs nothing, as long as the transcript is text with paths in it. +3. **Conversation** (`ask`): `find_transcript` and `fork`, plus `title` if + the harness keeps one outside the transcript. + +**The degraded tier is a first-class case.** A harness with turn hooks and +no resumable transcript implements tier 1 alone, about 40 lines on Codex's +model. `save` finds none of its sessions, `restore` reports a bundled one +as `"status": "unsupported"`, and `ask` fails with `unsupported-agent`. +Blame and log are complete. A harness with no hooks at all gets no tier +today; the shape for it is a stop-only hook (each turn's end snapshot +becomes the next turn's start, which `stop` already handles) or, with no +signal at all, attribution to the span between two `snapshot` calls, +which nothing drives yet. + +Codex took ~600 lines (`codex.rs`), most of it the format: where a turn +starts and ends, the live cwd, a prefix fork. The questions to answer +first for the next harness, in the order they decide the cost: does resume +need anything besides the transcript file (Codex: no; this is the one that +could make restore impractical); are hooks trusted or gated (Codex: gated); +what names a turn in the transcript; where the live cwd and branch are +recorded. Cursor, Gemini CLI and Copilot CLI have not been examined. +Nothing here is verified about them. + ## Layout One Rust crate at the root: a library holding every module, and the `loch` @@ -220,6 +373,7 @@ src/ │ # blame/log/ask/backfill/gc/hook/help/version ├── agent.rs # the adapter boundary: what loch needs from one agent harness ├── claude.rs # Claude Code adapter: path encoding, discovery, metadata, turns, fork +├── codex.rs # Codex adapter: rollout discovery, live cwd, turns by id, prefix fork ├── bundle.rs # bundle format, gzip, content-addressed ref ├── format.rs # loch format: turn and content ids, derived files ├── ingest.rs # Claude Code JSONL -> loch turns (the converter) @@ -243,6 +397,7 @@ src/ tests/ # integration tests, one file per module plus cli.rs ├── derived_reader/ # a verifying reader for derived files, shared by three tests ├── trace.rs # hooks, blame, log and ask end to end, squash and clone included +├── codex.rs # the Codex adapter end to end, on synthetic rollouts ├── backfill.rs # backfill's two sources, contested commits, renames └── corpus.rs # opt-in, against this machine's transcripts (LOCH_CORPUS=1) examples/bench_hook.rs # per-call wall clock of `loch hook`, any number of binaries @@ -579,8 +734,10 @@ never a code. The set today: | `author-key-unreadable` | `ingest --author-key` named a file that isn't an OpenSSH public key | | `file-unreadable` | `blame`/`log`/`ask` named a file that can't be read | | `not-linked` | `ask` on a line no recorded turn wrote | -| `transcript-missing` | a turn wrote the line but its transcript is in neither Claude's directory nor the store | +| `transcript-missing` | a turn wrote the line but its transcript is in neither its agent's directory nor the store | | `turn-not-found` | the transcript no longer holds the record a turn ended on | +| `unknown-agent` | `--agent` named an agent this build doesn't know | +| `unsupported-agent` | `ask` on a turn whose agent's adapter can't fork or resume | | `unknown-command` | no such subcommand | | `usage` | argparse rejected the arguments (exit status 2) | | `internal` | an unexpected exception | @@ -622,6 +779,29 @@ JSON mode carries the same fact as a payload field and leaves stderr empty. `save` and `list` carry the same signal ahead of time as `otherCwds`. +**Several agents, additively.** Each session in `list`, `save` and +`restore` carries `agent` (`claude-code`, `codex`) and `agentVersion`. +`claudeVersion` keeps meaning Claude Code's version, so it is null on a +Codex session rather than reused. `install` writes every agent's hooks +unless `--agent` picks one. Its top-level `settings`/`added`/`removed` +stay the first agent's (Claude's by default), and `agents` lists each, +with `needsReview` true where the agent won't run the hooks just added +until a person approves them. A restore of a session whose agent this +build lacks is `"status": "unsupported"`. None of this changed a field's +meaning, so `schema` stays 2. Blame's payload gained nothing. Its `agent` +field now says `codex` for Codex turns, and `turn`/`conversation` are null +for them, since the loch converter reads Claude's format alone. Consumers +keying on `agent == "claude-code"` (the Ness blame gutter) should expect +the other value. + +**One bundle, several agents, unchanged refs.** A bundle's `agent` is its +first session's, and a session of another agent carries its own `agent` +key. The key is omitted whenever it would equal the bundle's, so a bundle +of one agent's sessions, every Claude bundle ever made included, packs to +the bytes it always did (`tests/bundle.rs` pins them, and +`tests/codex.rs` checks a Claude-only `save` carries no new key). Index +entries name their first session's agent. + **Never the matched text.** Redaction is reported as `{"": }` plus a `redacted` total, exactly as much as the prose summary carries and no more — `save`'s stdout lands in the next agent's transcript. The one field @@ -920,10 +1100,48 @@ kind, so it is worth knowing about: a stale `LOCHY_STORE=s3://...` makes shim is ever wanted, the shape is to read `LOCH_*` first, fall back to the old name, and warn on stderr in text mode only. +**Codex is verified end to end on real sessions** (codex-cli 0.166.0, +scratch repositories, a temporary store): +- **Hooks and blame.** `install --agent codex` wrote `.codex/hooks.json`, + and a session of two `exec` turns, each editing `greet.py` through the + shell, was recorded turn by turn under `edits/codex/`. `blame` gave + lines 1–2 to the first turn and 3–6 to the second, with `"agent": + "codex"` and Codex's own thread title. A human-committed line stayed + unattributed. +- **A cancelled turn.** In the TUI, Esc mid-turn ran no `Stop`. The next + prompt closed the turn as `interrupted`, keeping its edit, and the next + turn recorded none of it. +- **ask.** `ask greet.py:1 --at-turn` forked at the first turn's + `task_complete`, and resumed, the fork knew that turn's codeword and not + the second's. Without `--at-turn` it knew both. +- **save and restore across machines.** The bundle was rewritten to + another machine's home and repo path, then restored with `--new-id` into + a different directory. It came back with `residualOriginPaths` and + `foreignCwds` both empty, no trace of the foreign home or the old id in + the file, every cwd naming the target, and `codex resume` recalled both + codewords and named the new directory as its cwd. +- **Discovery.** All 70 local rollouts (four CLI versions) are found under + their live cwd. A Claude `save` of 100 real sessions gave the same refs + before and after the adapter extraction. +- **Install beside Ness.** `install --local` against a copy of this + machine's `~/.codex/hooks.json` kept every Ness group byte for byte and + in place, and appended loch's. + +Not verified: the trust prompt was seen but loch's hooks were never +trusted through it. Every hook run used `--dangerously-bypass-hook-trust` +on a scratch repository, so how the TUI flow and `needsReview` read to a +person is untested. + +Codex gaps: `ingest` and `backfill` are Claude-only (SPEC.md §8's converter; +see the tool-call note above); a moved session has no branch; `--local` +installs into the user's hooks file, so loch runs for every Codex project on +the machine (it refuses `/` and home, as always); a fork has no title; +`archived_sessions` isn't searched. + Also missing: `restore --map` (design intent recorded above, deliberately not built on this branch), any other index dimension (`cwd` is the obvious next one, and the layout takes it without a migration), PR-level -git pointers for bundles, and no adapters beyond Claude Code. +git pointers for bundles, and no adapters beyond Claude Code and Codex. `restore` still needs a full 64-character ref — the index makes refs discoverable, but nothing resolves a prefix. diff --git a/src/agent.rs b/src/agent.rs index 41a9b9d..5f2d940 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -129,6 +129,11 @@ pub trait Agent: Sync { ) -> Result, StoreError> { Ok(None) } + /// The session's title, where the agent keeps one outside the + /// transcript. + fn title(&self, _session_id: &str) -> Option { + None + } /// A new session holding the conversation up to `cut` (the end, if none), /// filed under `target_cwd`. fn fork( @@ -142,7 +147,7 @@ pub trait Agent: Sync { } } -static ALL: &[&dyn Agent] = &[&crate::claude::CLAUDE_CODE]; +static ALL: &[&dyn Agent] = &[&crate::claude::CLAUDE_CODE, &crate::codex::CODEX]; pub fn all() -> &'static [&'static dyn Agent] { ALL diff --git a/src/bundle.rs b/src/bundle.rs index 5351ba7..2536dfb 100644 --- a/src/bundle.rs +++ b/src/bundle.rs @@ -20,16 +20,34 @@ pub struct BundleOrigin { pub hostname: String, } -#[derive(Clone)] +#[derive(Clone, Default)] pub struct BundleSession { pub session_id: String, + /// Set only where the session's agent differs from the bundle's, so a + /// bundle of one agent's sessions — every Claude bundle before Codex — + /// keeps its bytes, and its ref. + pub agent: Option, pub cwd: String, pub git_branch: Option, pub claude_version: Option, + /// Any other agent's version: `claudeVersion` keeps meaning Claude's. + pub agent_version: Option, pub modified_at: String, pub transcript: String, } +impl BundleSession { + pub fn agent_of<'a>(&'a self, bundle: &'a Bundle) -> &'a str { + self.agent.as_deref().unwrap_or(&bundle.agent) + } + + pub fn version(&self) -> Option<&str> { + self.claude_version + .as_deref() + .or(self.agent_version.as_deref()) + } +} + #[derive(Clone)] pub struct Bundle { pub version: i64, @@ -40,15 +58,21 @@ pub struct Bundle { } fn session_json(session: &BundleSession) -> Value { - let mut record = - object! {"sessionId" => session.session_id.as_str(), "cwd" => session.cwd.as_str()}; + let mut record = object! {"sessionId" => session.session_id.as_str()}; // Omitted rather than null: the ref is a hash of these bytes. + if let Some(agent) = &session.agent { + record.insert("agent".into(), agent.as_str().into()); + } + record.insert("cwd".into(), session.cwd.as_str().into()); if let Some(branch) = &session.git_branch { record.insert("gitBranch".into(), branch.as_str().into()); } if let Some(version) = &session.claude_version { record.insert("claudeVersion".into(), version.as_str().into()); } + if let Some(version) = &session.agent_version { + record.insert("agentVersion".into(), version.as_str().into()); + } record.insert("modifiedAt".into(), session.modified_at.as_str().into()); record.insert("transcript".into(), session.transcript.as_str().into()); Value::Object(record) @@ -205,8 +229,11 @@ pub fn unpack_bundle(data: &[u8]) -> Result { .map(str::to_string) .ok_or_else(|| format!("'{}'", key)) }; + let optional = |key: &str| session.get(key).and_then(Value::as_str).map(str::to_string); sessions.push(BundleSession { session_id: required("sessionId")?, + agent: optional("agent"), + agent_version: optional("agentVersion"), cwd: required("cwd")?, git_branch: session .get("gitBranch") diff --git a/src/cli.rs b/src/cli.rs index 2eb0ffd..20d2a10 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -166,8 +166,9 @@ fn describe_entry(entry: &IndexEntry) -> String { _ => "[no branch]".into(), }; let when = py::truncate(&entry.created_at, 16).replace('T', " "); - let version = match &entry.claude_version { - Some(v) if !v.is_empty() => format!(" claude {}", v), + let version = match (&entry.claude_version, &entry.agent_version) { + (Some(v), _) if !v.is_empty() => format!(" claude {}", v), + (_, Some(v)) if !v.is_empty() => format!(" {} {}", entry.agent, v), _ => String::new(), }; format!( @@ -181,16 +182,33 @@ fn describe_entry(entry: &IndexEntry) -> String { ) } +/// Every selected agent's sessions for a cwd, newest first. fn collect( + agents: &[&dyn Agent], cwd: Option<&str>, branch: Option<&str>, session: Option<&str>, ) -> (String, Vec) { let resolved = resolve_cwd(&cwd.map(str::to_string).unwrap_or_else(sys::getcwd)); - let sessions = claude::CLAUDE_CODE.list_sessions(&resolved, branch, session); + let mut sessions: Vec = agents + .iter() + .flat_map(|agent| agent.list_sessions(&resolved, branch, session)) + .collect(); + // Stable, so one agent's sessions keep their own order on a tie. + sessions.sort_by(|a, b| py::cmp(&b.modified_at, &a.modified_at)); (resolved, sessions) } +fn agents_arg(id: Option<&str>) -> std::result::Result, Failure> { + agent::selected(id) + .map_err(|message| Failure::Error(CommandError::new("unknown-agent", message))) +} + +fn none_found(agents: &[&dyn Agent], cwd: &str) -> String { + let ids: Vec<&str> = agents.iter().map(|a| a.id()).collect(); + format!("no {} sessions found for {}", ids.join(" or "), cwd) +} + fn parser(command: &str) -> Parser { Parser::new(&format!("loch {}", command)) } @@ -202,11 +220,13 @@ fn strings(items: &[String]) -> Value { fn session_payload(meta: &SessionMeta) -> Value { Value::Object(object! { "sessionId" => meta.session_id.as_str(), + "agent" => meta.agent, "path" => meta.path.as_str(), "cwd" => meta.cwd.as_str(), "otherCwds" => strings(&meta.other_cwds), "branch" => Value::opt_str(meta.git_branch.as_deref()), - "claudeVersion" => Value::opt_str(meta.version.as_deref()), + "claudeVersion" => Value::opt_str(meta.version.as_deref().filter(|_| meta.agent == AGENT)), + "agentVersion" => Value::opt_str(meta.version.as_deref()), "bytes" => meta.bytes as i64, "modifiedAt" => meta.modified_at.as_str(), "summary" => Value::opt_str(meta.summary.as_deref()), @@ -226,6 +246,7 @@ fn entry_payload(entry: &IndexEntry) -> Value { "sessions" => entry.sessions, "cwd" => entry.cwd.as_str(), "claudeVersion" => Value::opt_str(entry.claude_version.as_deref()), + "agentVersion" => Value::opt_str(entry.claude_version.as_deref().or(entry.agent_version.as_deref())), }) } @@ -235,6 +256,7 @@ pub fn command_list(argv: &[String]) -> Run { let mut p = parser("list"); p.option("--cwd") .option("--branch") + .option("--agent") .flag("--remote", None) .flag("--all", Some("every")) .option("--store"); @@ -243,9 +265,10 @@ pub fn command_list(argv: &[String]) -> Run { if args.flag("remote") || args.flag("every") || store.is_some() { return list_remote(cwd, branch, store, args.flag("every")); } - let (cwd, sessions) = collect(cwd.as_deref(), branch.as_deref(), None); + let agents = agents_arg(args.str("agent").as_deref())?; + let (cwd, sessions) = collect(&agents, cwd.as_deref(), branch.as_deref(), None); let text = if sessions.is_empty() { - format!("no {} sessions found for {}\n", AGENT, cwd) + format!("{}\n", none_found(&agents, &cwd)) } else { let mut text = format!("{} session(s) for {}\n", sessions.len(), cwd); for meta in &sessions { @@ -345,19 +368,22 @@ pub fn command_save(argv: &[String]) -> Run { p.option("--cwd") .option("--branch") .option("--session") + .option("--agent") .option("--store"); let args = p.parse(argv)?; + let agents = agents_arg(args.str("agent").as_deref())?; let (cwd, sessions) = collect( + &agents, args.str("cwd").as_deref(), args.str("branch").as_deref(), args.str("session").as_deref(), ); if sessions.is_empty() { - return err( - "no-sessions", - format!("no {} sessions found for {}", AGENT, cwd), - ); + return err("no-sessions", none_found(&agents, &cwd)); } + // The bundle is its first session's agent's; any other session names its + // own, so a bundle of one agent's sessions has the bytes it always had. + let bundle_agent = sessions[0].agent; let mut packed_sessions = Vec::new(); let mut redactions = Vec::new(); for meta in &sessions { @@ -386,11 +412,14 @@ pub fn command_save(argv: &[String]) -> Run { ) } }; + let is_claude = meta.agent == AGENT; packed_sessions.push(BundleSession { session_id: meta.session_id.clone(), + agent: (meta.agent != bundle_agent).then(|| meta.agent.to_string()), cwd: meta.cwd.clone(), git_branch: meta.git_branch.clone(), - claude_version: meta.version.clone(), + claude_version: meta.version.clone().filter(|_| is_claude), + agent_version: meta.version.clone().filter(|_| !is_claude), modified_at: meta.modified_at.clone(), transcript: scrubbed.text, }); @@ -398,7 +427,7 @@ pub fn command_save(argv: &[String]) -> Run { } let bundle = Bundle { version: BUNDLE_VERSION, - agent: AGENT.into(), + agent: bundle_agent.into(), created_at: sys::iso_timestamp(sys::creation_time()), origin: BundleOrigin { home: home_dir(), @@ -470,9 +499,11 @@ pub fn command_save(argv: &[String]) -> Run { "redacted" => total, "sessions" => bundle.sessions.iter().zip(&redactions).map(|(s, counts)| Value::Object(object! { "sessionId" => s.session_id.as_str(), + "agent" => s.agent_of(&bundle), "branch" => Value::opt_str(s.git_branch.as_deref()), "cwd" => s.cwd.as_str(), "claudeVersion" => Value::opt_str(s.claude_version.as_deref()), + "agentVersion" => Value::opt_str(s.version()), "modifiedAt" => s.modified_at.as_str(), "redactions" => counts_value(counts), })).collect::>(), @@ -489,6 +520,7 @@ pub fn command_save(argv: &[String]) -> Run { // -- restore ------------------------------------------------------------------ struct Restored { + agent: String, session_id: String, origin_session_id: String, branch: Option, @@ -502,6 +534,7 @@ struct Restored { fn restored_payload(session: &Restored) -> Value { Value::Object(object! { "sessionId" => session.session_id.as_str(), + "agent" => session.agent.as_str(), "originSessionId" => session.origin_session_id.as_str(), "branch" => Value::opt_str(session.branch.as_deref()), "status" => session.status, @@ -539,10 +572,29 @@ pub fn command_restore(argv: &[String]) -> Run { Err(error) => return err("bundle-unreadable", format!("{}: {}", described, error)), }; let target_cwd = resolve_cwd(&args.str("into").unwrap_or_else(sys::getcwd)); - let adapter: &dyn Agent = &claude::CLAUDE_CODE; let target_home = home_dir(); let mut restored = Vec::new(); for session in &bundle.sessions { + let agent_id = session.agent_of(&bundle).to_string(); + // A bundle from a build that knows agents this one doesn't, or one + // whose adapter can't restore. + let Some(adapter) = agent::by_id(&agent_id).filter(|a| { + a.restore_path("", &target_cwd, &session.session_id) + .is_some() + }) else { + restored.push(Restored { + agent: agent_id, + session_id: session.session_id.clone(), + origin_session_id: session.session_id.clone(), + branch: session.git_branch.clone(), + status: "unsupported", + path: String::new(), + residual: Vec::new(), + resume_command: None, + foreign: Vec::new(), + }); + continue; + }; let target_session_id = if args.flag("new_id") { sys::uuid4() } else { @@ -557,17 +609,13 @@ pub fn command_restore(argv: &[String]) -> Run { target_session_id: Some(target_session_id.clone()), }; let transcript = rewrite::rewrite_transcript(&session.transcript, &spec); - let Some(mut destination) = - adapter.restore_path(&transcript, &target_cwd, &target_session_id) - else { - return Err(Failure::Internal(format!( - "{} sessions can't be restored", - adapter.name() - ))); - }; + let mut destination = adapter + .restore_path(&transcript, &target_cwd, &target_session_id) + .unwrap_or_default(); let existing = adapter.existing_transcript(&target_cwd, &target_session_id); if existing.is_some() && !args.flag("force") { restored.push(Restored { + agent: agent_id.clone(), session_id: target_session_id, origin_session_id: session.session_id.clone(), branch: session.git_branch.clone(), @@ -589,6 +637,7 @@ pub fn command_restore(argv: &[String]) -> Run { fs::write(&destination, transcript.as_bytes()) .map_err(|e| Failure::Internal(sys::os_error(&e, &destination)))?; restored.push(Restored { + agent: agent_id.clone(), session_id: target_session_id.clone(), origin_session_id: session.session_id.clone(), branch: session.git_branch.clone(), @@ -616,12 +665,19 @@ pub fn command_restore(argv: &[String]) -> Run { }; let mut warnings: Vec = restored .iter() - .filter(|s| s.status == "skipped") + .filter(|s| s.status != "restored") .map(|s| { - format!( - " skipped {} (already exists; --force to overwrite)\n", - s.session_id - ) + if s.status == "unsupported" { + format!( + " skipped {} ({} sessions aren't supported by this build)\n", + s.session_id, s.agent + ) + } else { + format!( + " skipped {} (already exists; --force to overwrite)\n", + s.session_id + ) + } }) .collect(); for session in &restored { @@ -789,16 +845,16 @@ pub fn command_ingest(argv: &[String]) -> Run { } } } + // The loch converter reads Claude Code's transcripts alone (SPEC.md §8). + let agents: Vec<&dyn Agent> = vec![&claude::CLAUDE_CODE]; let (cwd, sessions) = collect( + &agents, args.str("cwd").as_deref(), args.str("branch").as_deref(), args.str("session").as_deref(), ); if sessions.is_empty() { - return err( - "no-sessions", - format!("no {} sessions found for {}", AGENT, cwd), - ); + return err("no-sessions", none_found(&agents, &cwd)); } let out = args.str("out").unwrap_or_else(default_derived); fs::create_dir_all(&out).map_err(|e| Failure::Internal(sys::os_error(&e, &out)))?; @@ -898,8 +954,12 @@ fn which(name: &str) -> Option { pub fn command_install(argv: &[String]) -> Run { let mut p = parser("install"); - p.option("--cwd").flag("--local", None).option("--command"); + p.option("--cwd") + .flag("--local", None) + .option("--command") + .option("--agent"); let args = p.parse(argv)?; + let agents = agents_arg(args.str("agent").as_deref())?; let cwd = args .str("cwd") .filter(|c| !c.is_empty()) @@ -913,36 +973,63 @@ pub fn command_install(argv: &[String]) -> Run { .unwrap_or_else(|| sys::abspath(&std::env::args().next().unwrap_or_default())), None => "loch".into(), }; - let adapter: &dyn Agent = &claude::CLAUDE_CODE; - let settings = adapter.hooks_file(&root, args.flag("local")); - let installed = trace::install_hooks(&settings, &command, adapter) - .map_err(|trace::InstallError::Internal(m)| Failure::Internal(m))?; - let mut text = if installed.added.is_empty() { - format!("loch hooks already installed in {}\n", settings) - } else { - format!( - "installed loch hooks ({}) in {}\n", - installed.added.join(", "), - settings - ) - }; - if !installed.removed.is_empty() { - text.push_str(&format!( - "removed the old per-command hooks ({})\n", - installed.removed.join(", ") + let mut text = String::new(); + let mut results = Vec::new(); + for adapter in &agents { + let settings = adapter.hooks_file(&root, args.flag("local")); + let installed = trace::install_hooks(&settings, &command, *adapter) + .map_err(|trace::InstallError::Internal(m)| Failure::Internal(m))?; + if installed.added.is_empty() { + text.push_str(&format!("loch hooks already installed in {}\n", settings)); + } else { + text.push_str(&format!( + "installed loch hooks ({}) in {}\n", + installed.added.join(", "), + settings + )); + } + if !installed.removed.is_empty() { + text.push_str(&format!( + "removed the old per-command hooks ({})\n", + installed.removed.join(", ") + )); + } + text.push_str(&format!("{}\n", adapter.install_note())); + results.push(( + adapter.id(), + settings, + installed, + adapter.hooks_need_review(), )); } - text.push_str(&format!("{}\n", adapter.install_note())); - Ok(Outcome::with( - "install", - object! { - "settings" => settings.as_str(), - "command" => command.as_str(), - "added" => strings(&installed.added), - "removed" => strings(&installed.removed), - }, - text, - )) + // The first agent's at the top level, as before there were several. + let (_, settings, installed, _) = &results[0]; + let mut payload = object! { + "settings" => settings.as_str(), + "command" => command.as_str(), + "added" => strings(&installed.added), + "removed" => strings(&installed.removed), + }; + payload.insert( + "agents".into(), + Value::Array( + results + .iter() + .map(|(id, settings, installed, review)| { + Value::Object(object! { + "agent" => *id, + "settings" => settings.as_str(), + "added" => strings(&installed.added), + "removed" => strings(&installed.removed), + // The agent won't run a new hook until a person + // approves it; loch never approves its own. + "needsReview" => *review && !installed.added.is_empty(), + }) + }) + .collect(), + ), + ); + Ok(Outcome::with("install", payload, text)) } // -- blame / log / ask ------------------------------------------------------------- diff --git a/src/codex.rs b/src/codex.rs new file mode 100644 index 0000000..297a6e1 --- /dev/null +++ b/src/codex.rs @@ -0,0 +1,587 @@ +//! The Codex CLI adapter. +//! +//! Codex files a session by date, not by directory: +//! `$CODEX_HOME/sessions/YYYY/MM/DD/rollout-