diff --git a/CLAUDE.md b/CLAUDE.md index 73795d3..1ac3a53 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -98,6 +98,15 @@ requirements fixed the rest of the design: `SessionEnd`, the third hook — closes it first, marked `interrupted`. Every state and record file is written aside and renamed, so a hook killed mid-write leaves the old file or the new one, never half of either. +- **Hooks never touch the network.** They write the edit record, its file + index and a copy of the transcript to the local store (`~/.loch/store`, + `store::local_store`), whatever `LOCH_STORE` says, and so do `backfill`'s + records. `blame`, `log` and `ask` read only that store. Publishing from the + hook was the first design, and a remote that didn't answer held every + `Stop` for the S3 timeout (`end` took 8.3s against an unreachable bucket), + while Codex kills a `SessionEnd` hook at 3s, so the last turn's record + never left the machine. Getting records to and from a remote is an explicit + step, like git's push and fetch. `hooks_never_wait_on_a_remote` pins it. - **No background process.** Snapshots are taken on demand with a stat cache, the way git's index works: files whose size and mtime are unchanged aren't read again. A harness with no hooks gets coarser attribution, never a @@ -254,6 +263,100 @@ and unpacking. That is what makes `reindex` a repair command and what makes a half-failed `save` leave a recoverable store rather than a corrupt one. Nothing may end up knowable only from the index. +**Push and pull, git style: `save` is `commit`.** The local store +(`~/.loch/store`) is where everything is recorded first, bundles included. +Named remotes (`loch remote`, kept in `~/.loch/config`) are where `push` sends and `pull` fetches from, as git's +remotes are. `blame`, `log` and `ask` read only the local store, so a +teammate's turns arrive by `pull`, never by a read that waits on the network. +- **What moves.** `push` sends the current project's bundles with their + branch entries, and its sessions' edit records, file index and transcripts + (`--all` for every project's). A bundle belongs to a project if any session + in it ran there: sending every bundle on the machine, as the first cut did, + put one client's transcripts on another's remote. A bundle whose sessions' + directories are gone from this machine can't be placed and goes only with + `--all`. Bundles were redacted by `save` and go as they are, so a ref is the + same everywhere. Transcripts are kept verbatim locally and redacted on the + way out. One in which a secret survives redaction is skipped and named in + `redactionFailed`, the rest still goes, and the push ends `redaction-failed`. + Redaction is deterministic, so failing the whole push would block every + later one. Edit records hold line hashes, and their `prompt` was redacted + when recorded. `pull` fetches records with their transcripts, scoped through + the remote's file index, so a session whose turns edited no file isn't + pulled; it has nothing to blame anyway. Bundles are not pulled. +- **Edit records merge, they are never replaced.** A session restored under + its own id and resumed is recorded by two machines, and a record is one + mutable object per session. Writing it whole erased the other machine's + turns, locally (the hook started from its working copy alone, which `pull` + never fills) and on the remote (the next push). So `EditRecord::merge` + takes both copies' turns, a turn known by its prompt's id (else by when it + ran), the later stop winning. The hook merges the working copy with the + store's, `pull` merges into the local copy, and `push` merges the remote's + copy in before it uploads and keeps the merge here. Two pushes of one session + at the same moment can still drop one's new turns from the remote, until + that machine's record next changes and its push merges them back. The + other side of merging: a turn removed on one machine (a `backfill` re-run + dropping a contested backfilled turn) comes back from any other copy, and + only a tombstone removes anything for good. That is the trade taken, since + a lost turn is silent and a resurrected one is visible. + Transcripts are still one object per key, last writer wins. Claude's keys + name the project directory, so a session resumed in another checkout gets + its own key, but a Codex rollout's name doesn't change on restore. +- **What has been sent is remembered here, not there.** `~/.loch/pushed/.json` maps each key to the hash of the local bytes last sent, so the + remote stays a set of independent objects (no manifest, per "No single + index object") and a second push sends only what changed. Losing that file + only re-sends. A stale one is the silent case: a remote emptied or replaced + by anything but `delete --remote` makes every push say it is up to date. + `push --force` ignores the markers. Push sends a bundle before its entries + and a record before its file index, the order `save` and the hooks keep, so + a push cut short leaves what `reindex` can repair. +- **A delete on a remote stays deleted.** A tombstone (`tombstones/bundle/ + `, `tombstones/session//`) is one new key per delete and + holds no content. Every push reads them first and sends nothing they cover, + so a teammate's copy can't bring a deleted session back. It reads them + again afterwards and withdraws what a delete racing it covered, which + closes the race in practice but not atomically. Every pull copies them here + and forgets loch's copies of what they cover, but never an agent's + transcript in its own directory. Being able to delete is why loch uses + object storage, so this is stricter than git on purpose. Whether a local + tombstone should hold for every remote is to be tested against use. +- **The store commands, by git's answer.** `save` writes the bundle here, + and `save --push []` sends that bundle alone afterwards. A push + failing after the save is reported with the ref, since the bundle exists. + `restore` looks here first, then fetches the one bundle from the remote + (`fetchedFrom`), checks that its bytes hash to the ref, and keeps it, as + git keeps what it fetched. Content addressing is what makes any remote's + copy as good as another's. `list --saved` is this machine's bundles, + `list --remote` is `ls-remote`, and plain `list` is still the live + sessions. `delete ` is local. With `--remote` it writes the tombstone + on the remote first (so a racing push sees it), deletes there, and + tombstones and deletes here too. `delete --session ` does the same for + a session's record, file index and transcripts, which is the delete that + matters, since transcripts are what leak. A ref in neither place is + `bundle-not-found`, and no tombstone is written for a typo. `reindex` is + per store. `--store ` still works everywhere, meaning `--remote ` + (`save --push ` for `save`), which is the meaning callers had. +- **The one silent change, made loud.** A caller with `LOCH_STORE` set that + runs a plain `save` used to upload. Now it gets `ok: true` and a bundle on + this machine only, so it is warned (stderr in text, `"deprecated": + "LOCH_STORE"` in JSON), and `schema` is 3. The Harness "send worktree to + remote" flow needs `save --push` (or a push to the destination as a + remote), and `restore` there finds the bundle by fetching it. +- **A remote's keys are someone else's input.** `FileStore` refuses a key + with an empty, `.` or `..` segment, and `pull` takes a record only for an + agent this build knows, an id `is_safe_session_id` accepts, and contents + that name the session and project its key does. Anything else is counted + as `refused` and never written. +- **The remote is never guessed.** A command names a remote or a URI, else + `LOCH_REMOTE`, else `LOCH_STORE` (its old meaning, with a warning on + stderr in text mode and `"deprecated": "LOCH_STORE"` in JSON), else + `origin`, else the only remote. Several remotes and no `origin` is + `ambiguous-remote`, since a push to the wrong one publishes transcripts. A + URI scheme the store doesn't know is `invalid-uri`: `create_store` reads + anything else as a relative path, so `ssh://host` would have become a + local directory a push succeeded into. The local store itself is refused + as a remote, compared resolved, so a symlink to it is refused too. + ## Empirical findings about Claude Code's storage These were verified by experiment, not documentation, and are not stable @@ -474,7 +577,7 @@ binary on top of it. The toolchain is pinned in `rust-toolchain.toml`. 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 +│ # blame/log/ask/backfill/push/pull/remote/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 @@ -492,7 +595,9 @@ src/ ├── output.rs # result envelope, the two renderers, structured failures ├── redact.rs # secret scrubbing, applied on save before packing ├── rewrite.rs # path rewriting (the load-bearing logic) -├── store.rs # Store interface + local-fs backend +├── store.rs # Store interface + local-fs backend, the local store +├── remote.rs # named remotes in ~/.loch/config, and which one a command means +├── sync.rs # push and pull: markers of what was sent, tombstones ├── s3.rs # the S3-compatible backend, SigV4 by hand ├── json.rs # JSON reading and writing, RFC 8785 canonical form ├── argparse.rs # command-line parsing, usage errors and -h @@ -796,12 +901,14 @@ So every command takes `--json`, accepted either before or after the subcommand, and answers with exactly one document on stdout: ```json -{"schema": 2, "ok": true, "command": "save", "ref": "...", "bytes": 331, ...} +{"schema": 3, "ok": true, "command": "save", "ref": "...", "bytes": 331, ...} ``` `schema` is the envelope version. It exists so a consumer can detect a format change it doesn't understand; bump it when a field changes meaning or -disappears, not when one is added. +disappears, not when one is added. It went to 3 when `save` stopped writing to +`LOCH_STORE` (its `store` names this machine's store now) and `blame`, `log`, +`ask` and `backfill` lost `--store`. **Built once per command, rendered twice.** Each `command_*` returns a `Result` — the payload, the prose, and any stderr warnings — and `main()` @@ -812,7 +919,7 @@ prose that describes it will rot the first time someone edits the prose. **Failures are documents, on stdout.** ```json -{"schema": 2, "ok": false, "command": "restore", "code": "nothing-restored", +{"schema": 3, "ok": false, "command": "restore", "code": "nothing-restored", "error": "nothing restored", "sessions": [{"status": "skipped", ...}]} ``` @@ -831,7 +938,7 @@ never a code. The set today: | `redaction-failed` | a secret survived redaction; nothing was uploaded | | `transcript-unreadable` | `save` found a transcript that isn't UTF-8; nothing was uploaded | | `missing-ref` | `restore`/`delete` called without a ref | -| `bundle-not-found` | the store answered and the ref isn't there | +| `bundle-not-found` | the store answered and the ref isn't there (for `restore`, not here and not on the remote) | | `store-unreachable` | the store didn't answer | | `bundle-unreadable` | the bytes arrived and won't unpack | | `nothing-restored` | every session in the bundle was skipped | @@ -842,6 +949,13 @@ never a code. The set today: | `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 | +| `session-not-found` | `delete --session` on a session with no record here (or on the remote) | +| `no-remote` | a command that needs a remote named none, and none is configured | +| `ambiguous-remote` | several remotes are configured, none is `origin`, and none was named | +| `unknown-remote` | no remote by that name | +| `remote-exists` | `remote add` of a name already taken | +| `invalid-uri` | a remote URI no store understands, or the local store itself | +| `config-unreadable` | `~/.loch/config` exists and won't parse (it is never overwritten) | | `unknown-command` | no such subcommand | | `usage` | argparse rejected the arguments (exit status 2) | | `internal` | an unexpected exception | @@ -1117,7 +1231,7 @@ kinds don't justify an async runtime and several MB. The signer is pinned to AWS's two published examples (a header-signed GET and a signed query string). Listings send `encoding-type=url` and decode the keys, so a key with any character survives the XML. A store that doesn't answer fails -after 20s rather than holding a turn. The tests that need an endpoint are +after 20s. No hook ever waits on that, since hooks write only locally. The tests that need an endpoint are `#[ignore]`d in `tests/store.rs` and `tests/index.rs`, and read it from `LOCH_TEST_S3_ENDPOINT` (bucket `LOCH_TEST_S3_BUCKET`, default `sessions`): `moto_server` or MinIO will do. moto's verifier rejects correct signatures on @@ -1222,7 +1336,7 @@ release exists yet. generator are attributed to the turn that ran them, with no edit tool involved. - **History rewrites don't matter.** After a squash, a fresh clone with an - empty HOME and only the store in common blames the same lines to the same + empty HOME and only a copy of the store blames the same lines to the same turns, and finds the transcripts in the store. - **A person's text isn't the agent's.** A line someone later rewrote is unattributed, a re-indented one keeps its turn, and a person's lone `}` is diff --git a/src/attribution.rs b/src/attribution.rs index 49b473c..c01fe04 100644 --- a/src/attribution.rs +++ b/src/attribution.rs @@ -260,6 +260,33 @@ impl EditRecord { }) } + /// Both copies' turns, each once, oldest first. A session restored under its + /// own id and resumed elsewhere is recorded by two machines, so neither copy + /// may replace the other: a whole-record write would erase the turns only the + /// other copy has. A turn is known by its prompt's id, else by when it ran; + /// where both copies hold one, the one that ended later wins, since Claude + /// Code can stop twice for one prompt and the second stop's record is the + /// whole turn. + pub fn merge(&self, other: &EditRecord) -> EditRecord { + let identity = |turn: &TurnRecord| match &turn.prompt_uuid { + Some(id) => (Some(id.clone()), None, None), + None => (None, turn.started.clone(), Some(turn.ended.clone())), + }; + let mut turns: Vec = Vec::new(); + for turn in self.turns.iter().chain(other.turns.iter()) { + match turns.iter_mut().find(|t| identity(t) == identity(turn)) { + Some(have) if have.ended < turn.ended => *have = turn.clone(), + Some(_) => {} + None => turns.push(turn.clone()), + } + } + turns.sort_by(|a, b| a.ended.cmp(&b.ended)); + EditRecord { + turns, + ..self.clone() + } + } + /// Every path any turn changed, each once. pub fn paths(&self) -> Vec { let mut paths: Vec = self @@ -316,6 +343,12 @@ pub fn load_local(agent: &str, session: &str) -> Option { EditRecord::from_json(&json::loads(&text).ok()?) } +/// The record as `store` holds it. +pub fn load_stored(store: &dyn Store, agent: &str, session: &str) -> Option { + let data = store.get(&edits_key(agent, session)).ok()?; + EditRecord::from_json(&json::loads(&String::from_utf8(data).ok()?).ok()?) +} + pub fn save_local(record: &EditRecord) -> std::io::Result<()> { let path = local_path(&record.agent, &record.session); snapshot::write_atomically( @@ -355,22 +388,58 @@ fn local_records() -> Vec { pub fn publish(store: &dyn Store, record: &EditRecord) -> Result<(), StoreError> { let body = json::dumps(&record.to_json(), json::COMPACT_UNICODE); store.put(&edits_key(&record.agent, &record.session), body.as_bytes())?; - for path in record.paths() { - let key = index::index_key( - FILE, - Some(&file_value(&record.project, &path)), - &record.session, - ); - let entry = - object! {"agent" => record.agent.as_str(), "session" => record.session.as_str()}; - store.put( - &key, - json::dumps(&Value::Object(entry), json::DEFAULT).as_bytes(), - )?; + for (key, entry) in file_entries(record) { + store.put(&key, &entry)?; } Ok(()) } +/// The file index's entry for each path a record changed, keyed as stored. +pub fn file_entries(record: &EditRecord) -> Vec<(String, Vec)> { + let entry = object! {"agent" => record.agent.as_str(), "session" => record.session.as_str()}; + let body = json::dumps(&Value::Object(entry), json::DEFAULT).into_bytes(); + record + .paths() + .iter() + .map(|path| { + ( + index::index_key( + FILE, + Some(&file_value(&record.project, path)), + &record.session, + ), + body.clone(), + ) + }) + .collect() +} + +/// Forgets a session on this machine: the hooks' working copy of its record +/// and the local store's copy, with its file index. `pull` does this for a +/// session a remote has tombstoned. +/// Returns whether there was anything to forget. +pub fn forget_local(store: &dyn Store, agent: &str, session: &str) -> Result { + let key = edits_key(agent, session); + let stored = store + .get(&key) + .ok() + .and_then(|data| String::from_utf8(data).ok()) + .and_then(|text| json::loads(&text).ok()) + .and_then(|v| EditRecord::from_json(&v)); + let working = load_local(agent, session); + if stored.is_none() && working.is_none() { + return Ok(false); + } + for record in stored.iter().chain(working.iter()) { + for (entry, _) in file_entries(record) { + store.delete(&entry)?; + } + } + store.delete(&key)?; + let _ = fs::remove_file(local_path(agent, session)); + Ok(true) +} + /// Every edit record that changed `path` in `project`: the store's, by its /// file index, and this machine's own, which may hold turns the store hasn't /// been sent yet. Where both have a session, the one with more turns wins. @@ -597,4 +666,30 @@ mod tests { let records = vec![record(vec![("1", vec!["return compute(x)"])])]; assert!(attribute(" return compute(x)\n", &["f.py".into()], &records)[0].is_some()); } + + #[test] + fn merging_keeps_each_turn_once_and_the_later_stop_of_one_prompt() { + let turn = |id: &str, ended: &str| TurnRecord { + prompt_uuid: Some(id.into()), + end_uuid: None, + started: None, + ended: ended.into(), + prompt: None, + interrupted: false, + backfilled: false, + files: Vec::new(), + }; + let mut mine = record(vec![]); + mine.turns = vec![turn("a", "1"), turn("b", "2")]; + let mut theirs = record(vec![]); + theirs.turns = vec![turn("a", "1"), turn("b", "3"), turn("c", "4")]; + let merged = mine.merge(&theirs); + let ended: Vec<(&str, &str)> = merged + .turns + .iter() + .map(|t| (t.prompt_uuid.as_deref().unwrap(), t.ended.as_str())) + .collect(); + assert_eq!(ended, vec![("a", "1"), ("b", "3"), ("c", "4")]); + assert_eq!(theirs.merge(&mine).turns, merged.turns, "either way round"); + } } diff --git a/src/cli.rs b/src/cli.rs index 0c0397e..9c34256 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -15,9 +15,11 @@ use crate::object; use crate::output::{fail, CommandError, Outcome, JSON_FLAG}; use crate::py; use crate::redact; +use crate::remote::{self, Remote, RemoteError}; use crate::rewrite::{self, ForeignCwd, RewriteSpec}; use crate::snapshot; -use crate::store::{create_store, resolve_store_uri, Store, StoreError}; +use crate::store::{Store, StoreError}; +use crate::sync::{self, SyncError}; use crate::sys; use crate::trace::{self, Link, Resolver, TraceError}; use std::collections::HashMap; @@ -96,10 +98,6 @@ fn index_error(description: &str, error: IndexError) -> Failure { } } -fn open_store(uri: Option<&str>) -> std::result::Result, Failure> { - create_store(&resolve_store_uri(uri)).map_err(|e| Failure::Internal(e.0)) -} - pub fn format_bytes(count: u64) -> String { if count < 1024 { format!("{}B", count) @@ -257,13 +255,20 @@ pub fn command_list(argv: &[String]) -> Run { p.option("--cwd") .option("--branch") .option("--agent") - .flag("--remote", None) + .option_optional("--remote", "", "NAME") + .flag("--saved", None) .flag("--all", Some("every")) .option("--store"); let args = p.parse(argv)?; - let (cwd, branch, store) = (args.str("cwd"), args.str("branch"), args.str("store")); - if args.flag("remote") || args.flag("every") || store.is_some() { - return list_remote(cwd, branch, store, args.flag("every")); + let (cwd, branch) = (args.str("cwd"), args.str("branch")); + let every = args.flag("every"); + if let Some(asked) = remote_asked(&args) { + let (remote, store) = open_remote(asked.as_deref())?; + return list_bundles(cwd, branch, store.as_ref(), Some(&remote), every); + } + if args.flag("saved") || every { + let local = crate::store::local_store(); + return list_bundles(cwd, branch, &local, None, every); } let agents = agents_arg(args.str("agent").as_deref())?; let (cwd, sessions) = collect(&agents, cwd.as_deref(), branch.as_deref(), None); @@ -280,6 +285,7 @@ pub fn command_list(argv: &[String]) -> Run { "list", object! { "remote" => false, + "saved" => false, "cwd" => cwd.as_str(), "branch" => Value::opt_str(branch.as_deref()), "sessions" => sessions.iter().map(session_payload).collect::>(), @@ -294,13 +300,15 @@ pub fn current_branch(cwd: &str) -> Option { (!branch.is_empty()).then(|| branch.to_string()) } -fn list_remote( +/// Saved bundles, by their branch entries: this machine's (`--saved`), or a +/// remote's (`--remote`, git's `ls-remote`). +fn list_bundles( cwd: Option, branch: Option, - uri: Option, + store: &dyn Store, + remote: Option<&Remote>, every: bool, ) -> Run { - let store = open_store(uri.as_deref())?; let cwd = resolve_cwd(&cwd.unwrap_or_else(sys::getcwd)); let branch = branch.or_else(|| current_branch(&cwd)); let prefix = if every { @@ -308,8 +316,8 @@ fn list_remote( } else { index::value_prefix(BRANCH, branch.as_deref()) }; - let described = store.describe(); - let entries = index::load_entries(store.as_ref(), &prefix) + let described = remote.map_or_else(|| store.describe(), Remote::label); + let entries = index::load_entries(store, &prefix) .map_err(|e| index_error(&format!("could not list {}", described), e))?; let mut refs: Vec<&str> = entries.iter().map(|e| e.ref_.as_str()).collect(); refs.sort(); @@ -338,18 +346,26 @@ fn list_remote( } text }; - Ok(Outcome::with( - "list", - object! { - "remote" => true, - "store" => described.as_str(), - "all" => every, - "branch" => if every { Value::Null } else { Value::opt_str(branch.as_deref()) }, - "bundles" => refs.len(), - "entries" => entries.iter().map(entry_payload).collect::>(), - }, - text, - )) + let mut payload = object! { + "remote" => remote.is_some(), + "saved" => remote.is_none(), + "store" => store.describe(), + "all" => every, + "branch" => if every { Value::Null } else { Value::opt_str(branch.as_deref()) }, + "bundles" => refs.len(), + "entries" => entries.iter().map(entry_payload).collect::>(), + }; + let mut outcome_warnings = Vec::new(); + if let Some(remote) = remote { + payload.insert("remoteName".into(), Value::opt_str(remote.name.as_deref())); + if remote.deprecated { + payload.insert("deprecated".into(), Value::str("LOCH_STORE")); + } + outcome_warnings.extend(remote.warning()); + } + let mut outcome = Outcome::with("list", payload, text); + outcome.warnings = outcome_warnings; + Ok(outcome) } // -- save --------------------------------------------------------------------- @@ -369,8 +385,14 @@ pub fn command_save(argv: &[String]) -> Run { .option("--branch") .option("--session") .option("--agent") + .option_optional("--push", "", "REMOTE") .option("--store"); let args = p.parse(argv)?; + // `--store ` is the older spelling of `--push `. + let push_to: Option> = match args.str("store").filter(|s| !s.is_empty()) { + Some(uri) => Some(Some(uri)), + None => args.str("push").map(|r| Some(r).filter(|r| !r.is_empty())), + }; let agents = agents_arg(args.str("agent").as_deref())?; let (cwd, sessions) = collect( &agents, @@ -439,14 +461,50 @@ pub fn command_save(argv: &[String]) -> Run { bundle.version = bundle.required_version(); let packed = bundle::pack_bundle(&bundle).map_err(|e| Failure::Internal(e.0))?; let ref_ = bundle::bundle_ref(&packed); - let store = open_store(args.str("store").as_deref())?; + // Resolved before anything is written, so a remote that can't be named + // fails the save rather than leaving a bundle it didn't ask for. + let remote = match &push_to { + Some(asked) => Some(open_remote(asked.as_deref())?), + None => None, + }; + let store = crate::store::local_store(); let described = format!("could not write to {}", store.describe()); // Bundle first: an index entry is derived from it. store .put(&index::bundle_key(&ref_), &packed) .map_err(|e| store_error(&described, e))?; - let entries = index::index_bundle(store.as_ref(), &bundle, &ref_, packed.len()) + let entries = index::index_bundle(&store, &bundle, &ref_, packed.len()) .map_err(|e| store_error(&described, e))?; + let pushed = match &remote { + Some((remote, opened)) => { + let mut report = sync::PushReport::new(false); + let result = sync::push( + &store, + opened.as_ref(), + &remote.uri, + sync::Scope::Bundle(&ref_), + &mut report, + ); + let summary = with_remote(report.payload(), remote); + if let Err(error) = result { + return Err(match sync_error(remote, error) { + Failure::Error(mut failure) => { + failure.message = + format!("saved {} on this machine, but {}", ref_, failure.message); + failure.payload = object! { + "ref" => ref_.as_str(), + "store" => store.describe(), + "pushed" => Value::Object(summary), + }; + Failure::Error(failure) + } + other => other, + }); + } + Some((remote, report, summary)) + } + None => None, + }; let total: usize = redactions.iter().map(|c| c.values().sum::()).sum(); let mut text = String::new(); @@ -485,11 +543,37 @@ pub fn command_save(argv: &[String]) -> Run { store.describe() )); text.push_str(&format!("indexed under {}\n", indexed.join(", "))); + match &pushed { + Some((remote, report, _)) if report.tombstoned > 0 => text.push_str(&format!( + "not pushed: {} has deleted this bundle\n", + remote.label() + )), + Some((remote, report, _)) if report.total() == 0 => { + text.push_str(&format!("{} already has it\n", remote.label())) + } + Some((remote, _, _)) => text.push_str(&format!("pushed to {}\n", remote.label())), + None => {} + } text.push_str(&format!("ref {}\n", ref_)); + // A caller that set LOCH_STORE expected `save` to upload, as it did + // before remotes; answering `ok` and keeping the bundle here would be the + // silent failure, so it is told. + let mut warnings = Vec::new(); + let stale_store = push_to.is_none() && std::env::var_os("LOCH_STORE").is_some(); + if stale_store { + warnings.push( + "LOCH_STORE is set, but save keeps bundles on this machine now; `loch save --push` or `loch push` sends them\n" + .to_string(), + ); + } - Ok(Outcome::with( + let mut outcome = Outcome::with( "save", object! { + "pushed" => match &pushed { + Some((_, _, summary)) => Value::Object(summary.clone()), + None => Value::Null, + }, "ref" => ref_.as_str(), "bytes" => packed.len(), "store" => store.describe(), @@ -515,7 +599,17 @@ pub fn command_save(argv: &[String]) -> Run { })).collect::>(), }, text, - )) + ); + if stale_store { + outcome + .payload + .insert("deprecated".into(), Value::str("LOCH_STORE")); + } + if let Some((remote, _, _)) = &pushed { + warnings.extend(remote.warning()); + } + outcome.warnings = warnings; + Ok(outcome) } // -- restore ------------------------------------------------------------------ @@ -555,23 +649,54 @@ pub fn command_restore(argv: &[String]) -> Run { let mut p = parser("restore"); p.positional("ref", Nargs::Optional) .option("--into") + .option_optional("--remote", "", "NAME") .option("--store") .flag("--force", None) .flag("--new-id", Some("new_id")); let args = p.parse(argv)?; - let Some(ref_) = args.str("ref").filter(|r| !r.is_empty()) else { + let (ref_, asked) = ref_and_remote(&args); + let Some(ref_) = ref_ else { return err("missing-ref", "restore requires a bundle ref"); }; - let store = open_store(args.str("store").as_deref())?; - let described = format!("could not read {} from {}", ref_, store.describe()); - let packed = store - .get(&index::bundle_key(&ref_)) - .map_err(|e| store_error(&described, e))?; + let local = crate::store::local_store(); + let (packed, fetched) = match local.get(&index::bundle_key(&ref_)) { + Ok(packed) => (packed, None), + Err(StoreError::Missing(_)) => { + let (remote, packed) = fetch_bundle(&ref_, asked)?; + (packed, Some(remote)) + } + Err(e) => { + return Err(store_error( + &format!("could not read {} from {}", ref_, local.describe()), + e, + )) + } + }; + let described = format!( + "could not read {} from {}", + ref_, + fetched + .as_ref() + .map_or_else(|| local.describe(), Remote::label) + ); let bundle = match bundle::unpack_bundle(&packed) { Ok(bundle) => bundle, // Fetched fine and still unusable: neither absent nor unreachable. Err(error) => return err("bundle-unreadable", format!("{}: {}", described, error)), }; + // Kept, as git keeps what it fetched: the bytes hash to the ref, so this + // copy is the bundle, whichever remote it came from. + if fetched.is_some() { + let cached = local + .put(&index::bundle_key(&ref_), &packed) + .and_then(|()| index::index_bundle(&local, &bundle, &ref_, packed.len()).map(|_| ())); + if let Err(e) = cached { + return Err(store_error( + &format!("could not keep {} in {}", ref_, local.describe()), + e, + )); + } + } let target_cwd = resolve_cwd(&args.str("into").unwrap_or_else(sys::getcwd)); let target_home = home_dir(); let mut restored = Vec::new(); @@ -652,7 +777,9 @@ pub fn command_restore(argv: &[String]) -> Run { let payload = object! { "ref" => ref_.as_str(), - "store" => store.describe(), + "store" => local.describe(), + // Where the bundle came from: here, or fetched from a remote. + "fetchedFrom" => fetched.as_ref().map_or(Value::Null, Remote::payload), "cwd" => target_cwd.as_str(), "origin" => object! { "hostname" => bundle.origin.hostname.as_str(), @@ -678,6 +805,9 @@ pub fn command_restore(argv: &[String]) -> Run { } }) .collect(); + if let Some(remote) = &fetched { + warnings.extend(remote.warning()); + } for session in &restored { for (origin, foreign) in &session.foreign { warnings.push(format!( @@ -735,35 +865,248 @@ pub fn command_restore(argv: &[String]) -> Run { pub fn command_delete(argv: &[String]) -> Run { let mut p = parser("delete"); - p.positional("ref", Nargs::Optional).option("--store"); + p.positional("ref", Nargs::Optional) + .option("--session") + .option("--agent") + .option_optional("--remote", "", "NAME") + .option("--store"); let args = p.parse(argv)?; - let Some(ref_) = args.str("ref").filter(|r| !r.is_empty()) else { - return err("missing-ref", "delete requires a bundle ref"); + let (ref_, asked) = ref_and_remote(&args); + let session = args.str("session").filter(|s| !s.is_empty()); + let local = crate::store::local_store(); + let remote = match &asked { + Some(asked) => Some(open_remote(asked.as_deref())?), + None => None, }; - let store = open_store(args.str("store").as_deref())?; - let removed = index::delete_bundle(store.as_ref(), &ref_).map_err(|e| { - index_error( - &format!("could not delete {} from {}", ref_, store.describe()), - e, - ) - })?; - let mut text: String = removed + let deleted = match (ref_, session) { + (Some(_), Some(_)) => { + let mut error = CommandError::new("usage", "delete takes a ref or --session, not both"); + error.exit_status = 2; + return Err(Failure::Error(error)); + } + (None, None) => return err("missing-ref", "delete requires a bundle ref or --session"), + (Some(ref_), None) => delete_bundle_everywhere(&local, remote.as_ref(), &ref_)?, + (None, Some(session)) => { + delete_session_everywhere(&local, remote.as_ref(), &session, args.str("agent"))? + } + }; + let mut text: String = deleted + .removed .iter() .map(|k| format!(" removed {}\n", k)) .collect(); - text.push_str(&format!("\ndeleted {} from {}\n", ref_, store.describe())); - Ok(Outcome::with( - "delete", - object! {"ref" => ref_.as_str(), "store" => store.describe(), "removed" => strings(&removed)}, - text, - )) + for key in &deleted.removed_remote { + text.push_str(&format!(" removed {} from the remote\n", key)); + } + let what = deleted.subject.clone(); + match &remote { + Some((remote, _)) => text.push_str(&format!( + "\ndeleted {} from {} and this machine; a tombstone keeps it deleted\n", + what, + remote.label() + )), + None => text.push_str(&format!("\ndeleted {} from {}\n", what, local.describe())), + } + let mut payload = object! { + "ref" => Value::opt_str(deleted.ref_.as_deref()), + "session" => Value::opt_str(deleted.session.as_deref()), + "store" => local.describe(), + "removed" => strings(&deleted.removed), + "removedRemote" => strings(&deleted.removed_remote), + "tombstones" => strings(&deleted.tombstones), + }; + let mut outcome_warnings = Vec::new(); + if let Some((remote, _)) = &remote { + payload = with_remote(payload, remote); + outcome_warnings.extend(remote.warning()); + } else { + payload.insert("remote".into(), Value::Null); + } + let mut outcome = Outcome::with("delete", payload, text); + outcome.warnings = outcome_warnings; + Ok(outcome) +} + +struct Deleted { + subject: String, + ref_: Option, + session: Option, + removed: Vec, + removed_remote: Vec, + tombstones: Vec, +} + +/// A bundle, from this machine and, with a remote, from it too. On a remote +/// the tombstone is written first, so a push racing the delete sees it before +/// the bundle is gone; here it is written as well, so this machine never +/// pushes the bundle anywhere again. +fn delete_bundle_everywhere( + local: &crate::store::FileStore, + remote: Option<&(Remote, Box)>, + ref_: &str, +) -> std::result::Result { + let mut deleted = Deleted { + subject: ref_.to_string(), + ref_: Some(ref_.to_string()), + session: None, + removed: Vec::new(), + removed_remote: Vec::new(), + tombstones: Vec::new(), + }; + let local_failure = |e| { + index_error( + &format!("could not delete {} from {}", ref_, local.describe()), + e, + ) + }; + let Some((remote, opened)) = remote else { + deleted.removed = index::delete_bundle(local, ref_).map_err(local_failure)?; + return Ok(deleted); + }; + let described = format!("could not delete {} from {}", ref_, remote.label()); + // A ref in neither place is a typo, not a delete: refused before any + // tombstone is written, as a local delete of it is. + let key = index::bundle_key(ref_); + let on_remote = opened + .list(&key) + .map_err(|e| store_error(&described, e))? + .contains(&key); + if !on_remote && !local.exists(&key) { + return Err(store_error( + &described, + StoreError::Missing(format!("no object at {}", key)), + )); + } + let tombstone = sync::bundle_tombstone(ref_); + opened + .put(&tombstone, &sync::tombstone_body()) + .map_err(|e| store_error(&described, e))?; + deleted.tombstones.push(tombstone.clone()); + deleted.removed_remote = match index::delete_bundle(opened.as_ref(), ref_) { + Ok(removed) => removed, + Err(IndexError::Store(StoreError::Missing(_))) => Vec::new(), + // A bundle that won't unpack still goes; its entries wait for reindex. + Err(IndexError::Unreadable(_)) => { + let key = index::bundle_key(ref_); + opened + .delete(&key) + .map_err(|e| store_error(&described, e))?; + vec![key] + } + Err(e) => return Err(index_error(&described, e)), + }; + local + .put(&tombstone, &sync::tombstone_body()) + .map_err(|e| store_error(&format!("could not write {}", tombstone), e))?; + deleted.removed = match index::delete_bundle(local, ref_) { + Ok(removed) => removed, + Err(IndexError::Store(StoreError::Missing(_))) => Vec::new(), + Err(e) => return Err(local_failure(e)), + }; + Ok(deleted) +} + +/// A session's edit record, file index and transcripts, from this machine +/// and, with a remote, from it too, tombstoned as a bundle is. The agent's +/// own transcript in its own directory is never touched. +fn delete_session_everywhere( + local: &crate::store::FileStore, + remote: Option<&(Remote, Box)>, + session: &str, + agent_id: Option, +) -> std::result::Result { + if !agent::is_safe_session_id(session) { + let mut error = CommandError::new("usage", "--session is not a session id"); + error.exit_status = 2; + return Err(Failure::Error(error)); + } + let agents: Vec = match agent_id { + Some(id) => vec![agents_arg(Some(&id))? + .first() + .map(|a| a.id().to_string()) + .unwrap_or(id)], + None => { + let mut found = sync::agents_of_session(local, session) + .map_err(|e| store_error(&format!("could not read {}", local.describe()), e))?; + for id in agent::all().iter().map(|a| a.id()) { + if attribution::load_local(id, session).is_some() && !found.iter().any(|f| f == id) + { + found.push(id.to_string()); + } + } + if let Some((remote, opened)) = remote { + for id in sync::agents_of_session(opened.as_ref(), session) + .map_err(|e| store_error(&format!("could not read {}", remote.label()), e))? + { + if !found.contains(&id) { + found.push(id); + } + } + } + found + } + }; + if agents.is_empty() { + return err( + "session-not-found", + format!("no record of session {} here or on the remote", session), + ); + } + let mut deleted = Deleted { + subject: format!("session {}", session), + ref_: None, + session: Some(session.to_string()), + removed: Vec::new(), + removed_remote: Vec::new(), + tombstones: Vec::new(), + }; + let local_failure = |e| store_error(&format!("could not delete from {}", local.describe()), e); + for agent in &agents { + let tombstone = sync::session_tombstone(agent, session); + if let Some((remote, opened)) = remote { + let described = format!( + "could not delete session {} from {}", + session, + remote.label() + ); + opened + .put(&tombstone, &sync::tombstone_body()) + .map_err(|e| store_error(&described, e))?; + deleted.tombstones.push(tombstone.clone()); + deleted.removed_remote.extend( + sync::delete_session(opened.as_ref(), agent, session) + .map_err(|e| store_error(&described, e))?, + ); + local + .put(&tombstone, &sync::tombstone_body()) + .map_err(local_failure)?; + } + deleted + .removed + .extend(sync::delete_session(local, agent, session).map_err(local_failure)?); + if attribution::forget_local(local, agent, session).map_err(local_failure)? { + deleted + .removed + .push(format!("~/.loch/edits/{}/{}.json", agent, session)); + } + } + if remote.is_none() && deleted.removed.is_empty() { + return err( + "session-not-found", + format!("no record of session {} on this machine", session), + ); + } + Ok(deleted) } pub fn command_reindex(argv: &[String]) -> Run { let mut p = parser("reindex"); - p.option("--store"); + p.option_optional("--remote", "", "NAME").option("--store"); let args = p.parse(argv)?; - let store = open_store(args.str("store").as_deref())?; + let store: Box = match remote_asked(&args) { + Some(asked) => open_remote(asked.as_deref())?.1, + None => Box::new(crate::store::local_store()), + }; let described = format!("could not reindex {}", store.describe()); let result = index::reindex(store.as_ref()).map_err(|e| index_error(&described, e))?; // The file index, re-derived from the edit records the same way, with @@ -1080,8 +1423,10 @@ pub fn command_install(argv: &[String]) -> Run { // -- blame / log / ask ------------------------------------------------------------- -fn store_or_none(uri: Option<&str>) -> Option> { - create_store(&resolve_store_uri(uri)).ok() +/// The local store, which is all `blame`, `log`, `ask` and `backfill` read +/// or write: a remote's records arrive by `pull`, as git's do by `fetch`. +fn local() -> Option> { + Some(Box::new(crate::store::local_store())) } fn flat(text: &str, limit: usize) -> String { @@ -1292,11 +1637,10 @@ pub fn command_blame(argv: &[String]) -> Run { p.positional("file", Nargs::One) .option_optional("--html", "", "PATH") .option_metavar("--lines", "RANGES") - .flag("--no-open", None) - .option("--store"); + .flag("--no-open", None); let args = p.parse(argv)?; let file = args.str("file").unwrap_or_default(); - let store = store_or_none(args.str("store").as_deref()); + let store = local(); let blamed = blame_file(&file, store.as_deref())?; // One mark per turn, handed out in order of first appearance in the file, @@ -1437,10 +1781,10 @@ fn line_target(target: &str) -> std::result::Result<(String, Option<(usize, usiz pub fn command_log(argv: &[String]) -> Run { let mut p = parser("log"); - p.positional("target", Nargs::One).option("--store"); + p.positional("target", Nargs::One); let args = p.parse(argv)?; let (file, lines) = line_target(&args.str("target").unwrap_or_default())?; - let store = store_or_none(args.str("store").as_deref()); + let store = local(); let blamed = blame_file(&file, store.as_deref())?; if let Some((_, last)) = lines { if last > blamed.owners.len() { @@ -1514,8 +1858,7 @@ pub fn command_ask(argv: &[String]) -> Run { p.positional("target", Nargs::One) .positional("question", Nargs::Optional) .flag("--at-turn", None) - .flag("--no-launch", None) - .option("--store"); + .flag("--no-launch", None); let args = p.parse(argv)?; let as_json = json_requested(); let target = args.str("target").unwrap_or_default(); @@ -1523,7 +1866,7 @@ pub fn command_ask(argv: &[String]) -> Run { (file, Some((line, _))) => (file, line), (_, None) => return err("usage", format!("{} is not :", target)), }; - let store = store_or_none(args.str("store").as_deref()); + let store = local(); let blamed = blame_file(&file, store.as_deref())?; if line > blamed.owners.len() { return err( @@ -1551,7 +1894,7 @@ pub fn command_ask(argv: &[String]) -> Run { return err( "transcript-missing", format!( - "session {} wrote it, but its transcript is neither in {} nor in the store", + "session {} wrote it, but its transcript is neither in {} nor in the local store", link.session_id, adapter.sessions_dir() ), @@ -1667,14 +2010,14 @@ fn exec_agent(root: &str, command: &[String]) -> Run { /// transcripts' edit calls and the commits the agent made. pub fn command_backfill(argv: &[String]) -> Run { let mut p = parser("backfill"); - p.option("--cwd").option("--store"); + p.option("--cwd"); let args = p.parse(argv)?; let cwd = args .str("cwd") .filter(|c| !c.is_empty()) .unwrap_or_else(sys::getcwd); let root = snapshot::workspace_root(&cwd); - let store = store_or_none(args.str("store").as_deref()); + let store = local(); let results = crate::backfill::backfill(&cwd, store.as_deref()); let mut text = String::new(); for r in &results { @@ -1713,6 +2056,286 @@ pub fn command_backfill(argv: &[String]) -> Run { )) } +// -- remotes, as the store commands name them ------------------------------------------ + +/// `--remote []`, or the older `--store `, which means the same: +/// `None` when neither was given, `Some(None)` for the default remote. +fn remote_asked(args: &crate::argparse::Args) -> Option> { + if let Some(uri) = args.str("store").filter(|s| !s.is_empty()) { + return Some(Some(uri)); + } + args.str("remote") + .map(|r| Some(r).filter(|r| !r.is_empty())) +} + +/// The ref and the remote of `restore`/`delete`. `--remote` takes an +/// optional value, so `delete --remote ` hands it the ref, as argparse +/// does; no remote can be named like a ref, so it is given back. +fn ref_and_remote(args: &crate::argparse::Args) -> (Option, Option>) { + let ref_ = args.str("ref").filter(|r| !r.is_empty()); + let asked = remote_asked(args); + match (&ref_, &asked) { + (None, Some(Some(name))) if remote::looks_like_ref(name) && args.str("store").is_none() => { + (Some(name.clone()), Some(None)) + } + _ => (ref_, asked), + } +} + +/// A bundle this machine doesn't have, from the remote `asked` names (or the +/// default one), checked against its ref. +fn fetch_bundle( + ref_: &str, + asked: Option>, +) -> std::result::Result<(Remote, Vec), Failure> { + let resolved = remote::resolve(asked.clone().flatten().as_deref()); + let (remote, opened) = match resolved { + // Nothing to fetch from, and nobody asked for a remote: the bundle + // simply isn't here. + Err(e) if asked.is_none() && e.code == "no-remote" => { + return err( + "bundle-not-found", + format!( + "{} is not on this machine, and there is no remote to fetch it from", + ref_ + ), + ) + } + Err(e) => return Err(remote_error(e)), + Ok(remote) => { + let opened = remote.open().map_err(remote_error)?; + (remote, opened) + } + }; + let described = format!("could not read {} from {}", ref_, remote.label()); + let packed = opened + .get(&index::bundle_key(ref_)) + .map_err(|e| store_error(&described, e))?; + if bundle::bundle_ref(&packed) != ref_ { + return err( + "bundle-unreadable", + format!("{}: its bytes don't hash to the ref", described), + ); + } + Ok((remote, packed)) +} + +// -- push / pull ---------------------------------------------------------------------- + +fn sync_error(remote: &Remote, error: SyncError) -> Failure { + match error { + SyncError::Store(e) => store_error(&format!("could not reach {}", remote.label()), e), + SyncError::Redaction(message) => { + Failure::Error(CommandError::new("redaction-failed", message)) + } + } +} + +/// The remote a command named, opened, and refused if it is this machine's +/// own store: pushing there would mark everything sent and send nothing. +fn open_remote(asked: Option<&str>) -> std::result::Result<(Remote, Box), Failure> { + let remote = remote::resolve(asked).map_err(remote_error)?; + let opened = remote.open().map_err(remote_error)?; + // Resolved, so a symlink to the local store is caught too. + let resolved = |path: &str| { + fs::canonicalize(path) + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|_| sys::abspath(path)) + }; + if !remote.uri.starts_with("s3://") + && resolved(remote.uri.trim_start_matches("file://")) + == resolved(&crate::store::default_store()) + { + return err( + "invalid-uri", + format!("{} is this machine's own store, not a remote", remote.uri), + ); + } + Ok((remote, opened)) +} + +/// The project a sync covers: the one `--cwd` (or the current directory) is +/// in, or every project with `--all`. +fn sync_scope(args: &crate::argparse::Args) -> Option { + if args.flag("all") { + return None; + } + let cwd = args + .str("cwd") + .filter(|c| !c.is_empty()) + .unwrap_or_else(sys::getcwd); + Some(attribution::project_id(&snapshot::workspace_root(&cwd))) +} + +fn with_remote(mut payload: crate::json::Map, remote: &Remote) -> crate::json::Map { + payload.insert("remote".into(), remote.payload()); + if remote.deprecated { + payload.insert("deprecated".into(), Value::str("LOCH_STORE")); + } + payload +} + +pub fn command_push(argv: &[String]) -> Run { + let mut p = parser("push"); + p.positional("remote", Nargs::Optional) + .option("--cwd") + .flag("--all", None) + .flag("--dry-run", None) + .flag("--force", None); + let args = p.parse(argv)?; + let (remote, opened) = open_remote(args.str("remote").as_deref())?; + let project = sync_scope(&args); + let local = crate::store::local_store(); + let mut report = sync::PushReport::new(args.flag("dry_run")); + report.force = args.flag("force"); + let scope = match &project { + Some(project) => sync::Scope::Project(project), + None => sync::Scope::All, + }; + let result = sync::push(&local, opened.as_ref(), &remote.uri, scope, &mut report); + let mut payload = report.payload(); + payload.insert("project".into(), Value::opt_str(project.as_deref())); + let payload = with_remote(payload, &remote); + if let Err(error) = result { + return Err(match sync_error(&remote, error) { + Failure::Error(mut failure) => { + failure.payload = payload; + Failure::Error(failure) + } + other => other, + }); + } + let mut outcome = Outcome::with( + "push", + payload, + format!("{}: {}", remote.label(), report.text()), + ); + outcome.warnings.extend(remote.warning()); + Ok(outcome) +} + +pub fn command_pull(argv: &[String]) -> Run { + let mut p = parser("pull"); + p.positional("remote", Nargs::Optional) + .option("--cwd") + .flag("--all", None); + let args = p.parse(argv)?; + let (remote, opened) = open_remote(args.str("remote").as_deref())?; + let project = sync_scope(&args); + let local = crate::store::local_store(); + let mut report = sync::PullReport::default(); + let result = sync::pull(&local, opened.as_ref(), project.as_deref(), &mut report); + let mut payload = report.payload(); + payload.insert("project".into(), Value::opt_str(project.as_deref())); + let payload = with_remote(payload, &remote); + if let Err(error) = result { + return Err(match sync_error(&remote, error) { + Failure::Error(mut failure) => { + failure.payload = payload; + Failure::Error(failure) + } + other => other, + }); + } + let mut outcome = Outcome::with( + "pull", + payload, + format!("{}: {}", remote.label(), report.text()), + ); + outcome.warnings.extend(remote.warning()); + Ok(outcome) +} + +// -- remote --------------------------------------------------------------------------- + +fn remote_error(error: RemoteError) -> Failure { + let mut failure = CommandError::new(error.code, error.message); + if error.code == "usage" { + failure.exit_status = 2; + } + Failure::Error(failure) +} + +/// `remote [list]`, `remote add `, `remote remove `. +pub fn command_remote(argv: &[String]) -> Run { + let (sub, rest) = match argv.split_first() { + Some((sub, rest)) if !sub.starts_with('-') => (sub.as_str(), rest), + _ => ("list", argv), + }; + match sub { + "add" => { + let mut p = parser("remote add"); + p.positional("name", Nargs::One) + .positional("uri", Nargs::One); + let args = p.parse(rest)?; + let added = remote::add( + &args.str("name").unwrap_or_default(), + &args.str("uri").unwrap_or_default(), + ) + .map_err(remote_error)?; + Ok(Outcome::with( + "remote", + object! {"action" => "add", "remote" => added.payload()}, + format!("added remote {} {}\n", added.label(), added.uri), + )) + } + "remove" => { + let mut p = parser("remote remove"); + p.positional("name", Nargs::One); + let args = p.parse(rest)?; + let removed = + remote::remove(&args.str("name").unwrap_or_default()).map_err(remote_error)?; + Ok(Outcome::with( + "remote", + object! {"action" => "remove", "remote" => removed.payload()}, + format!("removed remote {} {}\n", removed.label(), removed.uri), + )) + } + "list" => { + parser("remote list").parse(rest)?; + let remotes = remote::remotes().map_err(remote_error)?; + let default = remote::default_name(&remotes); + let mut text = String::new(); + for (name, uri) in &remotes { + let marker = if default.as_deref() == Some(name) { + " (default)" + } else { + "" + }; + text.push_str(&format!( + "{} {}{}\n", + name, + uri.as_str().unwrap_or_default(), + marker + )); + } + if remotes.is_empty() { + text.push_str("no remotes; `loch remote add origin `\n"); + } + Ok(Outcome::with( + "remote", + object! { + "action" => "list", + "remotes" => remotes.iter().map(|(name, uri)| Value::Object(object! { + "name" => name.as_str(), + "uri" => uri.clone(), + })).collect::>(), + "default" => Value::opt_str(default.as_deref()), + }, + text, + )) + } + other => { + let mut error = CommandError::new( + "usage", + format!("unknown remote action {:?} (add, remove, list)", other), + ); + error.exit_status = 2; + Err(Failure::Error(error)) + } + } +} + // -- gc ------------------------------------------------------------------------------ /// Deletes the snapshots nothing needs: the hooks do this on their own every @@ -1770,6 +2393,9 @@ pub fn dispatch(command: &str, argv: &[String]) -> Option { "log" => command_log(argv), "hook" => command_hook(argv), "gc" => command_gc(argv), + "remote" => command_remote(argv), + "push" => command_push(argv), + "pull" => command_pull(argv), "backfill" => command_backfill(argv), "help" => command_help(argv), "version" => command_version(argv), diff --git a/src/hook.rs b/src/hook.rs index 6d54154..3ab22fb 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -4,8 +4,9 @@ //! //! `prompt` snapshots the workspace; `stop` snapshots it again and records the //! lines the turn added (see `attribution.rs`) in the session's edit record, -//! and copies the transcript into the store, since Claude Code deletes -//! transcripts after `cleanupPeriodDays` (30 by default). +//! and copies the transcript into the local store, since Claude Code deletes +//! transcripts after `cleanupPeriodDays` (30 by default). Nothing here reaches +//! a remote; `push` does that. //! //! **Every turn gets closed by someone.** Claude Code runs no `Stop` when a //! turn is cancelled, and a crash runs nothing at all. Left alone, the next @@ -127,13 +128,23 @@ fn close_turn( store: Option<&dyn Store>, ) -> Result { let end = snapshot::snapshot(root)?; - 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(), - turns: Vec::new(), - }); + // The working copy, and whatever `pull` brought into the store for this + // session: a session restored under its own id is recorded on two + // machines, and starting from the working copy alone would write over the + // other machine's turns. + let working = attribution::load_local(agent.id(), session); + let stored = store.and_then(|store| attribution::load_stored(store, agent.id(), session)); + let mut record = match (working, stored) { + (Some(working), Some(stored)) => working.merge(&stored), + (Some(one), None) | (None, Some(one)) => one, + (None, None) => EditRecord { + agent: agent.id().into(), + session: session.into(), + project: attribution::project_id(root), + root: root.into(), + turns: Vec::new(), + }, + }; // With no baseline at all, everything in the workspace would look new; the // turn is recorded with nothing attributed, as the baseline for the next. let files = match start { @@ -497,11 +508,14 @@ pub fn run(name: &str, agent_id: &str, scope: Option, stdin: &[u8]) { }, Err(Stop) => None, }; - let store = || store::create_store(&store::resolve_store_uri(None)).ok(); + // Always the local store, whatever `LOCH_STORE` says: the agent waits on + // this hook, so it must never wait on the network. + let local = store::local_store(); + let store: Option<&dyn Store> = Some(&local); let _ = match name { - "prompt" => prompt(agent, &event, store().as_deref()), - "stop" => stop(agent, &event, store().as_deref()), - "end" => end(agent, &event, store().as_deref()), + "prompt" => prompt(agent, &event, store), + "stop" => stop(agent, &event, store), + "end" => end(agent, &event, store), // 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 f6addc6..33c1a37 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,9 +22,11 @@ pub mod json; pub mod output; pub mod py; pub mod redact; +pub mod remote; pub mod rewrite; pub mod s3; pub mod snapshot; pub mod store; +pub mod sync; pub mod sys; pub mod trace; diff --git a/src/output.rs b/src/output.rs index 4ec7e62..fe40806 100644 --- a/src/output.rs +++ b/src/output.rs @@ -3,7 +3,7 @@ use crate::json::{self, Map, Value}; use std::io::Write; -pub const SCHEMA: i64 = 2; +pub const SCHEMA: i64 = 3; pub const JSON_FLAG: &str = "--json"; diff --git a/src/remote.rs b/src/remote.rs new file mode 100644 index 0000000..a581752 --- /dev/null +++ b/src/remote.rs @@ -0,0 +1,283 @@ +//! Named remotes, git style: `~/.loch/config` maps names to store URIs, and +//! `push`, `pull` and every command that reaches past this machine name one, +//! or take the default. +//! +//! The local store (`store::local_store`) is not a remote and has no name; +//! everything is recorded there first. + +use crate::json::{self, Map, Value}; +use crate::object; +use crate::snapshot; +use crate::store::{self, Store}; + +pub const DEFAULT_NAME: &str = "origin"; + +/// The store a command reaches past this machine to. +pub struct Remote { + /// `None` for one given as a URI, or by `LOCH_REMOTE`/`LOCH_STORE`. + pub name: Option, + pub uri: String, + /// Named by `LOCH_STORE`, which meant the store the hooks wrote to before + /// there were remotes. It still works, and says so. + pub deprecated: bool, +} + +impl Remote { + pub fn open(&self) -> Result, RemoteError> { + store::create_store(&self.uri).map_err(|e| RemoteError::new("invalid-uri", e.0)) + } + + /// How the remote is named in prose: its name, else its URI. + pub fn label(&self) -> String { + self.name.clone().unwrap_or_else(|| self.uri.clone()) + } + + pub fn payload(&self) -> Value { + Value::Object(object! { + "name" => Value::opt_str(self.name.as_deref()), + "uri" => self.uri.as_str(), + }) + } + + pub fn warning(&self) -> Option { + self.deprecated.then(|| { + "LOCH_STORE now names a remote; set LOCH_REMOTE, or `loch remote add origin `\n" + .to_string() + }) + } +} + +#[derive(Debug)] +pub struct RemoteError { + pub code: &'static str, + pub message: String, +} + +impl RemoteError { + fn new(code: &'static str, message: impl Into) -> Self { + RemoteError { + code, + message: message.into(), + } + } +} + +pub fn config_path() -> std::path::PathBuf { + snapshot::loch_home().join("config") +} + +/// The remotes, in the order they were added. A config that doesn't exist +/// holds none; one that exists and won't parse is an error, since treating it +/// as empty would let `remote add` overwrite it. +pub fn remotes() -> Result { + let path = config_path(); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Map::new()), + Err(e) => { + return Err(RemoteError::new( + "config-unreadable", + format!("{}: {}", path.display(), e), + )) + } + }; + let unreadable = || { + RemoteError::new( + "config-unreadable", + format!("{} is not a loch config", path.display()), + ) + }; + let config = json::loads(&text).map_err(|_| unreadable())?; + let Value::Object(config) = config else { + return Err(unreadable()); + }; + match config.get("remotes") { + None => Ok(Map::new()), + Some(Value::Object(remotes)) if remotes.values().all(|v| v.as_str().is_some()) => { + Ok(remotes.clone()) + } + Some(_) => Err(unreadable()), + } +} + +/// Written aside and renamed, like every file loch keeps, so a killed write +/// leaves the old config or the new one. +fn write_remotes(remotes: Map) -> Result<(), RemoteError> { + let config = Value::Object(object! {"remotes" => Value::Object(remotes)}); + snapshot::write_atomically( + &config_path(), + json::dumps(&config, json::DEFAULT).as_bytes(), + ) + .map_err(|e| { + RemoteError::new( + "config-unreadable", + format!("{}: {}", config_path().display(), e), + ) + }) +} + +/// A bundle ref: 64 lowercase hex digits. No remote may be named like one, +/// so `delete --remote ` can be read the way it was meant. +pub fn looks_like_ref(text: &str) -> bool { + text.len() == 64 && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +fn valid_name(name: &str) -> bool { + !name.is_empty() + && !looks_like_ref(name) + && !name.starts_with('-') + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) +} + +/// A name or a URI where a remote is asked for, as `git push ` takes +/// either. Every URI holds a `/`, and no name can. +fn is_uri(text: &str) -> bool { + text.contains('/') +} + +/// The URI as the config keeps it. A scheme the store doesn't know is +/// refused: `create_store` takes anything else as a relative path, so +/// `ssh://host` would become a local directory named `ssh:` and a push to it +/// would succeed. A relative path is made absolute, so a remote doesn't +/// depend on where it was added from. +fn normalize(uri: &str) -> Result { + if let Some((scheme, _)) = uri.split_once("://") { + if !matches!(scheme, "s3" | "file") { + return Err(RemoteError::new( + "invalid-uri", + format!("unsupported store URI {} (a path, file:// or s3://)", uri), + )); + } + } else if !uri.starts_with('/') { + return Ok(crate::sys::abspath(uri)); + } + store::create_store(uri).map_err(|e| RemoteError::new("invalid-uri", e.0))?; + Ok(uri.into()) +} + +pub fn add(name: &str, uri: &str) -> Result { + if !valid_name(name) { + return Err(RemoteError::new( + "usage", + format!( + "{:?} is not a remote name (letters, digits, '.', '_' and '-')", + name + ), + )); + } + let uri = normalize(uri)?; + let mut remotes = remotes()?; + if remotes.contains_key(name) { + return Err(RemoteError::new( + "remote-exists", + format!("remote {} already exists", name), + )); + } + remotes.insert(name.into(), Value::str(uri.as_str())); + write_remotes(remotes)?; + Ok(Remote { + name: Some(name.into()), + uri, + deprecated: false, + }) +} + +pub fn remove(name: &str) -> Result { + let mut remotes = remotes()?; + let Some(uri) = remotes.shift_remove(name) else { + return Err(unknown(name)); + }; + write_remotes(remotes)?; + Ok(Remote { + name: Some(name.into()), + uri: uri.as_str().unwrap_or_default().into(), + deprecated: false, + }) +} + +pub fn list() -> Result, RemoteError> { + Ok(remotes()? + .into_iter() + .map(|(name, uri)| Remote { + name: Some(name), + uri: uri.as_str().unwrap_or_default().into(), + deprecated: false, + }) + .collect()) +} + +fn unknown(name: &str) -> RemoteError { + RemoteError::new("unknown-remote", format!("no remote named {}", name)) +} + +fn from_env(variable: &str) -> Option { + std::env::var(variable).ok().filter(|v| !v.is_empty()) +} + +/// The remote a command means: the one it names (or the URI it gives), else +/// `LOCH_REMOTE`, else the deprecated `LOCH_STORE`, else `origin`, else the +/// only remote there is. Several remotes and no `origin` is ambiguous rather +/// than a guess, since a push to the wrong one publishes transcripts. +pub fn resolve(asked: Option<&str>) -> Result { + if let Some(asked) = asked.filter(|a| !a.is_empty()) { + if is_uri(asked) { + return Ok(Remote { + name: None, + uri: normalize(asked)?, + deprecated: false, + }); + } + let remotes = remotes()?; + return match remotes.get(asked) { + Some(uri) => Ok(Remote { + name: Some(asked.into()), + uri: uri.as_str().unwrap_or_default().into(), + deprecated: false, + }), + None => Err(unknown(asked)), + }; + } + for (variable, deprecated) in [("LOCH_REMOTE", false), ("LOCH_STORE", true)] { + if let Some(uri) = from_env(variable) { + return Ok(Remote { + name: None, + uri: normalize(&uri)?, + deprecated, + }); + } + } + let remotes = remotes()?; + match default_name(&remotes) { + Some(name) => Ok(Remote { + uri: remotes[name.as_str()].as_str().unwrap_or_default().into(), + name: Some(name), + deprecated: false, + }), + None if remotes.is_empty() => Err(RemoteError::new( + "no-remote", + "no remote configured; `loch remote add origin `, or set LOCH_REMOTE", + )), + None => Err(RemoteError::new( + "ambiguous-remote", + format!( + "{} remotes and none named {}; name one", + remotes.len(), + DEFAULT_NAME + ), + )), + } +} + +/// The configured remote a command takes when it names none: `origin`, or +/// the only one. +pub fn default_name(remotes: &Map) -> Option { + if remotes.contains_key(DEFAULT_NAME) { + Some(DEFAULT_NAME.into()) + } else if remotes.len() == 1 { + remotes.keys().next().cloned() + } else { + None + } +} diff --git a/src/store.rs b/src/store.rs index ff73c75..35ec0df 100644 --- a/src/store.rs +++ b/src/store.rs @@ -44,6 +44,11 @@ impl FileStore { FileStore { root: root.into() } } + /// Without reading it: `list` walks the whole store. + pub fn exists(&self, key: &str) -> bool { + is_safe_key(key) && Path::new(&self.path(key)).is_file() + } + /// `Path(root) / key`, which collapses repeated and trailing slashes. fn path(&self, key: &str) -> String { let mut path = self.root.trim_end_matches('/').to_string(); @@ -60,6 +65,27 @@ impl FileStore { } } +/// Whether a key names a place inside the store when made a path: no empty, +/// `.` or `..` segment, nothing a path would read as a root or a separator. +/// Keys `pull` writes are named by a remote, which is someone else's input. +pub fn is_safe_key(key: &str) -> bool { + !key.is_empty() + && !key.contains(['\\', '\0']) + && key + .split('/') + .all(|seg| !seg.is_empty() && seg != "." && seg != "..") +} + +fn refuse_unsafe(key: &str) -> Result<(), StoreError> { + if is_safe_key(key) { + Ok(()) + } else { + Err(StoreError::Missing( + "refused a key outside the store".into(), + )) + } +} + fn unreachable(error: &std::io::Error, path: &str) -> StoreError { StoreError::Unreachable(sys::os_error(error, path)) } @@ -69,14 +95,18 @@ impl Store for FileStore { self.root.clone() } + /// Written aside and renamed: the local store is what the hooks write and + /// `pull` fills while either may be killed, so a reader sees the old + /// object or the new one, never half of either. fn put(&self, key: &str, data: &[u8]) -> Result<(), StoreError> { + refuse_unsafe(key)?; let path = self.path(key); - let parent = sys::dirname(&path); - fs::create_dir_all(&parent).map_err(|e| unreachable(&e, &parent))?; - fs::write(&path, data).map_err(|e| unreachable(&e, &path)) + crate::snapshot::write_atomically(Path::new(&path), data) + .map_err(|e| unreachable(&e, &path)) } fn get(&self, key: &str) -> Result, StoreError> { + refuse_unsafe(key)?; let path = self.path(key); fs::read(&path).map_err(|error| match error.kind() { std::io::ErrorKind::NotFound => StoreError::Missing(format!("no object at {}", key)), @@ -99,6 +129,7 @@ impl Store for FileStore { } fn delete(&self, key: &str) -> Result<(), StoreError> { + refuse_unsafe(key)?; let path = self.path(key); match fs::remove_file(&path) { Ok(()) => Ok(()), @@ -116,6 +147,11 @@ fn walk(dir: &Path, relative: &str, keys: &mut Vec) { }; for entry in entries.flatten() { let name = entry.file_name().to_string_lossy().into_owned(); + // A write in progress (`put` stages `..tmp` and renames + // it), which no key names. + if name.starts_with('.') { + continue; + } let key = if relative.is_empty() { name.clone() } else { @@ -136,11 +172,12 @@ pub fn default_store() -> String { sys::join(&sys::join(&home_dir(), ".loch"), "store") } -pub fn resolve_store_uri(explicit: Option<&str>) -> String { - if let Some(uri) = explicit { - return uri.to_string(); - } - std::env::var("LOCH_STORE").unwrap_or_else(|_| default_store()) +/// This machine's own store, which the hooks, `backfill`, `blame`, `log` and +/// `ask` use and nothing else. They never reach the network: a remote that +/// doesn't answer would hold a turn for its timeout, and Codex kills a +/// `SessionEnd` hook at 3s. +pub fn local_store() -> FileStore { + FileStore::new(default_store()) } #[derive(Debug)] diff --git a/src/sync.rs b/src/sync.rs new file mode 100644 index 0000000..ed1022c --- /dev/null +++ b/src/sync.rs @@ -0,0 +1,939 @@ +//! `push` and `pull`: moving what this machine recorded to a remote, and what +//! a remote holds to this machine, as git's push and fetch do. Nothing else +//! reaches a remote for attribution; the hooks write the local store alone. +//! +//! **No manifest on the remote.** What a push has sent is remembered on this +//! machine (`~/.loch/pushed/.json`, key → hash of the local bytes), +//! so the remote stays a set of independent objects, each written whole by one +//! PUT. Bundles and index entries commute, as `save`s always have. Edit records +//! don't, being one mutable object per session, so they are merged by turn on +//! every push, pull and hook rather than replaced. +//! +//! **A delete on a remote stays deleted.** `delete --remote` leaves a +//! tombstone there (`tombstones/bundle/`, `tombstones/session// +//! `), one new key per delete, holding no content. Every push reads them +//! first and sends nothing they cover, so a teammate's copy can't bring a +//! deleted session back, and reads them again afterwards to withdraw what a +//! delete racing it covered. Every pull copies them here and forgets what +//! they cover. Being able to really delete is why loch uses object storage, +//! so this is stricter than git on purpose. + +use crate::agent; +use crate::attribution::{self, EditRecord, EDITS_PREFIX, FILE}; +use crate::index::{self, BRANCH, BUNDLES_PREFIX}; +use crate::json::{self, Map, Value}; +use crate::object; +use crate::redact; +use crate::snapshot; +use crate::store::{self, FileStore, Store, StoreError}; +use crate::sys; +use crate::trace; +use indexmap::IndexMap; +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +pub const TOMBSTONES_PREFIX: &str = "tombstones/"; +const TRANSCRIPTS_PREFIX: &str = "transcripts/"; + +pub fn bundle_tombstone(ref_: &str) -> String { + format!("{}bundle/{}", TOMBSTONES_PREFIX, ref_) +} + +pub fn session_tombstone(agent: &str, session: &str) -> String { + format!("{}session/{}/{}", TOMBSTONES_PREFIX, agent, session) +} + +/// A tombstone says when and from where, and nothing about what it buried. +pub fn tombstone_body() -> Vec { + let body = object! { + "deletedAt" => sys::iso_timestamp(sys::now()), + "host" => sys::hostname(), + }; + json::dumps(&Value::Object(body), json::DEFAULT).into_bytes() +} + +#[derive(Clone, Debug, PartialEq)] +enum Owner { + Bundle(String), + Session(String), +} + +/// What the tombstones cover. Sessions are matched by id alone: ids are +/// UUIDs, and a file-index key names no agent. +#[derive(Default)] +struct Dead { + refs: BTreeSet, + sessions: BTreeSet<(String, String)>, +} + +impl Dead { + fn from_keys(keys: &[String]) -> Dead { + let mut dead = Dead::default(); + for key in keys { + let Some(rest) = key.strip_prefix(TOMBSTONES_PREFIX) else { + continue; + }; + let parts: Vec<&str> = rest.split('/').collect(); + match parts.as_slice() { + ["bundle", ref_] => { + dead.refs.insert(ref_.to_string()); + } + ["session", agent, session] => { + dead.sessions + .insert((agent.to_string(), session.to_string())); + } + _ => {} + } + } + dead + } + + fn covers(&self, owner: &Owner) -> bool { + match owner { + Owner::Bundle(ref_) => self.refs.contains(ref_), + Owner::Session(session) => self.sessions.iter().any(|(_, s)| s == session), + } + } +} + +#[derive(Debug)] +pub enum SyncError { + Store(StoreError), + /// A secret survived redaction in a transcript; it was not sent. + Redaction(String), +} + +impl From for SyncError { + fn from(error: StoreError) -> Self { + SyncError::Store(error) + } +} + +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Bundle, + BranchEntry, + Record, + FileEntry, + Transcript, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::Bundle => "bundles", + Kind::BranchEntry => "branchEntries", + Kind::Record => "records", + Kind::FileEntry => "fileEntries", + Kind::Transcript => "transcripts", + } + } +} + +const KINDS: [Kind; 5] = [ + Kind::Bundle, + Kind::BranchEntry, + Kind::Record, + Kind::FileEntry, + Kind::Transcript, +]; + +fn counts_payload(counts: &BTreeMap<&'static str, usize>) -> Value { + let mut map = Map::new(); + for kind in KINDS { + map.insert( + kind.name().into(), + Value::int(*counts.get(kind.name()).unwrap_or(&0) as i64), + ); + } + Value::Object(map) +} + +/// What a push sends. +#[derive(Clone, Copy)] +pub enum Scope<'a> { + /// This project's bundles and sessions. + Project(&'a str), + /// Every bundle, and every session. + All, + /// One bundle and its entries, for `save --push`. + Bundle(&'a str), +} + +struct Item { + key: String, + kind: Kind, + owner: Owner, + /// Bytes to send that the local store doesn't hold as such. + data: Option>, +} + +/// `edits//.json`, for an agent this build knows and an id +/// that can be a file name. +fn parse_edits_key(key: &str) -> Option<(String, String)> { + let rest = key.strip_prefix(EDITS_PREFIX)?; + let (agent, file) = rest.split_once('/')?; + let session = file.strip_suffix(".json")?; + (agent::by_id(agent).is_some() && agent::is_safe_session_id(session)) + .then(|| (agent.to_string(), session.to_string())) +} + +fn parse_record(data: &[u8]) -> Option { + String::from_utf8(data.to_vec()) + .ok() + .and_then(|text| json::loads(&text).ok()) + .and_then(|v| EditRecord::from_json(&v)) +} + +/// Whether a stored transcript key is the session's. Both adapters' keys end +/// with the id and `.jsonl`, after a `/` (Claude) or a `-` (Codex's rollout +/// names). +fn transcript_of(key: &str, agent: &str, session: &str) -> bool { + let Some(rest) = key.strip_prefix(&trace::transcripts_prefix(agent)) else { + return false; + }; + let Some(stem) = rest.strip_suffix(".jsonl") else { + return false; + }; + let Some(before) = stem.strip_suffix(session) else { + return false; + }; + // No segment may start with `.`: `find_transcript` would skip it, and it + // is how a staged write is named. + let segments_ok = rest.split('/').all(|seg| !seg.starts_with('.')); + segments_ok && (before.is_empty() || before.ends_with('/') || before.ends_with('-')) +} + +/// The project a file-index key's value belongs to is the part before the +/// path; values are `:`, and project ids hold one colon. +fn file_index_session(key: &str, project: &str) -> Option { + let rest = key.strip_prefix(&index::dimension_prefix(FILE))?; + let (value, session) = rest.split_once('/')?; + index::unquote(value) + .starts_with(&format!("{}:", project)) + .then(|| session.to_string()) +} + +/// This machine's sessions in the local store, with their records. +fn local_sessions(local: &dyn Store) -> Result, StoreError> { + let mut sessions = Vec::new(); + for key in local.list(EDITS_PREFIX)? { + let Some((agent, session)) = parse_edits_key(&key) else { + continue; + }; + let Some(record) = local.get(&key).ok().and_then(|d| parse_record(&d)) else { + continue; + }; + sessions.push((agent, session, record)); + } + Ok(sessions) +} + +/// Whether any session a bundle holds ran in `project`. A project-scoped push +/// must not send a bundle saved in another repository: that would publish one +/// client's transcripts to another's remote. A session whose directory is gone +/// from this machine can't be placed, and is only sent by `--all`. +fn bundle_in_project( + local: &dyn Store, + key: &str, + project: &str, + projects: &mut HashMap, +) -> Result { + for cwd in bundle_cwds(local, key)? { + let id = projects.entry(cwd.clone()).or_insert_with(|| { + if std::path::Path::new(&cwd).is_dir() { + attribution::project_id(&snapshot::workspace_root(&cwd)) + } else { + String::new() + } + }); + if id == project { + return Ok(true); + } + } + Ok(false) +} + +/// The cwds of a bundle's sessions. A ref is the hash of the bundle's bytes, +/// so the answer never changes and is kept (`~/.loch/cache/bundle-cwds/`) +/// rather than unpacking every bundle on every push. +fn bundle_cwds(local: &dyn Store, key: &str) -> Result, StoreError> { + let ref_ = index::ref_from_key(key); + let cached = snapshot::loch_home() + .join("cache/bundle-cwds") + .join(format!("{}.json", ref_)); + if let Some(Value::Array(cwds)) = std::fs::read_to_string(&cached) + .ok() + .and_then(|text| json::loads(&text).ok()) + { + return Ok(cwds + .iter() + .filter_map(|c| c.as_str().map(str::to_string)) + .collect()); + } + let packed = local.get(key)?; + let Ok(bundle) = crate::bundle::unpack_bundle(&packed) else { + return Ok(Vec::new()); + }; + let mut cwds: Vec = bundle.sessions.iter().map(|s| s.cwd.clone()).collect(); + cwds.sort(); + cwds.dedup(); + let body = Value::Array(cwds.iter().map(|c| Value::str(c.as_str())).collect()); + let _ = snapshot::write_atomically(&cached, json::dumps(&body, json::DEFAULT).as_bytes()); + Ok(cwds) +} + +/// Everything a push would send, in the order it has to arrive: a bundle +/// before its index entries and a record before its file index, as `save` and +/// the hooks have always written them, so a push cut short leaves objects +/// `reindex` can re-derive entries from rather than entries naming nothing. +fn plan(local: &dyn Store, scope: Scope) -> Result, StoreError> { + let mut items = Vec::new(); + let mut projects = HashMap::new(); + let branch_entries = local.list(&index::dimension_prefix(BRANCH))?; + for key in local.list(BUNDLES_PREFIX)? { + if !key.ends_with(".loch") { + continue; + } + let ref_ = index::ref_from_key(&key); + let wanted = match scope { + Scope::Bundle(only) => only == ref_, + Scope::All => true, + Scope::Project(project) => bundle_in_project(local, &key, project, &mut projects)?, + }; + if !wanted { + continue; + } + items.push(Item { + key: key.clone(), + kind: Kind::Bundle, + owner: Owner::Bundle(ref_.clone()), + data: None, + }); + for entry in branch_entries + .iter() + .filter(|k| k.ends_with(&format!("/{}", ref_))) + { + items.push(Item { + key: entry.clone(), + kind: Kind::BranchEntry, + owner: Owner::Bundle(ref_.clone()), + data: None, + }); + } + } + let project = match scope { + Scope::Bundle(_) => return Ok(items), + Scope::Project(project) => Some(project), + Scope::All => None, + }; + let transcripts = local.list(TRANSCRIPTS_PREFIX)?; + for (agent, session, record) in local_sessions(local)? { + if project.is_some_and(|p| record.project != p) { + continue; + } + let owner = Owner::Session(session.clone()); + items.push(Item { + key: attribution::edits_key(&agent, &session), + kind: Kind::Record, + owner: owner.clone(), + data: None, + }); + for (key, entry) in attribution::file_entries(&record) { + items.push(Item { + key, + kind: Kind::FileEntry, + owner: owner.clone(), + data: Some(entry), + }); + } + for key in transcripts + .iter() + .filter(|k| transcript_of(k, &agent, &session)) + { + items.push(Item { + key: key.clone(), + kind: Kind::Transcript, + owner: owner.clone(), + data: None, + }); + } + } + Ok(items) +} + +// -- what a push has sent ---------------------------------------------------------------- + +fn markers_path(uri: &str) -> std::path::PathBuf { + snapshot::loch_home().join("pushed").join(format!( + "{}.json", + &snapshot::content_hash(uri.as_bytes())[..16] + )) +} + +fn load_markers(uri: &str) -> BTreeMap { + let mut markers = BTreeMap::new(); + let Some(Value::Object(body)) = std::fs::read_to_string(markers_path(uri)) + .ok() + .and_then(|text| json::loads(&text).ok()) + else { + return markers; + }; + if let Some(Value::Object(keys)) = body.get("keys") { + for (key, hash) in keys { + if let Some(hash) = hash.as_str() { + markers.insert(key.clone(), hash.to_string()); + } + } + } + markers +} + +/// A lost write only means sending some objects again. +fn save_markers(uri: &str, markers: &BTreeMap) { + let keys: Map = markers + .iter() + .map(|(k, v)| (k.clone(), Value::str(v.as_str()))) + .collect(); + let body = Value::Object(object! {"uri" => uri, "keys" => Value::Object(keys)}); + let _ = snapshot::write_atomically( + &markers_path(uri), + json::dumps(&body, json::COMPACT_UNICODE).as_bytes(), + ); +} + +// -- push --------------------------------------------------------------------------------- + +#[derive(Default)] +pub struct PushReport { + pub dry_run: bool, + /// Send everything in scope, whatever the markers say: the remote was + /// emptied or replaced by something other than `delete --remote`, so the + /// markers claim objects it no longer holds. + pub force: bool, + sent: BTreeMap<&'static str, usize>, + pub up_to_date: usize, + /// Left unsent because a tombstone covers it. + pub tombstoned: usize, + /// Sent, then deleted again because a delete raced the push. + pub withdrawn: usize, + /// Transcripts that aren't UTF-8 and so can't be redacted; never sent. + pub unreadable: Vec, + /// Transcripts in which a secret survived redaction; never sent, and the + /// push fails as `redaction-failed` once everything else has gone. + pub redaction_failed: Vec, + pub redactions: IndexMap, +} + +impl PushReport { + pub fn new(dry_run: bool) -> Self { + PushReport { + dry_run, + ..Default::default() + } + } + + pub fn total(&self) -> usize { + self.sent.values().sum() + } + + pub fn payload(&self) -> Map { + let mut redactions = Map::new(); + for (rule, count) in &self.redactions { + redactions.insert(rule.clone(), Value::int(*count as i64)); + } + object! { + "dryRun" => self.dry_run, + "pushed" => counts_payload(&self.sent), + "total" => self.total(), + "upToDate" => self.up_to_date, + "tombstoned" => self.tombstoned, + "withdrawn" => self.withdrawn, + "unreadable" => self.unreadable.iter().map(|k| Value::str(k.as_str())).collect::>(), + "redactionFailed" => self.redaction_failed.iter().map(|k| Value::str(k.as_str())).collect::>(), + "redactions" => Value::Object(redactions), + "redacted" => self.redactions.values().sum::(), + } + } + + pub fn text(&self) -> String { + let verb = if self.dry_run { "would push" } else { "pushed" }; + let parts: Vec = KINDS + .iter() + .filter_map(|kind| { + let n = *self.sent.get(kind.name()).unwrap_or(&0); + (n > 0).then(|| format!("{} {}", n, kind.name())) + }) + .collect(); + let mut text = if parts.is_empty() { + "everything up to date\n".to_string() + } else { + format!("{} {}\n", verb, parts.join(", ")) + }; + if self.up_to_date > 0 && !parts.is_empty() { + text.push_str(&format!("{} already up to date\n", self.up_to_date)); + } + if self.tombstoned > 0 { + text.push_str(&format!( + "{} left unsent: deleted on the remote\n", + self.tombstoned + )); + } + if self.withdrawn > 0 { + text.push_str(&format!( + "{} withdrawn: deleted on the remote while pushing\n", + self.withdrawn + )); + } + if !self.unreadable.is_empty() { + text.push_str(&format!( + "{} transcript(s) not sent: not UTF-8, so they can't be redacted\n", + self.unreadable.len() + )); + } + let summary = redact::summarize(&self.redactions); + if !summary.is_empty() { + text.push_str(&format!("{}\n", summary)); + } + text + } +} + +/// Sends what the local store holds that `remote` hasn't been sent, within +/// `scope`: bundles, and sessions' edit records, file index and transcripts. Bundles were redacted by `save` +/// and go as they are, so a ref is the same everywhere; transcripts are +/// redacted on the way out, since the hooks keep them verbatim. +pub fn push( + local: &dyn Store, + remote: &dyn Store, + uri: &str, + scope: Scope, + report: &mut PushReport, +) -> Result<(), SyncError> { + let dead = Dead::from_keys( + &[ + remote.list(TOMBSTONES_PREFIX)?, + local.list(TOMBSTONES_PREFIX)?, + ] + .concat(), + ); + let items = plan(local, scope)?; + let mut markers = load_markers(uri); + let mut sent: Vec<(String, Owner)> = Vec::new(); + let result = send(local, remote, items, &dead, &mut markers, &mut sent, report); + if !report.dry_run { + save_markers(uri, &markers); + } + result?; + if report.dry_run || sent.is_empty() { + return redaction_verdict(report); + } + let after = Dead::from_keys(&remote.list(TOMBSTONES_PREFIX)?); + for (key, owner) in &sent { + if after.covers(owner) && !dead.covers(owner) { + remote.delete(key)?; + markers.remove(key); + report.withdrawn += 1; + } + } + if report.withdrawn > 0 { + save_markers(uri, &markers); + } + redaction_verdict(report) +} + +fn redaction_verdict(report: &PushReport) -> Result<(), SyncError> { + if report.redaction_failed.is_empty() { + return Ok(()); + } + Err(SyncError::Redaction(format!( + "{} transcript(s) not sent: a secret still matched after redaction", + report.redaction_failed.len() + ))) +} + +/// A record is sent merged with the remote's copy, and the merge is kept here +/// too, so a push never writes over turns another machine recorded for the +/// same session. Two pushes of one session at the same moment can still drop +/// the turns one of them added from the remote, until that machine's record +/// next changes and its push merges them back in. +fn merge_with_remote( + local: &dyn Store, + remote: &dyn Store, + key: &str, + data: Vec, + hash: String, +) -> Result<(Vec, String), SyncError> { + let Some(mine) = parse_record(&data) else { + return Ok((data, hash)); + }; + let theirs = match remote.get(key) { + Ok(bytes) => { + parse_record(&bytes).filter(|r| r.agent == mine.agent && r.session == mine.session) + } + Err(StoreError::Missing(_)) => None, + Err(e) => return Err(e.into()), + }; + let Some(theirs) = theirs else { + return Ok((data, hash)); + }; + let merged = mine.merge(&theirs); + if merged.turns == mine.turns { + return Ok((data, hash)); + } + // The merge's file entries go after it, from the plan: the other copy's + // are on the remote already, and this one's are queued behind the record. + attribution::publish(local, &merged)?; + let body = local.get(key)?; + let hash = snapshot::content_hash(&body); + Ok((body, hash)) +} + +fn send( + local: &dyn Store, + remote: &dyn Store, + items: Vec, + dead: &Dead, + markers: &mut BTreeMap, + sent: &mut Vec<(String, Owner)>, + report: &mut PushReport, +) -> Result<(), SyncError> { + for item in items { + if dead.covers(&item.owner) { + report.tombstoned += 1; + continue; + } + let data = match item.data { + Some(data) => data, + None => match local.get(&item.key) { + Ok(data) => data, + Err(StoreError::Missing(_)) => continue, + Err(e) => return Err(e.into()), + }, + }; + let hash = snapshot::content_hash(&data); + if !report.force && markers.get(&item.key) == Some(&hash) { + report.up_to_date += 1; + continue; + } + let (data, hash) = if item.kind == Kind::Record && !report.dry_run { + merge_with_remote(local, remote, &item.key, data, hash)? + } else { + (data, hash) + }; + let body = if item.kind == Kind::Transcript { + let Ok(text) = std::str::from_utf8(&data) else { + report.unreadable.push(item.key); + continue; + }; + // Redaction is deterministic, so this transcript would fail every + // push; it is skipped and named, and the rest still goes. + let Ok(scrubbed) = redact::redact(text) else { + report.redaction_failed.push(item.key); + continue; + }; + for (rule, count) in scrubbed.counts { + *report.redactions.entry(rule).or_insert(0) += count; + } + scrubbed.text.into_bytes() + } else { + data + }; + if !report.dry_run { + remote.put(&item.key, &body)?; + markers.insert(item.key.clone(), hash); + } + *report.sent.entry(item.kind.name()).or_insert(0) += 1; + sent.push((item.key, item.owner)); + } + Ok(()) +} + +// -- delete ------------------------------------------------------------------------------- + +/// Removes a session's record, file index and transcripts from `store`, and +/// returns the keys removed. The file index is found from the record, so a +/// store holding the entries without the record keeps them until `reindex`. +pub fn delete_session( + store: &dyn Store, + agent: &str, + session: &str, +) -> Result, StoreError> { + let mut removed = Vec::new(); + let key = attribution::edits_key(agent, session); + if let Some(record) = store.get(&key).ok().and_then(|d| parse_record(&d)) { + for (entry, _) in attribution::file_entries(&record) { + store.delete(&entry)?; + removed.push(entry); + } + store.delete(&key)?; + removed.push(key); + } + for transcript in store.list(&trace::transcripts_prefix(agent))? { + if transcript_of(&transcript, agent, session) { + store.delete(&transcript)?; + removed.push(transcript); + } + } + Ok(removed) +} + +/// The agents whose records or transcripts in `store` name `session`. +pub fn agents_of_session(store: &dyn Store, session: &str) -> Result, StoreError> { + let mut agents = Vec::new(); + for agent in agent::all() { + let id = agent.id(); + let has_record = store.get(&attribution::edits_key(id, session)).is_ok(); + let has_transcript = store + .list(&trace::transcripts_prefix(id))? + .iter() + .any(|k| transcript_of(k, id, session)); + if has_record || has_transcript { + agents.push(id.to_string()); + } + } + Ok(agents) +} + +// -- pull --------------------------------------------------------------------------------- + +#[derive(Default)] +pub struct PullReport { + pub records: usize, + pub transcripts: usize, + pub up_to_date: usize, + pub tombstones: usize, + /// Sessions and bundles removed from this machine because a remote + /// tombstone covers them. + pub forgotten: usize, + /// Keys the remote named that can't be a place in the local store, or + /// records that don't say what their key does. Never written. + pub refused: usize, +} + +impl PullReport { + pub fn payload(&self) -> Map { + object! { + "records" => self.records, + "transcripts" => self.transcripts, + "upToDate" => self.up_to_date, + "tombstones" => self.tombstones, + "forgotten" => self.forgotten, + "refused" => self.refused, + } + } + + pub fn text(&self) -> String { + let mut text = if self.records + self.transcripts == 0 { + "already up to date\n".to_string() + } else { + format!( + "pulled {} record(s), {} transcript(s)\n", + self.records, self.transcripts + ) + }; + if self.forgotten > 0 { + text.push_str(&format!( + "forgot {} deleted on the remote\n", + self.forgotten + )); + } + if self.refused > 0 { + text.push_str(&format!( + "refused {} object(s) whose key or content was malformed\n", + self.refused + )); + } + text + } +} + +/// Fetches the edit records `remote` holds for `project` (every one, for +/// `None`) that know more turns than this machine's copy, with their +/// transcripts, and forgets what the remote's tombstones cover. Bundles are +/// not fetched; `restore` fetches the one it is asked for. +/// +/// Everything the remote names is someone else's input: a key is written only +/// if it is a place inside the store, a session only if its id can be a file +/// name, and a record only if it says what its key does. +pub fn pull( + local: &FileStore, + remote: &dyn Store, + project: Option<&str>, + report: &mut PullReport, +) -> Result<(), SyncError> { + for key in remote.list(TOMBSTONES_PREFIX)? { + if !store::is_safe_key(&key) { + report.refused += 1; + continue; + } + if local.exists(&key) { + continue; + } + match remote.get(&key) { + Ok(data) => local.put(&key, &data)?, + Err(StoreError::Missing(_)) => continue, + Err(e) => return Err(e.into()), + } + report.tombstones += 1; + } + let dead = Dead::from_keys(&local.list(TOMBSTONES_PREFIX)?); + forget(local, &dead, report)?; + + let scoped: Option> = match project { + Some(project) => Some( + remote + .list(&index::dimension_prefix(FILE))? + .iter() + .filter_map(|key| file_index_session(key, project)) + .collect(), + ), + None => None, + }; + let transcripts = remote.list(TRANSCRIPTS_PREFIX)?; + for key in remote.list(EDITS_PREFIX)? { + let Some((agent, session)) = parse_edits_key(&key) else { + report.refused += 1; + continue; + }; + if dead.covers(&Owner::Session(session.clone())) + || scoped.as_ref().is_some_and(|s| !s.contains(&session)) + { + continue; + } + let data = match remote.get(&key) { + Ok(data) => data, + Err(StoreError::Missing(_)) => continue, + Err(e) => return Err(e.into()), + }; + let Some(record) = parse_record(&data) + .filter(|r| r.agent == agent && r.session == session) + .filter(|r| project.is_none_or(|p| r.project == p)) + else { + report.refused += 1; + continue; + }; + // Merged, never replaced: this machine may have recorded turns of the + // same session (a restore that kept its id) that the remote lacks. + let have = attribution::load_stored(local, &agent, &session); + let merged = match &have { + Some(have) => have.merge(&record), + None => record, + }; + let newer = have.is_none_or(|have| merged.turns != have.turns); + if newer { + attribution::publish(local, &merged)?; + report.records += 1; + } else { + report.up_to_date += 1; + } + for transcript in transcripts + .iter() + .filter(|k| transcript_of(k, &agent, &session)) + { + if !store::is_safe_key(transcript) { + report.refused += 1; + continue; + } + if !newer && local.exists(transcript) { + continue; + } + match remote.get(transcript) { + Ok(data) => local.put(transcript, &data)?, + Err(StoreError::Missing(_)) => continue, + Err(e) => return Err(e.into()), + } + report.transcripts += 1; + } + } + Ok(()) +} + +/// Removes from this machine what tombstones cover: loch's own copies, never +/// an agent's transcript in its own directory. +fn forget(local: &FileStore, dead: &Dead, report: &mut PullReport) -> Result<(), SyncError> { + for ref_ in &dead.refs { + let key = index::bundle_key(ref_); + if !local.exists(&key) { + continue; + } + if index::delete_bundle(local, ref_).is_err() { + local.delete(&key)?; + } + report.forgotten += 1; + } + if dead.sessions.is_empty() { + return Ok(()); + } + let transcripts = local.list(TRANSCRIPTS_PREFIX)?; + for (agent, session) in &dead.sessions { + if !agent::is_safe_session_id(session) || agent::by_id(agent).is_none() { + continue; + } + let mut forgot = attribution::forget_local(local, agent, session)?; + for key in transcripts + .iter() + .filter(|k| transcript_of(k, agent, session)) + { + local.delete(key)?; + forgot = true; + } + if forgot { + report.forgotten += 1; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn transcript_keys_are_matched_to_their_session() { + let id = "11111111-2222-3333-4444-555555555555"; + assert!(transcript_of( + &format!("transcripts/claude-code/-repo/{}.jsonl", id), + "claude-code", + id + )); + assert!(transcript_of( + &format!("transcripts/codex/rollout-2026-01-01T00-00-00-{}.jsonl", id), + "codex", + id + )); + assert!(!transcript_of( + &format!("transcripts/claude-code/-repo/x{}.jsonl", id), + "claude-code", + id + )); + assert!(!transcript_of( + &format!("transcripts/claude-code/.hidden/{}.jsonl", id), + "claude-code", + id + )); + assert!(!transcript_of( + &format!("transcripts/codex/{}.jsonl", id), + "claude-code", + id + )); + } + + #[test] + fn tombstones_cover_bundles_and_sessions() { + let dead = Dead::from_keys(&[ + bundle_tombstone("abc"), + session_tombstone("codex", "s1"), + "tombstones/other/x".into(), + ]); + assert!(dead.covers(&Owner::Bundle("abc".into()))); + assert!(dead.covers(&Owner::Session("s1".into()))); + assert!(!dead.covers(&Owner::Session("abc".into()))); + } + + #[test] + fn file_index_keys_name_their_project() { + let key = index::index_key(FILE, Some("git:abc:src/a.rs"), "s1"); + assert_eq!(file_index_session(&key, "git:abc"), Some("s1".into())); + assert_eq!(file_index_session(&key, "git:ab"), None); + } +} diff --git a/src/usage.txt b/src/usage.txt index 98a2771..deddb3f 100644 --- a/src/usage.txt +++ b/src/usage.txt @@ -2,24 +2,29 @@ loch — save and restore agent coding sessions across machines Usage: loch list [--cwd ] [--branch ] [--agent ] - loch list --remote [--branch ] [--all] [--store ] + loch list --saved | --remote [] [--branch ] [--all] loch save [--cwd ] [--branch ] [--session ] [--agent ] - [--store ] - loch restore [--into ] [--store ] [--force] [--new-id] - loch delete [--store ] - loch reindex [--store ] + [--push []] + loch restore [--into ] [--remote ] [--force] [--new-id] + loch delete | --session [--agent ] [--remote []] + loch reindex [--remote []] loch ingest [--cwd ] [--branch ] [--session ] [--author | --author-key ] [--out ] loch install [--local | --project] [--cwd ] [--command ] [--agent ] loch blame [--html [] [--lines ] [--no-open]] - [--store ] - loch log [:[-]] [--store ] + loch log [:[-]] loch ask : [] [--at-turn] [--no-launch] - [--store ] - loch backfill [--cwd ] [--store ] + loch backfill [--cwd ] attribute turns from before the hooks + loch push [] [--all] [--cwd ] [--dry-run] [--force] + send this project's bundles, records and + transcripts to a remote + loch pull [] [--all] [--cwd ] + fetch this project's records and transcripts + loch remote [list] | add | remove + the stores push and pull reach (~/.loch/config) loch gc delete snapshots nothing needs (the hooks also do this every 50 snapshots) loch hook prompt | stop | end [--agent ] (run by the agent's harness) @@ -35,8 +40,19 @@ Stores: local directory s3://bucket/prefix any S3-compatible endpoint +Like git: `save` packs a bundle into this machine's store (~/.loch/store), +and `push` sends it, with what the hooks recorded, to a remote. `restore` takes +a bundle from here, or fetches it from the remote. `delete` removes from here +alone, and with --remote from the remote too, leaving a tombstone so no push +brings it back. Transcripts are redacted on the way out; blame, log and ask +read only what is here, which `pull` brings up to date. + +A remote is a name from `loch remote` or a URI (--store still works). +Without one: LOCH_REMOTE, then `origin`, then the only remote there is. + Environment: - LOCH_STORE default store URI + LOCH_REMOTE the remote push and pull use, ahead of the configured one + LOCH_STORE the old name for LOCH_REMOTE, read with a warning SOURCE_DATE_EPOCH fixed createdAt for save, so a bundle is reproducible LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) LOCH_S3_REGION region override @@ -47,15 +63,16 @@ Derived conversation files go to ~/.loch/derived unless --out says otherwise. `install` adds hooks that snapshot the workspace when a prompt is submitted, when the agent stops and when the session ends, and record which lines each -turn added — however it added them — in the store, along with the session's -transcript. By default they go in your own settings (Claude Code's -settings.json under CLAUDE_CONFIG_DIR or ~/.claude, Codex's -$CODEX_HOME/hooks.json) and run in every git repository. --local puts them in -this project on this machine alone (.claude/settings.local.json; Codex has no -uncommitted file, so .codex/hooks.json), and --project in its committed -settings for everyone. A turn is recorded once, however many of these reach -it. Codex runs new hooks only after you trust them in its /hooks, and a -project's only in a project it trusts. +turn added — however it added them — in the local store (~/.loch/store), +along with the session's transcript; hooks never reach a remote store. By +default they go in your own settings (Claude Code's settings.json under +CLAUDE_CONFIG_DIR or ~/.claude, Codex's $CODEX_HOME/hooks.json) and run in +every git repository. --local puts them in this project on this machine alone +(.claude/settings.local.json; Codex has no uncommitted file, so +.codex/hooks.json), and --project in its committed settings for everyone. A +turn is recorded once, however many of these reach it. Codex runs new hooks +only after you trust them in its /hooks, and a project's only in a project it +trusts. Nothing is written to git, so squashes and rebases don't lose anything. `blame` shows which turn wrote each line, `log` every turn that changed a file or line range; `ask` forks that conversation and resumes it in the agent that diff --git a/tests/cli.rs b/tests/cli.rs index 91af02c..01fca58 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -890,7 +890,11 @@ fn test_json_save_reports_the_ref_and_redaction_counts_without_the_match() { .unwrap() .len(); assert_eq!(at(&document, "bytes"), &Value::int(size as i64)); - assert_eq!(text(&document, "store"), s(&store)); + // Saved here, and pushed to the store `--store` named. + assert!(text(&document, "store").ends_with("/.loch/store")); + let pushed = at(&document, "pushed"); + assert_eq!(text(at(pushed, "remote"), "uri"), s(&store)); + assert_eq!(at(at(pushed, "pushed"), "bundles"), &Value::int(1)); assert_eq!(at(&document, "redacted"), &Value::int(1)); let session = only(&document, "sessions"); assert_eq!(text(session, "sessionId"), "abc"); diff --git a/tests/codex.rs b/tests/codex.rs index 4868818..b295482 100644 --- a/tests/codex.rs +++ b/tests/codex.rs @@ -79,7 +79,8 @@ impl World { command .current_dir(cwd) .env("HOME", &self.home) - .env("LOCH_STORE", &self.store) + .env_remove("LOCH_STORE") + .env("LOCH_REMOTE", &self.store) .env("GIT_CONFIG_GLOBAL", self.root_gitconfig()) .env("GIT_CONFIG_NOSYSTEM", "1") .env("GIT_AUTHOR_NAME", "Test") @@ -270,8 +271,8 @@ impl World { fn edit_record(&self) -> Value { let path = self - .store - .join("edits/codex") + .home + .join(".loch/store/edits/codex") .join(format!("{}.json", SESSION)); json::loads(&fs::read_to_string(path).unwrap()).unwrap() } @@ -548,7 +549,7 @@ fn a_codex_session_saves_and_restores_onto_another_machine() { world.begin(SESSION, TURN_B, &repo, 2, &format!("now in {}", repo)); world.finish(SESSION, TURN_B, 2); - let save = world.ok(&["save"]); + let save = world.ok(&["save", "--push"]); let saved = &items(&save, "sessions")[0]; assert_eq!(text(saved, "agent"), "codex"); assert_eq!(text(saved, "agentVersion"), "0.166.0"); @@ -599,7 +600,7 @@ fn restore_finds_a_session_filed_under_another_day() { let world = World::new(); world.meta(SESSION, &s(&world.repo), "feat/x"); world.begin(SESSION, TURN_A, &s(&world.repo), 1, "hello"); - let reference = text(&world.ok(&["save"]), "ref").to_string(); + let reference = text(&world.ok(&["save", "--push"]), "ref").to_string(); let there = world.elsewhere("b"); let elsewhere = there .home @@ -643,7 +644,7 @@ fn one_bundle_carries_both_agents_and_restores_each_to_its_own() { s(&world.rollout(SESSION)) )); - let save = world.ok(&["save"]); + let save = world.ok(&["save", "--push"]); let agents: Vec<&str> = items(&save, "sessions") .iter() .map(|s| text(s, "agent")) @@ -696,7 +697,7 @@ fn a_bundle_of_claude_sessions_alone_has_no_agent_fields() { ), ) .unwrap(); - let save = world.ok(&["save"]); + let save = world.ok(&["save", "--push"]); let packed = fs::read( world .store @@ -893,7 +894,7 @@ fn a_timestamp_a_bundle_carries_cannot_crash_restore() { )], ); world.begin(SESSION, TURN_A, &repo, 1, "hello"); - let reference = text(&world.ok(&["save"]), "ref").to_string(); + let reference = text(&world.ok(&["save", "--push"]), "ref").to_string(); let there = world.elsewhere("b"); let restore = there.ok(&["restore", &reference]); let path = text(&items(&restore, "sessions")[0], "path").to_string(); @@ -1015,15 +1016,14 @@ fn collect_files(dir: &Path, into: &mut Vec) { // -- SessionEnd under Codex's 3s clamp --------------------------------------------------- -/// Codex kills a `SessionEnd` hook after 3s. `end` closes the open turn -/// locally — snapshot, diff, the edit record written aside and renamed — -/// before it touches the store, so a kill during a slow store loses the -/// store's copy and not the turn. This pins that order, and what the kill -/// leaves behind: the record on this machine, nothing in the store (no later -/// hook of an ended session publishes it), and the session's state still -/// open. +/// Codex kills a `SessionEnd` hook after 3s. When hooks published to the +/// store, a store that hung held `end` past that, and the kill left the +/// session's last turn on this machine alone with nothing to publish it +/// later. Hooks now write only the local store, so `end` finishes well inside +/// the clamp whatever `LOCH_STORE` names, and closes the turn and lets the +/// session's state go. #[test] -fn a_session_end_killed_while_the_store_hangs_keeps_the_turn_locally() { +fn a_session_end_finishes_inside_codex_s_clamp_while_a_remote_hangs() { use std::net::TcpListener; use std::time::{Duration, Instant}; let world = World::new(); @@ -1039,14 +1039,6 @@ fn a_session_end_killed_while_the_store_hangs_keeps_the_turn_locally() { // A store that accepts and never answers. let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); - let held = std::thread::spawn(move || { - let mut open = Vec::new(); - for stream in listener.incoming().take(1) { - open.push(stream); - } - std::thread::sleep(Duration::from_secs(10)); - drop(open); - }); let mut child = world .command(env!("CARGO_BIN_EXE_loch"), &world.repo) .args(["hook", "end", "--agent", "codex"]) @@ -1067,37 +1059,29 @@ fn a_session_end_killed_while_the_store_hangs_keeps_the_turn_locally() { .write_all(world.event(SESSION, None, None).as_bytes()) .unwrap(); let started = Instant::now(); - while started.elapsed() < Duration::from_secs(3) { - if child.try_wait().unwrap().is_some() { - break; - } - std::thread::sleep(Duration::from_millis(50)); + while started.elapsed() < Duration::from_secs(3) && child.try_wait().unwrap().is_none() { + std::thread::sleep(Duration::from_millis(20)); } - assert!( - child.try_wait().unwrap().is_none(), - "end was still waiting on the store at 3s" - ); - child.kill().unwrap(); - child.wait().unwrap(); - drop(held); + let finished = child.try_wait().unwrap(); + if finished.is_none() { + child.kill().unwrap(); + } + drop(listener); + assert!(finished.is_some(), "end was still running at 3s"); - let local = world - .home - .join(".loch/edits/codex") - .join(format!("{}.json", SESSION)); - let record = json::loads(&fs::read_to_string(&local).unwrap()).unwrap(); + let record = world.edit_record(); let turns = items(&record, "turns"); assert_eq!(turns.len(), 1); assert_eq!(text(&turns[0], "promptUuid"), TURN_A); assert_eq!(turns[0].get("interrupted"), Some(&Value::Bool(true))); assert!(!items(&turns[0], "files").is_empty()); assert!( - world + !world .home .join(".loch/sessions") .join(format!("{}.json", SESSION)) .exists(), - "the kill came before the state was let go" + "the session's state was let go" ); } @@ -1194,7 +1178,7 @@ fn a_second_spelling_of_the_live_cwd_is_not_another_cwd() { fn both_spellings_of_the_live_cwd_are_restored_into_the_target() { let world = World::new(); a_session_through_two_spellings(&world); - let reference = text(&world.ok(&["save"]), "ref").to_string(); + let reference = text(&world.ok(&["save", "--push"]), "ref").to_string(); let there = world.elsewhere("b"); let restore = there.ok(&["restore", &reference, "--new-id"]); let session = &items(&restore, "sessions")[0]; @@ -1209,3 +1193,285 @@ fn both_spellings_of_the_live_cwd_are_restored_into_the_target() { at(session, "foreignCwds") ); } + +// -- save is commit, push is push --------------------------------------------------------- + +impl World { + /// `loch --json` with no remote in the environment. + fn json_without_remote(&self, args: &[&str]) -> (Value, i32, String) { + let out = self + .command(env!("CARGO_BIN_EXE_loch"), &self.repo) + .args(args) + .arg("--json") + .env_remove("LOCH_REMOTE") + .output() + .unwrap(); + let text = String::from_utf8(out.stdout).unwrap(); + ( + json::loads(text.trim()).unwrap(), + out.status.code().unwrap(), + String::from_utf8(out.stderr).unwrap(), + ) + } + + fn one_saved_session(&self) { + let repo = s(&self.repo); + self.meta(SESSION, &repo, "feat/x"); + self.begin(SESSION, TURN_A, &repo, 1, "the work"); + self.finish(SESSION, TURN_A, 1); + } + + fn local_bundle(&self, reference: &str) -> PathBuf { + self.home + .join(".loch/store/bundles") + .join(format!("{}.loch", reference)) + } +} + +#[test] +fn save_keeps_the_bundle_here_until_it_is_pushed() { + let world = World::new(); + world.one_saved_session(); + let save = world.ok(&["save"]); + let reference = text(&save, "ref").to_string(); + assert_eq!(save.get("pushed"), Some(&Value::Null)); + assert!(world.local_bundle(&reference).is_file()); + assert!(!world.store.exists(), "nothing reached the remote"); + let saved = world.ok(&["list", "--saved"]); + assert_eq!(saved.get("bundles").unwrap().as_i64(), Some(1)); + assert!(saved.get("saved").unwrap().truthy()); + let remote = world.ok(&["list", "--remote"]); + assert_eq!(remote.get("bundles").unwrap().as_i64(), Some(0)); + + // Not on the far side yet; then pushed, and there. + let there = world.elsewhere("b"); + let (missing, code) = there.json(&["restore", &reference]); + assert_eq!((text(&missing, "code"), code), ("bundle-not-found", 1)); + let push = world.ok(&["push"]); + assert_eq!(at(at(&push, "pushed"), "bundles").as_i64(), Some(1)); + assert_eq!(at(at(&push, "pushed"), "branchEntries").as_i64(), Some(1)); + assert_eq!( + world + .ok(&["list", "--remote"]) + .get("bundles") + .unwrap() + .as_i64(), + Some(1) + ); + let restore = there.ok(&["restore", &reference]); + assert!(at(&restore, "fetchedFrom").get("uri").is_some()); + // Kept here once fetched, so the next restore needs no remote. + assert!(there.local_bundle(&reference).is_file()); + let (again, _, _) = there.json_without_remote(&["restore", &reference, "--force"]); + assert!(again.get("ok").unwrap().truthy(), "{:?}", again); + assert_eq!(again.get("fetchedFrom"), Some(&Value::Null)); +} + +#[test] +fn restore_without_a_remote_says_the_bundle_is_not_here() { + let world = World::new(); + let reference = "a".repeat(64); + let (document, code, _) = world.json_without_remote(&["restore", &reference]); + assert_eq!((text(&document, "code"), code), ("bundle-not-found", 1)); + let (document, _, _) = world.json_without_remote(&["restore", &reference, "--remote"]); + assert_eq!(text(&document, "code"), "no-remote"); +} + +#[test] +fn a_fetched_bundle_must_hash_to_its_ref() { + let world = World::new(); + world.one_saved_session(); + let reference = text(&world.ok(&["save", "--push"]), "ref").to_string(); + let forged = "b".repeat(64); + fs::copy( + world.store.join(format!("bundles/{}.loch", reference)), + world.store.join(format!("bundles/{}.loch", forged)), + ) + .unwrap(); + let there = world.elsewhere("b"); + let (document, _) = there.json(&["restore", &forged]); + assert_eq!(text(&document, "code"), "bundle-unreadable"); + assert!(!there.local_bundle(&forged).exists()); +} + +#[test] +fn a_bundle_deleted_on_the_remote_stays_deleted() { + let world = World::new(); + world.one_saved_session(); + let reference = text(&world.ok(&["save", "--push"]), "ref").to_string(); + let packed = fs::read(world.local_bundle(&reference)).unwrap(); + let there = world.elsewhere("b"); + there.ok(&["restore", &reference]); + + // A local delete leaves the remote alone. + let local = world.ok(&["delete", &reference]); + assert_eq!(local.get("remote"), Some(&Value::Null)); + assert!(!world.local_bundle(&reference).exists()); + assert!(world + .store + .join(format!("bundles/{}.loch", reference)) + .is_file()); + + // `--remote `: the ref is taken for what it is. + let gone = there.ok(&["delete", "--remote", &reference]); + assert_eq!(items(&gone, "tombstones").len(), 1); + assert!(!world + .store + .join(format!("bundles/{}.loch", reference)) + .exists()); + assert!(!there.local_bundle(&reference).exists()); + + // A machine still holding it can't push it back, and forgets it when it + // pulls. + fs::create_dir_all(world.local_bundle(&reference).parent().unwrap()).unwrap(); + fs::write(world.local_bundle(&reference), &packed).unwrap(); + fs::remove_dir_all(world.home.join(".loch/pushed")).unwrap(); + let push = world.ok(&["push"]); + assert_eq!(push.get("tombstoned").unwrap().as_i64(), Some(1)); + assert_eq!(push.get("total").unwrap().as_i64(), Some(0)); + assert!(!world + .store + .join(format!("bundles/{}.loch", reference)) + .exists()); + let pull = world.ok(&["pull"]); + assert_eq!(pull.get("forgotten").unwrap().as_i64(), Some(1)); + assert!(!world.local_bundle(&reference).exists()); + + let (absent, code) = world.json(&["delete", "--remote", &"c".repeat(64)]); + assert_eq!((text(&absent, "code"), code), ("bundle-not-found", 1)); + assert!(!world + .store + .join(format!("tombstones/bundle/{}", "c".repeat(64))) + .exists()); +} + +#[test] +fn a_session_deleted_on_the_remote_takes_its_transcript_and_record() { + let world = World::new(); + world.turn( + TURN_A, + 1, + "write it", + "echo 'a line the turn wrote' > a.txt", + ); + world.ok(&["push"]); + assert!(world + .store + .join(format!("edits/codex/{}.json", SESSION)) + .is_file()); + let transcripts = world.store.join("transcripts/codex"); + assert_eq!(fs::read_dir(&transcripts).unwrap().count(), 1); + + let deleted = world.ok(&["delete", "--session", SESSION, "--remote"]); + assert_eq!( + items(&deleted, "tombstones")[0].as_str(), + Some(format!("tombstones/session/codex/{}", SESSION).as_str()) + ); + assert!(!world + .store + .join(format!("edits/codex/{}.json", SESSION)) + .exists()); + assert_eq!(fs::read_dir(&transcripts).unwrap().count(), 0); + assert!(world + .store + .join("index/file") + .read_dir() + .map_or(true, |mut d| d + .all(|e| fs::read_dir(e.unwrap().path()).unwrap().count() == 0))); + // This machine's copies go too, never the agent's own rollout. + assert!(!world + .home + .join(format!(".loch/store/edits/codex/{}.json", SESSION)) + .exists()); + assert!(!world + .home + .join(format!(".loch/edits/codex/{}.json", SESSION)) + .exists()); + assert!(world.rollout(SESSION).is_file()); + // The next turn records the session again, and push won't send it. + world.turn(TURN_B, 2, "more", "echo 'another line' >> a.txt"); + let push = world.ok(&["push"]); + assert_eq!(push.get("total").unwrap().as_i64(), Some(0)); + + let (unknown, code) = world.json(&["delete", "--session", "nope"]); + assert_eq!((text(&unknown, "code"), code), ("session-not-found", 1)); + let (bad, code) = world.json(&["delete", "--session", "../x"]); + assert_eq!((text(&bad, "code"), code), ("usage", 2)); +} + +#[test] +fn loch_store_set_and_a_plain_save_is_told_it_did_not_upload() { + let world = World::new(); + world.one_saved_session(); + let out = world + .command(env!("CARGO_BIN_EXE_loch"), &world.repo) + .args(["save", "--json"]) + .env_remove("LOCH_REMOTE") + .env("LOCH_STORE", &world.store) + .output() + .unwrap(); + assert!(out.stderr.is_empty(), "JSON mode keeps stderr empty"); + let document = json::loads(String::from_utf8(out.stdout).unwrap().trim()).unwrap(); + assert_eq!(text(&document, "deprecated"), "LOCH_STORE"); + let out = world + .command(env!("CARGO_BIN_EXE_loch"), &world.repo) + .args(["save"]) + .env_remove("LOCH_REMOTE") + .env("LOCH_STORE", &world.store) + .output() + .unwrap(); + assert!(String::from_utf8_lossy(&out.stderr).contains("save --push")); +} + +#[test] +fn a_push_that_fails_after_save_keeps_the_bundle_and_names_it() { + let world = World::new(); + world.one_saved_session(); + let blocked = world.root.join("blocked"); + fs::write(&blocked, "not a store").unwrap(); + let (document, code) = world.json(&["save", "--push", &s(&blocked)]); + assert_eq!((text(&document, "code"), code), ("store-unreachable", 1)); + let reference = text(&document, "ref").to_string(); + assert!(world.local_bundle(&reference).is_file()); + assert!(text(&document, "error").starts_with(&format!("saved {} on this machine", reference))); +} + +#[test] +fn a_push_sends_only_this_project_s_bundles_unless_asked_for_all() { + let world = World::new(); + world.one_saved_session(); + let here = text(&world.ok(&["save"]), "ref").to_string(); + // A second repository, with its own root commit and its own session. + let client = world.root.join("client"); + fs::create_dir_all(&client).unwrap(); + for args in [ + vec!["init", "-q", "-b", "main"], + vec!["commit", "-q", "--allow-empty", "-m", "client root"], + ] { + let out = world.command("git", &client).args(&args).output().unwrap(); + assert!(out.status.success()); + } + let other = "01a1f570-0000-7000-8000-00000000c11e"; + world.meta(other, &s(&client), "main"); + world.begin(other, TURN_B, &s(&client), 3, "client work"); + world.finish(other, TURN_B, 3); + let theirs = text(&world.ok(&["save", "--cwd", &s(&client)]), "ref").to_string(); + assert_ne!(here, theirs); + + let push = world.ok(&["push"]); + assert_eq!(at(at(&push, "pushed"), "bundles").as_i64(), Some(1)); + assert!(world.store.join(format!("bundles/{}.loch", here)).is_file()); + assert!( + !world + .store + .join(format!("bundles/{}.loch", theirs)) + .exists(), + "the client's transcripts stay off this project's remote" + ); + let all = world.ok(&["push", "--all"]); + assert_eq!(at(at(&all, "pushed"), "bundles").as_i64(), Some(1)); + assert!(world + .store + .join(format!("bundles/{}.loch", theirs)) + .is_file()); +} diff --git a/tests/remote.rs b/tests/remote.rs new file mode 100644 index 0000000..46e8294 --- /dev/null +++ b/tests/remote.rs @@ -0,0 +1,151 @@ +//! `loch remote` and the config it keeps, in a scratch HOME. + +use loch::json::{self, Value}; +use std::fs; +use std::path::PathBuf; +use std::process::Command; +use std::sync::atomic::{AtomicUsize, Ordering}; + +static COUNTER: AtomicUsize = AtomicUsize::new(0); + +struct Home(PathBuf); + +impl Drop for Home { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn home() -> Home { + let path = std::env::temp_dir().join(format!( + "loch-test-remote-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).unwrap(); + Home(path) +} + +fn loch(home: &Home, args: &[&str]) -> (Value, i32) { + let out = Command::new(env!("CARGO_BIN_EXE_loch")) + .args(args) + .arg("--json") + .env("HOME", &home.0) + .env_remove("LOCH_STORE") + .env_remove("LOCH_REMOTE") + .output() + .unwrap(); + assert!( + out.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let doc = json::loads(String::from_utf8(out.stdout).unwrap().trim()).unwrap(); + (doc, out.status.code().unwrap()) +} + +fn code(doc: &Value) -> &str { + doc.get("code").and_then(Value::as_str).unwrap_or("") +} + +fn names(doc: &Value) -> Vec { + doc.get("remotes") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|r| r.get("name").unwrap().as_str().unwrap().to_string()) + .collect() +} + +#[test] +fn remotes_are_added_listed_and_removed_in_order() { + let h = home(); + let (empty, status) = loch(&h, &["remote"]); + assert_eq!(status, 0); + assert!(names(&empty).is_empty()); + assert_eq!(empty.get("default"), Some(&Value::Null)); + + let (added, _) = loch(&h, &["remote", "add", "backup", "/tmp/loch-backup"]); + assert!(added.get("ok").unwrap().truthy()); + assert!(added.get("command").unwrap().is_str("remote")); + // The only remote is the default. + let (one, _) = loch(&h, &["remote", "list"]); + assert!(one.get("default").unwrap().is_str("backup")); + + loch(&h, &["remote", "add", "origin", "s3://bucket/prefix"]); + let (two, _) = loch(&h, &["remote", "list"]); + assert_eq!(names(&two), vec!["backup", "origin"]); + assert!(two.get("default").unwrap().is_str("origin")); + + let (removed, _) = loch(&h, &["remote", "remove", "origin"]); + assert!(removed + .get("remote") + .unwrap() + .get("uri") + .unwrap() + .is_str("s3://bucket/prefix")); + let (left, _) = loch(&h, &["remote", "list"]); + assert_eq!(names(&left), vec!["backup"]); +} + +#[test] +fn remote_failures_have_codes() { + let h = home(); + loch(&h, &["remote", "add", "origin", "/tmp/x"]); + let (exists, status) = loch(&h, &["remote", "add", "origin", "/tmp/y"]); + assert_eq!((code(&exists), status), ("remote-exists", 1)); + let (unknown, _) = loch(&h, &["remote", "remove", "nope"]); + assert_eq!(code(&unknown), "unknown-remote"); + let (bad_name, status) = loch(&h, &["remote", "add", "a/b", "/tmp/z"]); + assert_eq!((code(&bad_name), status), ("usage", 2)); + let (bad_uri, _) = loch(&h, &["remote", "add", "web", "http://example.com"]); + assert_eq!(code(&bad_uri), "invalid-uri"); + let (bad_action, status) = loch(&h, &["remote", "rename"]); + assert_eq!((code(&bad_action), status), ("usage", 2)); + let (missing, status) = loch(&h, &["remote", "add", "only-a-name"]); + assert_eq!((code(&missing), status), ("usage", 2)); +} + +#[test] +fn a_config_that_will_not_parse_is_never_overwritten() { + let h = home(); + fs::create_dir_all(h.0.join(".loch")).unwrap(); + fs::write(h.0.join(".loch/config"), "not json").unwrap(); + let (listed, _) = loch(&h, &["remote"]); + assert_eq!(code(&listed), "config-unreadable"); + let (added, _) = loch(&h, &["remote", "add", "origin", "/tmp/x"]); + assert_eq!(code(&added), "config-unreadable"); + assert_eq!( + fs::read_to_string(h.0.join(".loch/config")).unwrap(), + "not json" + ); +} + +#[test] +fn a_relative_path_is_kept_absolute_and_an_unknown_scheme_refused() { + let h = home(); + let out = Command::new(env!("CARGO_BIN_EXE_loch")) + .args(["remote", "add", "here", "rel/store", "--json"]) + .current_dir(&h.0) + .env("HOME", &h.0) + .output() + .unwrap(); + let added = json::loads(String::from_utf8(out.stdout).unwrap().trim()).unwrap(); + let uri = added + .get("remote") + .unwrap() + .get("uri") + .unwrap() + .as_str() + .unwrap() + .to_string(); + assert!( + uri.starts_with('/') && uri.ends_with("/rel/store"), + "{}", + uri + ); + let (ssh, _) = loch(&h, &["remote", "add", "box", "ssh://host/path"]); + assert_eq!(code(&ssh), "invalid-uri"); +} diff --git a/tests/store.rs b/tests/store.rs index df1b17d..440af7a 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -11,7 +11,7 @@ //! exist; each test works under its own unique prefix within it. use loch::s3::S3Store; -use loch::store::{create_store, default_store, resolve_store_uri, FileStore, Store, StoreError}; +use loch::store::{create_store, FileStore, Store, StoreError}; use std::fs; use std::path::PathBuf; use std::sync::{Mutex, MutexGuard}; @@ -134,24 +134,26 @@ fn create_store_rejects_a_bucketless_s3_uri() { } #[test] -fn resolve_store_uri_prefers_explicit_then_env() { +fn the_remote_is_named_then_loch_remote_then_loch_store() { let _guard = env_lock(); - let saved = std::env::var_os("LOCH_STORE"); - - std::env::remove_var("LOCH_STORE"); - let unset = resolve_store_uri(None); - std::env::set_var("LOCH_STORE", "s3://from-env/x"); - let from_env = resolve_store_uri(None); - let explicit = resolve_store_uri(Some("/explicit")); - - match saved { - Some(value) => std::env::set_var("LOCH_STORE", value), - None => std::env::remove_var("LOCH_STORE"), + let saved: Vec<_> = ["LOCH_REMOTE", "LOCH_STORE"] + .iter() + .map(|v| (*v, std::env::var_os(v))) + .collect(); + std::env::set_var("LOCH_STORE", "s3://old/x"); + let old = loch::remote::resolve(None).unwrap(); + std::env::set_var("LOCH_REMOTE", "s3://new/x"); + let new = loch::remote::resolve(None).unwrap(); + let named = loch::remote::resolve(Some("/explicit")).unwrap(); + for (variable, value) in saved { + match value { + Some(value) => std::env::set_var(variable, value), + None => std::env::remove_var(variable), + } } - - assert_eq!(unset, default_store()); - assert_eq!(from_env, "s3://from-env/x"); - assert_eq!(explicit, "/explicit"); + assert_eq!((old.uri.as_str(), old.deprecated), ("s3://old/x", true)); + assert_eq!((new.uri.as_str(), new.deprecated), ("s3://new/x", false)); + assert_eq!(named.uri, "/explicit"); } #[test] diff --git a/tests/trace.rs b/tests/trace.rs index b9d30d2..c4d0442 100644 --- a/tests/trace.rs +++ b/tests/trace.rs @@ -57,7 +57,7 @@ impl World { transcript: home .join(".claude/projects/-repo") .join(format!("{}.jsonl", SESSION)), - store: root.join("store"), + store: home.join(".loch/store"), root, home, repo, @@ -88,7 +88,7 @@ impl World { "PATH", format!("{}:/usr/bin:/bin", s(&self.root.join("bin"))), ) - .env("LOCH_STORE", &self.store) + .env_remove("LOCH_STORE") .env("GIT_CONFIG_GLOBAL", self.root.join("gitconfig")) .env("GIT_CONFIG_NOSYSTEM", "1") .env("GIT_AUTHOR_NAME", "Test") @@ -463,23 +463,51 @@ fn a_person_s_edits_between_turns_are_not_the_agent_s() { assert_eq!(owners(&w.json(&["blame", "notes.txt"])), vec![None]); } +/// `loch --json` as another machine: its own HOME, in `cwd`. +fn json_on(w: &World, home: &Path, cwd: &Path, args: &[&str]) -> Value { + let out = w + .command(env!("CARGO_BIN_EXE_loch"), cwd) + .args(args) + .arg("--json") + .env("HOME", home) + .output() + .unwrap(); + assert!( + out.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + json::loads(String::from_utf8(out.stdout).unwrap().trim()).unwrap() +} + +fn pushed(doc: &Value, kind: &str) -> i64 { + doc.get("pushed") + .unwrap() + .get(kind) + .unwrap() + .as_i64() + .unwrap() +} + #[test] fn the_link_survives_a_squash_and_a_fresh_clone() { let w = calculator_world(); + let remote = w.root.join("remote"); + let push = w.json(&["push", &s(&remote)]); + assert!(push.get("ok").unwrap().truthy(), "{:?}", push); w.git(&w.repo, &["add", "-A"]); w.git(&w.repo, &["commit", "-q", "-m", "squashed"]); let clone = w.root.join("teammate"); w.git(&w.root, &["clone", "-q", &s(&w.repo), &s(&clone)]); - // Another machine: its own empty HOME, only the store in common. + // Another machine: its own empty HOME, only the remote in common. let other_home = w.root.join("other-home"); fs::create_dir_all(&other_home).unwrap(); - let out = w - .command(env!("CARGO_BIN_EXE_loch"), &clone) - .args(["blame", "calc.py", "--json"]) - .env("HOME", &other_home) - .output() - .unwrap(); - let blame = json::loads(String::from_utf8(out.stdout).unwrap().trim()).unwrap(); + let before = json_on(&w, &other_home, &clone, &["blame", "calc.py"]); + assert_eq!(owners(&before)[4], None, "nothing until it pulls"); + let pull = json_on(&w, &other_home, &clone, &["pull", &s(&remote)]); + assert_eq!(pull.get("records").unwrap().as_i64(), Some(1)); + assert_eq!(pull.get("transcripts").unwrap().as_i64(), Some(1)); + let blame = json_on(&w, &other_home, &clone, &["blame", "calc.py"]); assert_eq!( owners(&blame)[4], some("make sub safer and generate the table") @@ -487,8 +515,205 @@ fn the_link_survives_a_squash_and_a_fresh_clone() { let first = &blame.get("conversations").unwrap().as_array().unwrap()[0]; assert!( first.get("available").unwrap().truthy(), - "the transcript comes from the store" + "the transcript came with the pull" ); + let again = json_on(&w, &other_home, &clone, &["pull", &s(&remote)]); + assert_eq!(again.get("records").unwrap().as_i64(), Some(0)); + assert_eq!(again.get("upToDate").unwrap().as_i64(), Some(1)); +} + +#[test] +fn push_sends_what_is_new_once() { + let mut w = calculator_world(); + let remote = w.root.join("remote"); + let dry = w.json(&["push", &s(&remote), "--dry-run"]); + assert_eq!(pushed(&dry, "records"), 1); + assert!(!remote.exists(), "a dry run sends nothing"); + let first = w.json(&["push", &s(&remote)]); + assert_eq!(pushed(&first, "records"), 1); + assert_eq!(pushed(&first, "fileEntries"), 2); + assert_eq!(pushed(&first, "transcripts"), 1); + assert!(remote + .join(format!("edits/claude-code/{}.json", SESSION)) + .is_file()); + let second = w.json(&["push", &s(&remote)]); + assert_eq!(second.get("total").unwrap().as_i64(), Some(0)); + assert_eq!(second.get("upToDate").unwrap().as_i64(), Some(4)); + // A new turn changes the record and the transcript, and only those go. + w.prompt("p3", "one more"); + w.sh("echo 'more_rows = 3' >> table.py"); + w.stop("p3"); + let third = w.json(&["push", &s(&remote)]); + assert_eq!(pushed(&third, "records"), 1); + assert_eq!(pushed(&third, "transcripts"), 1); + assert_eq!(pushed(&third, "fileEntries"), 0); +} + +#[test] +fn push_redacts_transcripts_and_leaves_the_local_copy_alone() { + let mut w = World::new(true); + w.prompt("p1", "deploy with AKIAABCDEFGHIJKLMNOP please"); + w.write("a.py", "deployed_it = True\n"); + w.stop("p1"); + let remote = w.root.join("remote"); + let push = w.json(&["push", &s(&remote)]); + assert!(push.get("redacted").unwrap().as_i64().unwrap() >= 1); + let key = format!("transcripts/claude-code/-repo/{}.jsonl", SESSION); + let sent = fs::read_to_string(remote.join(&key)).unwrap(); + assert!(!sent.contains("AKIAABCDEFGHIJKLMNOP") && sent.contains("[REDACTED:")); + let kept = fs::read_to_string(w.store.join(&key)).unwrap(); + assert!(kept.contains("AKIAABCDEFGHIJKLMNOP")); + assert!(fs::read_to_string(&w.transcript) + .unwrap() + .contains("AKIAABCDEFGHIJKLMNOP")); +} + +#[test] +fn push_and_pull_cover_this_project_unless_asked_for_all() { + let w = calculator_world(); + let elsewhere = w.root.join("elsewhere"); + fs::create_dir_all(&elsewhere).unwrap(); + w.git(&elsewhere, &["init", "-q", "-b", "main"]); + w.git( + &elsewhere, + &["commit", "-q", "--allow-empty", "-m", "other root"], + ); + let remote = w.root.join("remote"); + let there = json_on(&w, &w.home, &elsewhere, &["push", &s(&remote)]); + assert_eq!(there.get("total").unwrap().as_i64(), Some(0)); + assert!(there + .get("project") + .unwrap() + .as_str() + .unwrap() + .starts_with("git:")); + let all = json_on(&w, &w.home, &elsewhere, &["push", &s(&remote), "--all"]); + assert_eq!(pushed(&all, "records"), 1); + assert_eq!(all.get("project"), Some(&Value::Null)); + let other_home = w.root.join("other-home"); + fs::create_dir_all(&other_home).unwrap(); + let scoped = json_on(&w, &other_home, &elsewhere, &["pull", &s(&remote)]); + assert_eq!(scoped.get("records").unwrap().as_i64(), Some(0)); + let everything = json_on(&w, &other_home, &elsewhere, &["pull", &s(&remote), "--all"]); + assert_eq!(everything.get("records").unwrap().as_i64(), Some(1)); +} + +#[test] +fn a_remote_tombstone_stops_push_and_pull_forgets() { + let w = calculator_world(); + let remote = w.root.join("remote"); + w.json(&["push", &s(&remote)]); + let other_home = w.root.join("other-home"); + fs::create_dir_all(&other_home).unwrap(); + json_on(&w, &other_home, &w.repo, &["pull", &s(&remote)]); + // Deleted on the remote, as `delete --remote` will. + for key in [ + format!("edits/claude-code/{}.json", SESSION), + format!("transcripts/claude-code/-repo/{}.jsonl", SESSION), + ] { + fs::remove_file(remote.join(key)).unwrap(); + } + fs::remove_dir_all(remote.join("index/file")).unwrap(); + let tomb = remote.join(format!("tombstones/session/claude-code/{}", SESSION)); + fs::create_dir_all(tomb.parent().unwrap()).unwrap(); + fs::write(&tomb, "{}").unwrap(); + // The teammate who pulled it can't push it back. + fs::remove_dir_all(other_home.join(".loch/pushed")).ok(); + let back = json_on(&w, &other_home, &w.repo, &["push", &s(&remote)]); + assert_eq!(back.get("total").unwrap().as_i64(), Some(0)); + assert!(back.get("tombstoned").unwrap().as_i64().unwrap() >= 1); + assert!(!remote + .join("edits") + .join("claude-code") + .join(format!("{}.json", SESSION)) + .exists()); + // And a pull forgets loch's copies here, but never the agent's own. + let pull = w.json(&["pull", &s(&remote)]); + assert_eq!(pull.get("forgotten").unwrap().as_i64(), Some(1)); + assert!(!w + .store + .join(format!("edits/claude-code/{}.json", SESSION)) + .exists()); + assert!(!w + .home + .join(format!(".loch/edits/claude-code/{}.json", SESSION)) + .exists()); + assert!(w.transcript.is_file()); + assert_eq!(owners(&w.json(&["blame", "calc.py"]))[4], None); +} + +#[test] +fn pull_refuses_what_a_remote_names_badly() { + let w = World::new(true); + let remote = w.root.join("remote"); + fs::create_dir_all(remote.join("edits/claude-code")).unwrap(); + fs::create_dir_all(remote.join("edits/nobody")).unwrap(); + fs::write(remote.join("edits/claude-code/bad;id.json"), "{}").unwrap(); + fs::write(remote.join("edits/nobody/s1.json"), "{}").unwrap(); + // A record that claims to be another session than its key. + let other = "22222222-2222-3333-4444-555555555555"; + fs::write( + remote.join(format!("edits/claude-code/{}.json", other)), + format!( + r#"{{"loch": 1, "agent": "claude-code", "session": "{}", "project": "x", "turns": []}}"#, + SESSION + ), + ) + .unwrap(); + let pull = w.json(&["pull", &s(&remote), "--all"]); + assert!(pull.get("ok").unwrap().truthy()); + assert_eq!(pull.get("records").unwrap().as_i64(), Some(0)); + assert_eq!(pull.get("refused").unwrap().as_i64(), Some(3)); + assert!(!w.store.join("edits").exists()); +} + +#[test] +fn push_and_pull_need_a_remote_and_say_so() { + let w = calculator_world(); + let none = w.json(&["push"]); + assert!(none.get("code").unwrap().is_str("no-remote")); + let none = w.json(&["pull"]); + assert!(none.get("code").unwrap().is_str("no-remote")); + let unknown = w.json(&["push", "nope"]); + assert!(unknown.get("code").unwrap().is_str("unknown-remote")); + let own = w.json(&["push", &s(&w.store)]); + assert!(own.get("code").unwrap().is_str("invalid-uri")); + // A named remote, and the default when there is one. + let remote = w.root.join("remote"); + w.json(&["remote", "add", "origin", &s(&remote)]); + let push = w.json(&["push"]); + assert!(push + .get("remote") + .unwrap() + .get("name") + .unwrap() + .is_str("origin")); + assert_eq!(pushed(&push, "records"), 1); +} + +#[test] +fn loch_store_still_names_the_remote_with_a_warning() { + let w = calculator_world(); + let remote = w.root.join("remote"); + let out = w + .command(env!("CARGO_BIN_EXE_loch"), &w.repo) + .args(["push"]) + .env("LOCH_STORE", &remote) + .output() + .unwrap(); + assert!(out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("LOCH_REMOTE")); + let doc = { + let out = w + .command(env!("CARGO_BIN_EXE_loch"), &w.repo) + .args(["push", "--json"]) + .env("LOCH_STORE", &remote) + .output() + .unwrap(); + assert!(out.stderr.is_empty()); + json::loads(String::from_utf8(out.stdout).unwrap().trim()).unwrap() + }; + assert!(doc.get("deprecated").unwrap().is_str("LOCH_STORE")); } #[test] @@ -605,6 +830,53 @@ fn hooks_never_fail_and_never_print() { } } +/// A remote that accepts connections and never answers, as a hung S3 does. +fn hung_remote() -> (std::net::TcpListener, String) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + (listener, endpoint) +} + +#[test] +fn hooks_never_wait_on_a_remote() { + let mut w = World::new(true); + let (_listener, endpoint) = hung_remote(); + w.prompt("p1", "write it"); + w.write("a.py", "written_while_the_remote_hangs = 1\n"); + w.record(format!( + r#"{{"type": "assistant", "uuid": "p1-end", "parentUuid": "p1", "sessionId": "{}", "cwd": "{}", "timestamp": "2026-11-18T10:01:30.000Z", "message": {{"role": "assistant", "content": [{{"type": "text", "text": "done"}}]}}}}"#, + SESSION, + s(&w.repo) + )); + let started = std::time::Instant::now(); + for name in ["stop", "end"] { + let mut child = w + .command(env!("CARGO_BIN_EXE_loch"), &w.repo) + .args(["hook", name]) + .env("LOCH_STORE", "s3://bucket/prefix") + .env("LOCH_S3_ENDPOINT", &endpoint) + .env("AWS_ACCESS_KEY_ID", "test") + .env("AWS_SECRET_ACCESS_KEY", "test") + .stdin(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(w.event().as_bytes()) + .unwrap(); + assert!(child.wait().unwrap().success()); + } + assert!( + started.elapsed() < std::time::Duration::from_secs(3), + "took {:?}", + started.elapsed() + ); + assert!(owners(&w.json(&["blame", "a.py"]))[0].is_some()); + assert!(w.store.join("transcripts/claude-code").is_dir()); +} + #[test] fn stop_snapshots_the_transcript_into_the_store() { let mut w = World::new(true); @@ -1105,3 +1377,124 @@ fn an_identical_stop_after_the_duplicate_window_is_handled() { vec![some("two steps"); 2] ); } + +fn turn_prompts(record: &Value) -> Vec { + record + .get("turns") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|t| t.get("promptUuid").unwrap().as_str().unwrap().to_string()) + .collect() +} + +fn stored_record(store: &Path) -> Value { + let text = + fs::read_to_string(store.join(format!("edits/claude-code/{}.json", SESSION))).unwrap(); + json::loads(&text).unwrap() +} + +/// A machine that pulled a session and then recorded turns of it under the +/// same id (a restore that kept the id) has the pulled record in its store and +/// no working copy. Its next turn must add to that record, not replace it. +#[test] +fn a_turn_adds_to_a_pulled_record_rather_than_replacing_it() { + let mut w = calculator_world(); + fs::remove_dir_all(w.home.join(".loch/edits")).unwrap(); + w.prompt("p3", "after the pull"); + w.sh("echo 'reviewer_line = 1' >> table.py"); + w.stop("p3"); + assert_eq!( + turn_prompts(&stored_record(&w.store)), + vec!["p1", "p2", "p3"] + ); +} + +/// Two machines recorded different turns of one session. A push merges the +/// remote's copy in rather than writing over it, and keeps the merge here. +#[test] +fn diverged_records_merge_on_push_and_pull() { + let w = calculator_world(); + let remote = w.root.join("remote"); + w.json(&["push", &s(&remote)]); + // The other machine's copy: the first turn, and one this machine never saw. + let theirs = remote.join(format!("edits/claude-code/{}.json", SESSION)); + let mut record = json::loads(&fs::read_to_string(&theirs).unwrap()).unwrap(); + if let Value::Object(map) = &mut record { + let turns = map.get_mut("turns").unwrap(); + if let Value::Array(list) = turns { + list.truncate(1); + let mut extra = list[0].clone(); + if let Value::Object(turn) = &mut extra { + turn.insert("promptUuid".into(), Value::str("elsewhere")); + turn.insert("ended".into(), Value::str("2026-11-18T11:00:00.000000Z")); + } + list.push(extra); + } + } + fs::write(&theirs, json::dumps(&record, json::DEFAULT)).unwrap(); + // And this machine recorded another turn since its last push. + let mut w = w; + w.prompt("p3", "one more here"); + w.sh("echo 'here_line = 3' >> table.py"); + w.stop("p3"); + + let push = w.json(&["push", &s(&remote)]); + assert!(push.get("ok").unwrap().truthy(), "{:?}", push); + let merged = vec!["p1", "p2", "p3", "elsewhere"]; + assert_eq!(turn_prompts(&stored_record(&remote)), merged); + assert_eq!(turn_prompts(&stored_record(&w.store)), merged); + + // A third machine that has only its own turn merges both in on pull. + let other_home = w.root.join("other-home"); + let other_store = other_home.join(".loch/store"); + fs::create_dir_all(other_store.join("edits/claude-code")).unwrap(); + let mut solo = stored_record(&w.store); + if let Value::Object(map) = &mut solo { + if let Some(Value::Array(list)) = map.get_mut("turns") { + list.retain(|t| t.get("promptUuid").unwrap().is_str("p1")); + let mut mine = list[0].clone(); + if let Value::Object(turn) = &mut mine { + turn.insert("promptUuid".into(), Value::str("third")); + turn.insert("ended".into(), Value::str("2026-11-18T12:00:00.000000Z")); + } + list.push(mine); + } + } + fs::write( + other_store.join(format!("edits/claude-code/{}.json", SESSION)), + json::dumps(&solo, json::DEFAULT), + ) + .unwrap(); + let pull = json_on(&w, &other_home, &w.repo, &["pull", &s(&remote)]); + assert_eq!(pull.get("records").unwrap().as_i64(), Some(1)); + assert_eq!( + turn_prompts(&stored_record(&other_store)), + vec!["p1", "p2", "p3", "elsewhere", "third"] + ); +} + +#[test] +fn push_force_resends_what_the_markers_claim_was_sent() { + let w = calculator_world(); + let remote = w.root.join("remote"); + w.json(&["push", &s(&remote)]); + fs::remove_dir_all(&remote).unwrap(); + let stale = w.json(&["push", &s(&remote)]); + assert_eq!(stale.get("total").unwrap().as_i64(), Some(0)); + let forced = w.json(&["push", &s(&remote), "--force"]); + assert_eq!(pushed(&forced, "records"), 1); + assert!(remote + .join(format!("edits/claude-code/{}.json", SESSION)) + .is_file()); +} + +#[test] +fn a_symlink_to_the_local_store_is_not_a_remote() { + let w = calculator_world(); + let link = w.root.join("link-to-store"); + std::os::unix::fs::symlink(&w.store, &link).unwrap(); + let push = w.json(&["push", &s(&link)]); + assert!(push.get("code").unwrap().is_str("invalid-uri")); +}