Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
282 changes: 272 additions & 10 deletions CLAUDE.md

Large diffs are not rendered by default.

175 changes: 175 additions & 0 deletions src/agent.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
//! 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<String>,
/// The harness's own version, as its transcript records it.
pub version: Option<String>,
pub bytes: u64,
pub modified_at: String,
pub summary: Option<String>,
/// 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<String>,
}

/// 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<String>,
pub prompt: Option<String>,
pub started: Option<String>,
pub end_uuid: Option<String>,
pub ended: Option<String>,
}

/// 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/<id>/`. `None` keeps none.
fn transcript_key(&self, _path: &str, _session_id: &str) -> Option<String> {
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<SessionMeta> {
Vec::new()
}
fn read_session_meta(&self, _path: &str) -> Option<SessionMeta> {
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()
}
/// Whether `restore` can file a session of this agent's: the transport
/// tier is implemented.
fn can_restore(&self) -> bool {
false
}
/// Where a restored transcript goes. `raw` is the rewritten transcript.
fn restore_path(&self, _raw: &str, _cwd: &str, _session_id: &str) -> Option<String> {
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<String> {
None
}
/// argv that resumes the session.
fn resume_command(&self, _session_id: &str) -> Option<Vec<String>> {
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<Option<String>, StoreError> {
Ok(None)
}
/// The session's title, where the agent keeps one outside the
/// transcript.
fn title(&self, _session_id: &str) -> Option<String> {
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<Fork, ForkError> {
Err(ForkError::Unsupported(self.name()))
}
}

static ALL: &[&dyn Agent] = &[&crate::claude::CLAUDE_CODE, &crate::codex::CODEX];

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.
/// `all` names every agent too.
pub fn selected(id: Option<&str>) -> Result<Vec<&'static dyn Agent>, String> {
match id.filter(|id| !id.is_empty()) {
None | Some("all") => 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(", "))
}),
}
}
3 changes: 1 addition & 2 deletions src/backfill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
76 changes: 66 additions & 10 deletions src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,67 @@ use crate::sys;
use sha2::{Digest, Sha256};
use std::io::Read;

/// A bundle of Claude Code sessions alone: every bundle made before Codex,
/// and every one since that holds only Claude sessions, keeps this, and its
/// bytes.
pub const BUNDLE_VERSION: i64 = 1;

/// A bundle holding any other agent's session. A build that predates agents
/// ignores `agent` and would restore a Codex session as a Claude transcript
/// while reporting success; it refuses any version but 1, so this makes it
/// fail loudly instead.
pub const AGENTS_VERSION: i64 = 2;

#[derive(Clone)]
pub struct BundleOrigin {
pub home: String,
pub platform: String,
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<String>,
pub cwd: String,
pub git_branch: Option<String>,
pub claude_version: Option<String>,
/// Any other agent's version: `claudeVersion` keeps meaning Claude's.
pub agent_version: Option<String>,
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())
}
}

impl Bundle {
/// The version these sessions need: 1 unless any isn't Claude Code's.
pub fn required_version(&self) -> i64 {
let claude_only = self
.sessions
.iter()
.all(|s| s.agent_of(self) == crate::claude::AGENT);
if claude_only {
BUNDLE_VERSION
} else {
AGENTS_VERSION
}
}
}

#[derive(Clone)]
pub struct Bundle {
pub version: i64,
Expand All @@ -40,15 +82,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)
Expand Down Expand Up @@ -168,16 +216,21 @@ pub fn unpack_bundle(data: &[u8]) -> Result<Bundle, String> {
})?;
let root = value.as_object().ok_or("the bundle is not a JSON object")?;
let version = root.get("version");
let current = matches!(version, Some(Value::Int(d)) if d == "1")
let read = if matches!(version, Some(Value::Int(d)) if d == "1")
|| matches!(version, Some(Value::Bool(true)))
|| matches!(version, Some(Value::Float(f)) if *f == 1.0);
if !current {
|| matches!(version, Some(Value::Float(f)) if *f == 1.0)
{
BUNDLE_VERSION
} else if matches!(version, Some(Value::Int(d)) if d == "2") {
AGENTS_VERSION
} else {
return Err(format!(
"unsupported bundle version {} (this build reads {})",
"unsupported bundle version {} (this build reads {} and {})",
py_str(version),
BUNDLE_VERSION
BUNDLE_VERSION,
AGENTS_VERSION
));
}
};
let empty = Map::new();
let origin = match root.get("origin") {
None => &empty,
Expand Down Expand Up @@ -205,8 +258,11 @@ pub fn unpack_bundle(data: &[u8]) -> Result<Bundle, String> {
.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")
Expand All @@ -221,7 +277,7 @@ pub fn unpack_bundle(data: &[u8]) -> Result<Bundle, String> {
});
}
Ok(Bundle {
version: BUNDLE_VERSION,
version: read,
agent: text_of(root, "agent"),
created_at: text_of(root, "createdAt"),
origin: BundleOrigin {
Expand Down
Loading
Loading