diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..78ddf77 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,36 @@ +{ + "hooks": { + "PreToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "loch hook pre-tool 2>/dev/null || true" + } + ], + "matcher": "Bash" + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "loch hook post-tool 2>/dev/null || true" + } + ], + "matcher": "Bash" + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "loch hook stop 2>/dev/null || true" + } + ] + } + ] + } +} diff --git a/CLAUDE.md b/CLAUDE.md index 5c3af6a..a7bab5c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,6 +12,13 @@ it elsewhere with paths rewritten so the session actually resumes. Currently supports Claude Code. Codex and Cursor are the intended next adapters. +It is also becoming the **conversation format**: `loch ingest` turns a +session into a content-addressed graph of turns that can be forked, shared +and eventually merged between people. loch is the `git` of that world and an +editor (Ness first) is the `vim`. The format is specified in `SPEC.md`, which +is the one design document here on purpose: it is meant to be implementable +by someone who never reads this file. + ## Why it exists The driving use case is **PR review**: a reviewer should be able to pull @@ -27,12 +34,16 @@ travel with the code they produced. - **Not a Harness feature.** Harness is one consumer among many. Anything that only makes sense inside Harness belongs in Harness. -- **Not a normalized cross-agent schema.** Resume is same-agent only — - a Claude transcript can't be resumed by Codex, the tool-call schemas - differ. Native blobs round-trip; normalization would be lossy for the - one thing that matters. A normalized projection may come later for - review rendering, but it is not the source of truth. -- **Not git-backed storage.** See below. +- **Not a normalized source of truth.** Resume is same-agent only — a + Claude transcript can't be resumed by Codex, the tool-call schemas differ. + Native blobs round-trip; normalization would be lossy for the one thing + that matters. The loch format *is* a normalized projection, and that is + exactly its status: derived, stamped with the converter that made it, + regenerated from the raw source whenever the converter improves. The raw + transcript stays the thing that has to survive. +- **Not git-backed storage for content.** See below. Turn envelopes (which + hold hashes and structure, never transcript text) are a different + question — SPEC.md §9 and §13. ## Design decisions and their reasoning @@ -54,10 +65,14 @@ change the identity of a bundle. a reviewer wants one ref to pull. `save` filters by cwd/branch/session and packs everything matching. -**Link at branch level, not per commit.** A reviewer asks "what produced -this PR," not "what produced commit abc123." Commit-level pointers would -drag in squash-merge, rebase, and `post-rewrite` handling for no benefit. -(Nothing writes git pointers yet — this is the intended shape.) +**Link at branch level, not per commit — for bundles.** A reviewer asks +"what produced this PR," not "what produced commit abc123." Commit-level +pointers would drag in squash-merge, rebase, and `post-rewrite` handling for +no benefit. (Nothing writes git pointers yet — this is the intended shape.) +The conversation graph is the exception: forking at a turn needs the disk +state *at that turn*, so turns get per-commit pins kept alive by refs, which +is precisely the squash/rebase problem this avoided, taken on deliberately +(SPEC.md §10). **No single index object.** A shared `index.json` would need read-modify-write on every save, so two machines saving concurrently would @@ -130,19 +145,39 @@ Python 3.10 through 3.13, Poetry, boto3 behind an extra. ``` loch/ -├── cli.py # entry point, arg parsing, list/save/restore/delete/reindex +├── cli.py # entry point, arg parsing, list/save/restore/delete/reindex/ingest ├── claude.py # Claude Code adapter: path encoding, session discovery, metadata ├── bundle.py # bundle format, gzip, content-addressed ref +├── format.py # loch format: canonical JSON, turn and content ids, derived files +├── ingest.py # Claude Code JSONL -> loch turns (the converter) ├── index.py # store key layout, derived index entries, delete and reindex +├── trace.py # commit -> conversation notes, hooks, blame, log, backfill, ask's fork +├── blame_html.py # `blame --html`: self-contained page, no external assets ├── git.py # current branch of a checkout, for the list default ├── output.py # result envelope, the two renderers, structured failures ├── redact.py # secret scrubbing, applied on save before packing ├── rewrite.py # path rewriting (the load-bearing logic) └── store.py # Store interface + local-fs and S3-compatible backends test/ -└── test_*.py # one module per source module +├── test_corpus.py # opt-in, against this machine's transcripts (LOCH_CORPUS=1) +└── test_*.py # one module per source module ``` +`ingest.py` normalizes with `rewrite.py`'s machinery rather than its own: +`compile_replacements` is the same single pass with the same guards, fed +placeholder targets (`{{loch:root}}`, `{{loch:home}}`, …) instead of another +machine's paths. That sharing is what makes a turn id survive `restore` — a +copy rewritten by one set of pairs normalizes back through the same set — so +a change to the guards changes both behaviours at once, which is the point. +`test_corpus.py` is the check that it still holds on real data: 3809 of 3810 +sessions keep every turn id across a simulated move, and the one that doesn't +is a transcript that already contains the destination paths (SPEC.md §14.1). + +The turn core holds the content's *hash*, not the content, so deleting +content never invalidates an id. Anything that makes a turn's id depend on +content directly breaks tombstones; anything that makes it depend on facts +(timestamps, record uuids, model, cwd) breaks stability across copies. + The store layout is: ``` @@ -451,6 +486,12 @@ never a code. The set today: | `s3-extra-missing` | an `s3://` store on an install without the `s3` extra | | `bundle-unreadable` | the bytes arrived and won't unpack | | `nothing-restored` | every session in the bundle was skipped | +| `author-key-unreadable` | `ingest --author-key` named a file that isn't an OpenSSH public key | +| `not-a-repository` | `install`/`blame`/`log`/`ask`/`backfill` outside a git repository | +| `not-linked` | `ask` on a commit with no conversation note, or an uncommitted line | +| `transcript-missing` | the note exists but the transcript is in neither Claude's directory nor the store | +| `call-not-found` | the transcript has no result for the noted tool call | +| `git-failed` | a git command failed | | `unknown-command` | no such subcommand | | `usage` | argparse rejected the arguments (exit status 2) | | `internal` | an unexpected exception | @@ -648,6 +689,22 @@ CI and no release, so the first tag push is also the first execution of the release path. No release exists yet, so the wheel URL in the README points at a `v0.1.0` that has to be cut before it resolves. +**Blame and ask (`trace.py`) are a working demo on this repository.** All 12 +commits whose sessions still existed were backfilled exactly; the 50 from +August have no conversation left, because Claude Code had already deleted +their transcripts (`cleanupPeriodDays`, default 30) — the reason the stop +hook snapshots every session into the store. Backfill could not have used +commit hashes from tool output: `git commit -q` prints none, which is why +hooks capture links live. A fork made by `ask` was resumed with +`claude --resume -p` and answered from the original conversation. Known gaps: +the fork resumes in the current checkout rather than a worktree at the commit +(a pin, §10); the transcript snapshot is one mutable key per session rather +than content-addressed `raw/`; subagent sidecars aren't snapshotted; +backfill reads every transcript on the machine (~25s on 750MB). The hook +input's `tool_use_id` is used when present and otherwise recovered from the +transcript by command; which one current Claude Code sends hasn't been +observed, since hooks only load at session start. + The rename from lochy carried no compatibility shim: `LOCHY_STORE`, `LOCHY_S3_ENDPOINT`, `LOCHY_S3_REGION` and the `~/.lochy/store` default are simply no longer read. That was chosen because nothing had been released and @@ -660,12 +717,29 @@ old name, and warn on stderr in text mode only. 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), any git -integration (no notes, no PR-level pointers), and no adapters beyond -Claude Code. +obvious next one, and the layout takes it without a migration), PR-level +git pointers for bundles, and no adapters beyond Claude Code. `restore` still needs a full 64-character ref — the index makes refs discoverable, but nothing resolves a prefix. +**The loch format (SPEC.md) is v1 draft.** `loch ingest` converts every +session in the local corpus (3810 sessions, 266k turns) and the derived files +read back verified and byte-identical; re-ingest is idempotent. The draft +questions are all settled in SPEC.md §13, including no salt on content +hashes: privacy of withheld content is not a goal. What it doesn't do yet: write anything to a store (derived +files go to `~/.loch/derived`, raw sources aren't snapshotted), convert +subagent sidecars, give each of a moved session's cwds its own root, capture +git pins, or emit back to Claude Code JSONL. Until the first conversation is +shared, ids may change between commits (SPEC.md §12). The bundle format and +everything `save`/`restore` do are unchanged. + +`format.canonical` is RFC 8785 written out by hand rather than `json.dumps`, +because Python's float repr and code-point key order both disagree with it. +That costs speed: the corpus check went from about 3.5 to about 5.5 minutes. +If it ever matters, the fast path is `json.dumps` for any value containing no +float, no non-BMP key and no lone surrogate, which is nearly all of them, and checking the two +agree is a one-line property test. + ## Conventions - Verify before committing: `poetry run ruff check`, diff --git a/README.md b/README.md index d591b0d..de6c8ac 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,39 @@ loch reindex `save` bundles every session matching the filter, so a branch with several sessions produces a single ref. +## Blame a line back to its conversation + +```sh +loch install # once per repo: Claude Code hooks, committed in .claude/ +loch backfill # link commits made before the hooks, where it can be exact + +loch blame loch/format.py +# 102-112 6eb7b0d Canonicalize per RFC 8785, fold agent events into facts +# session 37d467e5 "loch-format-v1" — asked: "none of those seem like open questions…" +loch blame --html loch/format.py # the whole file in a browser, tinted by conversation + +loch log loch/format.py:105 # every conversation that ever changed line 105 +loch log loch/format.py:90-120 # ...or a range, followed through edits and moves +loch log loch/format.py # ...or the whole file, followed through renames + +loch ask loch/format.py:105 "why not just json.dumps?" +# forks the conversation that wrote line 105 and resumes it in Claude Code, +# from where it ended; --at-commit stops it just after the commit instead +``` + +`blame --html` writes the same thing as a page and opens it: every line of the +file tinted by the conversation that wrote it, a key of what each one asked, +and a line's `loch ask` command a click away. `--lines 1-20,90-120` limits it +to an excerpt. + +With the hooks installed, every commit an agent makes gets a git note on +`refs/notes/loch` naming the session and tool call that made it, and every +session's transcript is copied into the store when it stops — Claude Code +deletes its own after 30 days. Notes hold no transcript text; share them with +`git push origin refs/notes/loch`. `ask` never touches the original session: +it writes a new one holding the conversation, filed under +the current checkout, so the follow-up sees today's code, not the commit's. + ## Scripting it Every command takes `--json`, before or after the subcommand, and prints one @@ -123,6 +156,8 @@ An empty result is `{"sessions": []}` with `ok: true`, not a failure, and ``` bundles/.loch the bundle, named by the hash of its bytes index/branch// a small entry per branch the bundle touches +transcripts/claude-code//.jsonl + latest snapshot of a session, from the stop hook ``` `loch list --remote` reads only the index, so listing a branch never @@ -157,6 +192,10 @@ These were `LOCHY_*` before the rename, and the default store was ignored rather than rejected — rename it, and `mv ~/.lochy ~/.loch` to keep existing bundles visible. +`loch ingest` converts sessions into the loch conversation format (see +[SPEC.md](SPEC.md)) and writes one derived file per session to +`~/.loch/derived`, or `--out `. + Credentials come from the standard AWS chain, so `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`, a shared profile, or an instance role all work. diff --git a/SPEC.md b/SPEC.md new file mode 100644 index 0000000..8936337 --- /dev/null +++ b/SPEC.md @@ -0,0 +1,372 @@ +# loch format, version 1 + +**Status: draft.** The derived-file format and the Claude Code converter +(§3–§8) are implemented in `loch/format.py` and `loch/ingest.py`. The storage, +pin and native-turn sections (§9–§11) describe intended shapes that nothing +writes yet. Questions this draft doesn't settle are collected in §13 rather +than guessed at. + +## 1. What this is for + +A conversation between people and agents should work like source code: owned +locally, content-addressed, forkable at any point, shareable without a central +server. loch is that layer — the `git` to an editor's `vim`. It knows nothing +about any particular UI. + +## 2. Three layers + +``` +raw source (agent-native, immutable, content-addressed) ← what must survive + │ converter (id + version) + ▼ +derived file (loch JSONL: turns, content, facts, heads) ← regenerable + │ + ▼ +tools (Ness, review UIs, sync, merge) ← read loch only +``` + +- **Raw source is the source of truth.** It is kept byte for byte. Claude + Code's transcript stays Claude Code's format; loch never edits it. +- **A derived file is one converter's understanding of one source at one + time.** It records which converter produced it. When a converter improves, + derived files are regenerated from the raw source; they are never migrated. +- **Tools read only the derived format.** Each new agent format costs one + converter into loch, not one per tool. + +## 3. Encoding and ids + +- **Canonical JSON** is RFC 8785 (JCS), so a second implementation in any + language reproduces an id byte for byte: + - UTF-8 output + - object keys sorted by UTF-16 code units + - no whitespace + - strings escaped as ECMAScript's `JSON.stringify` escapes them, including + a lone surrogate as `\udXXX`, which real transcripts contain + - floats printed by ECMAScript's Number-to-String (`1e+21`, `1e-7`, + `0.00001`, `100`) + - NaN and Infinity rejected + + **One departure:** integers print exactly at any size. JCS treats every + number as a double, which would silently round a large integer inside a + tool result. +- **Ids:** `sha256:` followed by 64 lowercase hex digits, the SHA-256 of the + canonical JSON. The prefix names the algorithm so a future one can coexist. + +## 4. The turn + +A turn is one node in the conversation graph. Its id is the hash of its +**core**: + +```json +{ + "loch": 1, + "kind": "message", + "author": {"kind": "human", "id": "alice"}, + "parents": ["sha256:…"], + "content": "sha256:…" +} +``` + +| field | meaning | +| --- | --- | +| `loch` | Format major version. A change to the core's meaning bumps it. | +| `kind` | `message`, `tool-result`, `context`, `compaction`, and reserved for native turns, `approval` and `note`. | +| `author` | `{"kind": "human" \| "agent" \| "tool" \| "system", ...}`. A human may carry `id`, normally `ssh:SHA256:` (§13). Agent, tool and system authors carry `agent` (e.g. `claude-code`). Absent fields are omitted, never `null`. | +| `parents` | Ordered list of parent turn ids. Empty means a root; two or more means a merge. | +| `content` | The id of the content object, never the content itself. | + +The core holds the content's **hash**, not the content. So content can be +deleted (tombstoned) while every id that depends on it, including every +descendant, stays verifiable. Turn ids form a Merkle DAG: a turn's id +transitively covers its whole ancestry. + +Deliberately **not** in the core: timestamps, the source record's uuid, model +name, branch, cwd. Two records that say the same thing, by the same author, +from the same parent are the same turn. + +### Content + +```json +{"blocks": [ ... ]} +``` + +Its id is the hash of exactly that object. Block types in v1: + +| type | fields | +| --- | --- | +| `text` | `text` | +| `thinking` | `text` | +| `redacted-thinking` | — | +| `tool-call` | `call` (the agent's call id), `name`, `input` | +| `tool-result` | `call`, `content` (blocks), `error: true` when the tool failed | +| `image` | `source` (agent-native image source, inline) | +| `x-:` | Agent-specific payload, passed through unconverted | + +Unknown agent blocks are **passed through** as `x-:block` rather than +dropped. A later converter can learn them, and someone holding only the +derived file hasn't lost anything. + +### Facts + +Per-turn metadata that is not identity: `line` and `uuid` of the source +record, `alsoUuids` (other records that collapsed into this turn), +`timestamp`, `messageId`, `model`, `gitBranch`, `version`, `cwd` +(normalized), `record` (the source record type), `subtype`, `danglingParent`, +and `events`: agent bookkeeping that followed this turn (§8). +Facts may differ between two derivations of the same turn. + +## 5. Normalization + +Turn ids must not depend on which machine, directory or session id a +transcript happened to have. Before hashing, every string in content and in +facts, including object keys, is put through one left-to-right pass: + +| replaced | with | guard | +| --- | --- | --- | +| a literal `{{loch:` | `{{loch:esc}}` | none | +| session cwd | `{{loch:root}}` | path-component boundary | +| home directory | `{{loch:home}}` | path-component boundary | +| Claude's encoded cwd slug | `{{loch:root-slug}}` | whole encoded component | +| session id | `{{loch:session}}` | none | + +The pass is single and longest-match-first, with the same boundary guards +`restore` uses (see `rewrite.py` and CLAUDE.md). So a session moved with +`loch restore` normalizes back to identical bytes. The escape makes the mapping +reversible: substituting the origin back in, `{{loch:esc}}` first, restores +the original exactly. When cwd equals home, only the root pair applies. + +The origin values themselves appear only in the derived file's header. + +## 6. Heads + +```json +{"type": "heads", "current": "sha256:…", "leaves": ["sha256:…", "…"]} +``` + +- `leaves` are turns with no children, in file order. A rewind inside one + session leaves more than one. +- `current` is the head the source agent considered live, if it says so. + Claude Code's `last-prompt.leafUuid` does; otherwise it is the last record. + +Named branches are local refs over turn ids, like git branch names, and are +outside the derived file (§13, conversation identity). + +## 7. Derived file + +JSONL in canonical encoding, one object per line, in this order: + +1. **One header:** + + ```json + {"type": "header", "loch": 1, + "converter": {"id": "claude-code", "version": 1}, + "source": {"id": "sha256:…", "agent": "claude-code", + "files": [{"path": "transcript.jsonl", "sha256": "sha256:…", "bytes": 123}]}, + "origin": {"cwd": "…", "home": "…", "sessionId": "…"}, + "author": {"kind": "human", "id": "alice"}, + "session": {"title": "…", "aiTitle": "…"}} + ``` + + - `source.id` is the hash of `{agent, files}`, with files in path order. + - `origin` is the only machine-specific part of the file. + +2. **Turn lines**, parents always before children: + + ```json + {"type": "turn", "id": "sha256:…", "turn": {core}, + "content": {"blocks": [...]}, "facts": {...}} + ``` + + A turn line without `content` is a **tombstone**: the id and core are + intact, the content is gone. + +3. **One heads line.** + +A reader must recompute every turn id and every present content id, and must +reject a turn that comes before one of its parents. A file that reads back is +internally consistent, not merely well-formed. + +The file is named `.-v.jsonl`. +Ingesting the same source with the same converter and author is +byte-identical. + +## 8. Claude Code converter, v1 + +**Source.** A session is `~/.claude/projects//.jsonl` plus +everything under `/`: subagent transcripts in `subagents/` and +spilled tool output in `tool-results/`. The manifest hashes all of it as +`transcript.jsonl` and `sidecar/`. In v1 only the transcript is +converted to turns (§13, subagents). + +**One chain record is one turn.** A chain record is any record with a +`uuid`. Its parent is the turn of its `parentUuid`. Consequences measured +against a real corpus of 3,810 sessions: + +- **A single API message is often several turns.** Claude Code writes an + assistant message one content block per record, and does so for 56% of + messages, with tool results between blocks in 12% of those. `facts.messageId` + regroups them. +- **A file is already a tree.** Rewinds and retries leave branches (126 of + 3,000 files), and they survive as multiple leaves. +- **Compaction is linked across.** A `compact_boundary` has + `parentUuid: null` and names its predecessor in `logicalParentUuid`, which + v1 follows, so a compacted session stays one connected graph. +- **Parents are ordered before children** using file order as the tiebreak. + A parent that never appears makes the record a root with + `facts.danglingParent`. + +| Claude record | kind | author | +| --- | --- | --- | +| `assistant` | `message` | agent | +| `user` with a `tool_result` block | `tool-result` | tool | +| `user` with `isMeta` or `isCompactSummary` | `context` | system | +| other `user` | `message` | the ingesting human | +| `attachment` | `context` | system | +| `system`, `compact_boundary` subtype | `compaction` | system | +| other `system` (hook summaries, turn durations, API retries) | not a turn: folded into the preceding turn's `facts.events` | — | +| records without `uuid` (titles, cost, mode, queue, api-request, …) | not turns | — | + +- **User and assistant content** is converted per §4. +- **`toolUseResult`**, Claude's structured duplicate of a tool result, stays + in the source. +- **Thinking signatures** stay in the source. +- **`attachment` and `system` records** are hashed as their payload minus the + envelope fields (uuid, parents, session, timestamp, cwd, branch, version, + entrypoint, userType, slug, isSidechain, agentId, requestId, promptId), + wrapped as `x-claude-code:attachment` or `x-claude-code:system`. +- **Folded events.** An event's uuid resolves to the turn it follows, so the + record after it links straight past. Ids are therefore the same whether or + not Claude Code wrote the event. An event with no turn before it goes into + the header's `session.events`. + +**Human author.** Given at ingest. `--author-key ` gives +`ssh:SHA256:`, the same string `ssh-keygen -l` prints, and +`--author ` takes any string. When neither is given, human turns are +unattributed (`{"kind": "human"}`). It is never guessed from git config or +the environment, because it is part of every id. + +**Verified properties**, checked on every session in the local corpus by +`test/test_corpus.py`: +- Ingest is idempotent. +- Every derived file reads back verified and byte-identical. +- Turn ids and heads are unchanged after a `restore`-style rewrite to another + home, cwd and session id. The one exception is a transcript whose content + already names the destination paths (§14.1). + +## 9. Storage: envelope and content (not yet implemented) + +Two object kinds, stored apart: + +| object | holds | store | +| --- | --- | --- | +| envelope | turn cores, heads, signatures, pins | anywhere, including git. Immutable and small, and holds no transcript text. | +| content | content objects, raw source blobs | a store objects can be **deleted** from | + +The bundle store chose S3 over git because a leaked secret in git can't be deleted. That +reasoning still holds for content and doesn't apply to envelopes. Deleting +content leaves a tombstone; the graph above it still verifies. Sharing a +conversation without some of its content is the same operation as deleting +it locally. Withheld content is absent, not secret: a short message can be +confirmed by guessing it (§13, salting). + +Intended layout, extending the existing store: + +``` +raw/ raw source file +content/ content object +turns/ turn core +``` + +## 10. Git pins (partly implemented) + +**Implemented: commit to turn.** A git note on `refs/notes/loch` links a +commit to the tool call that made it: + +```json +{"loch": 1, "agent": "claude-code", "session": "", "call": "", "captured": "hook"} +``` + +`captured` is `hook` when Claude Code hooks recorded it as the commit was made +(HEAD before and after each Bash call, bounded by commit time so a checkout +isn't mistaken for authorship), or `backfill` when it was matched afterwards: +exactly one Bash call whose command holds the commit's subject and whose run +brackets the commit's author or committer time. The note names the agent's own +ids, not a turn id, because it is written before any ingest; a reader resolves +it to the turn holding that `tool-call`. Notes carry no transcript text, so they +are envelopes in the §9 sense. `notes.rewriteRef` makes amend and rebase carry +them over. + +The rest is the original design, not yet built. + +A pin links a turn to the commit the working tree was at: + +```json +{"pin": "sha256:", "repo": "", "commit": ""} +``` + +- **Pins are annotations, not part of the core.** Pinning a turn later + doesn't change its id. +- **Each pinned commit is kept alive by a ref** + (`refs/loch/pins/`), so a squash or rebase can't garbage-collect + the disk state a fork would check out. +- Forking at a turn is: check out its pin in a new worktree, emit the + transcript up to that turn, resume. + +## 11. Native turns (not yet implemented) + +Turns that no agent transcript contains are first-class turns with no source: +- a second human's message +- a tool approval: an `approval` turn with a block such as + `{"type": "approval", "call": "…", "decision": "allow"}` +- a merge: any kind with two or more parents, typically an agent-written + summary message +- a notification ("Bob forked here"): a `note` turn + +They are written by the tool that creates them as a source of their own in +loch format. Signatures are separate objects over a turn id and stay out of +the core, so a turn can gain signatures without changing identity. + +## 12. Evolving + +- **Until the first conversation is shared, everything here is draft.** Ids + may change from one commit to the next, and nothing needs migrating, + because nothing exists outside one machine and every derived file can be + regenerated. +- **After that:** + - The **converter version** bumps whenever derived output changes. Old + derived files are re-derived, never migrated. + - A converter change that alters **core bytes**, and so ids, also bumps + the **format major version** (`loch`). It ships a `supersedes` map from + old ids to new, so anyone holding the old ids can follow them. + - **Adding** a block type, fact or header field is not a version change. + Readers ignore what they don't know. + +## 13. Decisions + +These were open in the first draft. Each is settled, with the reason. + +| question | answer | why | +| --- | --- | --- | +| Number encoding | RFC 8785, with exact integers (§3) | A second implementation must reproduce ids byte for byte. | +| Converter fixes vs stable ids | Free churn until first share, then version bump plus `supersedes` (§12) | Costs nothing now, and keeps ids followable later. | +| Turn granularity | One turn per agent record. Grouping into whole replies is a view built from `facts.messageId`. | The only option that keeps the agent's own tree, rewind branches included. | +| Agent bookkeeping in the graph | `context` stays a turn. `event` is folded into facts (§8). | Context shaped what the model saw. Events are an agent's internal records, and as turns they made about 2% of turns, and every id after them, depend on its internal shapes. | +| Human identity | `ssh:SHA256:` | Same as git's SSH signing: no new infrastructure, can be checked against keys people already publish, and the same key can sign turns later. | +| Who authors a transcript's human turns | Whoever ingests it | In practice the person who ran the session. Everyone else receives their derived file and doesn't re-ingest it. | +| Conversation identity | Its root turn id | Forks share the root, so they stay recognizably the same conversation. A merge has several. Heads are local names, like git branches. | +| Sessions that moved directories | Numbered roots (`{{loch:root:1}}`, …) for every cwd the session held, in order of first appearance | The current single root lets a copy that moves only one directory change ids. Not yet built. | +| Subagents | A child graph whose root's parent is the `tool-call` turn that spawned it | Keeps a subagent's turns reachable from the conversation that asked for them. Not yet built. | +| Spilled tool output and images | Separate content objects referenced by hash, rather than inline | They dedupe, and can be deleted on their own. Not yet built. | +| Raw snapshots | `ingest` writes the raw source to `raw/` in a store | Claude Code appends to live files. Re-ingesting a grown session keeps every earlier turn id (tested), so snapshots can be incremental. Not yet built. | +| Pin capture | Live, from the driving tool. Old transcripts get none and are not guessed. | A pin inferred from tool output that turns out wrong is worse than no pin. | +| Envelopes in git | Yes | They carry structure and hashes, never text. Deletability applies to content (§9). | +| Resume from a derived-only share | The emitter synthesizes context | Thinking signatures and `toolUseResult` exist only in the raw source. With it at hand, the emitter resumes natively. | +| Deleting content | A tombstone: the content object goes, every id stays. Not git's rule, where a missing object is corruption and removal means rewriting history. | The structure is git's (a turn holds its content's hash as a commit holds a tree's), so content still can't change without its ids changing. Only the presence rule differs. A removal is visible either way, as a hole rather than new ids, but a tombstone doesn't force a rewrite on everyone downstream, which a leaked secret shouldn't need. Replacing content rather than removing it is a fork, with new ids. A reader that wants git's guarantee can refuse incomplete conversations; nothing implements that check yet. | +| Salting content hashes | No salt. Content ids are the plain hash of the content object. | Keeping content private is not a goal. Deleting content exists to remove things like a leaked secret, which is too high-entropy to recover by guessing. A short deleted message ("yes", "lgtm") can be confirmed by hashing guesses against its envelope; that is accepted. Chaining wouldn't prevent it, since the guesser holds the parents too. | + +## 14. Known limits + +1. **Content that names the destination.** A known limit rather than a + question. A transcript that already contains the path it is later + restored to can't be told apart from a rewritten one. It happened once in + 3,810 sessions, in the session that built this test. diff --git a/loch/blame_html.py b/loch/blame_html.py new file mode 100644 index 0000000..d8cd47c --- /dev/null +++ b/loch/blame_html.py @@ -0,0 +1,273 @@ +"""`loch blame --html`: the annotated file as one self-contained page. + +A terminal can't hold what makes blame readable — background tints that don't +fight the code, a key that stays put, clicking a line to see what was asked — +so this renders the same payload `--json` carries into HTML with no external +assets, which opens anywhere and can be pasted into a post as-is. +""" + +import html +import json +from typing import Any + +# Soft enough to tint a background under code, distinct enough to tell apart +# in the margin. Cycled when a file has more conversations than colours. +PALETTE = ( + "#4f8cc9", + "#d08a3a", + "#8e6cc2", + "#4a9e6b", + "#c75b7a", + "#3a9ea5", + "#a8913a", + "#6b7fd1", +) +NONE_COLOUR = "#9aa0a6" + + +def _colour(mark: str, order: dict[str, int]) -> str: + if mark not in order: + return NONE_COLOUR + return PALETTE[order[mark] % len(PALETTE)] + + +def render( + file: str, + conversations: list[dict[str, Any]], + hunks: list[dict[str, Any]], + lines: dict[int, str], + visible: list[tuple[int, int]] | None = None, +) -> str: + order = {entry["mark"]: index for index, entry in enumerate(conversations)} + by_mark = {entry["mark"]: entry for entry in conversations} + + def shown(number: int) -> bool: + return visible is None or any(a <= number <= b for a, b in visible) + + rows: list[str] = [] + previous_mark: str | None = None + previous_number: int | None = None + for hunk in hunks: + mark = hunk["mark"] + colour = _colour(mark, order) + for number in range(hunk["start"], hunk["end"] + 1): + if not shown(number): + continue + if previous_number is not None and number != previous_number + 1: + rows.append('⋯') + previous_mark = None + label = "" + if mark != previous_mark: + entry = by_mark.get(mark) + if entry is not None: + asked = entry.get("prompt") or "(no prompt recorded)" + label = ( + f'{html.escape(mark)} · ' + f"{html.escape(_short(asked, 70))}" + ) + elif mark == "+": + label = 'not committed yet' + else: + label = 'no conversation recorded' + text = html.escape(lines.get(number, "")) or " " + rows.append( + f'' + f'{number}' + f'{text}{label}' + ) + previous_mark, previous_number = mark, number + + key: list[str] = [] + for entry in conversations: + colour = _colour(entry["mark"], order) + asked = entry.get("prompt") or ( + "(transcript not available)" + if not entry.get("available") + else "(no prompt recorded)" + ) + commits = ", ".join(commit[:7] for commit in entry["commits"]) + key.append( + f'
  • ' + f'{html.escape(entry["mark"])}' + f'“{html.escape(asked)}”' + f'session {html.escape(entry["session"][:8])}' + f" · {html.escape(commits)}
  • " + ) + + data = json.dumps( + {"file": file, "conversations": conversations}, ensure_ascii=False + ).replace(" str: + flat = " ".join(text.split()) + return flat if len(flat) <= limit else flat[: limit - 1] + "…" + + +def parse_ranges(spec: str) -> list[tuple[int, int]]: + """`1-12,99-110` → [(1, 12), (99, 110)]; a bare number is one line.""" + ranges = [] + for part in spec.split(","): + part = part.strip() + if not part: + continue + start, _, end = part.partition("-") + first = int(start) + ranges.append((first, int(end) if end else first)) + return ranges + + +TEMPLATE = """ + + + + + +{title} + + + +
    +
    {file}loch blame
    +
    {rows}
    + +
    + + + +""" diff --git a/loch/cli.py b/loch/cli.py index 75d711f..853aeec 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -1,18 +1,24 @@ import argparse import importlib.metadata +import json import os import platform import re +import shutil import socket import sys +import tempfile import time import uuid +import webbrowser from collections.abc import Iterator from contextlib import contextmanager from dataclasses import dataclass, field +from datetime import datetime, timezone from pathlib import Path from typing import Any, Callable, NoReturn +from .blame_html import parse_ranges, render from .bundle import ( BUNDLE_VERSION, Bundle, @@ -31,6 +37,7 @@ resolve_cwd, transcript_path_for, ) +from .format import pack_derived from .git import current_branch from .index import ( BRANCH, @@ -44,6 +51,14 @@ reindex, value_prefix, ) +from .ingest import ( + CONVERTER, + AuthorKeyError, + Origin, + derived_name, + ingest, + ssh_author_id, +) from .output import JSON_FLAG, CommandError, Result, emit, emit_error from .redact import RedactionError, redact, summarize from .rewrite import ( @@ -54,6 +69,25 @@ rewrite_transcript, ) from .store import MissingDependency, MissingObject, create_store, resolve_store_uri +from .trace import ( + NOTES_REF, + UNCOMMITTED, + Link, + Resolver, + TraceError, + backfill, + blame_hunks, + fork_session, + git, + history, + hook_post_tool, + hook_pre_tool, + install_hooks, + repo_root, + snapshot_transcript, +) + +DEFAULT_DERIVED = os.path.join(str(Path.home()), ".loch", "derived") USAGE = """loch — save and restore agent coding sessions across machines @@ -64,6 +98,17 @@ loch restore [--into ] [--store ] [--force] [--new-id] loch delete [--store ] loch reindex [--store ] + loch ingest [--cwd ] [--branch ] [--session ] + [--author | --author-key ] + [--out ] + loch install [--local] [--command ] + loch blame [--html [] [--lines ] [--no-open]] + [--store ] + loch log [:[-]] [--store ] + loch ask [] [--at-commit] [--no-launch] + [--store ] + loch backfill [--revision ] (default: every branch) + loch hook pre-tool | post-tool | stop (run by Claude Code) loch --version Every command takes --json, which replaces the text below with one machine- @@ -77,6 +122,16 @@ LOCH_STORE default store URI LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) LOCH_S3_REGION region override + +Derived conversation files go to ~/.loch/derived unless --out says otherwise. + +`install` adds Claude Code hooks to a repository that note, on every commit an +agent makes, the conversation and tool call that made it (git notes on +refs/notes/loch), and snapshot each session's transcript into the store. +`blame` shows which conversation wrote each line, `log` every conversation +that changed a file or line range over its history; `ask` forks that +conversation and resumes it in Claude Code — from its end, or with +--at-commit from just after the commit. """ @@ -590,6 +645,487 @@ def command_reindex(argv: list[str]) -> Result: ) +def command_ingest(argv: list[str]) -> Result: + parser = _parser("ingest") + parser.add_argument("--cwd") + parser.add_argument("--branch") + parser.add_argument("--session") + parser.add_argument("--author") + parser.add_argument("--author-key") + parser.add_argument("--out") + args = parser.parse_args(argv) + + author = args.author + if args.author_key is not None: + if author is not None: + fail("usage", "pass --author or --author-key, not both") + try: + author = ssh_author_id(Path(args.author_key).read_text(encoding="utf-8")) + except (OSError, AuthorKeyError) as error: + fail("author-key-unreadable", f"{args.author_key}: {error}") + + cwd, sessions = collect(args.cwd, args.branch, args.session) + if not sessions: + fail("no-sessions", f"no {AGENT} sessions found for {cwd}") + + out = args.out if args.out is not None else DEFAULT_DERIVED + os.makedirs(out, exist_ok=True) + home = home_dir() + + results: list[dict[str, Any]] = [] + lines: list[str] = [] + for meta in sessions: + derived = ingest(meta.path, Origin(meta.cwd, home, meta.session_id), author) + path = os.path.join(out, derived_name(derived)) + Path(path).write_bytes(pack_derived(derived)) + results.append( + { + "sessionId": meta.session_id, + "source": derived.header["source"]["id"], + "path": path, + "turns": len(derived.turns), + "heads": derived.heads, + } + ) + leaves = len(derived.heads["leaves"]) + lines.append( + f" {meta.session_id} {len(derived.turns)} turns {leaves} head(s)\n" + ) + + text = "".join(lines) + f"\ningested {len(sessions)} session(s) into {out}\n" + return Result( + command="ingest", + payload={ + "cwd": cwd, + "out": out, + "converter": CONVERTER, + "sessions": results, + }, + text=text, + ) + + +@contextmanager +def trace_errors() -> Iterator[None]: + try: + yield + except TraceError as error: + fail(error.code, str(error)) + + +def command_hook(argv: list[str]) -> Result: + """Run by Claude Code with the event as JSON on stdin. It must never fail + the tool call it wraps, so every error is swallowed and nothing is + written: a hook that breaks commits gets uninstalled.""" + name = argv[0] if argv else "" + try: + event = json.loads(sys.stdin.read() or "{}") + if not isinstance(event, dict): + event = {} + if name == "pre-tool": + hook_pre_tool(event) + elif name == "post-tool": + hook_post_tool(event) + elif name == "stop": + snapshot_transcript(event, create_store(resolve_store_uri())) + except Exception: + pass + return Result(command="hook") + + +def command_install(argv: list[str]) -> Result: + parser = _parser("install") + parser.add_argument("--cwd") + parser.add_argument("--local", action="store_true") + parser.add_argument("--command") + args = parser.parse_args(argv) + + with trace_errors(): + root = repo_root(args.cwd or os.getcwd()) + if args.command is not None: + command = args.command + elif args.local: + # A machine-specific path, which is why it only goes in the + # uncommitted settings file. + command = shutil.which("loch") or os.path.abspath(sys.argv[0]) + else: + command = "loch" + name = "settings.local.json" if args.local else "settings.json" + settings = os.path.join(root, ".claude", name) + added = install_hooks(settings, command) + # Amend and rebase copy a commit's note to its replacement only when told + # to, and an amended commit is still the one the conversation made. + git(root, "config", "notes.rewriteRef", NOTES_REF) + + text = ( + f"installed loch hooks ({', '.join(added)}) in {settings}\n" + if added + else f"loch hooks already installed in {settings}\n" + ) + text += ( + "restart Claude Code sessions in this repository to pick them up\n" + f"share links with: git push {NOTES_REF}\n" + ) + return Result( + command="install", + payload={"settings": settings, "command": command, "added": added}, + text=text, + ) + + +def _store_or_none(uri: str | None) -> Any: + try: + return create_store(resolve_store_uri(uri)) + except Exception: + return None + + +def _flat(text: str, limit: int) -> str: + flat = " ".join(text.split()) + return flat if len(flat) <= limit else flat[: limit - 1] + "…" + + +def _link_text(link: Link | None) -> str: + if link is None: + return "no conversation recorded" + if link.transcript is None: + return f"session {link.session_id[:8]} (transcript not available)" + title = f' "{link.title}"' if link.title else "" + prompt = f' — asked: "{_flat(link.prompt, 72)}"' if link.prompt else "" + return f"session {link.session_id[:8]}{title}{prompt}" + + +UNLINKED_MARK = "·" +UNCOMMITTED_MARK = "+" + + +def _mark(index: int) -> str: + letters = "" + index += 1 + while index: + index, remainder = divmod(index - 1, 26) + letters = chr(ord("A") + remainder) + letters + return letters + + +def command_blame(argv: list[str]) -> Result: + parser = _parser("blame") + parser.add_argument("file") + parser.add_argument("--html", nargs="?", const="", metavar="PATH") + parser.add_argument("--lines", metavar="RANGES") + parser.add_argument("--no-open", action="store_true") + parser.add_argument("--store") + args = parser.parse_args(argv) + + cwd = os.path.dirname(os.path.abspath(args.file)) or os.getcwd() + with trace_errors(): + root = repo_root(cwd) + hunks = blame_hunks(root, os.path.relpath(os.path.abspath(args.file), root)) + resolver = Resolver(root, _store_or_none(args.store)) + links: dict[str, Link | None] = {} + for hunk in hunks: + if hunk.commit not in links and hunk.commit != UNCOMMITTED: + links[hunk.commit] = resolver.resolve(hunk.commit) + + # One mark per request rather than per session: a long session makes many + # commits for many asks, and marking by session would paint the whole file + # one letter. Marks are handed out in order of first appearance in the + # file, so A is always the first conversation you read. + marks: dict[tuple[str, str], str] = {} + legend: list[dict[str, Any]] = [] + mark_of: dict[str, str] = {} + for hunk in hunks: + link = links.get(hunk.commit) + if hunk.commit == UNCOMMITTED: + mark_of[hunk.commit] = UNCOMMITTED_MARK + continue + if link is None: + mark_of[hunk.commit] = UNLINKED_MARK + continue + key = (link.session_id, link.prompt or link.call) + if key not in marks: + marks[key] = _mark(len(marks)) + legend.append({"mark": marks[key], **link.payload(), "commits": []}) + entry = next(item for item in legend if item["mark"] == marks[key]) + if hunk.commit not in entry["commits"]: + entry["commits"].append(hunk.commit) + mark_of[hunk.commit] = marks[key] + + rows: list[dict[str, Any]] = [] + for hunk in hunks: + link = links.get(hunk.commit) + rows.append( + { + "start": hunk.start, + "end": hunk.end, + "commit": None if hunk.commit == UNCOMMITTED else hunk.commit, + "summary": hunk.summary, + "mark": mark_of[hunk.commit], + "conversation": link.payload() if link is not None else None, + } + ) + text = _hunks_text(args.file, hunks, links) + payload: dict[str, Any] = { + "file": args.file, + "conversations": legend, + "hunks": rows, + } + if args.html is not None: + try: + visible = parse_ranges(args.lines) if args.lines else None + except ValueError: + fail("usage", f"--lines takes ranges like 1-12,99-110, not {args.lines}") + page = render( + args.file, + legend, + rows, + { + hunk.start + offset: line + for hunk in hunks + for offset, line in enumerate(hunk.lines) + }, + visible, + ) + target = args.html or os.path.join( + tempfile.gettempdir(), f"loch-blame-{os.path.basename(args.file)}.html" + ) + Path(target).write_text(page, encoding="utf-8") + payload["html"] = os.path.abspath(target) + text = f"wrote {payload['html']}\n" + if not args.no_open and JSON_FLAG not in sys.argv: + webbrowser.open(Path(target).resolve().as_uri()) + return Result(command="blame", payload=payload, text=text) + + +def _hunks_text(file: str, hunks: list[Any], links: dict[str, Link | None]) -> str: + lines = [f"{file}\n"] + for hunk in hunks: + link = links.get(hunk.commit) + span = f"{hunk.start}-{hunk.end}" if hunk.end > hunk.start else str(hunk.start) + if hunk.commit == UNCOMMITTED: + lines.append(f" {span:>9} uncommitted\n") + continue + lines.append(f" {span:>9} {hunk.commit[:7]} {hunk.summary[:60]}\n") + lines.append(f" {'':>9} {'':7} {_link_text(link)}\n") + linked = sum(1 for link in links.values() if link is not None) + lines.append( + f"\n{linked} of {len(links)} commit(s) linked to a conversation; " + f"follow one up with: loch ask {file}:\n" + ) + return "".join(lines) + + +def _history_target(target: str) -> tuple[str, tuple[int, int] | None]: + """`file`, `file:105` or `file:100-120`; a path that exists wins outright.""" + if os.path.exists(target): + return target, None + file, _, span = target.rpartition(":") + start, _, end = span.partition("-") + if not file or not start.isdigit() or (end and not end.isdigit()): + fail("usage", f"{target} is neither a file nor :[-]") + first, last = int(start), int(end) if end else int(start) + if first < 1 or last < first: + fail("usage", f"{span} is not a line range") + return file, (first, last) + + +def command_log(argv: list[str]) -> Result: + parser = _parser("log") + parser.add_argument("target") + parser.add_argument("--store") + args = parser.parse_args(argv) + + file, lines = _history_target(args.target) + cwd = os.path.dirname(os.path.abspath(file)) or os.getcwd() + with trace_errors(): + root = repo_root(cwd) + relative = os.path.relpath(os.path.abspath(file), root) + if lines is not None: + # -L past the end is a fatal git error with a worse message. + length = max((hunk.end for hunk in blame_hunks(root, relative)), default=0) + if lines[1] > length: + fail("usage", f"{file} has {length} lines, not {lines[1]}") + changes = history(root, relative, lines) + resolver = Resolver(root, _store_or_none(args.store)) + + # Grouped the way blame marks them — per request, not per session — and + # in order of most recent change, since "who touched this last" is the + # question a history is usually opened to answer. + conversations: list[dict[str, Any]] = [] + keyed: dict[tuple[str, str], dict[str, Any]] = {} + entries: list[dict[str, Any]] = [] + text = [] + for change in changes: + link = resolver.resolve(change.commit) + when = datetime.fromtimestamp(change.time, timezone.utc) + entries.append( + { + "commit": change.commit, + "time": when.strftime("%Y-%m-%dT%H:%M:%SZ"), + "summary": change.summary, + "conversation": link.payload() if link is not None else None, + } + ) + text.append( + f" {change.commit[:7]} {when:%Y-%m-%d} {change.summary[:60]}\n" + f" {'':7} {'':10} {_link_text(link)}\n" + ) + if link is None: + continue + key = (link.session_id, link.prompt or link.call) + if key not in keyed: + keyed[key] = {**link.payload(), "commits": []} + conversations.append(keyed[key]) + keyed[key]["commits"].append(change.commit) + + span = ( + "" + if lines is None + else (f":{lines[0]}" if lines[0] == lines[1] else f":{lines[0]}-{lines[1]}") + ) + header = ( + f"{file}{span}: {len(changes)} commit(s) from " + f"{len(conversations)} conversation(s), newest first\n" + ) + footer = "\nfollow one up with: loch ask \n" if conversations else "" + return Result( + command="log", + payload={ + "file": file, + "lines": None if lines is None else {"start": lines[0], "end": lines[1]}, + "conversations": conversations, + "commits": entries, + }, + text=header + "".join(text) + footer, + ) + + +def _resolve_commit(root: str, target: str) -> str: + file, _, line = target.rpartition(":") + if file and line.isdigit() and os.path.exists(file): + relative = os.path.relpath(os.path.abspath(file), root) + for hunk in blame_hunks(root, relative): + if hunk.start <= int(line) <= hunk.end: + if hunk.commit == UNCOMMITTED: + fail("not-linked", f"{target} is not committed yet") + return hunk.commit + fail("usage", f"{file} has no line {line}") + output = git( + root, "rev-parse", "--verify", "-q", f"{target}^{{commit}}", check=False + ) + if not output.strip(): + fail("usage", f"{target} is neither a commit nor :") + return output.strip() + + +def command_ask(argv: list[str]) -> Result: + parser = _parser("ask") + parser.add_argument("target") + parser.add_argument("question", nargs="?") + parser.add_argument("--at-commit", action="store_true") + parser.add_argument("--no-launch", action="store_true") + parser.add_argument("--store") + args = parser.parse_args(argv) + as_json = JSON_FLAG in sys.argv + + with trace_errors(): + root = repo_root(os.getcwd()) + commit = _resolve_commit(root, args.target) + link = Resolver(root, _store_or_none(args.store)).resolve(commit) + if link is None: + fail("not-linked", f"no conversation is recorded for {commit[:7]}") + if link.transcript is None: + fail( + "transcript-missing", + f"session {link.session_id} is linked but its transcript is " + "neither in ~/.claude/projects nor in the store", + ) + fork = fork_session( + link.transcript, + root, + call=link.call if args.at_commit else None, + title=f"loch ask {commit[:7]}", + ) + + command = ["claude", "--resume", fork.session_id] + if args.question: + command.append(args.question) + payload = { + "commit": commit, + "conversation": link.payload(), + "fork": { + "sessionId": fork.session_id, + "path": fork.path, + "cwd": fork.cwd, + "records": fork.records, + }, + "at": "commit" if args.at_commit else "end", + "launch": command, + } + where = "just after it" if args.at_commit else "to its end" + text = ( + f"forked session {fork.origin_session[:8]}, which made {commit[:7]}, " + f"{where}: {fork.records} records, as {fork.session_id}\n" + ) + if args.no_launch or as_json: + return Result( + command="ask", + payload=payload, + text=text + f"resume with: cd {root} && {' '.join(command)}\n", + ) + sys.stderr.write(text) + os.chdir(root) + os.execvp("claude", command) + + +def _progress_meter() -> Callable[[int, int, int, int], None] | None: + """A one-line counter on stderr, for a person watching a terminal only. + + JSON mode keeps stderr empty, and a pipe or log file would get every + redraw as garbage, so both get nothing. + """ + if JSON_FLAG in sys.argv or not sys.stderr.isatty(): + return None + last = [0.0] + + def meter(done: int, total: int, read: int, size: int) -> None: + now = time.monotonic() + if done < total and now - last[0] < 0.1: + return + last[0] = now + percent = 100 * read // size if size else 100 + sys.stderr.write( + f"\rscanning transcripts {done}/{total} " + f"({format_bytes(read)} of {format_bytes(size)}, {percent}%)\033[K" + ) + if done == total: + sys.stderr.write("\n") + sys.stderr.flush() + + return meter + + +def command_backfill(argv: list[str]) -> Result: + parser = _parser("backfill") + parser.add_argument("--cwd") + # Branches rather than --all, which would walk refs/notes/loch too. + parser.add_argument("--revision", default="--branches") + args = parser.parse_args(argv) + + with trace_errors(): + root = repo_root(args.cwd or os.getcwd()) + linked = backfill(root, args.revision, _progress_meter()) + rows = [ + {"commit": sha, "session": call.session_id, "call": call.call} + for sha, call in linked + ] + text = "".join( + f" {sha[:7]} session {call.session_id[:8]}\n" for sha, call in linked + ) + text += f"linked {len(linked)} commit(s)\n" + return Result(command="backfill", payload={"linked": rows}, text=text) + + def command_help(argv: list[str]) -> Result: return Result(command="help", payload={"usage": USAGE}, text=USAGE) @@ -625,6 +1161,13 @@ def _platform_name() -> str: "restore": command_restore, "delete": command_delete, "reindex": command_reindex, + "ingest": command_ingest, + "install": command_install, + "blame": command_blame, + "ask": command_ask, + "log": command_log, + "backfill": command_backfill, + "hook": command_hook, "help": command_help, "version": command_version, } diff --git a/loch/format.py b/loch/format.py new file mode 100644 index 0000000..0d8677b --- /dev/null +++ b/loch/format.py @@ -0,0 +1,257 @@ +import hashlib +import json +import re +from collections.abc import Iterable, Iterator +from dataclasses import dataclass, field +from decimal import Decimal +from typing import Any + +FORMAT_VERSION = 1 + +HASH_PREFIX = "sha256:" + + +class FormatError(ValueError): + """A derived file that doesn't parse, names a format this build can't + read, or carries an id its own contents don't hash to.""" + + +_LONE_SURROGATE = re.compile("[\ud800-\udfff]") + + +def _string(text: str) -> str: + """JSON.stringify's escaping, which Python's matches except for a lone + surrogate: Python writes it raw, which isn't valid UTF-8, where + ECMAScript escapes it. Transcripts do hold them — a `\\ud83d` cut from its + pair by truncation — so they are escaped rather than refused.""" + encoded = json.dumps(text, ensure_ascii=False) + if _LONE_SURROGATE.search(encoded): + encoded = _LONE_SURROGATE.sub( + lambda match: f"\\u{ord(match.group(0)):04x}", encoded + ) + return encoded + + +def _number(value: float) -> str: + """ECMAScript Number-to-String, as RFC 8785 requires. Python's repr finds + the same shortest round-trip digits but places the exponent differently + (`1e+16` and `1e-05` where ECMAScript writes `10000000000000000` and + `0.00001`), so only the digits are taken from it.""" + if value != value or value in (float("inf"), float("-inf")): + raise ValueError(f"{value} has no JSON representation") + if value == 0: + return "0" + sign = "-" if value < 0 else "" + parts = Decimal(repr(abs(value))).normalize().as_tuple() + digits = "".join(str(digit) for digit in parts.digits) + exponent = parts.exponent + assert isinstance(exponent, int) + k = len(digits) + n = k + exponent + if k <= n <= 21: + return sign + digits + "0" * (n - k) + if 0 < n <= 21: + return sign + digits[:n] + "." + digits[n:] + if -6 < n <= 0: + return sign + "0." + "0" * -n + digits + mantissa = digits[0] + ("." + digits[1:] if k > 1 else "") + power = n - 1 + return f"{sign}{mantissa}e{'+' if power >= 0 else '-'}{abs(power)}" + + +def _utf16_order(key: str) -> bytes: + return key.encode("utf-16-be", "surrogatepass") + + +def _encode(value: Any, out: list[str]) -> None: + if isinstance(value, str): + out.append(_string(value)) + elif value is None: + out.append("null") + elif value is True: + out.append("true") + elif value is False: + out.append("false") + elif isinstance(value, int): + out.append(str(value)) + elif isinstance(value, float): + out.append(_number(value)) + elif isinstance(value, dict): + out.append("{") + for index, key in enumerate(sorted(value, key=_utf16_order)): + if not isinstance(key, str): + raise TypeError(f"object key {key!r} is not a string") + if index: + out.append(",") + out.append(_string(key)) + out.append(":") + _encode(value[key], out) + out.append("}") + elif isinstance(value, (list, tuple)): + out.append("[") + for index, item in enumerate(value): + if index: + out.append(",") + _encode(item, out) + out.append("]") + else: + raise TypeError(f"{type(value).__name__} is not JSON") + + +def canonical(value: Any) -> bytes: + """RFC 8785 (JSON Canonicalization Scheme): the one encoding every id is + computed over, so a second implementation in any language can reproduce + an id byte for byte. Keys sort by UTF-16 code units, numbers print as + ECMAScript does, and strings escape as JSON.stringify does. + + One deliberate departure: an integer prints exactly, at any size. RFC + 8785 treats every number as a double, which would silently round a + 63-bit id inside a tool result; exact is what the transcript said.""" + out: list[str] = [] + _encode(value, out) + return "".join(out).encode("utf-8") + + +def digest(value: Any) -> str: + return HASH_PREFIX + hashlib.sha256(canonical(value)).hexdigest() + + +def digest_bytes(data: bytes) -> str: + return HASH_PREFIX + hashlib.sha256(data).hexdigest() + + +def hex_of(object_id: str) -> str: + if not object_id.startswith(HASH_PREFIX): + raise FormatError(f"not a {HASH_PREFIX} id: {object_id}") + return object_id[len(HASH_PREFIX) :] + + +@dataclass(frozen=True) +class Turn: + """One node of the conversation graph, in two halves. + + `core` is the hashed envelope — format version, kind, author, parents, and + the *hash* of the content, never the content itself. That indirection is + what lets content be deleted while every id that depends on it stays + verifiable: a tombstoned turn still hashes to its id. + + `facts` are what the converter knew about the turn that is not part of its + identity — timestamps, the source record's uuid and line, model, branch. + They are regenerable and may differ between two derivations of the same + turn without the turn being a different one.""" + + id: str + core: dict[str, Any] + blocks: list[dict[str, Any]] | None + facts: dict[str, Any] = field(default_factory=dict) + + +def content_id(blocks: list[dict[str, Any]]) -> str: + return digest({"blocks": blocks}) + + +def make_core( + kind: str, + author: dict[str, Any], + parents: list[str], + blocks: list[dict[str, Any]], +) -> dict[str, Any]: + return { + "loch": FORMAT_VERSION, + "kind": kind, + "author": author, + "parents": parents, + "content": content_id(blocks), + } + + +def make_turn( + kind: str, + author: dict[str, Any], + parents: list[str], + blocks: list[dict[str, Any]], + facts: dict[str, Any] | None = None, +) -> Turn: + core = make_core(kind, author, parents, blocks) + return Turn(id=digest(core), core=core, blocks=blocks, facts=facts or {}) + + +@dataclass(frozen=True) +class Derived: + """A converter's understanding of one source, at the time it ran. Throw it + away and re-derive whenever the converter improves; the source is what + has to survive.""" + + header: dict[str, Any] + turns: list[Turn] + heads: dict[str, Any] + + +def derived_lines(derived: Derived) -> Iterator[bytes]: + yield canonical({"type": "header", **derived.header}) + for turn in derived.turns: + record: dict[str, Any] = {"type": "turn", "id": turn.id, "turn": turn.core} + if turn.blocks is not None: + record["content"] = {"blocks": turn.blocks} + if turn.facts: + record["facts"] = turn.facts + yield canonical(record) + yield canonical({"type": "heads", **derived.heads}) + + +def pack_derived(derived: Derived) -> bytes: + return b"".join(line + b"\n" for line in derived_lines(derived)) + + +def verify_turn(turn: Turn) -> None: + if digest(turn.core) != turn.id: + raise FormatError(f"turn {turn.id} does not hash to its id") + if turn.blocks is not None and content_id(turn.blocks) != turn.core["content"]: + raise FormatError(f"turn {turn.id} content does not match its hash") + + +def read_derived(lines: Iterable[str]) -> Derived: + """Parses and verifies. Every id is recomputed, so a file that reads back + without raising is internally consistent, not merely well-formed.""" + header: dict[str, Any] | None = None + heads: dict[str, Any] = {} + turns: list[Turn] = [] + seen: set[str] = set() + + for number, line in enumerate(lines, start=1): + if not line.strip(): + continue + try: + record = json.loads(line) + except ValueError as error: + raise FormatError(f"line {number}: {error}") from error + kind = record.pop("type", None) + if kind == "header": + if record.get("loch") != FORMAT_VERSION: + raise FormatError( + f"unsupported loch format {record.get('loch')} " + f"(this build reads {FORMAT_VERSION})" + ) + header = record + elif kind == "turn": + content = record.get("content") + turn = Turn( + id=record["id"], + core=record["turn"], + blocks=content["blocks"] if content is not None else None, + facts=record.get("facts", {}), + ) + verify_turn(turn) + for parent in turn.core["parents"]: + if parent not in seen: + raise FormatError(f"turn {turn.id} precedes its parent {parent}") + seen.add(turn.id) + turns.append(turn) + elif kind == "heads": + heads = record + else: + raise FormatError(f"line {number}: unknown record type {kind!r}") + + if header is None: + raise FormatError("no header") + return Derived(header=header, turns=turns, heads=heads) diff --git a/loch/ingest.py b/loch/ingest.py new file mode 100644 index 0000000..4c77a9a --- /dev/null +++ b/loch/ingest.py @@ -0,0 +1,450 @@ +import base64 +import hashlib +import heapq +import json +import os +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from .claude import AGENT, encode_path +from .format import FORMAT_VERSION, Derived, Turn, digest, digest_bytes +from .format import make_turn as build_turn +from .rewrite import ( + ENCODED_COMPONENT_BOUNDARY, + PATH_BOUNDARY, + UNGUARDED, + compile_replacements, +) + +CONVERTER = {"id": AGENT, "version": 1} + +PLACEHOLDER_PREFIX = "{{loch:" +ESCAPE = "{{loch:esc}}" +ROOT = "{{loch:root}}" +HOME = "{{loch:home}}" +ROOT_SLUG = "{{loch:root-slug}}" +SESSION = "{{loch:session}}" + +AGENT_AUTHOR = {"kind": "agent", "agent": AGENT} +TOOL_AUTHOR = {"kind": "tool", "agent": AGENT} +SYSTEM_AUTHOR = {"kind": "system", "agent": AGENT} + +# Record fields that place a record (in time, on a machine, in Claude's own +# bookkeeping) rather than say anything. Excluded from the hashed payload of +# system and attachment turns; the identity of a user or assistant turn comes +# from message content alone, so this list doesn't reach those. +ENVELOPE_FIELDS = frozenset( + { + "type", + "uuid", + "parentUuid", + "logicalParentUuid", + "sessionId", + "session_id", + "timestamp", + "cwd", + "gitBranch", + "version", + "entrypoint", + "userType", + "slug", + "isSidechain", + "agentId", + "requestId", + "promptId", + } +) + + +@dataclass(frozen=True) +class Origin: + """Where the source lived when it was ingested. These are the only + machine-specific strings a derived file carries, and they live in its + header alone: every turn refers to them through placeholders.""" + + cwd: str + home: str + session_id: str + + +def normalizer(origin: Origin) -> Callable[[str], str]: + """Maps a string to its machine-neutral form, with the same single-pass, + boundary-guarded machinery restore rewrites with — so a session copied + elsewhere by `restore` normalizes back to the same bytes. + + The escape pair comes first in meaning though not in order: a literal + `{{loch:` already in a transcript becomes `{{loch:esc}}`, which keeps + every placeholder in the output unambiguous and the mapping reversible.""" + pairs = [ + (PLACEHOLDER_PREFIX, ESCAPE, UNGUARDED), + (origin.cwd, ROOT, PATH_BOUNDARY), + (encode_path(origin.cwd), ROOT_SLUG, ENCODED_COMPONENT_BOUNDARY), + (origin.session_id, SESSION, UNGUARDED), + ] + # A session run from the home directory itself is a root, not a home. + if origin.home != origin.cwd: + pairs.append((origin.home, HOME, PATH_BOUNDARY)) + return compile_replacements(pairs) + + +def normalize_value(value: Any, text: Callable[[str], str]) -> Any: + """Keys as well as values: a tool result can key a map by file path, and + `restore` rewrites the text of the whole record, keys included.""" + if isinstance(value, str): + return text(value) + if isinstance(value, list): + return [normalize_value(item, text) for item in value] + if isinstance(value, dict): + return {text(key): normalize_value(item, text) for key, item in value.items()} + return value + + +def _blocks_from_content(content: Any) -> list[dict[str, Any]]: + if isinstance(content, str): + return [{"type": "text", "text": content}] + if not isinstance(content, list): + return [] + return [_block(block) for block in content] + + +def _block(block: Any) -> dict[str, Any]: + if not isinstance(block, dict): + return {"type": "x-claude-code:block", "block": block} + kind = block.get("type") + if kind == "text": + return {"type": "text", "text": block.get("text", "")} + if kind == "thinking": + # The signature is Anthropic's attestation for resuming, not content, + # and it lives on in the source. + return {"type": "thinking", "text": block.get("thinking", "")} + if kind == "redacted_thinking": + return {"type": "redacted-thinking"} + if kind == "tool_use": + return { + "type": "tool-call", + "call": block.get("id"), + "name": block.get("name"), + "input": block.get("input"), + } + if kind == "tool_result": + normalized: dict[str, Any] = { + "type": "tool-result", + "call": block.get("tool_use_id"), + "content": _blocks_from_content(block.get("content")), + } + if block.get("is_error"): + normalized["error"] = True + return normalized + if kind == "image": + return {"type": "image", "source": block.get("source")} + # Unknown block types pass through whole rather than being dropped, so a + # later converter version can learn them without the source being re-read + # by anyone who only has the derived file. + return {"type": "x-claude-code:block", "block": block} + + +def _payload(record: dict[str, Any]) -> dict[str, Any]: + return {key: value for key, value in record.items() if key not in ENVELOPE_FIELDS} + + +def classify(record: dict[str, Any]) -> tuple[str, dict[str, Any], list[Any]] | None: + """(kind, author, blocks) for a chain record, or None for one that isn't + part of the conversation graph. The human author is filled in by the + caller, since only the ingest knows who it is.""" + kind = record.get("type") + message = record.get("message") + content = message.get("content") if isinstance(message, dict) else None + + if kind == "assistant": + return "message", AGENT_AUTHOR, _blocks_from_content(content) + if kind == "user": + blocks = _blocks_from_content(content) + if record.get("isCompactSummary") or record.get("isMeta"): + return "context", SYSTEM_AUTHOR, blocks + if any(block["type"] == "tool-result" for block in blocks): + return "tool-result", TOOL_AUTHOR, blocks + return "message", {"kind": "human"}, blocks + if kind == "attachment": + block = {"type": "x-claude-code:attachment", "attachment": _payload(record)} + return "context", SYSTEM_AUTHOR, [block] + if kind == "system": + block = {"type": "x-claude-code:system", "system": _payload(record)} + if record.get("subtype") == "compact_boundary": + return "compaction", SYSTEM_AUTHOR, [block] + return "event", SYSTEM_AUTHOR, [block] + return None + + +def _parent_uuid(record: dict[str, Any]) -> str | None: + """A compaction boundary has no parent by design and names the record it + logically follows instead. Following that link is what keeps a compacted + session one connected graph rather than a stack of disjoint roots.""" + parent = record.get("parentUuid") + if parent is None: + parent = record.get("logicalParentUuid") + return parent if isinstance(parent, str) else None + + +def _parse(raw: str) -> list[tuple[int, dict[str, Any]]]: + records: list[tuple[int, dict[str, Any]]] = [] + for number, line in enumerate(raw.split("\n"), start=1): + if not line.strip(): + continue + try: + record = json.loads(line) + except ValueError: + continue + if isinstance(record, dict): + records.append((number, record)) + return records + + +def _topological( + chain: list[tuple[int, dict[str, Any]]], +) -> tuple[list[tuple[int, dict[str, Any]]], set[str]]: + """File order wherever it already respects parentage, which for Claude's + append-only files is everywhere. Parents that never appear are dangling + (the record becomes a root); a cycle, which a well-formed file can't hold, + is broken the same way rather than looping.""" + present = {record["uuid"] for _, record in chain} + children: dict[str, list[int]] = {} + waiting = [0] * len(chain) + for index, (_, record) in enumerate(chain): + parent = _parent_uuid(record) + if parent is not None and parent in present and parent != record["uuid"]: + children.setdefault(parent, []).append(index) + waiting[index] = 1 + + ready = [index for index, count in enumerate(waiting) if count == 0] + heapq.heapify(ready) + ordered: list[tuple[int, dict[str, Any]]] = [] + done = [False] * len(chain) + while len(ordered) < len(chain): + if not ready: + stuck = next(index for index, finished in enumerate(done) if not finished) + waiting[stuck] = 0 + heapq.heappush(ready, stuck) + index = heapq.heappop(ready) + if done[index]: + continue + done[index] = True + ordered.append(chain[index]) + for child in children.get(chain[index][1]["uuid"], []): + if not done[child]: + waiting[child] -= 1 + if waiting[child] <= 0: + heapq.heappush(ready, child) + return ordered, present + + +def _facts( + number: int, record: dict[str, Any], text: Callable[[str], str] +) -> dict[str, Any]: + facts: dict[str, Any] = {"line": number, "uuid": record["uuid"]} + message = record.get("message") + if isinstance(message, dict): + for source, name in (("id", "messageId"), ("model", "model")): + if isinstance(message.get(source), str): + facts[name] = message[source] + for name in ("timestamp", "gitBranch", "version", "subtype"): + if isinstance(record.get(name), str): + facts[name] = record[name] + if isinstance(record.get("cwd"), str): + facts["cwd"] = text(record["cwd"]) + facts["record"] = record.get("type") + return facts + + +def _fold_event( + number: int, + record: dict[str, Any], + blocks: list[Any], + turn_of: dict[str, str], + turns: dict[str, Turn], + session: dict[str, Any], + text: Callable[[str], str], +) -> None: + """Hook summaries, turn durations, API retries: Claude Code's own + bookkeeping, written into the parent chain but not part of what anyone + said. As turns they made a quarter of the graph's identity depend on + Claude Code's internal record shapes. Folded into the facts of the turn + they follow instead, and the event's uuid resolves to that turn, so a + record whose parent was the event links straight past it.""" + event: dict[str, Any] = {"line": number, **normalize_value(blocks[0], text)} + if isinstance(record.get("timestamp"), str): + event["timestamp"] = record["timestamp"] + parent_uuid = _parent_uuid(record) + parent = turn_of.get(parent_uuid) if parent_uuid is not None else None + if parent is None: + session.setdefault("events", []).append(event) + return + turn_of[record["uuid"]] = parent + turns[parent].facts.setdefault("events", []).append(event) + + +def convert( + raw: str, origin: Origin, human: dict[str, Any] +) -> tuple[list[Turn], dict[str, Any], dict[str, Any]]: + """Claude Code JSONL to loch turns, plus heads and session-level facts. + + One chain record is one turn, and its parents are its `parentUuid`'s turn. + Assistant messages are therefore several turns when Claude split one API + message across records (one per content block) — `facts.messageId` is what + groups them back. Keeping records whole is what keeps Claude's own tree, + including the branches a rewind leaves in the file, intact as the graph. + + Two records whose cores are identical are one turn. That happens when a + rewind resubmits exactly what was said before from the same point, which + is the same turn by any reasonable reading; the later uuids are kept in + the first one's facts. + """ + text = normalizer(origin) + records = _parse(raw) + chain = [ + (number, record) + for number, record in records + if isinstance(record.get("uuid"), str) + ] + ordered, present = _topological(chain) + + turn_of: dict[str, str] = {} + turns: dict[str, Turn] = {} + has_children: set[str] = set() + last_turn: str | None = None + session: dict[str, Any] = {} + + for number, record in ordered: + classified = classify(record) + if classified is None: + continue + kind, author, blocks = classified + if kind == "event": + _fold_event(number, record, blocks, turn_of, turns, session, text) + continue + if author.get("kind") == "human": + author = human + parent_uuid = _parent_uuid(record) + facts = _facts(number, record, text) + parents: list[str] = [] + if parent_uuid is not None: + if parent_uuid in turn_of: + parents = [turn_of[parent_uuid]] + elif parent_uuid not in present: + facts["danglingParent"] = parent_uuid + + turn = build_turn(kind, author, parents, normalize_value(blocks, text), facts) + turn_of[record["uuid"]] = turn.id + last_turn = turn.id + if turn.id in turns: + turns[turn.id].facts.setdefault("alsoUuids", []).append(record["uuid"]) + else: + turns[turn.id] = turn + has_children.update(parents) + + current = last_turn + for _, record in records: + record_type = record.get("type") + if record_type == "last-prompt" and record.get("leafUuid") in turn_of: + current = turn_of[record["leafUuid"]] + elif record_type == "ai-title" and isinstance(record.get("aiTitle"), str): + session["aiTitle"] = record["aiTitle"] + elif record_type == "custom-title" and isinstance( + record.get("customTitle"), str + ): + session["title"] = record["customTitle"] + + heads: dict[str, Any] = { + "leaves": [turn_id for turn_id in turns if turn_id not in has_children] + } + if current is not None: + heads["current"] = current + return list(turns.values()), heads, normalize_value(session, text) + + +def source_files(transcript_path: str) -> list[tuple[str, str]]: + """The transcript and everything Claude files beside it for the session: + subagent transcripts and spilled tool output under `/`. All of + it is the source, and a source that dropped the sidecar would silently + lose every subagent conversation.""" + files = [("transcript.jsonl", transcript_path)] + sidecar = transcript_path[: -len(".jsonl")] + if os.path.isdir(sidecar): + for directory, _, names in os.walk(sidecar): + for name in names: + path = os.path.join(directory, name) + relative = os.path.relpath(path, sidecar).replace(os.sep, "/") + files.append((f"sidecar/{relative}", path)) + return sorted(files) + + +def source_manifest(transcript_path: str) -> tuple[dict[str, Any], str]: + """The content-addressed identity of the raw source: every file's hash, + in path order. Returns the manifest and the transcript text.""" + entries = [] + transcript = "" + for relative, path in source_files(transcript_path): + data = Path(path).read_bytes() + entries.append( + {"path": relative, "sha256": digest_bytes(data), "bytes": len(data)} + ) + if relative == "transcript.jsonl": + transcript = data.decode("utf-8", "surrogateescape") + manifest = {"agent": AGENT, "files": entries} + return {"id": digest(manifest), **manifest}, transcript + + +def ingest( + transcript_path: str, + origin: Origin, + author_id: str | None = None, +) -> Derived: + human: dict[str, Any] = {"kind": "human"} + # Omitted rather than null, for the same reason the bundle format omits + # absent metadata: the encoding of "unknown" is part of every id. + if author_id is not None: + human["id"] = author_id + + source, transcript = source_manifest(transcript_path) + turns, heads, session = convert(transcript, origin, human) + header: dict[str, Any] = { + "loch": FORMAT_VERSION, + "converter": CONVERTER, + "source": source, + "origin": { + "cwd": origin.cwd, + "home": origin.home, + "sessionId": origin.session_id, + }, + "author": human, + } + if session: + header["session"] = session + return Derived(header=header, turns=turns, heads=heads) + + +def derived_name(derived: Derived) -> str: + source = derived.header["source"]["id"].split(":", 1)[1] + converter = derived.header["converter"] + return f"{source}.{converter['id']}-v{converter['version']}.jsonl" + + +class AuthorKeyError(ValueError): + pass + + +def ssh_author_id(public_key: str) -> str: + """`ssh:SHA256:` — the fingerprint `ssh-keygen -l` prints, so an + author id can be checked by eye against a key someone already publishes + (GitHub serves them at /.keys), and the same key can later sign the + turns it authored.""" + fields = public_key.split() + if len(fields) < 2: + raise AuthorKeyError("not an OpenSSH public key line") + try: + blob = base64.b64decode(fields[1], validate=True) + except ValueError as error: + raise AuthorKeyError(f"key body is not base64: {error}") from error + fingerprint = base64.b64encode(hashlib.sha256(blob).digest()).decode() + return f"ssh:SHA256:{fingerprint.rstrip('=')}" diff --git a/loch/rewrite.py b/loch/rewrite.py index 2796772..8cf5a48 100644 --- a/loch/rewrite.py +++ b/loch/rewrite.py @@ -1,4 +1,5 @@ import re +from collections.abc import Callable from dataclasses import dataclass from .claude import encode_path, transcript_cwds @@ -21,55 +22,62 @@ class RewriteSpec: # `,`, spaces and newlines as often as with `/`. Erring strict is safe: an # unsubstituted path shows up in residual_origin_paths, while an over-eager # one corrupts the text silently. -_PATH_BOUNDARY = r"(?![A-Za-z0-9._-])" +PATH_BOUNDARY = r"(?![A-Za-z0-9._-])" # encode_path maps every non-alphanumeric to `-`, so `/sub` and # `-sub` encode identically and no lookahead can tell them apart. # The slug is therefore only rewritten as a whole path component, which # declines to touch `-worktrees-...`; guessing there is what # produced the corruption this guard exists to prevent. -_ENCODED_COMPONENT_BOUNDARY = r"(?![A-Za-z0-9-])" +ENCODED_COMPONENT_BOUNDARY = r"(?![A-Za-z0-9-])" # The session id is a UUID, not a path: it appears bare in filenames and in # `"sessionId":"..."` values, where no boundary rule holds. -_UNGUARDED = "" +UNGUARDED = "" -def _apply_replacements(text: str, pairs: list[tuple[str, str, str]]) -> str: +def compile_replacements(pairs: list[tuple[str, str, str]]) -> Callable[[str], str]: """Single left-to-right pass so a substitution's output can never be re-matched by a later pair. Longest patterns win, which keeps a cwd nested under a home directory from being half-rewritten by the home pair. Each alternative carries its own zero-width boundary guard, so a - longer pattern that fails its guard falls through to a shorter one.""" + longer pattern that fails its guard falls through to a shorter one. + + Sorted by length, never by caller order: the single-pass guarantee + depends on a nested path matching before the prefix that contains it.""" active = [ (source, dest, guard) for source, dest, guard in pairs if source and source != dest ] if not active: - return text + return lambda text: text ordered = sorted(active, key=lambda pair: len(pair[0]), reverse=True) lookup = {source: dest for source, dest, _ in ordered} pattern = re.compile( "|".join(re.escape(source) + guard for source, _, guard in ordered) ) - return pattern.sub(lambda match: lookup[match.group(0)], text) + return lambda text: pattern.sub(lambda match: lookup[match.group(0)], text) + + +def _apply_replacements(text: str, pairs: list[tuple[str, str, str]]) -> str: + return compile_replacements(pairs)(text) def rewrite_transcript(raw: str, spec: RewriteSpec) -> str: pairs = [ - (spec.origin_cwd, spec.target_cwd, _PATH_BOUNDARY), - (spec.origin_home, spec.target_home, _PATH_BOUNDARY), + (spec.origin_cwd, spec.target_cwd, PATH_BOUNDARY), + (spec.origin_home, spec.target_home, PATH_BOUNDARY), ( encode_path(spec.origin_cwd), encode_path(spec.target_cwd), - _ENCODED_COMPONENT_BOUNDARY, + ENCODED_COMPONENT_BOUNDARY, ), ] if spec.origin_session_id and spec.target_session_id: - pairs.append((spec.origin_session_id, spec.target_session_id, _UNGUARDED)) + pairs.append((spec.origin_session_id, spec.target_session_id, UNGUARDED)) return _apply_replacements(raw, pairs) diff --git a/loch/trace.py b/loch/trace.py new file mode 100644 index 0000000..cd5fd02 --- /dev/null +++ b/loch/trace.py @@ -0,0 +1,750 @@ +"""Which conversation made which commit, and getting back into it. + +A commit is linked to the turn that made it by a git note on `refs/notes/loch`: +a small JSON document naming the agent session and the tool call that ran +`git commit`. It holds no transcript text, so it travels with the repository +like any other envelope (SPEC.md §9, §10). The transcript it points at lives in +Claude's project directory or, once a hook has snapshotted it, in the store. + +Links are captured live, by Claude Code hooks around every Bash call, because +recovering them afterwards is unreliable: `git commit -q` prints no hash, and +commits made from a script never appear in any tool output. `backfill` exists +for history made before the hooks, and accepts only an exact match. +""" + +import hashlib +import json +import os +import subprocess +import time +import uuid +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any + +from .claude import ( + AGENT, + _display_summary, + home_dir, + projects_dir, + read_session_meta, + transcript_cwds, + transcript_path_for, +) +from .format import Turn +from .ingest import Origin, ingest +from .rewrite import RewriteSpec, rewrite_transcript +from .store import MissingObject, Store + +NOTES_REF = "refs/notes/loch" + +NOTE_VERSION = 1 + +TRANSCRIPTS_PREFIX = f"transcripts/{AGENT}/" + +UNCOMMITTED = "0" * 40 + +# How far a commit's committer time may sit outside the tool call that made it. +# Git records whole seconds and the transcript milliseconds, so one second of +# slack covers truncation; the rest covers a slow hook process. +CLOCK_SLACK = 2.0 + + +class TraceError(Exception): + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + + +def git(cwd: str, *args: str, check: bool = True, stdin: str | None = None) -> str: + result = subprocess.run( + ["git", "-C", cwd, *args], + capture_output=True, + text=True, + check=False, + input=stdin, + ) + if check and result.returncode != 0: + raise TraceError("git-failed", result.stderr.strip() or "git failed") + return result.stdout + + +def repo_root(cwd: str) -> str: + try: + return git(cwd, "rev-parse", "--show-toplevel").strip() + except (TraceError, OSError) as error: + raise TraceError("not-a-repository", f"{cwd} is not in a git repository") from ( + error + ) + + +def head(cwd: str) -> str | None: + return git(cwd, "rev-parse", "--verify", "-q", "HEAD", check=False).strip() or None + + +# -- notes ------------------------------------------------------------------ + + +def make_note(session_id: str, call: str, captured: str) -> dict[str, Any]: + return { + "loch": NOTE_VERSION, + "agent": AGENT, + "session": session_id, + "call": call, + "captured": captured, + } + + +def write_note(cwd: str, commit: str, note: dict[str, Any]) -> None: + body = json.dumps(note, sort_keys=True, separators=(",", ":")) + git(cwd, "notes", "--ref", NOTES_REF, "add", "-f", "-F", "-", commit, stdin=body) + + +def read_note(cwd: str, commit: str) -> dict[str, Any] | None: + text = git(cwd, "notes", "--ref", NOTES_REF, "show", commit, check=False) + try: + note = json.loads(text) + except ValueError: + return None + return note if isinstance(note, dict) and note.get("loch") == NOTE_VERSION else None + + +def noted_commits(cwd: str) -> set[str]: + listing = git(cwd, "notes", "--ref", NOTES_REF, "list", check=False) + return {line.split()[1] for line in listing.splitlines() if len(line.split()) == 2} + + +# -- hooks ------------------------------------------------------------------ + + +def _pending_dir(cwd: str) -> str: + git_dir = git(cwd, "rev-parse", "--absolute-git-dir").strip() + return os.path.join(git_dir, "loch", "pending") + + +def _call_key(event: dict[str, Any]) -> str: + call = event.get("tool_use_id") + if isinstance(call, str) and call: + return call + command = str((event.get("tool_input") or {}).get("command", "")) + return "cmd-" + hashlib.sha256(command.encode()).hexdigest()[:32] + + +def hook_pre_tool(event: dict[str, Any]) -> None: + """Remembers HEAD before a Bash call, so the matching post hook can tell + exactly which commits the call made rather than guessing from history.""" + cwd = str(event.get("cwd") or os.getcwd()) + try: + before = head(cwd) or "" + directory = _pending_dir(cwd) + except (TraceError, OSError): + return + os.makedirs(directory, exist_ok=True) + state = {"head": before, "at": time.time()} + Path(directory, _call_key(event)).write_text(json.dumps(state)) + + +def commits_made(cwd: str, before: str, after: str, since: float) -> list[str]: + """Commits reachable from `after` and not from `before`, and committed + after the call began. The time bound is what keeps a `git checkout` or a + fast-forward pull — which move HEAD onto commits someone else made — from + being attributed to this call.""" + span = f"{before}..{after}" if before else after + listing = git(cwd, "log", "--format=%H %ct", span) + made = [] + for line in listing.splitlines(): + sha, _, stamp = line.partition(" ") + if stamp and int(stamp) >= int(since) - 1: + made.append(sha) + return made + + +def _call_from_transcript(path: str, command: str) -> str | None: + """The tool call id, for a hook payload that didn't carry one: the last + Bash call in the transcript that ran exactly this command.""" + found = None + for record in _read_records(path): + for block in _content(record): + if ( + block.get("type") == "tool_use" + and block.get("name") == "Bash" + and (block.get("input") or {}).get("command") == command + ): + found = block.get("id") + return found if isinstance(found, str) else None + + +def hook_post_tool(event: dict[str, Any]) -> list[str]: + cwd = str(event.get("cwd") or os.getcwd()) + session_id = event.get("session_id") + if not isinstance(session_id, str): + return [] + try: + state_path = Path(_pending_dir(cwd), _call_key(event)) + state = json.loads(state_path.read_text()) + state_path.unlink() + except (TraceError, OSError, ValueError): + return [] + after = head(cwd) + if after is None or after == state["head"]: + return [] + + call = event.get("tool_use_id") + if not isinstance(call, str) or not call: + transcript = event.get("transcript_path") + command = str((event.get("tool_input") or {}).get("command", "")) + call = ( + _call_from_transcript(transcript, command) + if isinstance(transcript, str) + else None + ) + if call is None: + return [] + + made = commits_made(cwd, state["head"], after, state["at"]) + for commit in made: + write_note(cwd, commit, make_note(session_id, call, "hook")) + return made + + +def snapshot_transcript(event: dict[str, Any], store: Store) -> str | None: + """Copies the live transcript into the store. Claude Code deletes + transcripts after `cleanupPeriodDays` (30 by default), which would leave + every note pointing at nothing; this is the copy that outlives it. The + file is append-only, so the latest snapshot covers every earlier one and + one key per session suffices.""" + path = event.get("transcript_path") + session_id = event.get("session_id") + if not isinstance(path, str) or not isinstance(session_id, str): + return None + try: + data = Path(path).read_bytes() + except OSError: + return None + key = transcript_key(os.path.basename(os.path.dirname(path)), session_id) + store.put(key, data) + return key + + +def transcript_key(project: str, session_id: str) -> str: + return f"{TRANSCRIPTS_PREFIX}{project}/{session_id}.jsonl" + + +HOOK_EVENTS = { + "PreToolUse": ("Bash", "pre-tool"), + "PostToolUse": ("Bash", "post-tool"), + "Stop": (None, "stop"), +} + + +def install_hooks(settings_path: str, command: str) -> list[str]: + """Adds loch's hooks to a Claude Code settings file, keeping whatever else + is there. Returns the events it added; re-running adds nothing.""" + try: + settings = json.loads(Path(settings_path).read_text()) + except FileNotFoundError: + settings = {} + hooks = settings.setdefault("hooks", {}) + added = [] + for event, (matcher, name) in HOOK_EVENTS.items(): + # A checkout whose machine lacks loch gets a silent no-op rather than + # an error on every Bash call, since the settings file is committed. + line = f"{command} hook {name} 2>/dev/null || true" + groups = hooks.setdefault(event, []) + present = any( + entry.get("command") == line + for group in groups + for entry in group.get("hooks", []) + ) + if present: + continue + group: dict[str, Any] = {"hooks": [{"type": "command", "command": line}]} + if matcher is not None: + group["matcher"] = matcher + groups.append(group) + added.append(event) + os.makedirs(os.path.dirname(settings_path), exist_ok=True) + Path(settings_path).write_text(json.dumps(settings, indent=2) + "\n") + return added + + +# -- transcripts -------------------------------------------------------------- + + +def _records_of(raw: str) -> Iterator[dict[str, Any]]: + for line in raw.split("\n"): + if not line.strip(): + continue + try: + record = json.loads(line) + except ValueError: + continue + if isinstance(record, dict): + yield record + + +def _read_records(path: str) -> Iterator[dict[str, Any]]: + try: + raw = Path(path).read_text(encoding="utf-8", errors="surrogateescape") + except OSError: + return + yield from _records_of(raw) + + +def _content(record: dict[str, Any]) -> list[dict[str, Any]]: + message = record.get("message") + content = message.get("content") if isinstance(message, dict) else None + if not isinstance(content, list): + return [] + return [block for block in content if isinstance(block, dict)] + + +def find_transcript(session_id: str, store: Store | None) -> str | None: + """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 (claude.cwd_for_directory).""" + root = projects_dir() + if os.path.isdir(root): + for project in os.listdir(root): + path = os.path.join(root, project, f"{session_id}.jsonl") + if os.path.exists(path): + return path + if store is None: + return None + try: + keys = store.list(TRANSCRIPTS_PREFIX) + except Exception: + return None + for key in keys: + if key.endswith(f"/{session_id}.jsonl"): + project = key[len(TRANSCRIPTS_PREFIX) :].split("/")[0] + try: + data = store.get(key) + except MissingObject: + return None + cached = os.path.join( + home_dir(), ".loch", "cache", project, f"{session_id}.jsonl" + ) + os.makedirs(os.path.dirname(cached), exist_ok=True) + Path(cached).write_bytes(data) + return cached + return None + + +# -- blame -------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Hunk: + start: int + end: int + commit: str + summary: str + lines: tuple[str, ...] = () + + +def blame_hunks(cwd: str, path: str) -> list[Hunk]: + porcelain = git(cwd, "blame", "--porcelain", "--", path) + summaries: dict[str, str] = {} + lines: list[tuple[int, str, str]] = [] + current = "" + number = 0 + for line in porcelain.split("\n"): + if line.startswith("\t"): + # Each header is followed by the line's text, tab-prefixed. + lines.append((number, current, line[1:])) + continue + parts = line.split(" ") + if len(parts) >= 3 and len(parts[0]) == 40 and parts[1].isdigit(): + current, number = parts[0], int(parts[2]) + elif line.startswith("summary "): + summaries[current] = line[len("summary ") :] + + hunks: list[Hunk] = [] + for number, commit, text in sorted(lines): + last = hunks[-1] if hunks else None + if last is not None and last.commit == commit and last.end == number - 1: + hunks[-1] = Hunk( + last.start, number, commit, last.summary, (*last.lines, text) + ) + else: + hunks.append( + Hunk(number, number, commit, summaries.get(commit, ""), (text,)) + ) + return hunks + + +@dataclass(frozen=True) +class Change: + commit: str + time: int + summary: str + + +def history(cwd: str, path: str, lines: tuple[int, int] | None = None) -> list[Change]: + """Every commit that touched `path` (or just `lines` of it), newest first. + + `-L` follows the range through edits above it and through moves; a whole + file follows renames. Both are git's own tracking, so this answers "which + commits shaped these lines" exactly as `git log` would. + """ + scope = ( + ["-L", f"{lines[0]},{lines[1]}:{path}"] + if lines is not None + else ["--follow", "--", path] + ) + output = git(cwd, "log", "-s", "--format=%x1e%H%x1f%ct%x1f%s", *scope) + changes = [] + for record in output.split("\x1e")[1:]: + commit, time, summary = record.strip("\n").split("\x1f", 2) + changes.append(Change(commit, int(time), summary.split("\n", 1)[0])) + return changes + + +@dataclass(frozen=True) +class Link: + """A commit resolved to the conversation turn that made it.""" + + commit: str + session_id: str + call: str + captured: str + transcript: str | None + turn: str | None + conversation: str | None + title: str | None + prompt: str | None + + def payload(self) -> dict[str, Any]: + return { + "session": self.session_id, + "call": self.call, + "captured": self.captured, + "available": self.transcript is not None, + "turn": self.turn, + "conversation": self.conversation, + "title": self.title, + "prompt": self.prompt, + } + + +def _prompt_text(turn: Turn) -> str | None: + for block in turn.blocks or []: + text = block.get("text") if block.get("type") == "text" else None + if isinstance(text, str) and text.strip() and not text.startswith("<"): + return text + return None + + +class Resolver: + """Resolves commits to turns, ingesting each session once however many + commits and lines point into it.""" + + def __init__(self, cwd: str, store: Store | None) -> None: + self.cwd = cwd + self.store = store + self._sessions: dict[str, tuple[str | None, list[Turn], dict[str, Any]]] = {} + + def _session( + self, session_id: str + ) -> tuple[str | None, list[Turn], dict[str, Any]]: + if session_id not in self._sessions: + path = find_transcript(session_id, self.store) + turns: list[Turn] = [] + header: dict[str, Any] = {} + if path is not None: + meta = read_session_meta(path) + if meta is not None: + derived = ingest(path, Origin(meta.cwd, home_dir(), session_id)) + turns, header = derived.turns, derived.header + self._sessions[session_id] = (path, turns, header) + return self._sessions[session_id] + + def resolve(self, commit: str) -> Link | None: + note = read_note(self.cwd, commit) + if note is None: + return None + session_id, call = str(note.get("session")), str(note.get("call")) + path, turns, header = self._session(session_id) + by_id = {turn.id: turn for turn in turns} + + turn = next( + ( + candidate + for candidate in turns + if any( + block.get("type") == "tool-call" and block.get("call") == call + for block in candidate.blocks or [] + ) + ), + None, + ) + prompt = None + conversation = None + walker = turn + while walker is not None: + if ( + prompt is None + and walker.core["kind"] == "message" + and walker.core["author"].get("kind") == "human" + ): + prompt = _prompt_text(walker) + parents = walker.core["parents"] + if not parents: + conversation = walker.id + walker = by_id.get(parents[0]) if parents else None + + session = header.get("session") or {} + return Link( + commit=commit, + session_id=session_id, + call=call, + captured=str(note.get("captured")), + transcript=path, + turn=turn.id if turn is not None else None, + conversation=conversation, + title=session.get("title") or session.get("aiTitle"), + prompt=_display_summary(prompt), + ) + + +# -- backfill ----------------------------------------------------------------- + + +@dataclass(frozen=True) +class Call: + session_id: str + call: str + command: str + started: float + finished: float + + +def _seconds(stamp: Any) -> float | None: + if not isinstance(stamp, str): + return None + try: + return datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp() + except ValueError: + return None + + +def commit_calls(path: str) -> list[Call]: + """Every Bash call in a transcript that could have made a commit, with the + window between the call being issued and its result coming back.""" + session_id = os.path.basename(path)[: -len(".jsonl")] + issued: dict[str, tuple[str, float]] = {} + calls: list[Call] = [] + for record in _read_records(path): + stamp = _seconds(record.get("timestamp")) + for block in _content(record): + if block.get("type") == "tool_use" and block.get("name") == "Bash": + command = str((block.get("input") or {}).get("command", "")) + if "commit" in command and stamp is not None: + issued[str(block.get("id"))] = (command, stamp) + elif block.get("type") == "tool_result": + call = str(block.get("tool_use_id")) + if call in issued and stamp is not None: + command, started = issued.pop(call) + calls.append(Call(session_id, call, command, started, stamp)) + return calls + + +def backfill( + cwd: str, + revision: str = "HEAD", + progress: Callable[[int, int, int, int], None] | None = None, +) -> list[tuple[str, Call]]: + """Links commits made before the hooks existed, accepting only an exact + match: one Bash call whose command contains the commit's subject line and + whose run brackets the commit's timestamp. A commit with no such call, or + with two, stays unlinked — a wrong link would send `ask` into the wrong + conversation and look exactly like a right one. + + Either timestamp may fall in the window: a rebase or cherry-pick rewrites + the committer time and keeps the author time, and the conversation that + wrote the change is still the one that made the original commit.""" + listing = git(cwd, "log", "--format=%H%x00%at%x00%ct%x00%s", revision) + already = noted_commits(cwd) + pending: list[tuple[str, tuple[int, int], str]] = [] + for line in listing.splitlines(): + sha, authored, committed, subject = line.split("\x00", 3) + if sha not in already and subject: + pending.append((sha, (int(authored), int(committed)), subject)) + if not pending: + return [] + + subjects = {subject for _, _, subject in pending} + # Listed and sized up front so progress has a real total: reading every + # transcript on the machine is the whole cost (~25s on 750MB). + transcripts: list[tuple[str, int]] = [] + root = projects_dir() + for project in sorted(os.listdir(root)) if os.path.isdir(root) else []: + directory = os.path.join(root, project) + if not os.path.isdir(directory): + continue + for name in sorted(os.listdir(directory)): + if name.endswith(".jsonl"): + path = os.path.join(directory, name) + try: + transcripts.append((path, os.path.getsize(path))) + except OSError: + continue + total_bytes = sum(size for _, size in transcripts) + + calls: list[Call] = [] + read = 0 + for done, (path, size) in enumerate(transcripts, 1): + read += size + try: + raw = Path(path).read_text(encoding="utf-8", errors="replace") + except OSError: + raw = "" + if "git commit" in raw and any(subject in raw for subject in subjects): + calls.extend(commit_calls(path)) + if progress is not None: + progress(done, len(transcripts), read, total_bytes) + + linked: list[tuple[str, Call]] = [] + for sha, stamps, subject in pending: + matches = [ + call + for call in calls + if subject in call.command + and any( + call.started - CLOCK_SLACK <= stamp <= call.finished + CLOCK_SLACK + for stamp in stamps + ) + ] + if len({(call.session_id, call.call) for call in matches}) == 1: + write_note( + cwd, sha, make_note(matches[0].session_id, matches[0].call, "backfill") + ) + linked.append((sha, matches[0])) + return linked + + +# -- ask ---------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Fork: + session_id: str + path: str + cwd: str + records: int + origin_session: str + + +def _parent(record: dict[str, Any]) -> str | None: + parent = record.get("parentUuid") + if parent is None: + parent = record.get("logicalParentUuid") + return parent if isinstance(parent, str) else None + + +def fork_session( + transcript: str, + target_cwd: str, + call: str | None = None, + title: str | None = None, +) -> Fork: + """A new Claude session holding the conversation, filed under + `target_cwd` so `claude --resume` finds it. The original session is never + modified: a follow-up is a branch of the conversation, not more of it. + + With no `call` 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 is cut after the whole round of tool results that call + belongs to, not after the call alone: an assistant message that issued + parallel calls is one API message, and resuming with any of its results + missing is a malformed conversation.""" + raw = Path(transcript).read_text(encoding="utf-8", errors="surrogateescape") + records = [ + record for record in _records_of(raw) if isinstance(record.get("uuid"), str) + ] + children: dict[str, list[dict[str, Any]]] = {} + for record in records: + parent = _parent(record) + if parent is not None: + children.setdefault(parent, []).append(record) + + if call is None: + if not records: + raise TraceError("call-not-found", "the transcript holds no records") + return _write_fork(transcript, raw, records, records[-1], target_cwd, title) + + result = next( + ( + record + for record in records + if any( + block.get("type") == "tool_result" and block.get("tool_use_id") == call + for block in _content(record) + ) + ), + None, + ) + if result is None: + raise TraceError("call-not-found", f"no result for tool call {call}") + + leaf = result + while True: + following = [ + child + for child in children.get(leaf["uuid"], []) + if child.get("type") == "user" + and any(block.get("type") == "tool_result" for block in _content(child)) + ] + if not following: + break + leaf = following[0] + return _write_fork(transcript, raw, records, leaf, target_cwd, title) + + +def _write_fork( + transcript: str, + raw: str, + records: list[dict[str, Any]], + leaf: dict[str, Any], + target_cwd: str, + title: str | None, +) -> Fork: + by_uuid = {record["uuid"]: record for record in records} + keep: set[str] = set() + walker: dict[str, Any] | None = leaf + while walker is not None and walker["uuid"] not in keep: + keep.add(walker["uuid"]) + parent = _parent(walker) + walker = by_uuid.get(parent) if parent is not None else None + + meta = read_session_meta(transcript) + origin_cwd = meta.cwd if meta is not None else next(iter(transcript_cwds(raw))) + origin_session = os.path.basename(transcript)[: -len(".jsonl")] + new_id = str(uuid.uuid4()) + + kept = [ + json.dumps(record, ensure_ascii=False) + for record in records + if record["uuid"] in keep + ] + kept.append( + json.dumps( + { + "type": "custom-title", + "customTitle": title or f"loch ask: {origin_session[:8]}", + "sessionId": origin_session, + } + ) + ) + spec = RewriteSpec( + origin_cwd, home_dir(), target_cwd, home_dir(), origin_session, new_id + ) + text = rewrite_transcript("\n".join(kept) + "\n", spec) + + path = transcript_path_for(target_cwd, new_id) + os.makedirs(os.path.dirname(path), exist_ok=True) + Path(path).write_text(text, encoding="utf-8", errors="surrogateescape") + return Fork(new_id, path, target_cwd, len(keep), origin_session) diff --git a/test/test_cli.py b/test/test_cli.py index 1925cff..932f149 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -11,6 +11,7 @@ from loch.bundle import unpack_bundle from loch.claude import session_dir_for, transcript_cwds, transcript_path_for from loch.cli import main +from loch.format import read_derived def invoke( @@ -1047,3 +1048,84 @@ def test_json_help_is_a_document_rather_than_the_usage_block( ) assert (document["command"], document["ok"], code) == ("save", True, None) assert "--store" in document["usage"] + + +def test_ingest_writes_a_verified_derived_file_per_session( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path +) -> None: + home = tmp_path / "home" + project = tmp_path / "proj" + project.mkdir() + out_dir = tmp_path / "derived" + path = Path(transcript_path_for(str(project), "abc", str(home))) + path.parent.mkdir(parents=True) + path.write_text( + json.dumps( + { + "type": "user", + "uuid": "u-1", + "parentUuid": None, + "sessionId": "abc", + "cwd": str(project.resolve()), + "message": {"role": "user", "content": "hello"}, + } + ) + + "\n", + encoding="utf-8", + ) + + document, err, code = invoke_json( + monkeypatch, + capsys, + home, + "ingest", + "--json", + "--cwd", + str(project), + "--author", + "alice", + "--out", + str(out_dir), + ) + + assert (code, err) == (None, "") + assert document["converter"] == {"id": "claude-code", "version": 1} + [entry] = document["sessions"] + assert entry["turns"] == 1 + derived = read_derived(Path(entry["path"]).read_text(encoding="utf-8").split("\n")) + assert derived.header["author"] == {"kind": "human", "id": "alice"} + assert entry["heads"]["current"] == derived.turns[0].id + + +def test_ingest_fails_when_nothing_matches( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path +) -> None: + document, _, code = invoke_json( + monkeypatch, + capsys, + tmp_path / "home", + "ingest", + "--json", + "--cwd", + str(tmp_path), + "--out", + str(tmp_path / "derived"), + ) + + assert (code, document["code"]) == (1, "no-sessions") + + +def test_ingest_rejects_an_unreadable_author_key( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path +) -> None: + document, _, code = invoke_json( + monkeypatch, + capsys, + tmp_path / "home", + "ingest", + "--json", + "--author-key", + str(tmp_path / "missing.pub"), + ) + + assert (code, document["code"]) == (1, "author-key-unreadable") diff --git a/test/test_corpus.py b/test/test_corpus.py new file mode 100644 index 0000000..3a0052b --- /dev/null +++ b/test/test_corpus.py @@ -0,0 +1,78 @@ +"""Checks against this machine's real transcripts. Opt-in, since the corpus is +personal and its size is unbounded: `LOCH_CORPUS=1 poetry run pytest +test/test_corpus.py`, optionally with `LOCH_CORPUS_LIMIT=`. + +Nothing from a transcript is ever asserted on or printed — only session ids +and counts, so a failure report is safe to paste.""" + +import os +import uuid +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from loch.claude import SessionMeta, home_dir, projects_dir, read_session_meta +from loch.format import pack_derived, read_derived +from loch.ingest import Origin, convert, ingest +from loch.rewrite import RewriteSpec, rewrite_transcript + +pytestmark = pytest.mark.skipif( + not os.environ.get("LOCH_CORPUS"), reason="set LOCH_CORPUS=1 to run" +) + + +def corpus() -> Iterator[SessionMeta]: + limit = int(os.environ.get("LOCH_CORPUS_LIMIT", "0")) or None + root = projects_dir() + count = 0 + for directory in sorted(os.listdir(root)): + path = os.path.join(root, directory) + if not os.path.isdir(path): + continue + for name in sorted(os.listdir(path)): + if not name.endswith(".jsonl"): + continue + meta = read_session_meta(os.path.join(path, name)) + if meta is None: + continue + yield meta + count += 1 + if limit is not None and count >= limit: + return + + +def test_every_session_ingests_and_reads_back_verified() -> None: + failures = [] + for meta in corpus(): + origin = Origin(meta.cwd, home_dir(), meta.session_id) + packed = pack_derived(ingest(meta.path, origin)) + if pack_derived(ingest(meta.path, origin)) != packed: + failures.append((meta.session_id, "not idempotent")) + continue + lines = packed.decode("utf-8", "surrogatepass").split("\n") + if pack_derived(read_derived(lines)) != packed: + failures.append((meta.session_id, "does not round-trip")) + assert failures == [] + + +def test_turn_ids_survive_a_restore_to_another_machine() -> None: + """A transcript that already names the destination paths can't pass: its + content is indistinguishable from a rewritten root. Those are reported by + id, to check by hand, rather than failing the run.""" + target_cwd, target_home = "/srv/loch-corpus/checkout", "/home/loch-corpus" + unstable = [] + for meta in corpus(): + raw = Path(meta.path).read_text(encoding="utf-8") + new_id = str(uuid.uuid5(uuid.NAMESPACE_URL, meta.session_id)) + spec = RewriteSpec( + meta.cwd, home_dir(), target_cwd, target_home, meta.session_id, new_id + ) + before = convert(raw, Origin(meta.cwd, home_dir(), meta.session_id), {}) + after = convert( + rewrite_transcript(raw, spec), Origin(target_cwd, target_home, new_id), {} + ) + if [t.id for t in before[0]] != [t.id for t in after[0]]: + if target_cwd not in raw and target_home not in raw: + unstable.append(meta.session_id) + assert unstable == [] diff --git a/test/test_format.py b/test/test_format.py new file mode 100644 index 0000000..b23c80b --- /dev/null +++ b/test/test_format.py @@ -0,0 +1,165 @@ +import pytest + +from loch.format import ( + Derived, + FormatError, + Turn, + canonical, + content_id, + digest, + make_turn, + pack_derived, + read_derived, +) + +HUMAN = {"kind": "human", "id": "alice"} + + +def header() -> dict[str, object]: + return {"loch": 1, "converter": {"id": "test", "version": 1}} + + +def test_canonical_is_independent_of_key_order() -> None: + assert canonical({"b": 1, "a": [1, {"d": 2, "c": 3}]}) == canonical( + {"a": [1, {"c": 3, "d": 2}], "b": 1} + ) + + +def test_canonical_is_compact_and_keeps_non_ascii() -> None: + assert canonical({"a": "é", "b": [1, 2]}) == '{"a":"é","b":[1,2]}'.encode() + + +def test_canonical_refuses_nan() -> None: + with pytest.raises(ValueError): + canonical({"x": float("nan")}) + + +def test_turn_id_covers_the_content_hash_not_the_content() -> None: + turn = make_turn("message", HUMAN, [], [{"type": "text", "text": "hi"}]) + + assert turn.core["content"] == content_id([{"type": "text", "text": "hi"}]) + assert "blocks" not in turn.core + assert turn.id == digest(turn.core) + + +def test_facts_do_not_change_identity() -> None: + blocks = [{"type": "text", "text": "hi"}] + plain = make_turn("message", HUMAN, [], blocks) + annotated = make_turn("message", HUMAN, [], blocks, {"timestamp": "2026"}) + + assert plain.id == annotated.id + + +def test_parents_and_author_change_identity() -> None: + blocks = [{"type": "text", "text": "hi"}] + root = make_turn("message", HUMAN, [], blocks) + + assert make_turn("message", HUMAN, [root.id], blocks).id != root.id + assert make_turn("message", {"kind": "human"}, [], blocks).id != root.id + + +def chain() -> Derived: + first = make_turn("message", HUMAN, [], [{"type": "text", "text": "a"}]) + second = make_turn("message", HUMAN, [first.id], [{"type": "text", "text": "b"}]) + return Derived( + header=header(), + turns=[first, second], + heads={"current": second.id, "leaves": [second.id]}, + ) + + +def test_round_trips_byte_for_byte() -> None: + packed = pack_derived(chain()) + assert pack_derived(read_derived(packed.decode().split("\n"))) == packed + + +def test_reads_a_tombstoned_turn_and_still_verifies_its_id() -> None: + derived = chain() + tombstoned = Turn( + id=derived.turns[0].id, core=derived.turns[0].core, blocks=None, facts={} + ) + packed = pack_derived( + Derived(derived.header, [tombstoned, derived.turns[1]], derived.heads) + ) + + back = read_derived(packed.decode().split("\n")) + + assert back.turns[0].blocks is None + assert back.turns[0].id == derived.turns[0].id + + +def test_rejects_content_that_does_not_match_its_hash() -> None: + derived = chain() + forged = Turn( + id=derived.turns[0].id, + core=derived.turns[0].core, + blocks=[{"type": "text", "text": "forged"}], + ) + packed = pack_derived(Derived(derived.header, [forged], {})) + + with pytest.raises(FormatError, match="content does not match"): + read_derived(packed.decode().split("\n")) + + +def test_rejects_an_id_that_does_not_match_its_core() -> None: + derived = chain() + turn = derived.turns[0] + forged = Turn(id=digest({"other": 1}), core=turn.core, blocks=turn.blocks) + packed = pack_derived(Derived(derived.header, [forged], {})) + + with pytest.raises(FormatError, match="does not hash to its id"): + read_derived(packed.decode().split("\n")) + + +def test_rejects_a_turn_before_its_parent() -> None: + derived = chain() + packed = pack_derived( + Derived(derived.header, list(reversed(derived.turns)), derived.heads) + ) + + with pytest.raises(FormatError, match="precedes its parent"): + read_derived(packed.decode().split("\n")) + + +def test_rejects_an_unknown_format_version() -> None: + with pytest.raises(FormatError, match="unsupported loch format 2"): + read_derived(['{"type":"header","loch":2}']) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1e21, "1e+21"), + (1e20, "100000000000000000000"), + (1e16, "10000000000000000"), + (0.00001, "0.00001"), + (1e-7, "1e-7"), + (1.5e-7, "1.5e-7"), + (100.0, "100"), + (-0.0, "0"), + (5e-324, "5e-324"), + (1.7976931348623157e308, "1.7976931348623157e+308"), + (333333333.3333333, "333333333.3333333"), + (-1.5, "-1.5"), + ], +) +def test_numbers_print_as_ecmascript_does(value: float, expected: str) -> None: + assert canonical(value) == expected.encode() + + +def test_integers_stay_exact_beyond_double_precision() -> None: + assert canonical(2**70) == b"1180591620717411303424" + + +def test_keys_sort_by_utf16_code_units() -> None: + assert canonical({"￿": 1, "\U0001f600": 2, "a": 3}) == ( + '{"a":3,"\U0001f600":2,"￿":1}'.encode() + ) + + +def test_a_lone_surrogate_is_escaped() -> None: + assert canonical("x\ud83d") == b'"x\\ud83d"' + + +def test_control_characters_escape_as_json_stringify_does() -> None: + assert canonical('a\x01"\\\n') == b'"a\\u0001\\"\\\\\\n"' diff --git a/test/test_ingest.py b/test/test_ingest.py new file mode 100644 index 0000000..64b6a53 --- /dev/null +++ b/test/test_ingest.py @@ -0,0 +1,403 @@ +import base64 +import hashlib +import json +from pathlib import Path +from typing import Any + +import pytest + +from loch.format import pack_derived, read_derived +from loch.ingest import ( + ESCAPE, + HOME, + ROOT, + ROOT_SLUG, + SESSION, + AuthorKeyError, + Origin, + convert, + ingest, + ssh_author_id, +) +from loch.rewrite import RewriteSpec, rewrite_transcript + +HOME_DIR = "/Users/origin" +CWD = "/Users/origin/code/repo" +SESSION_ID = "11111111-1111-1111-1111-111111111111" +ORIGIN = Origin(CWD, HOME_DIR, SESSION_ID) +HUMAN = {"kind": "human"} + + +def record(uuid: str, parent: str | None, kind: str, **fields: Any) -> dict[str, Any]: + base: dict[str, Any] = { + "type": kind, + "uuid": uuid, + "parentUuid": parent, + "sessionId": SESSION_ID, + "cwd": CWD, + "gitBranch": "main", + "version": "2.0.0", + "timestamp": f"2026-01-01T00:00:{uuid[-2:]}Z", + } + base.update(fields) + return base + + +def user(uuid: str, parent: str | None, content: Any, **fields: Any) -> dict[str, Any]: + return record( + uuid, parent, "user", message={"role": "user", "content": content}, **fields + ) + + +def assistant( + uuid: str, parent: str | None, blocks: list[Any], message_id: str = "msg_1" +) -> dict[str, Any]: + message = {"id": message_id, "role": "assistant", "model": "m", "content": blocks} + return record(uuid, parent, "assistant", message=message) + + +def jsonl(*records: dict[str, Any]) -> str: + return "".join(json.dumps(r) + "\n" for r in records) + + +def session() -> str: + """A prompt, an assistant message split across two records (thinking, + then a tool call), the tool result, and a reply — the shape Claude Code + writes for one tool-using exchange.""" + return jsonl( + {"type": "custom-title", "customTitle": "demo", "sessionId": SESSION_ID}, + user("u-01", None, f"look at {CWD}/src/main.py"), + assistant("a-02", "u-01", [{"type": "thinking", "thinking": "hmm"}]), + assistant( + "a-03", + "a-02", + [ + { + "type": "tool_use", + "id": "toolu_1", + "name": "Read", + "input": {"file_path": f"{CWD}/src/main.py"}, + } + ], + ), + user( + "u-04", + "a-03", + [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "print()"}], + toolUseResult={"file": {"filePath": f"{CWD}/src/main.py"}}, + ), + assistant("a-05", "u-04", [{"type": "text", "text": "done"}], "msg_2"), + {"type": "last-prompt", "leafUuid": "a-05", "sessionId": SESSION_ID}, + ) + + +def test_one_turn_per_chain_record_linked_by_parent() -> None: + turns, heads, _ = convert(session(), ORIGIN, HUMAN) + + assert [turn.core["kind"] for turn in turns] == [ + "message", + "message", + "message", + "tool-result", + "message", + ] + for parent, child in zip(turns, turns[1:]): + assert child.core["parents"] == [parent.id] + assert turns[0].core["parents"] == [] + assert heads == {"current": turns[-1].id, "leaves": [turns[-1].id]} + + +def test_authors_follow_who_produced_the_record() -> None: + turns, _, _ = convert(session(), ORIGIN, {"kind": "human", "id": "alice"}) + + assert [turn.core["author"]["kind"] for turn in turns] == [ + "human", + "agent", + "agent", + "tool", + "agent", + ] + assert turns[0].core["author"] == {"kind": "human", "id": "alice"} + + +def test_split_assistant_message_is_regrouped_by_message_id_fact() -> None: + turns, _, _ = convert(session(), ORIGIN, HUMAN) + + assert [turn.facts.get("messageId") for turn in turns] == [ + None, + "msg_1", + "msg_1", + None, + "msg_2", + ] + + +def test_blocks_are_normalized_to_loch_shapes() -> None: + turns, _, _ = convert(session(), ORIGIN, HUMAN) + + assert turns[1].blocks == [{"type": "thinking", "text": "hmm"}] + assert turns[2].blocks == [ + { + "type": "tool-call", + "call": "toolu_1", + "name": "Read", + "input": {"file_path": f"{ROOT}/src/main.py"}, + } + ] + assert turns[3].blocks == [ + { + "type": "tool-result", + "call": "toolu_1", + "content": [{"type": "text", "text": "print()"}], + } + ] + + +def test_machine_specific_strings_become_placeholders() -> None: + raw = jsonl( + user( + "u-01", + None, + f"{CWD}/a {HOME_DIR}/.zshrc " + f"{HOME_DIR}/.claude/projects/-Users-origin-code-repo/{SESSION_ID}.jsonl " + "literal {{loch:root}}", + ) + ) + turns, _, _ = convert(raw, ORIGIN, HUMAN) + + assert turns[0].blocks == [ + { + "type": "text", + "text": f"{ROOT}/a {HOME}/.zshrc " + f"{HOME}/.claude/projects/{ROOT_SLUG}/{SESSION}.jsonl " + f"literal {ESCAPE}root}}}}", + } + ] + assert turns[0].facts["cwd"] == ROOT + + +def test_sibling_of_the_root_is_not_taken_for_it() -> None: + raw = jsonl(user("u-01", None, f"{CWD}-worktrees/feature/x")) + turns, _, _ = convert(raw, ORIGIN, HUMAN) + + assert turns[0].blocks == [ + {"type": "text", "text": f"{HOME}/code/repo-worktrees/feature/x"} + ] + + +def test_turn_ids_survive_a_restore_to_another_machine() -> None: + target = Origin( + "/home/bob/src/repo", "/home/bob", "2" * 8 + "-2222-2222-2222-" + "2" * 12 + ) + spec = RewriteSpec( + origin_cwd=CWD, + origin_home=HOME_DIR, + target_cwd=target.cwd, + target_home=target.home, + origin_session_id=SESSION_ID, + target_session_id=target.session_id, + ) + original = convert(session(), ORIGIN, HUMAN) + copied = convert(rewrite_transcript(session(), spec), target, HUMAN) + + assert [t.id for t in copied[0]] == [t.id for t in original[0]] + assert copied[1] == original[1] + + +def test_timestamps_and_record_uuids_are_facts_not_identity() -> None: + renamed = session().replace("u-01", "x-99").replace("00:01Z", "09:09Z") + original, _, _ = convert(session(), ORIGIN, HUMAN) + changed, _, _ = convert(renamed, ORIGIN, HUMAN) + + assert [t.id for t in changed] == [t.id for t in original] + assert changed[0].facts["uuid"] == "x-99" + + +def test_a_rewind_leaves_two_heads() -> None: + raw = jsonl( + user("u-01", None, "start"), + assistant("a-02", "u-01", [{"type": "text", "text": "first try"}], "m1"), + assistant("a-03", "u-01", [{"type": "text", "text": "second try"}], "m2"), + {"type": "last-prompt", "leafUuid": "a-02", "sessionId": SESSION_ID}, + ) + turns, heads, _ = convert(raw, ORIGIN, HUMAN) + + assert heads["leaves"] == [turns[1].id, turns[2].id] + assert heads["current"] == turns[1].id + + +def test_identical_resubmission_from_the_same_point_is_one_turn() -> None: + raw = jsonl( + user("u-01", None, "start"), + user("u-02", "u-01", "again"), + user("u-03", "u-01", "again"), + ) + turns, _, _ = convert(raw, ORIGIN, HUMAN) + + assert len(turns) == 2 + assert turns[1].facts["alsoUuids"] == ["u-03"] + + +def test_compaction_boundary_follows_its_logical_parent() -> None: + raw = jsonl( + user("u-01", None, "long conversation"), + record( + "s-02", + None, + "system", + subtype="compact_boundary", + logicalParentUuid="u-01", + content="Conversation compacted", + ), + user("u-03", "s-02", "summary of before", isCompactSummary=True), + ) + turns, heads, _ = convert(raw, ORIGIN, HUMAN) + + assert [t.core["kind"] for t in turns] == ["message", "compaction", "context"] + assert turns[1].core["parents"] == [turns[0].id] + assert heads["leaves"] == [turns[2].id] + + +def test_dangling_parent_becomes_a_root_and_says_so() -> None: + raw = jsonl(user("u-02", "u-gone", "orphan")) + turns, _, _ = convert(raw, ORIGIN, HUMAN) + + assert turns[0].core["parents"] == [] + assert turns[0].facts["danglingParent"] == "u-gone" + + +def test_a_child_written_before_its_parent_still_links() -> None: + raw = jsonl(user("u-02", "u-01", "child"), user("u-01", None, "parent")) + turns, _, _ = convert(raw, ORIGIN, HUMAN) + + assert turns[0].facts["uuid"] == "u-01" + assert turns[1].core["parents"] == [turns[0].id] + + +def test_unknown_blocks_and_records_pass_through_or_stay_out() -> None: + raw = jsonl( + {"type": "cost-state", "totalCostUSD": 1.0, "sessionId": SESSION_ID}, + assistant("a-01", None, [{"type": "future_block", "x": 1}]), + ) + turns, _, _ = convert(raw, ORIGIN, HUMAN) + + assert len(turns) == 1 + assert turns[0].blocks == [ + {"type": "x-claude-code:block", "block": {"type": "future_block", "x": 1}} + ] + + +def test_attachment_payload_excludes_the_record_envelope() -> None: + raw = jsonl( + record("t-01", None, "attachment", attachment={"type": "todo", "items": []}) + ) + turns, _, _ = convert(raw, ORIGIN, HUMAN) + + assert turns[0].core["kind"] == "context" + assert turns[0].blocks == [ + { + "type": "x-claude-code:attachment", + "attachment": {"attachment": {"type": "todo", "items": []}}, + } + ] + + +def write(tmp_path: Path, raw: str) -> Path: + path = tmp_path / f"{SESSION_ID}.jsonl" + path.write_text(raw, encoding="utf-8") + return path + + +def test_source_manifest_hashes_the_transcript_and_its_sidecar(tmp_path: Path) -> None: + path = write(tmp_path, session()) + sidecar = tmp_path / SESSION_ID / "subagents" + sidecar.mkdir(parents=True) + (sidecar / "agent-a.jsonl").write_text("{}\n", encoding="utf-8") + + derived = ingest(str(path), ORIGIN) + + files = derived.header["source"]["files"] + assert [f["path"] for f in files] == [ + "sidecar/subagents/agent-a.jsonl", + "transcript.jsonl", + ] + assert derived.header["source"]["id"].startswith("sha256:") + assert derived.header["session"] == {"title": "demo"} + + +def test_ingest_is_idempotent_and_reads_back_verified(tmp_path: Path) -> None: + path = write(tmp_path, session()) + + first = pack_derived(ingest(str(path), ORIGIN, "alice")) + second = pack_derived(ingest(str(path), ORIGIN, "alice")) + + assert first == second + assert pack_derived(read_derived(first.decode().split("\n"))) == first + + +def test_appending_to_a_session_keeps_every_earlier_turn_id(tmp_path: Path) -> None: + before = convert(session(), ORIGIN, HUMAN)[0] + grown = session() + jsonl(user("u-06", "a-05", "and then?")) + after = convert(grown, ORIGIN, HUMAN)[0] + + assert [t.id for t in after[: len(before)]] == [t.id for t in before] + + +def test_events_fold_into_the_turn_they_follow() -> None: + raw = jsonl( + user("u-01", None, "start"), + record("s-02", "u-01", "system", subtype="stop_hook_summary", hookCount=1), + assistant("a-03", "s-02", [{"type": "text", "text": "reply"}]), + {"type": "last-prompt", "leafUuid": "s-02", "sessionId": SESSION_ID}, + ) + turns, heads, _ = convert(raw, ORIGIN, HUMAN) + + assert [t.core["kind"] for t in turns] == ["message", "message"] + assert turns[1].core["parents"] == [turns[0].id] + [event] = turns[0].facts["events"] + assert event["type"] == "x-claude-code:system" + assert event["system"] == {"subtype": "stop_hook_summary", "hookCount": 1} + assert heads["current"] == turns[0].id + + +def test_events_do_not_change_the_ids_around_them() -> None: + plain = jsonl( + user("u-01", None, "start"), + assistant("a-03", "u-01", [{"type": "text", "text": "reply"}]), + ) + with_event = jsonl( + user("u-01", None, "start"), + record("s-02", "u-01", "system", subtype="turn_duration", durationMs=5), + assistant("a-03", "s-02", [{"type": "text", "text": "reply"}]), + ) + + assert [t.id for t in convert(with_event, ORIGIN, HUMAN)[0]] == [ + t.id for t in convert(plain, ORIGIN, HUMAN)[0] + ] + + +def test_an_event_with_no_turn_before_it_is_kept_at_session_level() -> None: + raw = jsonl( + record("s-01", None, "system", subtype="informational", content="hi"), + user("u-02", "s-01", "start"), + ) + turns, _, session = convert(raw, ORIGIN, HUMAN) + + assert len(turns) == 1 + assert session["events"][0]["system"]["subtype"] == "informational" + + +def test_ssh_author_id_is_the_ssh_keygen_fingerprint_of_the_key_blob() -> None: + """ssh-keygen -l hashes the decoded key blob with SHA-256 and prints it as + unpadded base64; checked against ssh-keygen by hand on a real key.""" + blob = b"\x00\x00\x00\x0bssh-ed25519" + bytes(range(32)) + line = "ssh-ed25519 " + base64.b64encode(blob).decode() + " me@host" + expected = base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=") + + assert ssh_author_id(line) == f"ssh:SHA256:{expected}" + assert ssh_author_id(line.rsplit(" ", 1)[0]) == ssh_author_id(line) + + +def test_ssh_author_id_rejects_something_that_is_not_a_key() -> None: + with pytest.raises(AuthorKeyError): + ssh_author_id("not-a-key") diff --git a/test/test_trace.py b/test/test_trace.py new file mode 100644 index 0000000..ff9738f --- /dev/null +++ b/test/test_trace.py @@ -0,0 +1,366 @@ +import json +import os +import subprocess +from pathlib import Path +from typing import Any + +import pytest + +from loch.claude import transcript_path_for +from loch.cli import main +from loch.store import FileStore +from loch.trace import ( + Resolver, + backfill, + fork_session, + hook_post_tool, + hook_pre_tool, + install_hooks, + read_note, + snapshot_transcript, +) + +SESSION = "11111111-2222-3333-4444-555555555555" +CALL = "toolu_commit" + + +@pytest.fixture +def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Path]: + home = tmp_path / "home" + repo = tmp_path / "repo" + home.mkdir() + repo.mkdir() + monkeypatch.setenv("HOME", str(home)) + for name in ("AUTHOR", "COMMITTER"): + monkeypatch.setenv(f"GIT_{name}_NAME", "Test") + monkeypatch.setenv(f"GIT_{name}_EMAIL", "test@example.com") + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "gitconfig")) + run(repo, "init", "-q", "-b", "main") + return {"home": home, "repo": repo, "tmp": tmp_path} + + +def run(repo: Path, *args: str, date: str | None = None) -> str: + extra = {"GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} if date else {} + return subprocess.run( + ["git", "-C", str(repo), *args], + capture_output=True, + text=True, + check=True, + env={**os.environ, **extra}, + ).stdout.strip() + + +def commit( + repo: Path, name: str, text: str, message: str, date: str | None = None +) -> str: + (repo / name).write_text(text) + run(repo, "add", name) + run(repo, "commit", "-q", "-m", message, date=date) + return run(repo, "rev-parse", "HEAD") + + +def transcript(repo: Path, command: str, prompt: str = "please add the file") -> str: + """human prompt -> assistant Bash call -> its result, as Claude writes it.""" + records: list[dict[str, Any]] = [ + { + "type": "user", + "uuid": "u1", + "parentUuid": None, + "sessionId": SESSION, + "cwd": str(repo), + "timestamp": "2026-01-01T00:00:00.000Z", + "message": {"role": "user", "content": prompt}, + }, + { + "type": "assistant", + "uuid": "a1", + "parentUuid": "u1", + "sessionId": SESSION, + "cwd": str(repo), + "timestamp": "2026-01-01T00:00:10.000Z", + "message": { + "id": "msg1", + "role": "assistant", + "content": [ + { + "type": "tool_use", + "id": CALL, + "name": "Bash", + "input": {"command": command}, + } + ], + }, + }, + { + "type": "user", + "uuid": "r1", + "parentUuid": "a1", + "sessionId": SESSION, + "cwd": str(repo), + "timestamp": "2026-01-01T00:00:20.000Z", + "message": { + "role": "user", + "content": [ + {"type": "tool_result", "tool_use_id": CALL, "content": "ok"} + ], + }, + }, + ] + path = transcript_path_for(str(repo), SESSION) + os.makedirs(os.path.dirname(path), exist_ok=True) + Path(path).write_text("".join(json.dumps(record) + "\n" for record in records)) + return path + + +def event(repo: Path, **fields: Any) -> dict[str, Any]: + return { + "session_id": SESSION, + "cwd": str(repo), + "tool_name": "Bash", + "tool_use_id": CALL, + "tool_input": {"command": "git commit"}, + **fields, + } + + +def test_hooks_note_exactly_the_commits_a_call_made(env: dict[str, Path]) -> None: + repo = env["repo"] + old = commit(repo, "a.txt", "a\n", "old work", date="2020-01-01T00:00:00Z") + run(repo, "checkout", "-q", "-b", "side") + other = commit(repo, "b.txt", "b\n", "someone else", date="2020-01-02T00:00:00Z") + run(repo, "checkout", "-q", "main") + + hook_pre_tool(event(repo)) + made = commit(repo, "c.txt", "c\n", "agent work") + assert hook_post_tool(event(repo)) == [made] + assert read_note(str(repo), made) == { + "loch": 1, + "agent": "claude-code", + "session": SESSION, + "call": CALL, + "captured": "hook", + } + + # Moving HEAD onto commits someone else made is not making them. + hook_pre_tool(event(repo, tool_use_id="toolu_checkout")) + run(repo, "checkout", "-q", "side") + assert hook_post_tool(event(repo, tool_use_id="toolu_checkout")) == [] + assert read_note(str(repo), other) is None + assert read_note(str(repo), old) is None + + +def test_a_call_that_leaves_head_alone_notes_nothing(env: dict[str, Path]) -> None: + repo = env["repo"] + commit(repo, "a.txt", "a\n", "first") + hook_pre_tool(event(repo)) + assert hook_post_tool(event(repo)) == [] + + +def test_hook_command_never_fails( + env: dict[str, Path], + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + import io + + monkeypatch.setattr("sys.stdin", io.StringIO("not json")) + monkeypatch.setattr("sys.argv", ["loch", "hook", "post-tool"]) + main() + assert capsys.readouterr().out == "" + + +def test_install_is_idempotent_and_keeps_existing_settings(tmp_path: Path) -> None: + settings = tmp_path / ".claude" / "settings.json" + settings.parent.mkdir() + settings.write_text(json.dumps({"model": "x", "hooks": {"Stop": [{"hooks": []}]}})) + assert install_hooks(str(settings), "loch") == [ + "PreToolUse", + "PostToolUse", + "Stop", + ] + assert install_hooks(str(settings), "loch") == [] + written = json.loads(settings.read_text()) + assert written["model"] == "x" + assert written["hooks"]["PreToolUse"][0]["matcher"] == "Bash" + assert len(written["hooks"]["Stop"]) == 2 + + +def test_stop_snapshots_the_transcript(env: dict[str, Path]) -> None: + path = transcript(env["repo"], "git commit -m 'x'") + store = FileStore(str(env["tmp"] / "store")) + key = snapshot_transcript({"session_id": SESSION, "transcript_path": path}, store) + assert key is not None + assert store.get(key) == Path(path).read_bytes() + + +def test_a_deleted_transcript_is_found_in_the_store(env: dict[str, Path]) -> None: + repo = env["repo"] + path = transcript(repo, "git commit -m 'add a'") + hook_pre_tool(event(repo)) + sha = commit(repo, "a.txt", "a\n", "add a") + hook_post_tool(event(repo)) + store = FileStore(str(env["tmp"] / "store")) + snapshot_transcript({"session_id": SESSION, "transcript_path": path}, store) + os.remove(path) + + link = Resolver(str(repo), store).resolve(sha) + assert link is not None and link.transcript is not None + assert link.prompt == "please add the file" + + +def test_backfill_links_only_an_exact_match(env: dict[str, Path]) -> None: + repo = env["repo"] + # The transcript's call ran 00:00:10-00:00:20; these straddle it. + inside = commit(repo, "a.txt", "a\n", "add a", date="2026-01-01T00:00:15Z") + outside = commit(repo, "b.txt", "b\n", "add a", date="2026-01-01T05:00:00Z") + unnamed = commit(repo, "c.txt", "c\n", "add c", date="2026-01-01T00:00:15Z") + transcript(repo, 'git add a.txt && git commit -m "add a"') + + seen: list[tuple[int, int, int, int]] = [] + linked = backfill(str(repo), "HEAD", lambda *step: seen.append(step)) + assert [sha for sha, _ in linked] == [inside] + # One step per transcript, ending with everything read. + assert seen and seen[-1][0] == seen[-1][1] and seen[-1][2] == seen[-1][3] > 0 + note = read_note(str(repo), inside) + assert note is not None and note["captured"] == "backfill" + assert read_note(str(repo), outside) is None + assert read_note(str(repo), unnamed) is None + assert backfill(str(repo), "HEAD") == [] + + +def test_blame_names_the_prompt_behind_each_line( + env: dict[str, Path], + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + repo = env["repo"] + commit(repo, "f.txt", "human line\n", "by hand") + transcript(repo, "git commit -am 'agent'", prompt="make it two lines") + hook_pre_tool(event(repo)) + sha = commit(repo, "f.txt", "human line\nagent line\n", "agent") + hook_post_tool(event(repo)) + + monkeypatch.chdir(repo) + monkeypatch.setattr("sys.argv", ["loch", "blame", "f.txt", "--json"]) + main() + hunks = json.loads(capsys.readouterr().out)["hunks"] + assert [(h["start"], h["conversation"] is None) for h in hunks] == [ + (1, True), + (2, False), + ] + assert hunks[1]["commit"] == sha + assert hunks[1]["conversation"]["prompt"] == "make it two lines" + assert hunks[1]["conversation"]["turn"].startswith("sha256:") + + +def test_log_finds_conversations_blame_has_painted_over( + env: dict[str, Path], + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + repo = env["repo"] + first = commit(repo, "f.txt", "one\nother\n", "by hand") + transcript(repo, "git commit -am 'agent'", prompt="reword line one") + hook_pre_tool(event(repo)) + agent = commit(repo, "f.txt", "uno\nother\n", "agent") + hook_post_tool(event(repo)) + last = commit(repo, "f.txt", "ONE\nother\n", "by hand again") + commit(repo, "f.txt", "ONE\nelse\n", "only line two") + + def log(target: str) -> dict[str, Any]: + monkeypatch.setattr("sys.argv", ["loch", "log", target, "--json"]) + main() + result: dict[str, Any] = json.loads(capsys.readouterr().out) + return result + + monkeypatch.chdir(repo) + # blame of line 1 sees only `last`; its history still holds the agent. + line = log("f.txt:1") + assert [c["commit"] for c in line["commits"]] == [last, agent, first] + assert [c["conversation"] is None for c in line["commits"]] == [True, False, True] + assert line["lines"] == {"start": 1, "end": 1} + assert [c["prompt"] for c in line["conversations"]] == ["reword line one"] + assert line["conversations"][0]["commits"] == [agent] + assert len(log("f.txt")["commits"]) == 4 + + monkeypatch.setattr("sys.argv", ["loch", "log", "f.txt:9", "--json"]) + with pytest.raises(SystemExit): + main() + assert json.loads(capsys.readouterr().out)["code"] == "usage" + + +def test_fork_cuts_after_the_whole_round_and_leaves_the_original( + env: dict[str, Path], +) -> None: + repo = env["repo"] + path = transcript(repo, "git commit") + records = [json.loads(line) for line in Path(path).read_text().splitlines()] + # A parallel second call in the same message, with its result after ours, + # then the conversation carrying on past the commit. + second = json.loads(json.dumps(records[1])) + second.update(uuid="a2", parentUuid="a1") + second["message"]["content"][0]["id"] = "toolu_other" + result_one = dict(records[2], parentUuid="a2") + result_two = json.loads(json.dumps(records[2])) + result_two.update(uuid="r2", parentUuid="r1") + result_two["message"]["content"][0]["tool_use_id"] = "toolu_other" + later = dict(records[0], uuid="u2", parentUuid="r2", message={"content": "more"}) + lines = [records[0], records[1], second, result_one, result_two, later] + original = "".join(json.dumps(record) + "\n" for record in lines) + Path(path).write_text(original) + + target = env["tmp"] / "elsewhere" + target.mkdir() + fork = fork_session(path, str(target), call=CALL) + + assert Path(path).read_text() == original + forked = [json.loads(line) for line in Path(fork.path).read_text().splitlines()] + assert [r.get("uuid") for r in forked] == ["u1", "a1", "a2", "r1", "r2", None] + assert {r["sessionId"] for r in forked} == {fork.session_id} + assert {r["cwd"] for r in forked if "cwd" in r} == {str(target)} + assert forked[-1]["type"] == "custom-title" + assert fork.path == transcript_path_for(str(target), fork.session_id) + + +def test_fork_without_a_call_runs_to_the_end_of_the_conversation( + env: dict[str, Path], +) -> None: + repo = env["repo"] + path = transcript(repo, "git commit") + records = [json.loads(line) for line in Path(path).read_text().splitlines()] + later = dict(records[0], uuid="u2", parentUuid="r1", message={"content": "more"}) + Path(path).write_text( + "".join(json.dumps(record) + "\n" for record in [*records, later]) + ) + + fork = fork_session(path, str(repo)) + forked = [json.loads(line) for line in Path(fork.path).read_text().splitlines()] + assert [r.get("uuid") for r in forked] == ["u1", "a1", "r1", "u2", None] + + +def test_blame_html_marks_every_line_with_its_conversation( + env: dict[str, Path], + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + repo = env["repo"] + commit(repo, "f.txt", "human line\n", "by hand") + transcript(repo, "git commit -am 'agent'", prompt="make it lines") + hook_pre_tool(event(repo)) + commit(repo, "f.txt", "human line\nagent line\n", "agent") + hook_post_tool(event(repo)) + (repo / "f.txt").write_text("human line\nagent line\nwork in progress\n") + + page = env["tmp"] / "blame.html" + monkeypatch.chdir(repo) + monkeypatch.setattr( + "sys.argv", ["loch", "blame", "f.txt", "--html", str(page), "--no-open"] + ) + main() + assert capsys.readouterr().out == f"wrote {page}\n" + html = page.read_text() + assert '" not in html.split("