diff --git a/CLAUDE.md b/CLAUDE.md index 5d051f3..7af56d8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -124,6 +124,39 @@ turns that wrote it before a rename), and by `backfill`. session's tool edits already explain are left to those edits, the more precise source. +- **Every worktree of the repository, live or removed.** Most agent work + happens in a worktree that is merged and deleted, so a backfill from any + checkout covers sessions whose cwd was in any worktree `git worktree list` + names, each edit's path made relative to the worktree it was written in. + A removed worktree is recognized **by what it wrote, not where it was**: + worktrees live wherever their creator put them (Ness nests them by branch + name, Claude Code under `.claude/worktrees`, people under `/tmp`), so no + layout is assumed. Each component prefix of the gone cwd is a candidate + root, and wins if the session's substantive lines (12+ characters, not + weak) are in this repository's files at the same relative paths, at the + tip of any branch, tag or worktree — at least 5 distinct lines, and + strictly more than any other prefix. A tie, or less, includes nothing. A + cwd inside another repository's checkout is never considered, whatever it + wrote, and nor is a directory that still exists but is no checkout of this + repository (scratch space, a `cp -r`): only a directory that is gone can + be a worktree git has forgotten. Blobs over 1MB are not read for evidence + and the rest are read 16MB at a time, so a lockfile at hundreds of tips + never sits in memory whole. The repository's tips are read as one tree walk per depth through + `cat-file --batch`, since hundreds of branches share nearly every subtree + (claude-harness: 666 tips, 7s by `ls-tree` per tip, 0.3s this way), and a + transcript is fully parsed only if a `file_path` in its raw text could land + on a path the repository has. On claude-harness this took backfill from 17 + turns to 185 across 45 sessions in 39 worktrees, and `src/main/loch.ts`, + written in a since-removed worktree, from 0 to 383 of 439 lines. + The honest limits: a removed worktree whose work never reached any ref + leaves no evidence (nor anything to blame); a session in a removed + worktree that worked only through Bash has no tool edits to be recognized + by, so it is skipped with its commits even when they are still reachable + (recognizing a gone cwd by an exactly-credited commit would fix that, and + is exact by construction); and a squash-merged commit + can't be credited by the commit rule, since its time is the merge's, not + the Bash call's — its lines come from the tool edits or not at all. + Hook-recorded turns are never replaced, and a re-run replaces only earlier backfilled turns. On this repository it rebuilt 21 turns across 2 sessions, and with rename-following, files written before the crate moved out of diff --git a/SPEC.md b/SPEC.md index 54750b1..93dc9b3 100644 --- a/SPEC.md +++ b/SPEC.md @@ -344,6 +344,11 @@ formatter re-indenting a turn's code doesn't sever the link. it is `git:` plus the repository's root commit (the smallest, if there are several): read once, and immune to anything later history does. Anywhere else it is `dir:` plus the root's directory name, which is weaker. +- **`root`** is the worktree the session worked in, and paths are relative to + it. It is informational, since matching is by `project` and path: a turn + written in any worktree of a repository blames in every other one once its + lines arrive there. A root may name a directory that no longer exists, + which is how a removed worktree's history survives. **Store layout:** diff --git a/src/backfill.rs b/src/backfill.rs index bea6727..1581e12 100644 --- a/src/backfill.rs +++ b/src/backfill.rs @@ -30,6 +30,7 @@ use crate::sys; use crate::trace::{self, content, py_str}; use std::collections::{HashMap, HashSet}; use std::fs; +use std::path::Path; /// How far a commit's time may sit outside the Bash call that made it: git /// records whole seconds and transcripts milliseconds, and a hook is slow. @@ -275,41 +276,479 @@ fn old_notes(root: &str) -> HashMap<(String, String), Vec> { found } -/// The transcripts that might hold this project's history: every local -/// session whose working directory lay inside `root`. -fn transcripts_for(root: &str) -> Vec<(String, String)> { +/// How many distinct substantive lines a session must have written, at the +/// same relative paths, into this repository's files before a directory that +/// no longer exists is taken for one of its former worktrees. +const EVIDENCE: usize = 5; + +/// The repository a backfill covers, whichever of its worktrees it was run +/// from: every worktree git knows of, and what its branches hold, to +/// recognize the worktrees it no longer knows of by the text written in them. +struct Repo { + root: String, + /// `git worktree list`, the main one first, including any whose + /// directory has gone but which git hasn't pruned yet. + worktrees: Vec, + /// Path → every blob it has at the tip of any branch, tag or worktree. + tree: HashMap>, + /// Blob → the hashes of its lines, read on demand. + blobs: HashMap>, +} + +impl Repo { + fn open(root: &str) -> Repo { + let mut repo = Repo { + root: root.to_string(), + worktrees: vec![root.to_string()], + tree: HashMap::new(), + blobs: HashMap::new(), + }; + if !snapshot::has_git_marker(root) { + return repo; + } + let listing = + git::git(root, &["worktree", "list", "--porcelain"], None).unwrap_or_default(); + let mut tips: Vec = Vec::new(); + for line in listing.lines() { + if let Some(path) = line.strip_prefix("worktree ") { + let path = sys::realpath_strict(path).unwrap_or_else(|| path.to_string()); + if !repo.worktrees.contains(&path) { + repo.worktrees.push(path); + } + } else if let Some(head) = line.strip_prefix("HEAD ") { + tips.push(head.to_string()); + } + } + let refs = git::git( + root, + &[ + "for-each-ref", + "--format=%(objectname)", + "refs/heads", + "refs/remotes", + "refs/tags", + ], + None, + ) + .unwrap_or_default(); + tips.extend(refs.lines().map(str::to_string)); + tips.sort(); + tips.dedup(); + // Walked a level at a time rather than `ls-tree -r` per tip: hundreds + // of branches share nearly every subtree, and each (subtree, path) is + // read once. + let mut level: Vec<(String, String)> = tips + .iter() + .map(|tip| (format!("{}^{{tree}}", tip), String::new())) + .collect(); + let width = match git::git(root, &["rev-parse", "--show-object-format"], None) { + Ok(format) if format.trim() == "sha256" => 32, + _ => 20, + }; + let mut seen: HashSet<(String, String)> = HashSet::new(); + while !level.is_empty() { + let names: Vec<&str> = level.iter().map(|(name, _)| name.as_str()).collect(); + let mut next = Vec::new(); + for ((_, prefix), object) in level.iter().zip(batch(root, &names)) { + let Some((_, data)) = object else { + continue; + }; + for (mode, name, id) in tree_entries(&data, width).unwrap_or_default() { + let path = format!("{}{}", prefix, name); + if mode == "40000" { + let sub = (id, format!("{}/", path)); + if seen.insert(sub.clone()) { + next.push(sub); + } + } else if mode.starts_with("100") { + repo.tree.entry(path).or_default().insert(id); + } + } + } + level = next; + } + repo + } + + /// Reads every blob in `wanted` not yet read, in one `cat-file`. + fn load(&mut self, wanted: &HashSet) { + let missing: Vec<&str> = wanted + .iter() + .filter(|b| !self.blobs.contains_key(*b)) + .map(String::as_str) + .collect(); + // Sized first, so a lockfile at hundreds of tips is never held whole + // at once: anything over `BLOB_CAP` is skipped (generated files are + // poor evidence anyway), and the rest is read `BATCH_BYTES` at a time. + let mut chunk: Vec<&str> = Vec::new(); + let mut bytes = 0; + for (blob, size) in missing.iter().zip(sizes(&self.root, &missing)) { + match size { + Some(size) if size <= BLOB_CAP => { + if bytes + size > BATCH_BYTES && !chunk.is_empty() { + self.read(&chunk); + chunk.clear(); + bytes = 0; + } + chunk.push(blob); + bytes += size; + } + _ => { + self.blobs.insert(blob.to_string(), HashSet::new()); + } + } + } + self.read(&chunk); + } + + fn read(&mut self, blobs: &[&str]) { + for (blob, object) in blobs.iter().zip(batch(&self.root, blobs)) { + let lines = object + .map(|(_, data)| { + String::from_utf8_lossy(&data) + .lines() + .map(attribution::line_hash) + .collect() + }) + .unwrap_or_default(); + self.blobs.insert(blob.to_string(), lines); + } + } + + /// The live worktree `path` is in, the most deeply nested if several. + fn worktree_holding(&self, path: &str) -> Option<&String> { + self.worktrees + .iter() + .filter(|w| path == w.as_str() || inside(path, w).is_some()) + .max_by_key(|w| w.len()) + } +} + +/// The largest blob read for evidence, and how much is read in one go. +const BLOB_CAP: usize = 1 << 20; +const BATCH_BYTES: usize = 16 << 20; + +/// Each named object's size, from `cat-file --batch-check`; `None` for one +/// that doesn't exist. +fn sizes(root: &str, names: &[&str]) -> Vec> { + if names.is_empty() { + return Vec::new(); + } + let input: String = names.iter().map(|n| format!("{}\n", n)).collect(); + let out = git::git(root, &["cat-file", "--batch-check"], Some(&input)).unwrap_or_default(); + let mut found: Vec> = out + .lines() + .map(|line| { + let parts: Vec<&str> = line.split(' ').collect(); + match parts.as_slice() { + [_, _, size] => size.parse().ok(), + _ => None, + } + }) + .collect(); + found.resize(names.len(), None); + found +} + +/// Each named object as `cat-file --batch` gives it, `(id, contents)`, in the +/// order asked; `None` for one that doesn't exist. +fn batch(root: &str, names: &[&str]) -> Vec)>> { + if names.is_empty() { + return Vec::new(); + } + let input: String = names.iter().map(|n| format!("{}\n", n)).collect(); + let out = git::git_bytes(root, &["cat-file", "--batch"], Some(&input)).unwrap_or_default(); + let mut objects = Vec::with_capacity(names.len()); + let mut at = 0; + while objects.len() < names.len() { + let Some(end) = out[at..].iter().position(|&b| b == b'\n') else { + break; + }; + let header = String::from_utf8_lossy(&out[at..at + end]).into_owned(); + at += end + 1; + let parts: Vec<&str> = header.split(' ').collect(); + match ( + parts.as_slice(), + parts.get(2).and_then(|s| s.parse::().ok()), + ) { + ([id, _, _], Some(size)) => { + let body = out[at..(at + size).min(out.len())].to_vec(); + at += size + 1; + objects.push(Some((id.to_string(), body))); + } + _ => objects.push(None), + } + } + objects.resize(names.len(), None); + objects +} + +/// `(mode, name, id)` for each entry of a raw tree object whose ids are +/// `width` bytes. +fn tree_entries(data: &[u8], width: usize) -> Option> { + let mut entries = Vec::new(); + let mut at = 0; + while at < data.len() { + let space = at + data[at..].iter().position(|&b| b == b' ')?; + let nul = space + data[space..].iter().position(|&b| b == 0)?; + let id = data.get(nul + 1..nul + 1 + width)?; + let mode = std::str::from_utf8(&data[at..space]).ok()?; + if mode.is_empty() || !mode.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + entries.push(( + mode.to_string(), + String::from_utf8_lossy(&data[space + 1..nul]).into_owned(), + id.iter().map(|b| format!("{:02x}", b)).collect(), + )); + at = nul + 1 + width; + } + Some(entries) +} + +/// A line distinctive enough that finding it at the same path in two +/// unrelated repositories would be a coincidence. +fn substantive(line: &str) -> bool { + !attribution::is_weak(line) && line.trim().chars().count() >= 12 +} + +/// What a session's working directory says about where it worked. +enum Place { + /// A worktree of this repository: the directory its paths are relative to. + Root(String), + /// Somewhere that may have been one of its worktrees and isn't any more: + /// the candidate roots, outermost first, and the live worktree it lay + /// inside, if any, to fall back on. + Gone(Vec, Option), + /// Another repository's checkout. + Elsewhere, +} + +fn place(cwd: &str, repo: &Repo) -> Place { + let found = snapshot::workspace_root(cwd); + let checkout = snapshot::has_git_marker(&found).then_some(found); + let live = repo.worktree_holding(cwd).cloned(); + if Path::new(cwd).is_dir() { + if let Some(checkout) = &checkout { + if repo.worktrees.contains(checkout) { + return Place::Root(checkout.clone()); + } + } + // A directory that is still there and is no checkout of this + // repository — scratch space, an unpacked tarball, a `cp -r` — is + // what it is, whatever it wrote. Only one that is gone can have been + // a worktree git has forgotten. + if live.is_none() { + return Place::Elsewhere; + } + } + // A checkout above a directory that is gone is the one it was in — unless + // it also encloses this repository, as a home directory under git does. + let floor = match (&checkout, &live) { + // A repository nested in a worktree (a submodule, a vendored clone) + // is its own project. + (Some(checkout), Some(live)) if inside(checkout, live).is_some() => { + return Place::Elsewhere + } + (_, Some(live)) => Some(live.clone()), + (Some(checkout), None) if inside(&repo.root, checkout).is_some() => Some(checkout.clone()), + (Some(_), None) => return Place::Elsewhere, + (None, None) => None, + }; + let mut candidates: Vec = Vec::new(); + for (i, c) in cwd.char_indices().skip(1) { + if c == '/' { + candidates.push(cwd[..i].to_string()); + } + } + candidates.push(cwd.to_string()); + candidates.retain(|c| match &floor { + Some(floor) if live.as_ref() == Some(floor) => c == floor || inside(c, floor).is_some(), + Some(floor) => inside(c, floor).is_some(), + None => true, + }); + Place::Gone(candidates, live) +} + +/// The root a directory that no longer exists was a worktree of this +/// repository at, judged by the text the session wrote: the candidate under +/// which the most of it is in this repository's files at the same relative +/// paths. A tie, or too little, decides nothing. +fn recognize(candidates: &[String], turns: &[Turn], repo: &mut Repo) -> Option { + let edits: Vec<&(String, String)> = turns.iter().flat_map(|t| t.edits.iter()).collect(); + let mut wanted: HashSet = HashSet::new(); + for candidate in candidates { + for (file, _) in &edits { + if let Some(blobs) = inside(file, candidate).and_then(|p| repo.tree.get(&p)) { + wanted.extend(blobs.iter().cloned()); + } + } + } + repo.load(&wanted); + let mut scores: Vec<(usize, &String)> = Vec::new(); + for candidate in candidates { + let mut found: HashSet = HashSet::new(); + for (file, text) in &edits { + let Some(blobs) = inside(file, candidate).and_then(|p| repo.tree.get(&p)) else { + continue; + }; + for line in text.lines().filter(|l| substantive(l)) { + let hash = attribution::line_hash(line); + if blobs + .iter() + .any(|b| repo.blobs.get(b).is_some_and(|l| l.contains(&hash))) + { + found.insert(hash); + } + } + } + scores.push((found.len(), candidate)); + } + scores.sort_by(|a, b| b.0.cmp(&a.0)); + match scores.as_slice() { + [(best, root), rest @ ..] + if *best >= EVIDENCE && rest.first().is_none_or(|r| r.0 < *best) => + { + Some((*root).clone()) + } + _ => None, + } +} + +/// Whether a session in directories that are gone edited any path this +/// repository has under one of the candidate roots — read off the raw text, +/// since most such sessions belong to other repositories and parsing every +/// one of them whole is most of what backfill would cost. A path written +/// with an escape is taken as a possible match, so this only ever skips. +fn could_be_recognized(transcript: &str, places: &[Place], repo: &Repo) -> bool { + let Ok(raw) = fs::read_to_string(transcript) else { + return true; + }; + let candidates: Vec<&String> = places + .iter() + .flat_map(|p| match p { + Place::Gone(candidates, _) => candidates.iter().collect(), + _ => Vec::new(), + }) + .collect(); + let key = "\"file_path\":"; + let mut rest = raw.as_str(); + while let Some(at) = rest.find(key) { + rest = rest[at + key.len()..].trim_start_matches(' '); + let Some(value) = rest.strip_prefix('"') else { + continue; + }; + let Some(end) = value.find('"') else { + break; + }; + let file = &value[..end]; + if file.contains('\\') { + return true; + } + let known = candidates + .iter() + .any(|root| inside(file, root).is_some_and(|p| repo.tree.contains_key(&p))); + if known { + return true; + } + rest = &value[end..]; + } + false +} + +/// A session that worked in this repository, and the worktrees it worked in. +struct Session { + id: String, + /// The worktree its records are filed under: where it ended up. + root: String, + roots: Vec, + turns: Vec, +} + +/// The transcripts that hold this repository's history: every local session +/// whose working directory was one of its worktrees — the checkout `root`, +/// any other git still lists, or one since removed, which is recognized by +/// what the session wrote there rather than by where it was. Worktrees live +/// wherever their creator put them, so no layout is assumed. +fn sessions_for(repo: &mut Repo) -> Vec { let mut found = Vec::new(); let projects = claude::projects_dir(None); let Ok(dirs) = fs::read_dir(&projects) else { return found; }; + let mut paths: Vec = Vec::new(); for dir in dirs.flatten() { let Ok(files) = fs::read_dir(dir.path()) else { continue; }; for file in files.flatten() { let path = file.path().to_string_lossy().into_owned(); - if !path.ends_with(".jsonl") { - continue; + if path.ends_with(".jsonl") { + paths.push(path); } - let Some(meta) = claude::read_session_meta(&path) else { - continue; + } + } + for path in paths { + let Some(meta) = claude::read_session_meta(&path) else { + continue; + }; + let places: Vec = std::iter::once(&meta.cwd) + .chain(&meta.other_cwds) + .map(|cwd| place(cwd, repo)) + .collect(); + if places.iter().all(|p| matches!(p, Place::Elsewhere)) { + continue; + } + let only_gone = places + .iter() + .all(|p| matches!(p, Place::Elsewhere | Place::Gone(_, None))); + if only_gone && !could_be_recognized(&path, &places, repo) { + continue; + } + let turns = turns_of(&path); + let mut roots: Vec = Vec::new(); + for place in places { + let root = match place { + Place::Root(root) => Some(root), + Place::Gone(candidates, live) => recognize(&candidates, &turns, repo).or(live), + Place::Elsewhere => None, }; - let within = std::iter::once(&meta.cwd) - .chain(&meta.other_cwds) - .any(|cwd| cwd == root || inside(cwd, root).is_some()); - if within { - found.push((meta.session_id, path)); + if let Some(root) = root { + if !roots.contains(&root) { + roots.push(root); + } } } + if roots.is_empty() { + continue; + } + found.push(Session { + id: meta.session_id, + root: roots[0].clone(), + roots, + turns, + }); } - found.sort(); + found.sort_by(|a, b| a.id.cmp(&b.id)); found } +/// `file` relative to the worktree it was written in: the most deeply nested +/// of this session's and the repository's that holds it. +fn relative_to(file: &str, roots: &[String], repo: &Repo) -> Option { + roots + .iter() + .chain(&repo.worktrees) + .filter(|root| inside(file, root).is_some()) + .max_by_key(|root| root.len()) + .and_then(|root| inside(file, root)) +} + #[derive(Default)] pub struct Backfilled { pub session: String, + /// The worktree the session worked in, which may no longer exist. + pub root: String, pub turns: usize, pub edit_lines: usize, pub commit_lines: usize, @@ -373,14 +812,18 @@ pub fn backfill(cwd: &str, store: Option<&dyn Store>) -> Vec { } else { HashMap::new() }; - let sessions: Vec<(String, Vec)> = transcripts_for(&root) - .into_iter() - .map(|(session, path)| (session, turns_of(&path))) - .collect(); + let mut repo = Repo::open(&root); + let found = sessions_for(&mut repo); + let mut sessions: Vec<(String, Vec)> = Vec::new(); + let mut places: Vec<(String, Vec)> = Vec::new(); + for s in found { + sessions.push((s.id, s.turns)); + places.push((s.root, s.roots)); + } let credited = credit(&sessions, &history, ¬es); let mut results = Vec::new(); - for (session, turns) in sessions { + for ((session, turns), (session_root, roots)) in sessions.into_iter().zip(places) { // Every line a tool edit in this session wrote: a commit's share is // what these don't already explain. let tool_lines: HashSet = turns @@ -392,12 +835,13 @@ pub fn backfill(cwd: &str, store: Option<&dyn Store>) -> Vec { let mut built = Vec::new(); let mut result = Backfilled { session: session.clone(), + root: session_root.clone(), ..Backfilled::default() }; for turn in turns { let mut files: Vec = Vec::new(); for (file, text) in &turn.edits { - let Some(relative) = inside(file, &root) else { + let Some(relative) = relative_to(file, &roots, &repo) else { continue; }; let lines: Vec = text.lines().map(attribution::line_hash).collect(); @@ -456,7 +900,7 @@ pub fn backfill(cwd: &str, store: Option<&dyn Store>) -> Vec { agent: AGENT.into(), session: session.clone(), project: project.clone(), - root: root.clone(), + root: session_root.clone(), turns: Vec::new(), }); // The hooks' own turns stand; an earlier backfill's are replaced. diff --git a/src/cli.rs b/src/cli.rs index dbf906f..9e29919 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1538,6 +1538,7 @@ pub fn command_backfill(argv: &[String]) -> Run { "turns" => turns, "sessions" => results.iter().map(|r| Value::Object(object! { "session" => r.session.as_str(), + "root" => r.root.as_str(), "turns" => r.turns, "editLines" => r.edit_lines, "commitLines" => r.commit_lines, diff --git a/src/git.rs b/src/git.rs index c1e5d7d..fd29089 100644 --- a/src/git.rs +++ b/src/git.rs @@ -29,6 +29,29 @@ pub fn git_unchecked(cwd: &str, args: &[&str]) -> Result { } fn run(cwd: &str, args: &[&str], stdin: Option<&str>) -> Result<(bool, String, String), GitError> { + let (status, stdout, stderr) = run_bytes(cwd, args, stdin)?; + Ok(( + status, + String::from_utf8_lossy(&stdout).into_owned(), + String::from_utf8_lossy(&stderr).into_owned(), + )) +} + +/// Git's stdout as bytes, for output whose lengths are counted in bytes +/// (`cat-file --batch`), which a lossy decode would shift. +pub fn git_bytes(cwd: &str, args: &[&str], stdin: Option<&str>) -> Result, GitError> { + let (status, stdout, stderr) = run_bytes(cwd, args, stdin)?; + if !status { + return Err(GitError(String::from_utf8_lossy(&stderr).trim().into())); + } + Ok(stdout) +} + +fn run_bytes( + cwd: &str, + args: &[&str], + stdin: Option<&str>, +) -> Result<(bool, Vec, Vec), GitError> { let mut command = Command::new("git"); command .arg("-C") @@ -44,17 +67,23 @@ fn run(cwd: &str, args: &[&str], stdin: Option<&str>) -> Result<(bool, String, S let mut child = command .spawn() .map_err(|error| GitError(error.to_string()))?; - if let Some(input) = stdin { - if let Some(mut pipe) = child.stdin.take() { - let _ = pipe.write_all(input.as_bytes()); + // Fed from a thread: git may fill its stdout before it has read all of + // stdin (`cat-file --batch` does), and a writer waiting on it would wait + // forever. + let feeder = match (stdin, child.stdin.take()) { + (Some(input), Some(mut pipe)) => { + let input = input.to_string(); + Some(std::thread::spawn(move || { + let _ = pipe.write_all(input.as_bytes()); + })) } - } + _ => None, + }; let output = child .wait_with_output() .map_err(|error| GitError(error.to_string()))?; - Ok(( - output.status.success(), - String::from_utf8_lossy(&output.stdout).into_owned(), - String::from_utf8_lossy(&output.stderr).into_owned(), - )) + if let Some(feeder) = feeder { + let _ = feeder.join(); + } + Ok((output.status.success(), output.stdout, output.stderr)) } diff --git a/tests/backfill.rs b/tests/backfill.rs index 6e85e1a..443c1b4 100644 --- a/tests/backfill.rs +++ b/tests/backfill.rs @@ -132,7 +132,13 @@ impl World { /// A transcript as Claude Code files it, from (record) lines. fn transcript(&self, session: &str, records: &[String]) -> PathBuf { - let encoded: String = s(&self.repo) + self.transcript_in(&self.repo, session, records) + } + + /// A transcript filed under `cwd`, as Claude Code files a session + /// started there. + fn transcript_in(&self, cwd: &Path, session: &str, records: &[String]) -> PathBuf { + let encoded: String = s(cwd) .chars() .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) .collect(); @@ -144,11 +150,15 @@ impl World { } fn prompt(&self, session: &str, uuid: &str, at: &str, text: &str) -> String { + self.prompt_in(&self.repo, session, uuid, at, text) + } + + fn prompt_in(&self, cwd: &Path, session: &str, uuid: &str, at: &str, text: &str) -> String { format!( r#"{{"type": "user", "uuid": "{}", "sessionId": "{}", "cwd": "{}", "timestamp": "{}", "message": {{"role": "user", "content": "{}"}}}}"#, uuid, session, - s(&self.repo), + s(cwd), at, text ) @@ -175,6 +185,46 @@ impl World { ) } + /// A successful `Write` of `text` to `file`, made from `cwd`. + fn write_call( + &self, + cwd: &Path, + session: &str, + n: usize, + file: &Path, + text: &str, + ) -> Vec { + let at = |s: usize| format!("2026-08-01T00:{:02}:{:02}Z", n, s); + let input = format!( + r#"{{"file_path": "{}", "content": {}}}"#, + s(file), + json::dumps(&Value::Str(text.to_string()), json::DEFAULT) + ); + let swap = |line: String| { + line.replace( + &format!("\"cwd\": \"{}\"", s(&self.repo)), + &format!("\"cwd\": \"{}\"", s(cwd)), + ) + }; + vec![ + swap(self.tool( + session, + &format!("a{}", n), + &at(1), + &format!("t{}", n), + "Write", + &input, + )), + swap(self.result( + session, + &format!("r{}", n), + &at(2), + &format!("t{}", n), + false, + )), + ] + } + fn result(&self, session: &str, uuid: &str, at: &str, id: &str, error: bool) -> String { format!( r#"{{"type": "user", "uuid": "{}", "sessionId": "{}", "cwd": "{}", "timestamp": "{}", "message": {{"role": "user", "content": [{{"type": "tool_result", "tool_use_id": "{}", "content": "ok", "is_error": {}}}]}}}}"#, @@ -437,3 +487,193 @@ fn blame_follows_a_file_through_a_rename() { vec![some("write it")] ); } + +fn sessions(result: &Value) -> Vec<(String, String)> { + result + .get("sessions") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|s| { + ( + s.get("session").unwrap().as_str().unwrap().to_string(), + s.get("root").unwrap().as_str().unwrap().to_string(), + ) + }) + .collect() +} + +const FEATURE: &str = "def configure_feature(options):\n threshold = options.get('threshold', 10)\n enabled_flags = [f for f in options['flags'] if f]\n return build_feature(threshold, enabled_flags)\n\ndef build_feature(threshold, flags):\n return {'threshold': threshold, 'flags': flags}\n"; + +#[test] +fn a_session_in_a_sibling_worktree_is_backfilled_from_the_main_checkout() { + let w = World::new(); + // Nowhere near a `-worktrees` directory: git's list is what counts. + let tree = w.root.join("elsewhere/feature-tree"); + w.git(&["worktree", "add", "-q", "-b", "feature", &s(&tree)]); + let file = tree.join("wt.py"); + fs::write(&file, FEATURE).unwrap(); + let mut records = + vec![w.prompt_in(&tree, ONE, "p1", "2026-08-01T00:00:00Z", "add the feature")]; + records.extend(w.write_call(&tree, ONE, 1, &file, FEATURE)); + w.transcript_in(&tree, ONE, &records); + w.git(&["-C", &s(&tree), "add", "wt.py"]); + w.git(&["-C", &s(&tree), "commit", "-q", "-m", "feature"]); + w.git(&["merge", "-q", "feature"]); + + let result = w.loch(&["backfill"], ""); + assert_eq!(sessions(&result), vec![(ONE.to_string(), s(&tree))]); + let lines = owners(&w.loch(&["blame", "wt.py"], "")); + assert!( + lines.iter().all(|l| l == &some("add the feature")), + "{:?}", + lines + ); +} + +#[test] +fn a_removed_worktree_is_recognized_by_what_it_wrote_and_its_paths_are_made_relative_to_it() { + let w = World::new(); + // A branch-shaped, nested path, and a session whose cwd is a + // subdirectory of it: the root has to be found, not assumed. + let tree = w.root.join("trees/feat/remove-me"); + w.git(&["worktree", "add", "-q", "-b", "feat/remove-me", &s(&tree)]); + let sub = tree.join("src"); + let file = sub.join("feature.py"); + fs::create_dir_all(&sub).unwrap(); + fs::write(&file, FEATURE).unwrap(); + let mut records = vec![w.prompt_in(&sub, ONE, "p1", "2026-08-01T00:00:00Z", "build it")]; + records.extend(w.write_call(&sub, ONE, 1, &file, FEATURE)); + w.transcript_in(&tree, ONE, &records); + w.git(&["-C", &s(&tree), "add", "-A"]); + w.git(&["-C", &s(&tree), "commit", "-q", "-m", "feature"]); + // Squash-merged, then the worktree and its branch are gone. + w.git(&["merge", "-q", "--squash", "feat/remove-me"]); + w.git(&["commit", "-q", "-m", "feature (#12)"]); + w.git(&["worktree", "remove", "--force", &s(&tree)]); + w.git(&["branch", "-q", "-D", "feat/remove-me"]); + assert!(!tree.exists()); + + let result = w.loch(&["backfill"], ""); + assert_eq!(sessions(&result), vec![(ONE.to_string(), s(&tree))]); + let record = json::loads( + &fs::read_to_string( + w.home + .join(".loch/edits/claude-code") + .join(format!("{}.json", ONE)), + ) + .unwrap(), + ) + .unwrap(); + let text = json::dumps(&record, json::DEFAULT); + assert!(text.contains("\"src/feature.py\""), "{}", text); + let lines = owners(&w.loch(&["blame", "src/feature.py"], "")); + assert!(lines.iter().all(|l| l == &some("build it")), "{:?}", lines); +} + +#[test] +fn another_repository_s_sessions_are_not_picked_up() { + let w = World::new(); + w.write("shared.py", FEATURE); + w.git(&["add", "shared.py"]); + w.git(&["commit", "-q", "-m", "shared"]); + + // A live checkout of an unrelated repository, writing the very same text + // at the very same path: it is that repository's, whatever it wrote. + let other = w.root.join("other"); + fs::create_dir_all(&other).unwrap(); + w.git(&["-C", &s(&other), "init", "-q", "-b", "main"]); + let mut records = vec![w.prompt_in(&other, ONE, "p1", "2026-08-01T00:00:00Z", "other repo")]; + records.extend(w.write_call(&other, ONE, 1, &other.join("shared.py"), FEATURE)); + w.transcript_in(&other, ONE, &records); + + // A directory that is gone, which wrote a path this repository has but + // none of the text it holds there. + let gone = w.root.join("gone/project"); + let unrelated = + "print('an entirely different program')\nraise SystemExit('nothing in common here')\n"; + let mut records = vec![w.prompt_in(&gone, TWO, "p1", "2026-08-01T00:00:00Z", "gone repo")]; + records.extend(w.write_call(&gone, TWO, 1, &gone.join("shared.py"), unrelated)); + w.transcript_in(&gone, TWO, &records); + + let result = w.loch(&["backfill"], ""); + assert_eq!(sessions(&result), vec![]); + assert_eq!( + owners(&w.loch(&["blame", "shared.py"], "")), + vec![None; FEATURE.lines().count()] + ); +} + +#[test] +fn a_removed_worktree_nested_inside_the_main_checkout_is_recognized() { + let w = World::new(); + // Claude Code's own layout: the gone directory's nearest checkout is the + // main one, which must be its floor rather than its root. + let tree = w.repo.join(".claude/worktrees/nested"); + w.git(&["worktree", "add", "-q", "-b", "nested", &s(&tree)]); + let file = tree.join("nested.py"); + fs::write(&file, FEATURE).unwrap(); + let mut records = vec![w.prompt_in(&tree, ONE, "p1", "2026-08-01T00:00:00Z", "nest it")]; + records.extend(w.write_call(&tree, ONE, 1, &file, FEATURE)); + w.transcript_in(&tree, ONE, &records); + w.git(&["-C", &s(&tree), "add", "nested.py"]); + w.git(&["-C", &s(&tree), "commit", "-q", "-m", "nested"]); + w.git(&["merge", "-q", "nested"]); + w.git(&["worktree", "remove", "--force", &s(&tree)]); + w.git(&["branch", "-q", "-D", "nested"]); + assert!(!tree.exists()); + + let result = w.loch(&["backfill"], ""); + assert_eq!(sessions(&result), vec![(ONE.to_string(), s(&tree))]); + let lines = owners(&w.loch(&["blame", "nested.py"], "")); + assert!(lines.iter().all(|l| l == &some("nest it")), "{:?}", lines); +} + +#[test] +fn two_roots_with_equal_evidence_decide_nothing() { + let w = World::new(); + // The repository holds the same text at `f.py` and `a/f.py`, so a gone + // `/a/f.py` fits a root at `` exactly as well as one at `/a`. + w.write("f.py", FEATURE); + w.write("a/f.py", FEATURE); + w.git(&["add", "-A"]); + w.git(&["commit", "-q", "-m", "twice"]); + let gone = w.root.join("gone/x/a"); + let mut records = vec![w.prompt_in(&gone, ONE, "p1", "2026-08-01T00:00:00Z", "which root")]; + records.extend(w.write_call(&gone, ONE, 1, &gone.join("f.py"), FEATURE)); + w.transcript_in(&gone, ONE, &records); + + assert_eq!(sessions(&w.loch(&["backfill"], "")), vec![]); + // With one of the two gone, the same evidence decides. + w.git(&["rm", "-q", "f.py"]); + w.git(&["commit", "-q", "-m", "once"]); + assert_eq!( + sessions(&w.loch(&["backfill"], "")), + vec![(ONE.to_string(), s(&w.root.join("gone/x")))] + ); +} + +#[test] +fn a_directory_that_still_exists_outside_any_checkout_is_not_a_former_worktree() { + let w = World::new(); + w.write("shared.py", FEATURE); + w.git(&["add", "shared.py"]); + w.git(&["commit", "-q", "-m", "shared"]); + // A plain copy of the text, in a directory that is there and is no + // checkout: it is what it is, however much it matches. + let scratch = w.root.join("scratch"); + fs::create_dir_all(&scratch).unwrap(); + fs::write(scratch.join("shared.py"), FEATURE).unwrap(); + let mut records = vec![w.prompt_in(&scratch, ONE, "p1", "2026-08-01T00:00:00Z", "scratch")]; + records.extend(w.write_call(&scratch, ONE, 1, &scratch.join("shared.py"), FEATURE)); + w.transcript_in(&scratch, ONE, &records); + + assert_eq!(sessions(&w.loch(&["backfill"], "")), vec![]); + // Gone, the same session would have been a former worktree. + fs::remove_dir_all(&scratch).unwrap(); + assert_eq!( + sessions(&w.loch(&["backfill"], "")), + vec![(ONE.to_string(), s(&scratch))] + ); +}