diff --git a/CLAUDE.md b/CLAUDE.md index 5d051f3..04614cd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,8 +9,8 @@ laptop that produced it. `loch` packs those transcripts into a content-addressed bundle, stores it anywhere S3-compatible, and unpacks it elsewhere with paths rewritten so the session actually resumes. -Currently supports Claude Code. Codex and Cursor are the intended next -adapters. +Supports Claude Code and Codex, behind one adapter boundary (`agent.rs`, +below). Cursor is the obvious next one. It is also becoming the **conversation format**: `loch ingest` turns a session into a content-addressed graph of turns that can be forked, shared @@ -208,6 +208,159 @@ public API. Re-verify if something breaks. bigger window is a bet on a bound that the worst cases are the likeliest to break. +## Empirical findings about Codex's storage + +Verified on codex-cli 0.166.0 by experiment (scratch repositories, real +`codex exec` and TUI runs), against the 70 rollouts on one machine +(versions 0.46, 0.121, 0.165, 0.166). Not stable public API: re-verify if +something breaks. Claude's rules above do **not** carry over; each was +re-derived. + +- **Where sessions live:** `$CODEX_HOME/sessions/YYYY/MM/DD/rollout--.jsonl`, `$CODEX_HOME` defaulting to `~/.codex`. Filed by date, + not by directory, so there is no directory to look in and discovery reads + every rollout (`codex.rs`). That costs ~50ms for 70 rollouts (10MB) and is + linear in total bytes. +- **`codex resume ` needs the rollout file and nothing else.** A copy + under a fresh id, with no row in any sqlite file, resumed and recalled its + conversation, and Codex inserted the `threads` row itself afterwards. The + sqlite files are projections: `state_5.sqlite`'s `threads` holds + `rollout_path` and summary columns, and `thread_history_1.sqlite` is keyed + by rollout byte offset (`thread_history_projection_state`). Lookup is by + the id the file name ends with. The date directory and the time in the + name don't matter (a copy under `2025/03/01` resumed), so `restore` files + a session under the day its `session_meta` says it began. + `session_index.jsonl` holds thread names alone (appended, last wins), so + loch reads it for blame's title and never writes it. +- **Records** are `{"timestamp", "type", "payload"}`, newer ones with an + `ordinal`. `session_meta` comes first: `id` and `session_id`, `cwd`, + `cli_version`, `originator`, `git: {commit_hash, branch}`, + `history_mode` (`paginated` from 0.165, absent before). The id also + appears in `thread_settings_applied.thread_id`, `item_completed.thread_id` + and `token_usage_record.session_id`, so, as with Claude, minting an id + means rewriting every occurrence (the rewrite's session pair does), and + the file name too. +- **A turn is named by id.** `task_started`, `turn_context`, + `item_completed`, `token_usage_record` and `task_complete` carry + `payload.turn_id`, and response items carry it in + `internal_chat_message_metadata_passthrough.turn_id`. But a `resume` + writes `thread_settings_applied`, which names no turn, *before* the next + `task_started`, so "the last turn seen" puts it in the previous turn. A + turn therefore runs from the first to the last record **naming** it, + which is where `ask --at-turn` cuts. +- **What a person typed** is `event_msg` `item_completed` with a + `UserMessage` item (0.165+), or `event_msg` `user_message` (older). + `response_item` user messages are not it: Codex injects + `` and AGENTS.md as user messages. +- **The live cwd is the last `turn_context`'s.** `resume -C ` + appends a `turn_context` naming the new directory, and `session_meta` + keeps naming where the session began. Nothing else marks which is live, + and there is no directory-name disambiguator as there is for Claude. The + last turn is where the session most recently ran, which is what a + restore wants. Cwds are counted from `session_meta` and `turn_context` + only. `world_state` and tool calls name directories too, so a substring + count would cry wolf, as it would for Claude. +- **Codex does not resolve symlinks in `-C`.** A session begun in `/tmp/x` + recorded `/private/tmp/x` (the process's resolved cwd), and the same + session resumed with `-C /tmp/y` recorded `/tmp/y`. Discovery compares + cwds resolved. +- **The branch is recorded once,** in `session_meta.git.branch`, for the + directory the session began in. No turn records one, and neither does + `world_state`. A moved session's branch is unknowable from its rollout, so + it is reported as none (`[no branch]`, `%00` in the index) rather than + the old directory's, which is Claude's stale-branch defect. A session + begun through a symlink to where it is now has not moved. None of the 70 + local rollouts had moved, so this is the rare case, and it is the honest + answer. +- **Hooks** use Claude's file shape, + `{"hooks": {"": [{"hooks": [{"type": "command", "command", "timeout"}]}]}}`, + from `$CODEX_HOME/hooks.json` and `/.codex/hooks.json` (plus + plugins and config layers). 0.166 knows `PreToolUse`, + `PermissionRequest`, `PostToolUse`, `PreCompact`, `PostCompact`, + `SessionStart`, `SessionEnd`, `UserPromptSubmit`, `SubagentStart`, + `SubagentStop`, `Stop`, `Interrupt` and `PreModelRequest`. They're enabled + by `[features] hooks` (stable and on here; `codex_hooks` is its deprecated + alias). It clamps the `SessionEnd` and `Interrupt` timeouts to 3s. Captured + payloads: every event carries `session_id`, `transcript_path`, `cwd` and + `hook_event_name`. `UserPromptSubmit` and `Stop` add `turn_id`, `model` + and `permission_mode`; `UserPromptSubmit` adds `prompt`, and `Stop` adds + `stop_hook_active` and `last_assistant_message`. `SessionEnd` adds + `reason` and **no `turn_id`**. So `hook.rs` is unchanged; only reading the + turn back from the transcript differs. +- **New hooks don't run until a person trusts them.** Trust lives in + `config.toml` as `[hooks.state.":::"] + trusted_hash = "sha256:…"`. An untrusted hook is skipped silently in + `exec`, and the TUI opens with "Hooks need review: N hooks are new or + changed" (*Review hooks* / *Trust all and continue* / *Continue without + trusting*), with `/hooks` to manage them. The hash is not a plain SHA-256 + of the entry. **loch never writes trust**: it is the user's review of a + command that runs outside the sandbox, and forging it would defeat the + point. `install` reports `needsReview` and says to open `/hooks`. Trust is + keyed by position, so loch appends its hooks as new groups and leaves + every existing entry's position, and so its trust, alone. That is what + keeps Ness's user-level hooks trusted after a `--local` install. + `--dangerously-bypass-hook-trust` exists for automation. The tests used + it, and loch never passes it. +- **A cancelled turn gets no `Stop`.** Esc mid-turn writes `turn_aborted` + (`reason: "interrupted"`) and runs no `Stop`, exactly like Claude Code, + so the next prompt's hook closes it as `interrupted`, keeping its edits. + Verified in the TUI. `SessionEnd` runs on `/quit` and at the end of every + `exec`, so quitting mid-turn is closed the same way. The `Interrupt` event + would close a cancelled turn sooner, but no payload was captured and + nothing needs it, so it isn't installed. +- **`codex fork` can't cut at a turn** (no `--at-turn`), and needs a session + Codex can already find. `ask` writes its own fork instead: a prefix of the + rollout's lines, kept byte for byte, under a new id, rewritten into the + target cwd. It resumes with `codex resume `. It has no title, since + titles live in `session_index.jsonl`. +- **Tool calls changed shape across versions:** 0.166's are + `custom_tool_call`s named `exec` whose input is JavaScript calling + `tools.exec_command`, and older ones are `function_call`s. So backfill's + approach (the text an `Edit`/`Write` call carries) doesn't carry over, and + `backfill` stays Claude-only. + +## The adapter boundary, and what a third harness costs + +`agent.rs` is everything loch needs from one harness, in three tiers. Each +later tier's methods have defaults that decline, so an adapter is as big as +what the harness supports: + +1. **Attribution** (`blame`, `log`). Required: an `id`, the hook events + (a turn's start, its end, and ideally the session's end) and the hooks + file `install` writes. That is the whole requirement, because snapshots, + diffs, edit records and matching are harness-agnostic, and `hook.rs` + only needs a payload with `session_id` and `cwd` (Claude-shaped field + names; an adapter for differently named fields would add a payload + mapping). Optional: `current_turn` (which transcript record a turn began + and ended at, and its prompt) and `transcript_key` (keeping the + transcript in the store). Without them blame still works and says + nothing about what was asked. +2. **Transport** (`save`, `list`, `restore`): `list_sessions` with the + live-cwd/branch/version choice, `transcript_cwds`, `restore_path`, + `existing_transcript` and `resume_command`. The rewrite itself is shared + and needs nothing, as long as the transcript is text with paths in it. +3. **Conversation** (`ask`): `find_transcript` and `fork`, plus `title` if + the harness keeps one outside the transcript. + +**The degraded tier is a first-class case.** A harness with turn hooks and +no resumable transcript implements tier 1 alone, about 40 lines on Codex's +model. `save` finds none of its sessions, `restore` reports a bundled one +as `"status": "unsupported"`, and `ask` fails with `unsupported-agent`. +Blame and log are complete. A harness with no hooks at all gets no tier +today; the shape for it is a stop-only hook (each turn's end snapshot +becomes the next turn's start, which `stop` already handles) or, with no +signal at all, attribution to the span between two `snapshot` calls, +which nothing drives yet. + +Codex took ~600 lines (`codex.rs`), most of it the format: where a turn +starts and ends, the live cwd, a prefix fork. The questions to answer +first for the next harness, in the order they decide the cost: does resume +need anything besides the transcript file (Codex: no; this is the one that +could make restore impractical); are hooks trusted or gated (Codex: gated); +what names a turn in the transcript; where the live cwd and branch are +recorded. Cursor, Gemini CLI and Copilot CLI have not been examined. +Nothing here is verified about them. + ## Layout One Rust crate at the root: a library holding every module, and the `loch` @@ -218,7 +371,9 @@ src/ ├── main.rs # argv handling, dispatch, the two renderers' entry point ├── cli.rs # every command: list/save/restore/delete/reindex/ingest/install/ │ # blame/log/ask/backfill/gc/hook/help/version -├── claude.rs # Claude Code adapter: path encoding, session discovery, metadata +├── agent.rs # the adapter boundary: what loch needs from one agent harness +├── claude.rs # Claude Code adapter: path encoding, discovery, metadata, turns, fork +├── codex.rs # Codex adapter: rollout discovery, live cwd, turns by id, prefix fork ├── bundle.rs # bundle format, gzip, content-addressed ref ├── format.rs # loch format: turn and content ids, derived files ├── ingest.rs # Claude Code JSONL -> loch turns (the converter) @@ -242,6 +397,7 @@ src/ tests/ # integration tests, one file per module plus cli.rs ├── derived_reader/ # a verifying reader for derived files, shared by three tests ├── trace.rs # hooks, blame, log and ask end to end, squash and clone included +├── codex.rs # the Codex adapter end to end, on synthetic rollouts ├── backfill.rs # backfill's two sources, contested commits, renames └── corpus.rs # opt-in, against this machine's transcripts (LOCH_CORPUS=1) examples/bench_hook.rs # per-call wall clock of `loch hook`, any number of binaries @@ -578,8 +734,10 @@ never a code. The set today: | `author-key-unreadable` | `ingest --author-key` named a file that isn't an OpenSSH public key | | `file-unreadable` | `blame`/`log`/`ask` named a file that can't be read | | `not-linked` | `ask` on a line no recorded turn wrote | -| `transcript-missing` | a turn wrote the line but its transcript is in neither Claude's directory nor the store | +| `transcript-missing` | a turn wrote the line but its transcript is in neither its agent's directory nor the store | | `turn-not-found` | the transcript no longer holds the record a turn ended on | +| `unknown-agent` | `--agent` named an agent this build doesn't know | +| `unsupported-agent` | `ask` on a turn whose agent's adapter can't fork or resume | | `unknown-command` | no such subcommand | | `usage` | argparse rejected the arguments (exit status 2) | | `internal` | an unexpected exception | @@ -594,6 +752,15 @@ anything wider would relabel a bug in this process as a failure of the store. (`s3-extra-missing` existed while S3 needed an optional Python package; the binary carries its client, so it can't arise and is gone.) +**A payload never overwrites the envelope.** `schema`, `ok`, `command`, +`code` and `error` are the envelope's (`output::RESERVED`), and +`document` drops a payload key that reuses one. Until that rule existed, +`install`'s payload field `command`, the hooks' loch path, replaced the +envelope's, so `install --json` said `"command": "loch"` rather than +`"install"`. The field is `hookCommand` now. Nothing bumped `schema` for +it, since the envelope went back to its documented meaning, but a caller +that read the path from `install`'s `command` has to read `hookCommand`. + **Exactly one document per invocation, including parse failures.** `argparse.rs` returns `-h` and a bad flag as `Exit` values rather than printing and exiting, so `main()` renders both in the mode asked for. A bug @@ -621,6 +788,44 @@ JSON mode carries the same fact as a payload field and leaves stderr empty. `save` and `list` carry the same signal ahead of time as `otherCwds`. +**Several agents, additively.** Each session in `list`, `save` and +`restore` carries `agent` (`claude-code`, `codex`) and `agentVersion`. +`claudeVersion` keeps meaning Claude Code's version, so it is null on a +Codex session rather than reused. `list` and `save` cover every agent +unless `--agent` picks one, but **`install` writes Claude Code's hooks alone +unless asked** (`--agent codex`, or `--agent all`). Installing Codex's too +by default changed what existing callers did. With `--local`, Ness's +`install --local --command` would have started writing the user-wide +`$CODEX_HOME/hooks.json`, putting loch in every Codex project and a review +prompt in the next TUI. Without it, a `.codex/` would land in every +Claude-only repo. `install`'s top-level `settings`/`added`/`removed` stay +the first agent's (Claude's by default), and `agents` lists each, +with `needsReview` true where the agent won't run the hooks just added +until a person approves them. A restore of a session whose agent this +build lacks is `"status": "unsupported"`. None of this changed a field's +meaning, so `schema` stays 2. Blame's payload gained nothing. Its `agent` +field now says `codex` for Codex turns, and `turn`/`conversation` are null +for them, since the loch converter reads Claude's format alone. Consumers +keying on `agent == "claude-code"` (the Ness blame gutter) should expect +the other value. + +**One bundle, several agents, unchanged refs.** A bundle's `agent` is its +first session's, and a session of another agent carries its own `agent` +key. The key is omitted whenever it would equal the bundle's, so a bundle +of Claude's sessions, every Claude bundle ever made included, packs to the +bytes it always did (`tests/bundle.rs` pins them, and `tests/codex.rs` +checks a Claude-only `save` carries no new key). + +**A bundle holding any other agent's session is `version: 2`.** v0.2.0 reads +`version` and nothing about agents. Given a Codex session at version 1, it +would write it into `~/.claude/projects` and report `"status": "restored"`, +`ok: true`, with a `claude --resume` line: the silent failure this file keeps +warning about. It refuses any version but 1, so at 2 it fails loudly as +`bundle-unreadable` ("unsupported bundle version 2"). Claude-only bundles +stay at 1 and keep their refs, and no ref of a version-2 bundle predates +the rule, so nothing moved. `Bundle::required_version` decides it, and both +cases are pinned. Index entries name their first session's agent. + **Never the matched text.** Redaction is reported as `{"": }` plus a `redacted` total, exactly as much as the prose summary carries and no more — `save`'s stdout lands in the next agent's transcript. The one field @@ -678,7 +883,12 @@ which hands most of the hooks' speed back on every Bash call. bins through a `.cmd` wrapper anyway, the shim remains and still works. - **Hooks:** Ness should write the binary's absolute path with `loch install --local --command ` (settings.local.json, since the path is - machine-specific) rather than rely on PATH. + machine-specific) rather than rely on PATH. That installs Claude Code's + hooks alone. Codex's need `--agent codex` (or `all`), and with `--local` + that means the user-wide `$CODEX_HOME/hooks.json`, beside Ness's own + status hooks there. Ness should only ask for it with the user's say-so, + and must not rewrite that file wholesale, or loch's hooks go with it. + Codex won't run them until they're trusted in `/hooks`. **Builds reproduce.** `SOURCE_DATE_EPOCH` fixes `save`'s `createdAt`, the one clock in a bundle's bytes, so the same sessions pack to the same ref. @@ -776,6 +986,17 @@ The full alternation stays in the unit tests as an oracle, fuzzed against the fast path over 40k generated strings that exercise every rule. The test asserts each rule matched, so it can't pass vacuously. +**Codex discovery reads every rollout, on every `list` and `save`.** Both +cover every agent by default, so a Claude-only listing pays for it too: about +50ms for 10MB of rollouts, linear in their total size, and the rollouts +never age out, so a year of Codex use is paid on every listing. If it starts +to matter, the cheap fix is a substring check for the target cwd before the +full parse. Only the last `turn_context`'s cwd decides a match, so a rollout +whose bytes never contain the cwd string can't match and can be skipped. +The catch is matching through a symlink: Codex stores `-C` unresolved, so +the check has to try the target's unresolved spellings too, or skip only +when no form of it occurs. `--agent claude-code` avoids the scan today. + **S3 is SigV4 by hand over `ureq`/rustls**, not the AWS SDK: four request 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 @@ -830,10 +1051,13 @@ field it wants is `foreignCwds`. Its shape is keyed on the origin deliberately (above) — it was `{"": }` briefly and was changed before anything consumed it. -Nothing currently pins the bundle format. The two constraints above — -compact separators and omitted-not-null metadata — are held by prose -rather than by a test, so a well-meaning refactor could change every -ref the format produces without failing the suite. Note that +The bundle format is pinned by `tests/bundle.rs`: the exact packed JSON +and ref of a two-session bundle (an absent branch and version, non-ASCII, +escapes), and that re-packing an unpacked bundle reproduces its bytes. A +failure there means every existing ref would stop reproducing, which needs +a decision, not a test update. The adapter extraction was also checked +against real data: `save` and `list` on three project directories (100 +sessions) gave identical refs and output before and after. Note that `SessionMeta.other_cwds` is deliberately *not* packed into the bundle: the transcript is the source of truth for what directories it names, and adding a field would change the ref of every bundle for a value the @@ -916,10 +1140,48 @@ kind, so it is worth knowing about: a stale `LOCHY_STORE=s3://...` makes shim is ever wanted, the shape is to read `LOCH_*` first, fall back to the old name, and warn on stderr in text mode only. +**Codex is verified end to end on real sessions** (codex-cli 0.166.0, +scratch repositories, a temporary store): +- **Hooks and blame.** `install --agent codex` wrote `.codex/hooks.json`, + and a session of two `exec` turns, each editing `greet.py` through the + shell, was recorded turn by turn under `edits/codex/`. `blame` gave + lines 1–2 to the first turn and 3–6 to the second, with `"agent": + "codex"` and Codex's own thread title. A human-committed line stayed + unattributed. +- **A cancelled turn.** In the TUI, Esc mid-turn ran no `Stop`. The next + prompt closed the turn as `interrupted`, keeping its edit, and the next + turn recorded none of it. +- **ask.** `ask greet.py:1 --at-turn` forked at the first turn's + `task_complete`, and resumed, the fork knew that turn's codeword and not + the second's. Without `--at-turn` it knew both. +- **save and restore across machines.** The bundle was rewritten to + another machine's home and repo path, then restored with `--new-id` into + a different directory. It came back with `residualOriginPaths` and + `foreignCwds` both empty, no trace of the foreign home or the old id in + the file, every cwd naming the target, and `codex resume` recalled both + codewords and named the new directory as its cwd. +- **Discovery.** All 70 local rollouts (four CLI versions) are found under + their live cwd. A Claude `save` of 100 real sessions gave the same refs + before and after the adapter extraction. +- **Install beside Ness.** `install --local` against a copy of this + machine's `~/.codex/hooks.json` kept every Ness group byte for byte and + in place, and appended loch's. + +Not verified: the trust prompt was seen but loch's hooks were never +trusted through it. Every hook run used `--dangerously-bypass-hook-trust` +on a scratch repository, so how the TUI flow and `needsReview` read to a +person is untested. + +Codex gaps: `ingest` and `backfill` are Claude-only (SPEC.md §8's converter; +see the tool-call note above); a moved session has no branch; `install +--agent codex --local` installs into the user's hooks file, so loch runs for +every Codex project on the machine (it refuses `/` and home, as always); a +fork has no title; `archived_sessions` isn't searched. + Also missing: `restore --map` (design intent recorded above, deliberately not built on this branch), any other index dimension (`cwd` is the obvious next one, and the layout takes it without a migration), PR-level -git pointers for bundles, and no adapters beyond Claude Code. +git pointers for bundles, and no adapters beyond Claude Code and Codex. `restore` still needs a full 64-character ref — the index makes refs discoverable, but nothing resolves a prefix. diff --git a/src/agent.rs b/src/agent.rs new file mode 100644 index 0000000..9a91787 --- /dev/null +++ b/src/agent.rs @@ -0,0 +1,175 @@ +//! The agent adapter boundary: everything loch needs to know about one agent +//! harness, behind one trait, so the rest of loch — snapshots, attribution, +//! bundles, the store, the JSON contract — is written once. +//! +//! What an adapter has to provide comes in tiers, and each tier is useful on +//! its own: +//! +//! 1. **Attribution** — `id`, `hook_events`, `hooks_file`. Blame and log need +//! nothing else: a hook at a turn's start and end, carrying a session id +//! and a cwd. `current_turn` (what the transcript says the turn was) only +//! sharpens the record, and the default says nothing. +//! 2. **Transport** — `list_sessions`, `transcript_cwds`, `restore_path`, +//! `existing_transcript`, `resume_command`. `save`, `list` and `restore`. +//! 3. **Conversation** — `find_transcript`, `fork`. `ask`. +//! +//! Everything past tier 1 has a default that declines, so a harness with turn +//! hooks and nothing else is still an adapter. + +use crate::json::Map; +use crate::store::{Store, StoreError}; +use crate::trace::{Fork, ForkError}; + +#[derive(Clone, Debug)] +pub struct SessionMeta { + pub agent: &'static str, + pub session_id: String, + pub path: String, + pub cwd: String, + pub git_branch: Option, + /// The harness's own version, as its transcript records it. + pub version: Option, + pub bytes: u64, + pub modified_at: String, + pub summary: Option, + /// Directories the session also worked in before it moved. A restore has + /// one target cwd, so records naming these cannot be made correct on the + /// far side; surfacing them is the only honest option. + pub other_cwds: Vec, +} + +/// What the transcript says about a turn: the record that began it and the +/// last record written. Each id is whatever the agent's transcript uses to +/// name a position in itself — a record uuid for Claude Code, a turn id for +/// Codex — and only that agent's adapter ever interprets it. +#[derive(Default)] +pub struct TurnInfo { + pub prompt_uuid: Option, + pub prompt: Option, + pub started: Option, + pub end_uuid: Option, + pub ended: Option, +} + +/// A loch hook subcommand an agent event runs: `(event, name)`, e.g. +/// `("UserPromptSubmit", "prompt")`. +pub type HookEvent = (&'static str, &'static str); + +pub trait Agent: Sync { + /// Stable identifier: edit records, store keys, bundles, `--agent`. + fn id(&self) -> &'static str; + /// For prose. + fn name(&self) -> &'static str; + + // -- tier 1: attribution --------------------------------------------------- + + /// The events loch hooks, and the subcommand each runs. + fn hook_events(&self) -> &'static [HookEvent]; + /// The hooks file `install` writes, for a workspace root. + fn hooks_file(&self, root: &str, local: bool) -> String; + /// What `install` says after writing, beyond the file it wrote. + fn install_note(&self) -> &'static str; + /// Hooks this agent won't run until a person approves them. + fn hooks_need_review(&self) -> bool { + false + } + /// The turn `event` closes, as the transcript tells it. When the closing + /// hook belongs to the *next* prompt (`for_next`), that prompt may already + /// be written and is left out. + fn current_turn(&self, _transcript: &str, _event: &Map, _for_next: bool) -> TurnInfo { + TurnInfo::default() + } + /// Where the store keeps this session's transcript, under + /// `transcripts//`. `None` keeps none. + fn transcript_key(&self, _path: &str, _session_id: &str) -> Option { + None + } + + // -- tier 2: transport ------------------------------------------------------ + + /// Where this agent keeps transcripts, for messages. + fn sessions_dir(&self) -> String; + fn list_sessions( + &self, + _cwd: &str, + _branch: Option<&str>, + _session_id: Option<&str>, + ) -> Vec { + Vec::new() + } + fn read_session_meta(&self, _path: &str) -> Option { + None + } + /// Every working directory the transcript's records name, with how many + /// name it, in order of first appearance. + fn transcript_cwds(&self, _raw: &str) -> Vec<(String, usize)> { + Vec::new() + } + /// Whether `restore` can file a session of this agent's: the transport + /// tier is implemented. + fn can_restore(&self) -> bool { + false + } + /// Where a restored transcript goes. `raw` is the rewritten transcript. + fn restore_path(&self, _raw: &str, _cwd: &str, _session_id: &str) -> Option { + None + } + /// A transcript this machine already holds for the session, which a + /// restore must not silently duplicate or overwrite. + fn existing_transcript(&self, _cwd: &str, _session_id: &str) -> Option { + None + } + /// argv that resumes the session. + fn resume_command(&self, _session_id: &str) -> Option> { + None + } + + // -- tier 3: conversation ----------------------------------------------------- + + /// The agent's own copy if it still exists, else the store's. + fn find_transcript( + &self, + _session_id: &str, + _store: Option<&dyn Store>, + ) -> Result, StoreError> { + Ok(None) + } + /// The session's title, where the agent keeps one outside the + /// transcript. + fn title(&self, _session_id: &str) -> Option { + None + } + /// A new session holding the conversation up to `cut` (the end, if none), + /// filed under `target_cwd`. + fn fork( + &self, + _transcript: &str, + _target_cwd: &str, + _cut: Option<&str>, + _title: Option<&str>, + ) -> Result { + Err(ForkError::Unsupported(self.name())) + } +} + +static ALL: &[&dyn Agent] = &[&crate::claude::CLAUDE_CODE, &crate::codex::CODEX]; + +pub fn all() -> &'static [&'static dyn Agent] { + ALL +} + +pub fn by_id(id: &str) -> Option<&'static dyn Agent> { + all().iter().copied().find(|agent| agent.id() == id) +} + +/// The agents `--agent` names, or every one. +/// `all` names every agent too. +pub fn selected(id: Option<&str>) -> Result, String> { + match id.filter(|id| !id.is_empty()) { + None | Some("all") => Ok(all().to_vec()), + Some(id) => by_id(id).map(|agent| vec![agent]).ok_or_else(|| { + let known: Vec<&str> = all().iter().map(|a| a.id()).collect(); + format!("unknown agent {} (known: {})", id, known.join(", ")) + }), + } +} diff --git a/src/backfill.rs b/src/backfill.rs index bea6727..b100750 100644 --- a/src/backfill.rs +++ b/src/backfill.rs @@ -20,9 +20,8 @@ //! what an earlier backfill wrote. use crate::attribution::{self, EditRecord, FileChange, Hunk, TurnRecord}; -use crate::claude::{self, display_summary, AGENT}; +use crate::claude::{self, display_summary, is_human_prompt, prompt_text, AGENT}; use crate::git; -use crate::hook::{is_human_prompt, prompt_text}; use crate::json::{self, Map, Value}; use crate::snapshot; use crate::store::Store; diff --git a/src/bundle.rs b/src/bundle.rs index 5351ba7..4a7c719 100644 --- a/src/bundle.rs +++ b/src/bundle.rs @@ -11,8 +11,17 @@ use crate::sys; use sha2::{Digest, Sha256}; use std::io::Read; +/// A bundle of Claude Code sessions alone: every bundle made before Codex, +/// and every one since that holds only Claude sessions, keeps this, and its +/// bytes. pub const BUNDLE_VERSION: i64 = 1; +/// A bundle holding any other agent's session. A build that predates agents +/// ignores `agent` and would restore a Codex session as a Claude transcript +/// while reporting success; it refuses any version but 1, so this makes it +/// fail loudly instead. +pub const AGENTS_VERSION: i64 = 2; + #[derive(Clone)] pub struct BundleOrigin { pub home: String, @@ -20,16 +29,49 @@ pub struct BundleOrigin { pub hostname: String, } -#[derive(Clone)] +#[derive(Clone, Default)] pub struct BundleSession { pub session_id: String, + /// Set only where the session's agent differs from the bundle's, so a + /// bundle of one agent's sessions — every Claude bundle before Codex — + /// keeps its bytes, and its ref. + pub agent: Option, pub cwd: String, pub git_branch: Option, pub claude_version: Option, + /// Any other agent's version: `claudeVersion` keeps meaning Claude's. + pub agent_version: Option, pub modified_at: String, pub transcript: String, } +impl BundleSession { + pub fn agent_of<'a>(&'a self, bundle: &'a Bundle) -> &'a str { + self.agent.as_deref().unwrap_or(&bundle.agent) + } + + pub fn version(&self) -> Option<&str> { + self.claude_version + .as_deref() + .or(self.agent_version.as_deref()) + } +} + +impl Bundle { + /// The version these sessions need: 1 unless any isn't Claude Code's. + pub fn required_version(&self) -> i64 { + let claude_only = self + .sessions + .iter() + .all(|s| s.agent_of(self) == crate::claude::AGENT); + if claude_only { + BUNDLE_VERSION + } else { + AGENTS_VERSION + } + } +} + #[derive(Clone)] pub struct Bundle { pub version: i64, @@ -40,15 +82,21 @@ pub struct Bundle { } fn session_json(session: &BundleSession) -> Value { - let mut record = - object! {"sessionId" => session.session_id.as_str(), "cwd" => session.cwd.as_str()}; + let mut record = object! {"sessionId" => session.session_id.as_str()}; // Omitted rather than null: the ref is a hash of these bytes. + if let Some(agent) = &session.agent { + record.insert("agent".into(), agent.as_str().into()); + } + record.insert("cwd".into(), session.cwd.as_str().into()); if let Some(branch) = &session.git_branch { record.insert("gitBranch".into(), branch.as_str().into()); } if let Some(version) = &session.claude_version { record.insert("claudeVersion".into(), version.as_str().into()); } + if let Some(version) = &session.agent_version { + record.insert("agentVersion".into(), version.as_str().into()); + } record.insert("modifiedAt".into(), session.modified_at.as_str().into()); record.insert("transcript".into(), session.transcript.as_str().into()); Value::Object(record) @@ -168,16 +216,21 @@ pub fn unpack_bundle(data: &[u8]) -> Result { })?; let root = value.as_object().ok_or("the bundle is not a JSON object")?; let version = root.get("version"); - let current = matches!(version, Some(Value::Int(d)) if d == "1") + let read = if matches!(version, Some(Value::Int(d)) if d == "1") || matches!(version, Some(Value::Bool(true))) - || matches!(version, Some(Value::Float(f)) if *f == 1.0); - if !current { + || matches!(version, Some(Value::Float(f)) if *f == 1.0) + { + BUNDLE_VERSION + } else if matches!(version, Some(Value::Int(d)) if d == "2") { + AGENTS_VERSION + } else { return Err(format!( - "unsupported bundle version {} (this build reads {})", + "unsupported bundle version {} (this build reads {} and {})", py_str(version), - BUNDLE_VERSION + BUNDLE_VERSION, + AGENTS_VERSION )); - } + }; let empty = Map::new(); let origin = match root.get("origin") { None => &empty, @@ -205,8 +258,11 @@ pub fn unpack_bundle(data: &[u8]) -> Result { .map(str::to_string) .ok_or_else(|| format!("'{}'", key)) }; + let optional = |key: &str| session.get(key).and_then(Value::as_str).map(str::to_string); sessions.push(BundleSession { session_id: required("sessionId")?, + agent: optional("agent"), + agent_version: optional("agentVersion"), cwd: required("cwd")?, git_branch: session .get("gitBranch") @@ -221,7 +277,7 @@ pub fn unpack_bundle(data: &[u8]) -> Result { }); } Ok(Bundle { - version: BUNDLE_VERSION, + version: read, agent: text_of(root, "agent"), created_at: text_of(root, "createdAt"), origin: BundleOrigin { diff --git a/src/claude.rs b/src/claude.rs index 5e298e6..124afba 100644 --- a/src/claude.rs +++ b/src/claude.rs @@ -1,32 +1,25 @@ -//! The Claude Code adapter: where sessions live, how -//! their directory is named, and what a session's metadata is. +//! The Claude Code adapter: where sessions live, how their directory is +//! named, what a session's metadata is, how a turn reads in the transcript, +//! and how a conversation is forked. -use crate::json::{self, Value}; +pub use crate::agent::SessionMeta; +use crate::agent::{Agent, HookEvent, TurnInfo}; +use crate::json::{self, Map, Value}; +use crate::object; use crate::py; use crate::redact; +use crate::rewrite::{rewrite_transcript, RewriteSpec}; +use crate::store::{Store, StoreError}; use crate::sys; +use crate::trace::{self, content, records_of, Fork, ForkError, TraceError}; +use std::collections::{HashMap, HashSet}; use std::fs; +use std::path::Path; pub const AGENT: &str = "claude-code"; pub const SUMMARY_LIMIT: usize = 120; -#[derive(Clone, Debug)] -pub struct SessionMeta { - pub session_id: String, - pub path: String, - pub cwd: String, - pub git_branch: Option, - pub claude_version: Option, - pub bytes: u64, - pub modified_at: String, - pub summary: Option, - /// Directories the session also worked in before it moved. A restore has - /// one target cwd, so records naming these cannot be made correct on the - /// far side; surfacing them is the only honest option. - pub other_cwds: Vec, -} - /// `Path.home()`: `HOME` on Unix, `USERPROFILE` on Windows. pub fn home_dir() -> String { let name = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; @@ -189,10 +182,11 @@ pub fn read_session_meta(path: &str) -> Option { let ordered: Vec = counts.keys().cloned().collect(); let cwd = cwd_for_directory(&ordered, &sys::basename(&sys::dirname(path))); Some(SessionMeta { + agent: AGENT, session_id, path: path.into(), git_branch: branches.get(&cwd).cloned(), - claude_version: versions + version: versions .get(&cwd) .or_else(|| versions.values().next()) .cloned(), @@ -239,3 +233,382 @@ pub fn list_sessions( metas.sort_by(|a, b| py::cmp(&b.modified_at, &a.modified_at)); metas } + +// -- reading a turn -------------------------------------------------------------- + +/// A record a person typed: a user message that is neither a tool's result +/// nor Claude Code's own bookkeeping. +pub fn is_human_prompt(record: &Map) -> bool { + if !record.get("type").is_some_and(|t| t.is_str("user")) { + return false; + } + if record.get("isMeta").is_some_and(Value::truthy) + || record.get("isCompactSummary").is_some_and(Value::truthy) + { + return false; + } + match record.get("message").and_then(|m| m.get("content")) { + Some(Value::Str(_)) => true, + Some(Value::Array(_)) => !content(record) + .iter() + .any(|b| b.get("type").is_some_and(|t| t.is_str("tool_result"))), + _ => false, + } +} + +pub fn prompt_text(record: &Map) -> Option { + match record.get("message")?.get("content")? { + Value::Str(text) => Some(text.clone()), + Value::Array(_) => content(record) + .iter() + .find_map(|block| match block.get("text") { + Some(Value::Str(text)) if !text.is_empty() => Some(text.clone()), + _ => None, + }), + _ => None, + } +} + +/// The turn the transcript ends with. When the hook closing it belongs to the +/// *next* prompt, that prompt may already be written; `excluding` names it, +/// and it and everything after are left out. +pub fn current_turn(transcript: &str, excluding: Option<&str>) -> TurnInfo { + let records: Vec = trace::read_records(transcript) + .into_iter() + .filter(|r| matches!(r.get("uuid"), Some(Value::Str(_)))) + .collect(); + let mut end = records.len(); + if let Some(next) = excluding { + if let Some(at) = records.iter().rposition(is_human_prompt) { + if prompt_text(&records[at]).as_deref() == Some(next) { + end = at; + } + } + } + let mut info = TurnInfo::default(); + for record in &records[..end] { + let uuid = record + .get("uuid") + .and_then(Value::as_str) + .map(str::to_string); + let stamp = record + .get("timestamp") + .and_then(Value::as_str) + .map(str::to_string); + if is_human_prompt(record) { + info.prompt_uuid = uuid.clone(); + info.prompt = display_summary(prompt_text(record).as_deref()); + info.started = stamp.clone(); + } + info.end_uuid = uuid; + info.ended = stamp; + } + info +} + +// -- finding a transcript ------------------------------------------------------------ + +fn list_dir(path: &str) -> Vec { + fs::read_dir(path) + .map(|entries| { + entries + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect() + }) + .unwrap_or_default() +} + +/// Claude's own copy if it still exists, else the store's snapshot, fetched +/// into a cache laid out like Claude's project directory so the session's cwd +/// is chosen the same way. +pub fn find_transcript( + session_id: &str, + store: Option<&dyn Store>, +) -> Result, StoreError> { + let root = projects_dir(None); + if Path::new(&root).is_dir() { + for project in list_dir(&root) { + let path = sys::join( + &sys::join(&root, &project), + &format!("{}.jsonl", session_id), + ); + if Path::new(&path).exists() { + return Ok(Some(path)); + } + } + } + let Some(store) = store else { + return Ok(None); + }; + let prefix = trace::transcripts_prefix(AGENT); + let Ok(keys) = store.list(&prefix) else { + return Ok(None); + }; + let suffix = format!("/{}.jsonl", session_id); + for key in keys { + if key.ends_with(&suffix) { + let project = key[prefix.len()..] + .split('/') + .next() + .unwrap_or("") + .to_string(); + let data = match store.get(&key) { + Ok(data) => data, + Err(StoreError::Missing(_)) => return Ok(None), + Err(error) => return Err(error), + }; + let cache = sys::join(&trace::cache_dir(), &project); + let cached = sys::join(&cache, &format!("{}.jsonl", session_id)); + let _ = fs::create_dir_all(&cache); + let _ = fs::write(&cached, data); + return Ok(Some(cached)); + } + } + Ok(None) +} + +// -- forking ------------------------------------------------------------------------- + +fn parent(record: &Map) -> Option { + let parent = match record.get("parentUuid") { + None | Some(Value::Null) => record.get("logicalParentUuid"), + other => other, + }; + parent.and_then(Value::as_str).map(str::to_string) +} + +fn uuid(record: &Map) -> &str { + record.get("uuid").and_then(Value::as_str).unwrap_or("") +} + +/// A new Claude session holding the conversation, filed under `target_cwd`. +/// With no `cut` it holds the conversation to its end — the last record +/// written, which after a rewind is the branch the session was left on. With +/// one, it ends at that record: the last of the turn being asked about. +pub fn fork_session( + transcript: &str, + target_cwd: &str, + cut: Option<&str>, + title: Option<&str>, +) -> Result { + let bytes = + fs::read(transcript).map_err(|e| ForkError::Internal(sys::os_error(&e, transcript)))?; + let raw = py::decode_surrogateescape(&bytes); + let records: Vec = records_of(&raw) + .into_iter() + .filter(|r| matches!(r.get("uuid"), Some(Value::Str(_)))) + .collect(); + if records.is_empty() { + return Err(ForkError::Trace(TraceError::new( + "turn-not-found", + "the transcript holds no records", + ))); + } + let leaf = match cut { + None => records.len() - 1, + Some(cut) => match records.iter().rposition(|r| uuid(r) == cut) { + Some(leaf) => leaf, + None => { + return Err(ForkError::Trace(TraceError::new( + "turn-not-found", + format!("the transcript has no record {}", cut), + ))) + } + }, + }; + write_fork(transcript, &raw, &records, leaf, target_cwd, title) +} + +fn write_fork( + transcript: &str, + raw: &str, + records: &[Map], + leaf: usize, + target_cwd: &str, + title: Option<&str>, +) -> Result { + let mut by_uuid: HashMap<&str, usize> = HashMap::new(); + for (index, record) in records.iter().enumerate() { + by_uuid.insert(uuid(record), index); + } + let mut keep: HashSet = HashSet::new(); + let mut walker = Some(leaf); + while let Some(index) = walker { + let id = uuid(&records[index]).to_string(); + if keep.contains(&id) { + break; + } + keep.insert(id); + walker = parent(&records[index]).and_then(|p| by_uuid.get(p.as_str()).copied()); + } + + let origin_cwd = match read_session_meta(transcript) { + Some(meta) => meta.cwd, + None => match transcript_cwds(raw).into_iter().next() { + Some((cwd, _)) => cwd, + None => return Err(ForkError::Internal("the transcript names no cwd".into())), + }, + }; + let file = sys::basename(transcript); + let origin_session = file[..file.len().saturating_sub(".jsonl".len())].to_string(); + let new_id = sys::uuid4(); + + let mut kept: Vec = records + .iter() + .filter(|r| keep.contains(uuid(r))) + .map(|r| json::dumps(&Value::Object(r.clone()), json::UNICODE)) + .collect(); + let default_title = format!("loch ask: {}", py::truncate(&origin_session, 8)); + kept.push(json::dumps( + &Value::Object(object! { + "type" => "custom-title", + "customTitle" => title.filter(|t| !t.is_empty()).unwrap_or(&default_title), + "sessionId" => origin_session.as_str(), + }), + json::DEFAULT, + )); + let home = home_dir(); + let spec = RewriteSpec { + origin_cwd, + origin_home: home.clone(), + target_cwd: target_cwd.into(), + target_home: home, + origin_session_id: Some(origin_session.clone()), + target_session_id: Some(new_id.clone()), + }; + let text = rewrite_transcript(&format!("{}\n", kept.join("\n")), &spec); + let path = transcript_path_for(target_cwd, &new_id, None); + let parent_dir = sys::dirname(&path); + fs::create_dir_all(&parent_dir) + .map_err(|e| ForkError::Internal(sys::os_error(&e, &parent_dir)))?; + let bytes = py::encode_surrogateescape(&text) + .map_err(|_| ForkError::Internal("the fork holds an unencodable surrogate".into()))?; + fs::write(&path, bytes).map_err(|e| ForkError::Internal(sys::os_error(&e, &path)))?; + Ok(Fork { + session_id: new_id, + path, + cwd: target_cwd.into(), + records: keep.len(), + origin_session, + }) +} + +// -- the adapter ----------------------------------------------------------------------- + +pub struct ClaudeCode; + +pub static CLAUDE_CODE: ClaudeCode = ClaudeCode; + +/// A turn's two moments, which is all attribution needs, and the session's +/// end, which closes a turn a cancel left open. +const HOOK_EVENTS: &[HookEvent] = &[ + ("UserPromptSubmit", "prompt"), + ("Stop", "stop"), + ("SessionEnd", "end"), +]; + +impl Agent for ClaudeCode { + fn id(&self) -> &'static str { + AGENT + } + + fn name(&self) -> &'static str { + "Claude Code" + } + + fn hook_events(&self) -> &'static [HookEvent] { + HOOK_EVENTS + } + + /// The project's settings file, or with `local` the uncommitted one, since + /// a `--local` command is a machine-specific path. + fn hooks_file(&self, root: &str, local: bool) -> String { + let name = if local { + "settings.local.json" + } else { + "settings.json" + }; + sys::join(&sys::join(root, ".claude"), name) + } + + fn install_note(&self) -> &'static str { + "restart Claude Code sessions here to pick them up" + } + + fn current_turn(&self, transcript: &str, event: &Map, for_next: bool) -> TurnInfo { + let next = match event.get("prompt") { + Some(Value::Str(text)) if for_next => Some(text.as_str()), + _ => None, + }; + current_turn(transcript, next) + } + + /// Keyed by Claude's project directory, so a fetched copy can be filed + /// back under it and its cwd chosen the same way. + fn transcript_key(&self, path: &str, session_id: &str) -> Option { + let project = sys::basename(&sys::dirname(path)); + Some(format!( + "{}{}/{}.jsonl", + trace::transcripts_prefix(AGENT), + project, + session_id + )) + } + + fn sessions_dir(&self) -> String { + projects_dir(None) + } + + fn list_sessions( + &self, + cwd: &str, + branch: Option<&str>, + session_id: Option<&str>, + ) -> Vec { + list_sessions(cwd, branch, session_id, None) + } + + fn read_session_meta(&self, path: &str) -> Option { + read_session_meta(path) + } + + fn transcript_cwds(&self, raw: &str) -> Vec<(String, usize)> { + transcript_cwds(raw) + } + + fn can_restore(&self) -> bool { + true + } + + fn restore_path(&self, _raw: &str, cwd: &str, session_id: &str) -> Option { + Some(transcript_path_for(cwd, session_id, None)) + } + + fn existing_transcript(&self, cwd: &str, session_id: &str) -> Option { + let path = transcript_path_for(cwd, session_id, None); + Path::new(&path).exists().then_some(path) + } + + fn resume_command(&self, session_id: &str) -> Option> { + Some(vec!["claude".into(), "--resume".into(), session_id.into()]) + } + + fn find_transcript( + &self, + session_id: &str, + store: Option<&dyn Store>, + ) -> Result, StoreError> { + find_transcript(session_id, store) + } + + fn fork( + &self, + transcript: &str, + target_cwd: &str, + cut: Option<&str>, + title: Option<&str>, + ) -> Result { + fork_session(transcript, target_cwd, cut, title) + } +} diff --git a/src/cli.rs b/src/cli.rs index dbf906f..69e7076 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,13 +1,12 @@ //! Every command: each builds one `Outcome` — payload //! and prose together — and `main` renders it. +use crate::agent::{self, Agent}; use crate::argparse::{Exit, Nargs, Parser}; use crate::attribution::{self, EditRecord}; use crate::blame_html; use crate::bundle::{self, Bundle, BundleOrigin, BundleSession, BUNDLE_VERSION}; -use crate::claude::{ - self, home_dir, list_sessions, resolve_cwd, transcript_path_for, SessionMeta, AGENT, -}; +use crate::claude::{self, home_dir, resolve_cwd, SessionMeta, AGENT}; use crate::format; use crate::index::{self, IndexEntry, IndexError, BRANCH}; use crate::ingest::{self, Origin}; @@ -167,8 +166,9 @@ fn describe_entry(entry: &IndexEntry) -> String { _ => "[no branch]".into(), }; let when = py::truncate(&entry.created_at, 16).replace('T', " "); - let version = match &entry.claude_version { - Some(v) if !v.is_empty() => format!(" claude {}", v), + let version = match (&entry.claude_version, &entry.agent_version) { + (Some(v), _) if !v.is_empty() => format!(" claude {}", v), + (_, Some(v)) if !v.is_empty() => format!(" {} {}", entry.agent, v), _ => String::new(), }; format!( @@ -182,16 +182,33 @@ fn describe_entry(entry: &IndexEntry) -> String { ) } +/// Every selected agent's sessions for a cwd, newest first. fn collect( + agents: &[&dyn Agent], cwd: Option<&str>, branch: Option<&str>, session: Option<&str>, ) -> (String, Vec) { let resolved = resolve_cwd(&cwd.map(str::to_string).unwrap_or_else(sys::getcwd)); - let sessions = list_sessions(&resolved, branch, session, None); + let mut sessions: Vec = agents + .iter() + .flat_map(|agent| agent.list_sessions(&resolved, branch, session)) + .collect(); + // Stable, so one agent's sessions keep their own order on a tie. + sessions.sort_by(|a, b| py::cmp(&b.modified_at, &a.modified_at)); (resolved, sessions) } +fn agents_arg(id: Option<&str>) -> std::result::Result, Failure> { + agent::selected(id) + .map_err(|message| Failure::Error(CommandError::new("unknown-agent", message))) +} + +fn none_found(agents: &[&dyn Agent], cwd: &str) -> String { + let ids: Vec<&str> = agents.iter().map(|a| a.id()).collect(); + format!("no {} sessions found for {}", ids.join(" or "), cwd) +} + fn parser(command: &str) -> Parser { Parser::new(&format!("loch {}", command)) } @@ -203,11 +220,13 @@ fn strings(items: &[String]) -> Value { fn session_payload(meta: &SessionMeta) -> Value { Value::Object(object! { "sessionId" => meta.session_id.as_str(), + "agent" => meta.agent, "path" => meta.path.as_str(), "cwd" => meta.cwd.as_str(), "otherCwds" => strings(&meta.other_cwds), "branch" => Value::opt_str(meta.git_branch.as_deref()), - "claudeVersion" => Value::opt_str(meta.claude_version.as_deref()), + "claudeVersion" => Value::opt_str(meta.version.as_deref().filter(|_| meta.agent == AGENT)), + "agentVersion" => Value::opt_str(meta.version.as_deref()), "bytes" => meta.bytes as i64, "modifiedAt" => meta.modified_at.as_str(), "summary" => Value::opt_str(meta.summary.as_deref()), @@ -227,6 +246,7 @@ fn entry_payload(entry: &IndexEntry) -> Value { "sessions" => entry.sessions, "cwd" => entry.cwd.as_str(), "claudeVersion" => Value::opt_str(entry.claude_version.as_deref()), + "agentVersion" => Value::opt_str(entry.claude_version.as_deref().or(entry.agent_version.as_deref())), }) } @@ -236,6 +256,7 @@ pub fn command_list(argv: &[String]) -> Run { let mut p = parser("list"); p.option("--cwd") .option("--branch") + .option("--agent") .flag("--remote", None) .flag("--all", Some("every")) .option("--store"); @@ -244,9 +265,10 @@ pub fn command_list(argv: &[String]) -> Run { if args.flag("remote") || args.flag("every") || store.is_some() { return list_remote(cwd, branch, store, args.flag("every")); } - let (cwd, sessions) = collect(cwd.as_deref(), branch.as_deref(), None); + let agents = agents_arg(args.str("agent").as_deref())?; + let (cwd, sessions) = collect(&agents, cwd.as_deref(), branch.as_deref(), None); let text = if sessions.is_empty() { - format!("no {} sessions found for {}\n", AGENT, cwd) + format!("{}\n", none_found(&agents, &cwd)) } else { let mut text = format!("{} session(s) for {}\n", sessions.len(), cwd); for meta in &sessions { @@ -346,19 +368,22 @@ pub fn command_save(argv: &[String]) -> Run { p.option("--cwd") .option("--branch") .option("--session") + .option("--agent") .option("--store"); let args = p.parse(argv)?; + let agents = agents_arg(args.str("agent").as_deref())?; let (cwd, sessions) = collect( + &agents, args.str("cwd").as_deref(), args.str("branch").as_deref(), args.str("session").as_deref(), ); if sessions.is_empty() { - return err( - "no-sessions", - format!("no {} sessions found for {}", AGENT, cwd), - ); + return err("no-sessions", none_found(&agents, &cwd)); } + // The bundle is its first session's agent's; any other session names its + // own, so a bundle of one agent's sessions has the bytes it always had. + let bundle_agent = sessions[0].agent; let mut packed_sessions = Vec::new(); let mut redactions = Vec::new(); for meta in &sessions { @@ -387,19 +412,22 @@ pub fn command_save(argv: &[String]) -> Run { ) } }; + let is_claude = meta.agent == AGENT; packed_sessions.push(BundleSession { session_id: meta.session_id.clone(), + agent: (meta.agent != bundle_agent).then(|| meta.agent.to_string()), cwd: meta.cwd.clone(), git_branch: meta.git_branch.clone(), - claude_version: meta.claude_version.clone(), + claude_version: meta.version.clone().filter(|_| is_claude), + agent_version: meta.version.clone().filter(|_| !is_claude), modified_at: meta.modified_at.clone(), transcript: scrubbed.text, }); redactions.push(scrubbed.counts); } - let bundle = Bundle { + let mut bundle = Bundle { version: BUNDLE_VERSION, - agent: AGENT.into(), + agent: bundle_agent.into(), created_at: sys::iso_timestamp(sys::creation_time()), origin: BundleOrigin { home: home_dir(), @@ -408,6 +436,7 @@ pub fn command_save(argv: &[String]) -> Run { }, sessions: packed_sessions, }; + 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())?; @@ -471,9 +500,11 @@ pub fn command_save(argv: &[String]) -> Run { "redacted" => total, "sessions" => bundle.sessions.iter().zip(&redactions).map(|(s, counts)| Value::Object(object! { "sessionId" => s.session_id.as_str(), + "agent" => s.agent_of(&bundle), "branch" => Value::opt_str(s.git_branch.as_deref()), "cwd" => s.cwd.as_str(), "claudeVersion" => Value::opt_str(s.claude_version.as_deref()), + "agentVersion" => Value::opt_str(s.version()), "modifiedAt" => s.modified_at.as_str(), "redactions" => counts_value(counts), })).collect::>(), @@ -490,6 +521,7 @@ pub fn command_save(argv: &[String]) -> Run { // -- restore ------------------------------------------------------------------ struct Restored { + agent: String, session_id: String, origin_session_id: String, branch: Option, @@ -503,6 +535,7 @@ struct Restored { fn restored_payload(session: &Restored) -> Value { Value::Object(object! { "sessionId" => session.session_id.as_str(), + "agent" => session.agent.as_str(), "originSessionId" => session.origin_session_id.as_str(), "branch" => Value::opt_str(session.branch.as_deref()), "status" => session.status, @@ -543,6 +576,23 @@ pub fn command_restore(argv: &[String]) -> Run { let target_home = home_dir(); let mut restored = Vec::new(); for session in &bundle.sessions { + let agent_id = session.agent_of(&bundle).to_string(); + // A bundle from a build that knows agents this one doesn't, or one + // whose adapter can't restore. + let Some(adapter) = agent::by_id(&agent_id).filter(|a| a.can_restore()) else { + restored.push(Restored { + agent: agent_id, + session_id: session.session_id.clone(), + origin_session_id: session.session_id.clone(), + branch: session.git_branch.clone(), + status: "unsupported", + path: String::new(), + residual: Vec::new(), + resume_command: None, + foreign: Vec::new(), + }); + continue; + }; let target_session_id = if args.flag("new_id") { sys::uuid4() } else { @@ -557,37 +607,46 @@ pub fn command_restore(argv: &[String]) -> Run { target_session_id: Some(target_session_id.clone()), }; let transcript = rewrite::rewrite_transcript(&session.transcript, &spec); - let destination = transcript_path_for(&target_cwd, &target_session_id, None); - if Path::new(&destination).exists() && !args.flag("force") { + let mut destination = adapter + .restore_path(&transcript, &target_cwd, &target_session_id) + .unwrap_or_default(); + let existing = adapter.existing_transcript(&target_cwd, &target_session_id); + if existing.is_some() && !args.flag("force") { restored.push(Restored { + agent: agent_id.clone(), session_id: target_session_id, origin_session_id: session.session_id.clone(), branch: session.git_branch.clone(), status: "skipped", - path: destination, + path: existing.unwrap_or(destination), residual: Vec::new(), resume_command: None, foreign: Vec::new(), }); continue; } + // Overwriting in place: a second copy of one session id is a + // transcript the agent may pick either of. + if let Some(existing) = existing { + destination = existing; + } let parent = sys::dirname(&destination); fs::create_dir_all(&parent).map_err(|e| Failure::Internal(sys::os_error(&e, &parent)))?; fs::write(&destination, transcript.as_bytes()) .map_err(|e| Failure::Internal(sys::os_error(&e, &destination)))?; restored.push(Restored { + agent: agent_id.clone(), session_id: target_session_id.clone(), origin_session_id: session.session_id.clone(), branch: session.git_branch.clone(), status: "restored", path: destination, residual: rewrite::residual_origin_paths(&transcript, &spec), - resume_command: Some(format!( - "cd {} && claude --resume {}", - target_cwd, target_session_id - )), + resume_command: adapter + .resume_command(&target_session_id) + .map(|argv| format!("cd {} && {}", target_cwd, argv.join(" "))), // Pre-rewrite: the origin path only exists losslessly here. - foreign: rewrite::foreign_cwds(&session.transcript, &spec), + foreign: rewrite::foreign_cwds_of(adapter.transcript_cwds(&session.transcript), &spec), }); } @@ -604,12 +663,19 @@ pub fn command_restore(argv: &[String]) -> Run { }; let mut warnings: Vec = restored .iter() - .filter(|s| s.status == "skipped") + .filter(|s| s.status != "restored") .map(|s| { - format!( - " skipped {} (already exists; --force to overwrite)\n", - s.session_id - ) + if s.status == "unsupported" { + format!( + " skipped {} ({} sessions aren't supported by this build)\n", + s.session_id, s.agent + ) + } else { + format!( + " skipped {} (already exists; --force to overwrite)\n", + s.session_id + ) + } }) .collect(); for session in &restored { @@ -777,16 +843,16 @@ pub fn command_ingest(argv: &[String]) -> Run { } } } + // The loch converter reads Claude Code's transcripts alone (SPEC.md §8). + let agents: Vec<&dyn Agent> = vec![&claude::CLAUDE_CODE]; let (cwd, sessions) = collect( + &agents, args.str("cwd").as_deref(), args.str("branch").as_deref(), args.str("session").as_deref(), ); if sessions.is_empty() { - return err( - "no-sessions", - format!("no {} sessions found for {}", AGENT, cwd), - ); + return err("no-sessions", none_found(&agents, &cwd)); } let out = args.str("out").unwrap_or_else(default_derived); fs::create_dir_all(&out).map_err(|e| Failure::Internal(sys::os_error(&e, &out)))?; @@ -846,9 +912,17 @@ pub fn command_ingest(argv: &[String]) -> Run { pub fn command_hook(argv: &[String]) -> Run { use std::io::Read; let name = argv.first().map(String::as_str).unwrap_or(""); + // `hook [--agent ]`, read by hand: a hook must never fail on + // its arguments, and the lines earlier versions installed carry no flag. + let agent_id = argv + .iter() + .position(|a| a == "--agent") + .and_then(|i| argv.get(i + 1)) + .map(String::as_str) + .unwrap_or(AGENT); let mut stdin = Vec::new(); if std::io::stdin().read_to_end(&mut stdin).is_ok() { - crate::hook::run(name, &stdin); + crate::hook::run(name, agent_id, &stdin); } Ok(Outcome::new("hook")) } @@ -878,8 +952,15 @@ fn which(name: &str) -> Option { pub fn command_install(argv: &[String]) -> Run { let mut p = parser("install"); - p.option("--cwd").flag("--local", None).option("--command"); + p.option("--cwd") + .flag("--local", None) + .option("--command") + .option("--agent"); let args = p.parse(argv)?; + // Claude Code's alone unless asked: an install that also wrote Codex's + // hooks would, with --local, put loch in every Codex project on the + // machine, and without it drop a .codex/ into repos that never use Codex. + let agents = agents_arg(Some(args.str("agent").as_deref().unwrap_or(AGENT)))?; let cwd = args .str("cwd") .filter(|c| !c.is_empty()) @@ -893,40 +974,64 @@ pub fn command_install(argv: &[String]) -> Run { .unwrap_or_else(|| sys::abspath(&std::env::args().next().unwrap_or_default())), None => "loch".into(), }; - let name = if args.flag("local") { - "settings.local.json" - } else { - "settings.json" - }; - let settings = sys::join(&sys::join(&root, ".claude"), name); - let installed = trace::install_hooks(&settings, &command) - .map_err(|trace::InstallError::Internal(m)| Failure::Internal(m))?; - let mut text = if installed.added.is_empty() { - format!("loch hooks already installed in {}\n", settings) - } else { - format!( - "installed loch hooks ({}) in {}\n", - installed.added.join(", "), - settings - ) - }; - if !installed.removed.is_empty() { - text.push_str(&format!( - "removed the old per-command hooks ({})\n", - installed.removed.join(", ") + let mut text = String::new(); + let mut results = Vec::new(); + for adapter in &agents { + let settings = adapter.hooks_file(&root, args.flag("local")); + let installed = trace::install_hooks(&settings, &command, *adapter) + .map_err(|trace::InstallError::Internal(m)| Failure::Internal(m))?; + if installed.added.is_empty() { + text.push_str(&format!("loch hooks already installed in {}\n", settings)); + } else { + text.push_str(&format!( + "installed loch hooks ({}) in {}\n", + installed.added.join(", "), + settings + )); + } + if !installed.removed.is_empty() { + text.push_str(&format!( + "removed the old per-command hooks ({})\n", + installed.removed.join(", ") + )); + } + text.push_str(&format!("{}\n", adapter.install_note())); + results.push(( + adapter.id(), + settings, + installed, + adapter.hooks_need_review(), )); } - text.push_str("restart Claude Code sessions here to pick them up\n"); - Ok(Outcome::with( - "install", - object! { - "settings" => settings.as_str(), - "command" => command.as_str(), - "added" => strings(&installed.added), - "removed" => strings(&installed.removed), - }, - text, - )) + // The first agent's at the top level, as before there were several. + let (_, settings, installed, _) = &results[0]; + let mut payload = object! { + "settings" => settings.as_str(), + // Not `command`, which is the envelope's: the hooks' loch. + "hookCommand" => command.as_str(), + "added" => strings(&installed.added), + "removed" => strings(&installed.removed), + }; + payload.insert( + "agents".into(), + Value::Array( + results + .iter() + .map(|(id, settings, installed, review)| { + Value::Object(object! { + "agent" => *id, + "settings" => settings.as_str(), + "added" => strings(&installed.added), + "removed" => strings(&installed.removed), + // The agent won't run a new hook until a person + // approves it; loch never approves its own. + "needsReview" => *review && !installed.added.is_empty(), + }) + }) + .collect(), + ), + ); + Ok(Outcome::with("install", payload, text)) } // -- blame / log / ask ------------------------------------------------------------- @@ -1389,13 +1494,22 @@ pub fn command_ask(argv: &[String]) -> Run { ); }; let link = blamed.links[owner].clone(); + let Some(adapter) = agent::by_id(&link.agent) else { + return err( + "unsupported-agent", + format!( + "session {} wrote it, but this build doesn't know its agent, {}", + link.session_id, link.agent + ), + ); + }; let Some(transcript) = &link.transcript else { return err( "transcript-missing", format!( "session {} wrote it, but its transcript is neither in {} nor in the store", link.session_id, - claude::projects_dir(None) + adapter.sessions_dir() ), ); }; @@ -1408,26 +1522,32 @@ pub fn command_ask(argv: &[String]) -> Run { .map(|r| r.root.clone()) .filter(|root| Path::new(root).is_dir()) .unwrap_or_else(sys::getcwd); - let fork = trace::fork_session( - transcript, - &cwd, - if at_turn { - link.end_uuid.as_deref() - } else { - None - }, - Some(&format!("loch ask {}", target)), - ) - .map_err(|e| match e { - trace::ForkError::Trace(t) => Failure::from(t), - trace::ForkError::Internal(m) => Failure::Internal(m), - })?; + let fork = adapter + .fork( + transcript, + &cwd, + if at_turn { + link.end_uuid.as_deref() + } else { + None + }, + Some(&format!("loch ask {}", target)), + ) + .map_err(|e| match e { + trace::ForkError::Trace(t) => Failure::from(t), + trace::ForkError::Internal(m) => Failure::Internal(m), + trace::ForkError::Unsupported(name) => Failure::Error(CommandError::new( + "unsupported-agent", + format!("{} conversations can't be forked", name), + )), + })?; - let mut command = vec![ - "claude".to_string(), - "--resume".into(), - fork.session_id.clone(), - ]; + let Some(mut command) = adapter.resume_command(&fork.session_id) else { + return err( + "unsupported-agent", + format!("{} sessions can't be resumed", adapter.name()), + ); + }; if let Some(question) = args.str("question").filter(|q| !q.is_empty()) { command.push(question); } @@ -1468,11 +1588,11 @@ pub fn command_ask(argv: &[String]) -> Run { )); } eprint!("{}", text); - exec_claude(&fork.cwd, &command) + exec_agent(&fork.cwd, &command) } #[cfg(unix)] -fn exec_claude(root: &str, command: &[String]) -> Run { +fn exec_agent(root: &str, command: &[String]) -> Run { use std::os::unix::process::CommandExt; let _ = std::env::set_current_dir(root); let error = std::process::Command::new(&command[0]) @@ -1488,7 +1608,7 @@ fn exec_claude(root: &str, command: &[String]) -> Run { } #[cfg(not(unix))] -fn exec_claude(root: &str, command: &[String]) -> Run { +fn exec_agent(root: &str, command: &[String]) -> Run { let status = std::process::Command::new(&command[0]) .args(&command[1..]) .current_dir(root) diff --git a/src/codex.rs b/src/codex.rs new file mode 100644 index 0000000..1c4b29a --- /dev/null +++ b/src/codex.rs @@ -0,0 +1,594 @@ +//! The Codex CLI adapter. +//! +//! Codex files a session by date, not by directory: +//! `$CODEX_HOME/sessions/YYYY/MM/DD/rollout-