From 7db99c2aa1bb5ffa03fe8628d66b3a13b9c91d04 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 5 Nov 2026 14:21:24 -0500 Subject: [PATCH 01/16] Rename lochy to loch in the package, CLI and docs The package, console script, env vars (LOCH_STORE, LOCH_S3_ENDPOINT, LOCH_S3_REGION) and default store (~/.loch/store) are now loch. The GitHub repo is still ness-dev/lochy, so release URLs keep that slug. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 4 +-- CLAUDE.md | 22 +++++++-------- README.md | 50 +++++++++++++++++------------------ {lochy => loch}/__init__.py | 0 {lochy => loch}/bundle.py | 0 {lochy => loch}/claude.py | 2 +- {lochy => loch}/cli.py | 30 ++++++++++----------- {lochy => loch}/git.py | 0 {lochy => loch}/index.py | 0 {lochy => loch}/output.py | 2 +- {lochy => loch}/redact.py | 0 {lochy => loch}/rewrite.py | 0 {lochy => loch}/store.py | 10 +++---- pyproject.toml | 6 ++--- release.sh | 4 +-- test/test_bundle.py | 2 +- test/test_claude.py | 8 +++--- test/test_cli.py | 36 ++++++++++++------------- test/test_git.py | 2 +- test/test_index.py | 10 +++---- test/test_output.py | 4 +-- test/test_redact.py | 2 +- test/test_rewrite.py | 4 +-- test/test_store.py | 14 +++++----- 24 files changed, 106 insertions(+), 106 deletions(-) rename {lochy => loch}/__init__.py (100%) rename {lochy => loch}/bundle.py (100%) rename {lochy => loch}/claude.py (98%) rename {lochy => loch}/cli.py (96%) rename {lochy => loch}/git.py (100%) rename {lochy => loch}/index.py (100%) rename {lochy => loch}/output.py (96%) rename {lochy => loch}/redact.py (100%) rename {lochy => loch}/rewrite.py (100%) rename {lochy => loch}/store.py (95%) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c653d4d..4e01b16 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: # resolves to nothing — it has to be a full version. - uses: astral-sh/setup-uv@v10.0.1 - # A mismatch would publish v0.2.0 as an asset named lochy-0.1.0, and the + # A mismatch would publish v0.2.0 as an asset named loch-0.1.0, and the # install path is a pinned asset URL, so it is not something to discover # afterwards. - name: Check the tag against the packaged version @@ -39,7 +39,7 @@ jobs: run: | python3 -m venv /tmp/smoke /tmp/smoke/bin/pip install --quiet dist/*.whl - test "$(/tmp/smoke/bin/lochy --version)" = "lochy ${GITHUB_REF_NAME#v}" + test "$(/tmp/smoke/bin/loch --version)" = "loch ${GITHUB_REF_NAME#v}" # Both artifacts: the wheel is what `uv tool install` points at, the # sdist is what anyone building from source needs. diff --git a/CLAUDE.md b/CLAUDE.md index 8f89852..8618473 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,11 +1,11 @@ -# lochy — repo overview for Claude +# loch — repo overview for Claude ## What this is A standalone CLI that makes agent coding sessions portable between machines. Agent CLIs store transcripts in machine-local directories keyed by the working directory they ran in, which strands a session on the -laptop that produced it. `lochy` packs those transcripts into a +laptop that produced it. `loch` packs those transcripts into a content-addressed bundle, stores it anywhere S3-compatible, and unpacks it elsewhere with paths rewritten so the session actually resumes. @@ -105,7 +105,7 @@ public API. Re-verify if something breaks. disambiguator**, and the only one available — no field marks which cwd is current. - `"cwd"` also appears *inside* tool inputs and results, naming some - other process's directory. lochy's own `--json` output is one such + other process's directory. loch's own `--json` output is one such source, so anything counting cwds has to parse each record and read the top-level field, not grep the text. - Scale reference: 750MB across 428 project dirs on one active machine; @@ -129,7 +129,7 @@ public API. Re-verify if something breaks. Python 3.10 through 3.13, Poetry, boto3 behind an extra. ``` -lochy/ +loch/ ├── cli.py # entry point, arg parsing, list/save/restore/delete/reindex ├── claude.py # Claude Code adapter: path encoding, session discovery, metadata ├── bundle.py # bundle format, gzip, content-addressed ref @@ -295,7 +295,7 @@ given and neither is inferred. **Leaving foreign cwds unrewritten is possible — it is just not better.** The obvious objection, that it needs knowing which subtrees exist on the -destination, does not apply: lochy has the exact set of candidate cwds +destination, does not apply: loch has the exact set of candidate cwds already, having computed them to choose one, and those specific strings are known to be session working directories rather than dotfile or config references. So the rule "the home pair declines a value exactly equal to @@ -325,7 +325,7 @@ single-pass guarantee depends on a nested path matching before the shorter prefix that contains it, and caller order is arbitrary. This is a "keep doing that" note, not a change. -What makes it safe is that **the caller states the mapping; lochy never +What makes it safe is that **the caller states the mapping; loch never infers it.** The first consumer (Harness "send worktree to remote") can name all four paths without a guess: the origin worktree is what the user selected, the origin repo root comes from @@ -406,7 +406,7 @@ produce the same ref. ## The JSON contract -`lochy` is meant to be embedded in other tools — Harness is the first — and +`loch` is meant to be embedded in other tools — Harness is the first — and a caller that scrapes prose breaks the moment someone rewords a sentence. So every command takes `--json`, accepted either before or after the subcommand, and answers with exactly one document on stdout: @@ -523,14 +523,14 @@ is pinned to the floor rather than following the running interpreter, so a **boto3 is an optional `[s3]` extra.** What makes that safe is the lazy import in `S3Store._client`: the `file://` backend loads nothing third-party at runtime, so the SDK was only ever an install-time cost — 8 packages and 27MB, -of which botocore alone is 24MB against lochy's own 172KB. A default install +of which botocore alone is 24MB against loch's own 172KB. A default install is one package and 184KB. Keep the import inside the method, and keep any new `botocore` import *after* the `_client()` call that would have failed first, or the SDK's absence surfaces as a bare `ImportError` and gets mislabelled `store-unreachable`. The dev group still carries boto3, moto and the stubs, so the S3 backend stays fully covered by the suite. -**`lochy --version` reads package metadata**, so pyproject is the only place +**`loch --version` reads package metadata**, so pyproject is the only place the number is set. `importlib.metadata` raises `PackageNotFoundError` in a source checkout that was never installed, which reports `"unknown"` — pyproject can't be read as a fallback, since `tomllib` arrived in 3.11 and the floor is @@ -581,7 +581,7 @@ records were on `feat/send-worktree-to-remote`. Branch and version are now read from records carrying the *chosen* cwd. This is worth its own release note rather than folding into the cwd fix, because the blast radius is different: a consumer that carries the branch itself sees a -healthy-looking transfer while the lochy entry sits under a name nobody +healthy-looking transfer while the loch entry sits under a name nobody would look for it on, and every already-saved bundle from a moved session is filed wrong until re-saved or reindexed. @@ -612,7 +612,7 @@ coverage now, which is more than it had, but mocks agree with your assumptions by construction. A live run failed on `Access Denied` (the IAM user lacked `s3:PutObject`); the region mismatch that precedes that failure surfaces as "The bucket you are attempting to access must be -addressed using the specified endpoint," so set `LOCHY_S3_REGION` +addressed using the specified endpoint," so set `LOCH_S3_REGION` when the bucket's region differs from the AWS config default. Listing and deleting need IAM actions the bucket policy may not grant diff --git a/README.md b/README.md index 2ecba7b..dfbad0f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# lochy +# loch Save and restore agent coding sessions across machines. @@ -7,7 +7,7 @@ working directory they ran in. That makes a session effectively stuck to the laptop that produced it — you can't hand a teammate the conversation that produced a branch, and you can't pick one up on another machine. -`lochy` packs those transcripts into a portable, content-addressed +`loch` packs those transcripts into a portable, content-addressed bundle, stores it anywhere S3-compatible, and unpacks it on another machine with the paths rewritten so the session actually resumes. @@ -16,8 +16,8 @@ Currently supports Claude Code. ## Install ```sh -uv tool install https://github.com/ness-dev/lochy/releases/download/v0.1.0/lochy-0.1.0-py3-none-any.whl -lochy --version +uv tool install https://github.com/ness-dev/lochy/releases/download/v0.1.0/loch-0.1.0-py3-none-any.whl +loch --version ``` The wheel is `py3-none-any`, and [uv](https://docs.astral.sh/uv/) is a static @@ -34,7 +34,7 @@ in. The backend imports boto3 lazily, so a `file://` store never loads it and paying 27MB for a dependency most installs never reach isn't worth it: ```sh -uv tool install "lochy[s3] @ https://github.com/ness-dev/lochy/releases/download/v0.1.0/lochy-0.1.0-py3-none-any.whl" +uv tool install "loch[s3] @ https://github.com/ness-dev/lochy/releases/download/v0.1.0/loch-0.1.0-py3-none-any.whl" ``` Without it, an `s3://` store fails with `code: "s3-extra-missing"` rather than @@ -44,7 +44,7 @@ For development: ```sh poetry install # brings boto3, so the S3 backend is covered by the tests -poetry run lochy --help +poetry run loch --help poetry run pytest ``` @@ -52,27 +52,27 @@ poetry run pytest ```sh # what's on this machine for the current repo? -lochy list -lochy list --branch feature/checkout-flow +loch list +loch list --branch feature/checkout-flow # pack them up and push to a store -lochy save --branch feature/checkout-flow --store s3://my-bucket/sessions +loch save --branch feature/checkout-flow --store s3://my-bucket/sessions # -> packed e71cdcb1... [feature/checkout-flow] — redacted 2 secrets # -> ref 10482276de745032... # on another machine: what's been saved for the branch I'm on? -lochy list --remote --store s3://my-bucket/sessions -lochy list --remote --branch feature/checkout-flow -lochy list --all # every branch in the store +loch list --remote --store s3://my-bucket/sessions +loch list --remote --branch feature/checkout-flow +loch list --all # every branch in the store -lochy restore 10482276de745032... --store s3://my-bucket/sessions +loch restore 10482276de745032... --store s3://my-bucket/sessions # -> cd /path/to/repo && claude --resume e71cdcb1-7c2c-410b-8c73-91cdf0cba4b8 # a transcript that shouldn't be there any more -lochy delete 10482276de745032... +loch delete 10482276de745032... # rebuild the index from the bundles, if a save was interrupted -lochy reindex +loch reindex ``` `save` bundles every session matching the filter, so a branch with several @@ -84,22 +84,22 @@ Every command takes `--json`, before or after the subcommand, and prints one document on stdout instead of the text above: ```sh -lochy save --json --branch feature/checkout-flow --store /tmp/outbound +loch save --json --branch feature/checkout-flow --store /tmp/outbound # {"schema":1,"ok":true,"command":"save","ref":"10482276...","bytes":4712, # "redacted":2,"sessions":[{"sessionId":"e71cdcb1-...","branch":"feature/checkout-flow", # "redactions":{"aws-access-key":1,"jwt":1}}],"indexed":[...]} -ref=$(lochy save --json --store /tmp/outbound | jq -r .ref) -lochy restore --json "$ref" --into /path/to/repo --store /tmp/outbound +ref=$(loch save --json --store /tmp/outbound | jq -r .ref) +loch restore --json "$ref" --into /path/to/repo --store /tmp/outbound -lochy --version --json +loch --version --json # {"schema":1,"ok":true,"command":"version","version":"0.1.0"} ``` Failures are documents too, on stdout, so one stream carries both outcomes: ```sh -lochy restore --json deadbeef --store /tmp/outbound; echo "exit $?" +loch restore --json deadbeef --store /tmp/outbound; echo "exit $?" # {"schema":1,"ok":false,"command":"restore","code":"bundle-not-found", # "error":"could not read deadbeef from /tmp/outbound: ..."} # exit 1 @@ -125,9 +125,9 @@ bundles/.loch the bundle, named by the hash of its bytes index/branch// a small entry per branch the bundle touches ``` -`lochy list --remote` reads only the index, so listing a branch never +`loch list --remote` reads only the index, so listing a branch never downloads a bundle. Entries are derived from the bundles and hold nothing -that isn't already in them — `lochy reindex` rebuilds the whole index by +that isn't already in them — `loch reindex` rebuilds the whole index by scanning `bundles/`, and drops entries no bundle backs. Branch names are percent-encoded, so `feature/foo` stays one path segment @@ -148,9 +148,9 @@ itself for `list`/`reindex` and `s3:DeleteObject` for `delete`. | Variable | Purpose | | --- | --- | -| `LOCHY_STORE` | default store URI (else `~/.lochy/store`) | -| `LOCHY_S3_ENDPOINT` | custom endpoint for R2, MinIO, Backblaze, ... | -| `LOCHY_S3_REGION` | region override | +| `LOCH_STORE` | default store URI (else `~/.loch/store`) | +| `LOCH_S3_ENDPOINT` | custom endpoint for R2, MinIO, Backblaze, ... | +| `LOCH_S3_REGION` | region override | 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/lochy/__init__.py b/loch/__init__.py similarity index 100% rename from lochy/__init__.py rename to loch/__init__.py diff --git a/lochy/bundle.py b/loch/bundle.py similarity index 100% rename from lochy/bundle.py rename to loch/bundle.py diff --git a/lochy/claude.py b/loch/claude.py similarity index 98% rename from lochy/claude.py rename to loch/claude.py index 0b5bbee..02fd0ab 100644 --- a/lochy/claude.py +++ b/loch/claude.py @@ -92,7 +92,7 @@ def _records(raw: str) -> Iterator[dict[str, Any]]: def transcript_cwds(raw: str) -> dict[str, int]: """Every cwd a transcript's records name, with how many name it, in order of first appearance. Only the top-level field counts: `"cwd"` also occurs - inside tool inputs and results — lochy's own --json output among them — + inside tool inputs and results — loch's own --json output among them — where it names some other process's directory.""" counts: dict[str, int] = {} for record in _records(raw): diff --git a/lochy/cli.py b/loch/cli.py similarity index 96% rename from lochy/cli.py rename to loch/cli.py index 7fa41b5..75d711f 100644 --- a/lochy/cli.py +++ b/loch/cli.py @@ -55,16 +55,16 @@ ) from .store import MissingDependency, MissingObject, create_store, resolve_store_uri -USAGE = """lochy — save and restore agent coding sessions across machines +USAGE = """loch — save and restore agent coding sessions across machines Usage: - lochy list [--cwd ] [--branch ] - lochy list --remote [--branch ] [--all] [--store ] - lochy save [--cwd ] [--branch ] [--session ] [--store ] - lochy restore [--into ] [--store ] [--force] [--new-id] - lochy delete [--store ] - lochy reindex [--store ] - lochy --version + loch list [--cwd ] [--branch ] + loch list --remote [--branch ] [--all] [--store ] + loch save [--cwd ] [--branch ] [--session ] [--store ] + loch restore [--into ] [--store ] [--force] [--new-id] + loch delete [--store ] + loch reindex [--store ] + loch --version Every command takes --json, which replaces the text below with one machine- readable document on stdout. @@ -74,9 +74,9 @@ s3://bucket/prefix any S3-compatible endpoint Environment: - LOCHY_STORE default store URI - LOCHY_S3_ENDPOINT custom endpoint (R2, MinIO, ...) - LOCHY_S3_REGION region override + LOCH_STORE default store URI + LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) + LOCH_S3_REGION region override """ @@ -162,7 +162,7 @@ def print_help(self, file: Any = None) -> NoReturn: def _parser(command: str) -> argparse.ArgumentParser: - parser = _Parser(prog=f"lochy {command}") + parser = _Parser(prog=f"loch {command}") # Registered so the flag parses after the subcommand; main() reads the mode # off argv itself, because a failure before or during parsing has to render # in the mode the caller asked for. @@ -600,7 +600,7 @@ def installed_version() -> str: that was never installed has no metadata to read, and pyproject can't be parsed for it either — tomllib arrived in 3.11 and the floor is 3.10.""" try: - return importlib.metadata.version("lochy") + return importlib.metadata.version("loch") except importlib.metadata.PackageNotFoundError: return "unknown" @@ -608,7 +608,7 @@ def installed_version() -> str: def command_version(argv: list[str]) -> Result: version = installed_version() return Result( - command="version", payload={"version": version}, text=f"lochy {version}\n" + command="version", payload={"version": version}, text=f"loch {version}\n" ) @@ -648,7 +648,7 @@ def main() -> None: try: handler = COMMANDS.get(command) if handler is None: - fail("unknown-command", f"unknown command '{command}' (try: lochy help)") + fail("unknown-command", f"unknown command '{command}' (try: loch help)") result = handler(argv[1:]) except HelpRequested as help_text: result = Result(command, {"usage": help_text.text}, text=help_text.text) diff --git a/lochy/git.py b/loch/git.py similarity index 100% rename from lochy/git.py rename to loch/git.py diff --git a/lochy/index.py b/loch/index.py similarity index 100% rename from lochy/index.py rename to loch/index.py diff --git a/lochy/output.py b/loch/output.py similarity index 96% rename from lochy/output.py rename to loch/output.py index 3cd4e64..f186baf 100644 --- a/lochy/output.py +++ b/loch/output.py @@ -75,7 +75,7 @@ def emit_error(command: str, error: CommandError, as_json: bool) -> NoReturn: else: for warning in error.warnings: sys.stderr.write(warning) - sys.stderr.write(error.prose if error.prose else f"lochy: {error.message}\n") + sys.stderr.write(error.prose if error.prose else f"loch: {error.message}\n") raise SystemExit(error.exit_status) diff --git a/lochy/redact.py b/loch/redact.py similarity index 100% rename from lochy/redact.py rename to loch/redact.py diff --git a/lochy/rewrite.py b/loch/rewrite.py similarity index 100% rename from lochy/rewrite.py rename to loch/rewrite.py diff --git a/lochy/store.py b/loch/store.py similarity index 95% rename from lochy/store.py rename to loch/store.py index fdf1e46..a1106ad 100644 --- a/lochy/store.py +++ b/loch/store.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: from mypy_boto3_s3.client import S3Client -DEFAULT_STORE = os.path.join(str(Path.home()), ".lochy", "store") +DEFAULT_STORE = os.path.join(str(Path.home()), ".loch", "store") class MissingObject(Exception): @@ -101,11 +101,11 @@ def _client(self) -> "S3Client": except ImportError as error: raise MissingDependency( "the S3 backend needs boto3, which this install doesn't have " - "(reinstall as lochy[s3])" + "(reinstall as loch[s3])" ) from error - endpoint = os.environ.get("LOCHY_S3_ENDPOINT") - region = os.environ.get("LOCHY_S3_REGION") + endpoint = os.environ.get("LOCH_S3_ENDPOINT") + region = os.environ.get("LOCH_S3_REGION") return boto3.client( "s3", endpoint_url=endpoint, @@ -175,4 +175,4 @@ def create_store(uri: str) -> Store: def resolve_store_uri(explicit: str | None = None) -> str: if explicit is not None: return explicit - return os.environ.get("LOCHY_STORE", DEFAULT_STORE) + return os.environ.get("LOCH_STORE", DEFAULT_STORE) diff --git a/pyproject.toml b/pyproject.toml index abd29ac..d1dfbc0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [project] -name = "lochy" +name = "loch" version = "0.1.0" description = "Save and restore agent coding sessions across machines" authors = [{ name = "Mike Lyons", email = "mdl0394@gmail.com" }] @@ -14,14 +14,14 @@ dependencies = [] s3 = ["boto3 (>=1.37.31,<2.0.0)"] [project.scripts] -lochy = "lochy.cli:main" +loch = "loch.cli:main" [build-system] requires = ["poetry-core>=2.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] -packages = [{ include = "lochy" }] +packages = [{ include = "loch" }] [tool.poetry.group.dev.dependencies] pytest = "^8.2.2" diff --git a/release.sh b/release.sh index 9e0dd7f..bfdc24e 100755 --- a/release.sh +++ b/release.sh @@ -42,7 +42,7 @@ path.write_text(new) PY grep -q "^version = \"$version\"$" pyproject.toml || die "version bump did not apply" -# Not asserting `lochy --version` here: it reads installed package metadata, +# Not asserting `loch --version` here: it reads installed package metadata, # which still holds the old number until the bumped project is reinstalled. # The release workflow smoke-tests it against a freshly built wheel instead. echo "==> verifying" @@ -75,5 +75,5 @@ cat < Redaction: raise RedactionError("still matching") - monkeypatch.setattr("lochy.claude.redact", refuse) + monkeypatch.setattr("loch.claude.redact", refuse) path = write_session(tmp_path, "/Users/mike/proj", "abc", summary="anything") meta = read_session_meta(str(path)) @@ -231,7 +231,7 @@ def test_falls_back_to_the_first_cwd_when_the_directory_matches_nothing( def test_transcript_cwds_counts_only_the_top_level_field() -> None: - """`"cwd"` also occurs inside tool inputs and results — lochy's own --json + """`"cwd"` also occurs inside tool inputs and results — loch's own --json output among them — where it names some other process's directory.""" raw = "\n".join( [ diff --git a/test/test_cli.py b/test/test_cli.py index a92bed3..1925cff 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -8,9 +8,9 @@ import pytest from test_claude import SECRET, write_moved_session, write_session -from lochy.bundle import unpack_bundle -from lochy.claude import session_dir_for, transcript_cwds, transcript_path_for -from lochy.cli import main +from loch.bundle import unpack_bundle +from loch.claude import session_dir_for, transcript_cwds, transcript_path_for +from loch.cli import main def invoke( @@ -20,7 +20,7 @@ def invoke( *argv: str, ) -> tuple[str, str, int | None]: monkeypatch.setenv("HOME", str(home)) - monkeypatch.setattr("sys.argv", ["lochy", *argv]) + monkeypatch.setattr("sys.argv", ["loch", *argv]) code: int | None = None try: main() @@ -49,17 +49,17 @@ def test_help_is_printed_without_a_command( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path ) -> None: out, _, code = invoke(monkeypatch, capsys, tmp_path) - assert out.startswith("lochy — save and restore") + assert out.startswith("loch — save and restore") assert code is None def test_version_is_reported_in_both_renderings( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path ) -> None: - installed = importlib.metadata.version("lochy") + installed = importlib.metadata.version("loch") out, _, code = invoke(monkeypatch, capsys, tmp_path, "--version") - assert (out, code) == (f"lochy {installed}\n", None) + assert (out, code) == (f"loch {installed}\n", None) document, _, code = invoke_json( monkeypatch, capsys, tmp_path, "--version", "--json" @@ -83,7 +83,7 @@ def test_unknown_command_fails( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path ) -> None: _, err, code = invoke(monkeypatch, capsys, tmp_path, "bogus") - assert err == "lochy: unknown command 'bogus' (try: lochy help)\n" + assert err == "loch: unknown command 'bogus' (try: loch help)\n" assert code == 1 @@ -235,7 +235,7 @@ def test_restore_skips_an_existing_session_unless_forced( str(store), ) assert "skipped abc (already exists; --force to overwrite)" in err - assert err.endswith("lochy: nothing restored\n") + assert err.endswith("loch: nothing restored\n") assert code == 1 out, _, _ = invoke( @@ -301,7 +301,7 @@ def test_save_fails_when_nothing_matches( "--store", str(tmp_path / "store"), ) - assert err.startswith("lochy: no claude-code sessions found for") + assert err.startswith("loch: no claude-code sessions found for") assert code == 1 @@ -309,7 +309,7 @@ def test_restore_requires_a_ref( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path ) -> None: _, err, code = invoke(monkeypatch, capsys, tmp_path, "restore") - assert err == "lochy: restore requires a bundle ref\n" + assert err == "loch: restore requires a bundle ref\n" assert code == 1 @@ -319,7 +319,7 @@ def test_restore_reports_an_unreadable_ref( _, err, code = invoke( monkeypatch, capsys, tmp_path, "restore", "deadbeef", "--store", str(tmp_path) ) - assert err.startswith("lochy: could not read deadbeef from") + assert err.startswith("loch: could not read deadbeef from") assert code == 1 @@ -386,7 +386,7 @@ def test_list_remote_defaults_to_the_branch_you_are_on( home = tmp_path / "home" store = tmp_path / "store" ref = save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - monkeypatch.setattr("lochy.cli.current_branch", lambda cwd: "feature/foo") + monkeypatch.setattr("loch.cli.current_branch", lambda cwd: "feature/foo") out, _, _ = invoke( monkeypatch, capsys, home, "list", "--remote", "--store", str(store) @@ -431,7 +431,7 @@ def test_delete_removes_the_bundle_and_its_entries( _, err, code = invoke( monkeypatch, capsys, home, "restore", ref, "--store", str(store) ) - assert err.startswith(f"lochy: could not read {ref} from") + assert err.startswith(f"loch: could not read {ref} from") assert code == 1 @@ -441,7 +441,7 @@ def test_delete_reports_a_ref_that_is_not_there( _, err, code = invoke( monkeypatch, capsys, tmp_path, "delete", "deadbeef", "--store", str(tmp_path) ) - assert err.startswith("lochy: could not delete deadbeef from") + assert err.startswith("loch: could not delete deadbeef from") assert code == 1 @@ -974,14 +974,14 @@ def test_json_separates_an_uninstalled_sdk_from_a_store_that_did_not_answer( "s3://sessions/prefix", ) assert (document["code"], code) == ("s3-extra-missing", 1) - assert "lochy[s3]" in document["error"] + assert "loch[s3]" in document["error"] # With the SDK present, a store that doesn't answer is still that. def refuse(self: Any) -> None: raise OSError("connection refused") monkeypatch.delitem(sys.modules, "boto3") - monkeypatch.setattr("lochy.store.S3Store._client", refuse) + monkeypatch.setattr("loch.store.S3Store._client", refuse) document, _, code = invoke_json( monkeypatch, capsys, @@ -1040,7 +1040,7 @@ def test_json_help_is_a_document_rather_than_the_usage_block( ) -> None: document, _, code = invoke_json(monkeypatch, capsys, tmp_path, "--json") assert (document["command"], document["ok"], code) == ("help", True, None) - assert document["usage"].startswith("lochy — save and restore") + assert document["usage"].startswith("loch — save and restore") document, _, code = invoke_json( monkeypatch, capsys, tmp_path, "save", "--json", "--help" diff --git a/test/test_git.py b/test/test_git.py index 63f04e2..772f9ba 100644 --- a/test/test_git.py +++ b/test/test_git.py @@ -1,7 +1,7 @@ import subprocess from pathlib import Path -from lochy.git import current_branch +from loch.git import current_branch def test_current_branch_reads_the_checkout(tmp_path: Path) -> None: diff --git a/test/test_index.py b/test/test_index.py index a6087db..be1705d 100644 --- a/test/test_index.py +++ b/test/test_index.py @@ -4,7 +4,7 @@ import pytest from moto import mock_aws -from lochy.bundle import ( +from loch.bundle import ( BUNDLE_VERSION, Bundle, BundleOrigin, @@ -12,7 +12,7 @@ bundle_ref, pack_bundle, ) -from lochy.index import ( +from loch.index import ( BRANCH, bundle_key, decode_segment, @@ -27,7 +27,7 @@ reindex, value_prefix, ) -from lochy.store import FileStore, MissingObject, S3Store +from loch.store import FileStore, MissingObject, S3Store def session(session_id: str, branch: str | None, cwd: str = "/repo") -> BundleSession: @@ -213,8 +213,8 @@ def test_an_encoded_branch_survives_a_round_trip_through_s3( monkeypatch.setenv("AWS_ACCESS_KEY_ID", "testing") monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "testing") monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1") - monkeypatch.delenv("LOCHY_S3_ENDPOINT", raising=False) - monkeypatch.delenv("LOCHY_S3_REGION", raising=False) + monkeypatch.delenv("LOCH_S3_ENDPOINT", raising=False) + monkeypatch.delenv("LOCH_S3_REGION", raising=False) boto3.client("s3", region_name="us-east-1").create_bucket(Bucket="sessions") store = S3Store("sessions", "prefix") diff --git a/test/test_output.py b/test/test_output.py index 3208787..c9ed15b 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2,7 +2,7 @@ import pytest -from lochy.output import SCHEMA, CommandError, Result, document, emit, emit_error +from loch.output import SCHEMA, CommandError, Result, document, emit, emit_error def test_a_success_envelope_carries_no_error_fields() -> None: @@ -58,4 +58,4 @@ def test_an_error_exits_nonzero_in_both_modes( out, err = capsys.readouterr() assert failure.value.code == 2 assert out == "" - assert err == "lochy: bad flag\n" + assert err == "loch: bad flag\n" diff --git a/test/test_redact.py b/test/test_redact.py index 34adbfd..59acd4b 100644 --- a/test/test_redact.py +++ b/test/test_redact.py @@ -2,7 +2,7 @@ import pytest -from lochy.redact import RULES, RedactionError, Rule, redact, scan, summarize +from loch.redact import RULES, RedactionError, Rule, redact, scan, summarize # Structurally valid, obviously synthetic. Nothing here is or was a credential. FAKE = { diff --git a/test/test_rewrite.py b/test/test_rewrite.py index 45b1b5b..ab92abb 100644 --- a/test/test_rewrite.py +++ b/test/test_rewrite.py @@ -1,6 +1,6 @@ import json -from lochy.rewrite import ( +from loch.rewrite import ( ForeignCwd, RewriteSpec, foreign_cwds, @@ -216,7 +216,7 @@ def test_foreign_cwds_keys_on_the_origin_rather_than_a_reversal() -> None: def test_foreign_cwds_ignores_a_cwd_nested_in_tool_output() -> None: - """`"cwd"` also appears inside tool results — lochy's own --json output + """`"cwd"` also appears inside tool results — loch's own --json output among them — where it names some other process's directory. Counting those would fire on a restore that was entirely correct.""" raw = dumps( diff --git a/test/test_store.py b/test/test_store.py index d2c8249..bd9c821 100644 --- a/test/test_store.py +++ b/test/test_store.py @@ -6,7 +6,7 @@ import pytest from moto import mock_aws -from lochy.store import ( +from loch.store import ( DEFAULT_STORE, FileStore, MissingDependency, @@ -22,8 +22,8 @@ def aws_credentials(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("AWS_ACCESS_KEY_ID", "testing") monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "testing") monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1") - monkeypatch.delenv("LOCHY_S3_ENDPOINT", raising=False) - monkeypatch.delenv("LOCHY_S3_REGION", raising=False) + monkeypatch.delenv("LOCH_S3_ENDPOINT", raising=False) + monkeypatch.delenv("LOCH_S3_REGION", raising=False) def test_file_store_round_trips(tmp_path: Path) -> None: @@ -96,9 +96,9 @@ def test_create_store_rejects_a_bucketless_s3_uri() -> None: def test_resolve_store_uri_prefers_explicit_then_env( monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.delenv("LOCHY_STORE", raising=False) + monkeypatch.delenv("LOCH_STORE", raising=False) assert resolve_store_uri() == DEFAULT_STORE - monkeypatch.setenv("LOCHY_STORE", "s3://from-env/x") + monkeypatch.setenv("LOCH_STORE", "s3://from-env/x") assert resolve_store_uri() == "s3://from-env/x" assert resolve_store_uri("/explicit") == "/explicit" @@ -139,7 +139,7 @@ def test_s3_store_reports_an_uninstalled_sdk_as_such( lambda: S3Store("sessions", "bundles").list(""), lambda: S3Store("sessions", "bundles").delete("abc.loch"), ): - with pytest.raises(MissingDependency, match=r"lochy\[s3\]"): + with pytest.raises(MissingDependency, match=r"loch\[s3\]"): call() @@ -198,7 +198,7 @@ def test_s3_store_lists_past_the_first_page(aws_credentials: None) -> None: def test_s3_store_honours_the_region_override( aws_credentials: None, monkeypatch: pytest.MonkeyPatch ) -> None: - monkeypatch.setenv("LOCHY_S3_REGION", "us-east-2") + monkeypatch.setenv("LOCH_S3_REGION", "us-east-2") boto3.client("s3", region_name="us-east-2").create_bucket( Bucket="sessions", CreateBucketConfiguration={"LocationConstraint": "us-east-2"}, From 45b565e6f17ac919eae5c7804925ff2363547619 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 5 Nov 2026 14:36:07 -0500 Subject: [PATCH 02/16] Add loch format v1 and the Claude Code ingest converter loch/format.py defines the hashed turn: a core holding format version, kind, author, parents and the content hash, with content and per-turn facts kept beside it. Ids are sha256 over canonical JSON, and reading a derived file recomputes every one. loch/ingest.py converts a Claude Code session into a derived file. Each chain record becomes one turn whose parent is its parentUuid's turn, so rewind branches survive as separate heads. Compaction boundaries link through logicalParentUuid. Machine-specific strings (cwd, home, project slug, session id) become placeholders, using the same single-pass guarded rewrite restore uses, so turn ids are the same after a session moves machines. The source manifest hashes the transcript and its sidecar directory. loch ingest writes one derived file per session. test_corpus.py is an opt-in check against the local corpus (LOCH_CORPUS=1). Co-Authored-By: Claude Opus 5.5 --- loch/cli.py | 61 +++++++ loch/format.py | 176 ++++++++++++++++++++ loch/ingest.py | 398 ++++++++++++++++++++++++++++++++++++++++++++ loch/rewrite.py | 30 ++-- test/test_cli.py | 66 ++++++++ test/test_corpus.py | 78 +++++++++ test/test_format.py | 130 +++++++++++++++ test/test_ingest.py | 328 ++++++++++++++++++++++++++++++++++++ 8 files changed, 1256 insertions(+), 11 deletions(-) create mode 100644 loch/format.py create mode 100644 loch/ingest.py create mode 100644 test/test_corpus.py create mode 100644 test/test_format.py create mode 100644 test/test_ingest.py diff --git a/loch/cli.py b/loch/cli.py index 75d711f..b851313 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -31,6 +31,7 @@ resolve_cwd, transcript_path_for, ) +from .format import pack_derived from .git import current_branch from .index import ( BRANCH, @@ -44,6 +45,7 @@ reindex, value_prefix, ) +from .ingest import CONVERTER, Origin, derived_name, ingest from .output import JSON_FLAG, CommandError, Result, emit, emit_error from .redact import RedactionError, redact, summarize from .rewrite import ( @@ -55,6 +57,8 @@ ) from .store import MissingDependency, MissingObject, create_store, resolve_store_uri +DEFAULT_DERIVED = os.path.join(str(Path.home()), ".loch", "derived") + USAGE = """loch — save and restore agent coding sessions across machines Usage: @@ -64,6 +68,8 @@ loch restore [--into ] [--store ] [--force] [--new-id] loch delete [--store ] loch reindex [--store ] + loch ingest [--cwd ] [--branch ] [--session ] [--author ] + [--out ] loch --version Every command takes --json, which replaces the text below with one machine- @@ -77,6 +83,8 @@ 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. """ @@ -590,6 +598,58 @@ 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("--out") + args = parser.parse_args(argv) + + 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), args.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, + ) + + def command_help(argv: list[str]) -> Result: return Result(command="help", payload={"usage": USAGE}, text=USAGE) @@ -625,6 +685,7 @@ def _platform_name() -> str: "restore": command_restore, "delete": command_delete, "reindex": command_reindex, + "ingest": command_ingest, "help": command_help, "version": command_version, } diff --git a/loch/format.py b/loch/format.py new file mode 100644 index 0000000..ed06347 --- /dev/null +++ b/loch/format.py @@ -0,0 +1,176 @@ +import hashlib +import json +from collections.abc import Iterable, Iterator +from dataclasses import dataclass, field +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.""" + + +def canonical(value: Any) -> bytes: + """The one encoding every id is computed over. Sorted keys and compact + separators make it independent of construction order. `surrogatepass` + because a transcript can hold a lone surrogate (a `\\ud83d` cut from its + pair), and refusing to hash it would drop a real record. + + Floats go through Python's shortest round-trip repr, which agrees with + RFC 8785 for every value that has no exponent. See SPEC.md.""" + return json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode("utf-8", "surrogatepass") + + +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..610141f --- /dev/null +++ b/loch/ingest.py @@ -0,0 +1,398 @@ +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 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 + + for number, record in ordered: + classified = classify(record) + if classified is None: + continue + kind, author, blocks = classified + 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) + + session: dict[str, Any] = {} + 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" 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/test/test_cli.py b/test/test_cli.py index 1925cff..f5ae18b 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,68 @@ 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") 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..9cfbd79 --- /dev/null +++ b/test/test_format.py @@ -0,0 +1,130 @@ +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_hashes_a_lone_surrogate_rather_than_failing() -> None: + assert digest({"text": "\ud83d"}).startswith("sha256:") + + +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}']) diff --git a/test/test_ingest.py b/test/test_ingest.py new file mode 100644 index 0000000..a7330dd --- /dev/null +++ b/test/test_ingest.py @@ -0,0 +1,328 @@ +import json +from pathlib import Path +from typing import Any + +from loch.format import pack_derived, read_derived +from loch.ingest import ESCAPE, HOME, ROOT, ROOT_SLUG, SESSION, Origin, convert, ingest +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] From e94e598711f134a9770439d7211d3bf25300ff3c Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 5 Nov 2026 14:38:03 -0500 Subject: [PATCH 03/16] Specify loch format v1 and record the new direction in CLAUDE.md SPEC.md covers the three layers (raw source, derived file, tools), the hashed turn core, content blocks, normalization, heads, the derived file layout and the Claude Code mapping with corpus measurements. Storage, git pins and native turns are described as intended shapes, and unsettled questions are listed in section 13. CLAUDE.md now says where the loch format sits relative to the existing non-goals: a derived projection rather than a source of truth, content still kept out of git, and per-turn pins as a deliberate exception to branch-level linking. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 67 ++++++++-- README.md | 4 + SPEC.md | 364 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 423 insertions(+), 12 deletions(-) create mode 100644 SPEC.md diff --git a/CLAUDE.md b/CLAUDE.md index 8618473..5d8b575 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.14. ## 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,9 +145,11 @@ 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 ├── git.py # current branch of a checkout, for the list default ├── output.py # result envelope, the two renderers, structured failures @@ -140,9 +157,25 @@ loch/ ├── 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 §13.8). + +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: ``` @@ -656,6 +689,16 @@ 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, ~18ms each) and the +derived files read back verified and byte-identical; re-ingest is +idempotent. 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, capture git pins, or emit back to Claude Code JSONL. Nothing is +shared in this format yet, so SPEC.md §13.1 — what a converter fix that +changes ids should do — is still free to answer. The bundle format and +everything `save`/`restore` do are unchanged. + ## Conventions - Verify before committing: `poetry run ruff check`, diff --git a/README.md b/README.md index dfbad0f..97a49e4 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,10 @@ itself for `list`/`reindex` and `s3:DeleteObject` for `delete`. | `LOCH_S3_ENDPOINT` | custom endpoint for R2, MinIO, Backblaze, ... | | `LOCH_S3_REGION` | region override | +`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..d80e94f --- /dev/null +++ b/SPEC.md @@ -0,0 +1,364 @@ +# 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:** UTF-8, keys sorted, separators `,` and `:` with no + whitespace, non-ASCII written literally, NaN and Infinity rejected. Lone + surrogates are encoded with `surrogatepass` rather than refused, since real + transcripts contain them. +- **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. +- **Numbers:** floats use the shortest round-trip form, which matches RFC 8785 + for every value without an exponent (§13.4). + +## 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`, `event`, `compaction`, and reserved for native turns, `approval` and `note`. | +| `author` | `{"kind": "human" \| "agent" \| "tool" \| "system", ...}`. A human may carry `id`; 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`. +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.15). + +## 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.9). + +**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` | `event` | system | +| 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`. + +**Human author.** Given at ingest (`--author`). When absent, 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 (§13.8). + +## 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 | + +lochy 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. + +Intended layout, extending the existing store: + +``` +raw/ raw source file +content/ content object +turns/ turn core +``` + +## 10. Git pins (not yet implemented) + +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 + +- **Converter version** bumps when derived output changes. Re-derive old + files. +- **Format major version** (`loch`) bumps when the core changes meaning, and + is the only change that changes ids. +- **Adding a block type, fact or header field** is not a version change. + Readers ignore what they don't know. +- **A converter fix that changes core bytes changes ids.** Policy in §13.1. + +## 13. Open questions + +1. **Converter fixes vs stable ids.** Fixing how a record normalizes changes + its turn id and every descendant's. Options: + - freeze core-affecting converter behaviour per format major + - emit `supersedes` records mapping old ids to new + - accept churn until anything is shared + + Nothing is shared yet, so this is cheap to decide now and expensive later. +2. **Human identity.** What is an author `id`: email, SSH or GPG key + fingerprint, a DID? Because the author is in the core, two people + ingesting the same raw source with different `--author` get different + ids. Is the ingester really the author of a Claude transcript's human + turns? +3. **Tombstones aren't fully private.** A low-entropy content object ("yes", + "lgtm") can be confirmed from its hash after deletion. Option: a salt + inside the content object, derived deterministically per source so + re-ingest stays idempotent. +4. **Floats.** Python's repr diverges from RFC 8785 for exponent forms + (`1e+21` vs `1e21`). A second implementation in another language must + match bit for bit. Adopt RFC 8785 exactly? +5. **Turn granularity.** One turn per record is faithful and keeps Claude's + tree, but merge and review probably want message-level units. Should + message-level grouping be a derived view, which is the v1 answer, or the + identity unit? +6. **Should `context` and `event` turns be in the graph at all?** Hook + summaries, attachments and reminders are Claude Code internals that shape + the model's context. Today they are hashed turns (about 26% of all turns) + carrying `x-claude-code:*` payloads, so their identity depends on Claude + Code's internal record shapes. +7. **Sessions that moved directories.** Only the final cwd becomes + `{{loch:root}}`. Earlier cwds normalize under `{{loch:home}}`, so a copy + that moves the two directories differently won't match. Numbered roots? +8. **Content that names the destination.** A transcript that already + contains the path it is later restored to is indistinguishable from a + rewritten one. It happened once in 3,810 sessions, and that session was + the one that built this test. +9. **Subagents.** Sidechain transcripts are hashed in the source but not + converted. Natural shape: a child graph whose root's parent is the + `tool-call` turn that spawned it. +10. **Spilled tool output** (`tool-results/`) is referenced by path from + content. Inline it, or reference its source blob by hash? +11. **Images** are inline base64 inside content. Separate blob objects would + dedupe and could be deleted independently. +12. **Raw snapshots.** Claude appends to live files, so "immutable raw source" + means snapshotting at ingest. Should `ingest` write `raw/` to a + store? Appending a session and re-ingesting keeps every earlier turn id + (tested), so incremental ingest is safe. +13. **Pin capture.** Historical transcripts record a branch, never a commit. + Capture pins live (a hook in the driving tool), infer them from + `git commit` tool output, or both? And `refs/loch/pins/*` vs git notes. +14. **Envelopes in git** go against lochy's "not git-backed" decision only + in part: envelopes hold kinds, authors, hashes and structure, not text. + Is structure alone sensitive enough to rule git out too? +15. **Conversation identity.** Heads name leaves, but what names "the + conversation" across forks and machines — the root turn id, a + conversation object, or nothing? +16. **Resume from a derived-only share.** Thinking signatures and + `toolUseResult` stay in the raw source, so the emitter (loch → Claude + Code) can resume natively only with the raw source at hand. Otherwise it + synthesizes context. From dbed987c9829e76738d0ad30ebe4c2a3744bbcd3 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 5 Nov 2026 14:46:52 -0500 Subject: [PATCH 04/16] Point links at the renamed ness-dev/loch repo Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- test/test_redact.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 97a49e4..613b4f0 100644 --- a/README.md +++ b/README.md @@ -16,14 +16,14 @@ Currently supports Claude Code. ## Install ```sh -uv tool install https://github.com/ness-dev/lochy/releases/download/v0.1.0/loch-0.1.0-py3-none-any.whl +uv tool install https://github.com/ness-dev/loch/releases/download/v0.1.0/loch-0.1.0-py3-none-any.whl loch --version ``` The wheel is `py3-none-any`, and [uv](https://docs.astral.sh/uv/) is a static binary that brings its own CPython, so this needs no Python on the machine and no PyPI account behind it. Releases are attached to -[GitHub releases](https://github.com/ness-dev/lochy/releases) as a wheel +[GitHub releases](https://github.com/ness-dev/loch/releases) as a wheel and an sdist. Python 3.10 or newer if you'd rather install it yourself — `pipx install`, @@ -34,7 +34,7 @@ in. The backend imports boto3 lazily, so a `file://` store never loads it and paying 27MB for a dependency most installs never reach isn't worth it: ```sh -uv tool install "loch[s3] @ https://github.com/ness-dev/lochy/releases/download/v0.1.0/loch-0.1.0-py3-none-any.whl" +uv tool install "loch[s3] @ https://github.com/ness-dev/loch/releases/download/v0.1.0/loch-0.1.0-py3-none-any.whl" ``` Without it, an `s3://` store fails with `code: "s3-extra-missing"` rather than diff --git a/test/test_redact.py b/test/test_redact.py index 59acd4b..f6c52eb 100644 --- a/test/test_redact.py +++ b/test/test_redact.py @@ -95,7 +95,7 @@ def test_ordinary_transcript_content_survives_untouched() -> None: line(message="I refactored rewrite.py to keep the single-pass property."), line(commit="c4056e9a1f2b3c4d5e6f708192a3b4c5d6e7f809"), line(uuid="3f2a1b4c-5d6e-4f70-8192-a3b4c5d6e7f8"), - line(note="see https://github.com/ness-dev/lochy for the source"), + line(note="see https://github.com/ness-dev/loch for the source"), line(usage={"input_tokens": 12345678, "output_tokens": 4096}), line(path="~/.claude/projects/-Users-mike-proj/abc.jsonl"), line(sha256="a" * 64), From 5a2cc6bf653d16c61928728e8efb002d05024574 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 5 Nov 2026 14:46:57 -0500 Subject: [PATCH 05/16] Refer to the bundle store rather than lochy in SPEC.md Co-Authored-By: Claude Opus 5.5 --- SPEC.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SPEC.md b/SPEC.md index d80e94f..9bcc115 100644 --- a/SPEC.md +++ b/SPEC.md @@ -247,7 +247,7 @@ Two object kinds, stored apart: | 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 | -lochy chose S3 over git because a leaked secret in git can't be deleted. That +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 @@ -352,7 +352,7 @@ the core, so a turn can gain signatures without changing identity. 13. **Pin capture.** Historical transcripts record a branch, never a commit. Capture pins live (a hook in the driving tool), infer them from `git commit` tool output, or both? And `refs/loch/pins/*` vs git notes. -14. **Envelopes in git** go against lochy's "not git-backed" decision only +14. **Envelopes in git** go against the bundle store.s "not git-backed" decision only in part: envelopes hold kinds, authors, hashes and structure, not text. Is structure alone sensitive enough to rule git out too? 15. **Conversation identity.** Heads name leaves, but what names "the From 6eb7b0dc5edc3e7f81d582b54539c861b1849265 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 5 Nov 2026 15:48:09 -0500 Subject: [PATCH 06/16] Canonicalize per RFC 8785, fold agent events into facts, add --author-key canonical() is now RFC 8785 written out: ECMAScript number formatting, UTF-16 key order, and lone surrogates escaped. Integers stay exact at any size, the one deliberate departure. System records other than compaction boundaries (hook summaries, turn durations, API retries) no longer become turns. They go into the preceding turn's facts.events, and their uuid resolves to that turn, so ids are the same with or without them. ingest --author-key sets the human author to ssh:SHA256:, the same string ssh-keygen -l prints. A bad key fails with author-key-unreadable. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HcfcCN7pccwK1zeXf9hZqA --- loch/cli.py | 26 +++++++++-- loch/format.py | 109 ++++++++++++++++++++++++++++++++++++++------ loch/ingest.py | 54 +++++++++++++++++++++- test/test_cli.py | 16 +++++++ test/test_format.py | 43 +++++++++++++++-- test/test_ingest.py | 77 ++++++++++++++++++++++++++++++- 6 files changed, 300 insertions(+), 25 deletions(-) diff --git a/loch/cli.py b/loch/cli.py index b851313..3052798 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -45,7 +45,14 @@ reindex, value_prefix, ) -from .ingest import CONVERTER, Origin, derived_name, ingest +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 ( @@ -68,7 +75,8 @@ loch restore [--into ] [--store ] [--force] [--new-id] loch delete [--store ] loch reindex [--store ] - loch ingest [--cwd ] [--branch ] [--session ] [--author ] + loch ingest [--cwd ] [--branch ] [--session ] + [--author | --author-key ] [--out ] loch --version @@ -604,9 +612,19 @@ def command_ingest(argv: list[str]) -> Result: 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}") @@ -618,9 +636,7 @@ def command_ingest(argv: list[str]) -> Result: results: list[dict[str, Any]] = [] lines: list[str] = [] for meta in sessions: - derived = ingest( - meta.path, Origin(meta.cwd, home, meta.session_id), args.author - ) + 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( diff --git a/loch/format.py b/loch/format.py index ed06347..0d8677b 100644 --- a/loch/format.py +++ b/loch/format.py @@ -1,7 +1,9 @@ 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 @@ -14,21 +16,100 @@ class FormatError(ValueError): 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: - """The one encoding every id is computed over. Sorted keys and compact - separators make it independent of construction order. `surrogatepass` - because a transcript can hold a lone surrogate (a `\\ud83d` cut from its - pair), and refusing to hash it would drop a real record. - - Floats go through Python's shortest round-trip repr, which agrees with - RFC 8785 for every value that has no exponent. See SPEC.md.""" - return json.dumps( - value, - sort_keys=True, - separators=(",", ":"), - ensure_ascii=False, - allow_nan=False, - ).encode("utf-8", "surrogatepass") + """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: diff --git a/loch/ingest.py b/loch/ingest.py index 610141f..4c77a9a 100644 --- a/loch/ingest.py +++ b/loch/ingest.py @@ -1,3 +1,5 @@ +import base64 +import hashlib import heapq import json import os @@ -255,6 +257,33 @@ def _facts( 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]]: @@ -284,12 +313,16 @@ def convert( 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) @@ -310,7 +343,6 @@ def convert( turns[turn.id] = turn has_children.update(parents) - session: dict[str, Any] = {} current = last_turn for _, record in records: record_type = record.get("type") @@ -396,3 +428,23 @@ 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/test/test_cli.py b/test/test_cli.py index f5ae18b..932f149 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -1113,3 +1113,19 @@ def test_ingest_fails_when_nothing_matches( ) 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_format.py b/test/test_format.py index 9cfbd79..b23c80b 100644 --- a/test/test_format.py +++ b/test/test_format.py @@ -29,10 +29,6 @@ def test_canonical_is_compact_and_keeps_non_ascii() -> None: assert canonical({"a": "é", "b": [1, 2]}) == '{"a":"é","b":[1,2]}'.encode() -def test_canonical_hashes_a_lone_surrogate_rather_than_failing() -> None: - assert digest({"text": "\ud83d"}).startswith("sha256:") - - def test_canonical_refuses_nan() -> None: with pytest.raises(ValueError): canonical({"x": float("nan")}) @@ -128,3 +124,42 @@ def test_rejects_a_turn_before_its_parent() -> None: 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 index a7330dd..64b6a53 100644 --- a/test/test_ingest.py +++ b/test/test_ingest.py @@ -1,9 +1,24 @@ +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, Origin, convert, ingest +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" @@ -326,3 +341,63 @@ def test_appending_to_a_session_keeps_every_earlier_turn_id(tmp_path: Path) -> N 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") From 2fcc468e81326cb12ef3e4eda13dd525655e31f8 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 5 Nov 2026 15:48:09 -0500 Subject: [PATCH 07/16] Record the settled format decisions in SPEC.md The first draft's open questions are now a decisions table in section 13, each with its reason. Section 14 keeps the one still open (salting content hashes) and the known destination-path limit. Section 12 now states that ids may change until the first share, and that after that an id-changing converter change bumps the format version and ships a supersedes map. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HcfcCN7pccwK1zeXf9hZqA --- CLAUDE.md | 27 ++++++--- SPEC.md | 166 +++++++++++++++++++++++++++--------------------------- 2 files changed, 100 insertions(+), 93 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5d8b575..e568d24 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,7 @@ travel with the code they produced. 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.14. + question — SPEC.md §9 and §13. ## Design decisions and their reasoning @@ -169,7 +169,7 @@ 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 §13.8). +is a transcript that already contains the destination paths (SPEC.md §14.2). 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 @@ -484,6 +484,7 @@ 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 | | `unknown-command` | no such subcommand | | `usage` | argparse rejected the arguments (exit status 2) | | `internal` | an unexpected exception | @@ -690,15 +691,23 @@ Claude Code. 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, ~18ms each) and the -derived files read back verified and byte-identical; re-ingest is -idempotent. 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, capture git pins, or emit back to Claude Code JSONL. Nothing is -shared in this format yet, so SPEC.md §13.1 — what a converter fix that -changes ids should do — is still free to answer. The bundle format and +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 settled in SPEC.md §13; the one still open is §14.1, salting +content hashes. 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/SPEC.md b/SPEC.md index 9bcc115..1c3b1c7 100644 --- a/SPEC.md +++ b/SPEC.md @@ -35,14 +35,22 @@ tools (Ness, review UIs, sync, merge) ← read loch only ## 3. Encoding and ids -- **Canonical JSON:** UTF-8, keys sorted, separators `,` and `:` with no - whitespace, non-ASCII written literally, NaN and Infinity rejected. Lone - surrogates are encoded with `surrogatepass` rather than refused, since real - transcripts contain them. +- **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. -- **Numbers:** floats use the shortest round-trip form, which matches RFC 8785 - for every value without an exponent (§13.4). ## 4. The turn @@ -62,8 +70,8 @@ A turn is one node in the conversation graph. Its id is the hash of its | field | meaning | | --- | --- | | `loch` | Format major version. A change to the core's meaning bumps it. | -| `kind` | `message`, `tool-result`, `context`, `event`, `compaction`, and reserved for native turns, `approval` and `note`. | -| `author` | `{"kind": "human" \| "agent" \| "tool" \| "system", ...}`. A human may carry `id`; agent, tool and system authors carry `agent` (e.g. `claude-code`). Absent fields are omitted, never `null`. | +| `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. | @@ -103,7 +111,8 @@ derived file hasn't lost anything. 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`. +(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 @@ -140,7 +149,7 @@ The origin values themselves appear only in the derived file's header. 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.15). +outside the derived file (§13, conversation identity). ## 7. Derived file @@ -187,7 +196,7 @@ byte-identical. 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.9). +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 @@ -214,7 +223,7 @@ against a real corpus of 3,810 sessions: | other `user` | `message` | the ingesting human | | `attachment` | `context` | system | | `system`, `compact_boundary` subtype | `compaction` | system | -| other `system` | `event` | 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. @@ -225,8 +234,14 @@ against a real corpus of 3,810 sessions: 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`. - -**Human author.** Given at ingest (`--author`). When absent, human turns are +- **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. @@ -236,7 +251,7 @@ the environment, because it is part of every id. - 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 (§13.8). + already names the destination paths (§14.2). ## 9. Storage: envelope and content (not yet implemented) @@ -293,72 +308,55 @@ the core, so a turn can gain signatures without changing identity. ## 12. Evolving -- **Converter version** bumps when derived output changes. Re-derive old - files. -- **Format major version** (`loch`) bumps when the core changes meaning, and - is the only change that changes ids. -- **Adding a block type, fact or header field** is not a version change. - Readers ignore what they don't know. -- **A converter fix that changes core bytes changes ids.** Policy in §13.1. - -## 13. Open questions - -1. **Converter fixes vs stable ids.** Fixing how a record normalizes changes - its turn id and every descendant's. Options: - - freeze core-affecting converter behaviour per format major - - emit `supersedes` records mapping old ids to new - - accept churn until anything is shared - - Nothing is shared yet, so this is cheap to decide now and expensive later. -2. **Human identity.** What is an author `id`: email, SSH or GPG key - fingerprint, a DID? Because the author is in the core, two people - ingesting the same raw source with different `--author` get different - ids. Is the ingester really the author of a Claude transcript's human - turns? -3. **Tombstones aren't fully private.** A low-entropy content object ("yes", - "lgtm") can be confirmed from its hash after deletion. Option: a salt - inside the content object, derived deterministically per source so - re-ingest stays idempotent. -4. **Floats.** Python's repr diverges from RFC 8785 for exponent forms - (`1e+21` vs `1e21`). A second implementation in another language must - match bit for bit. Adopt RFC 8785 exactly? -5. **Turn granularity.** One turn per record is faithful and keeps Claude's - tree, but merge and review probably want message-level units. Should - message-level grouping be a derived view, which is the v1 answer, or the - identity unit? -6. **Should `context` and `event` turns be in the graph at all?** Hook - summaries, attachments and reminders are Claude Code internals that shape - the model's context. Today they are hashed turns (about 26% of all turns) - carrying `x-claude-code:*` payloads, so their identity depends on Claude - Code's internal record shapes. -7. **Sessions that moved directories.** Only the final cwd becomes - `{{loch:root}}`. Earlier cwds normalize under `{{loch:home}}`, so a copy - that moves the two directories differently won't match. Numbered roots? -8. **Content that names the destination.** A transcript that already - contains the path it is later restored to is indistinguishable from a - rewritten one. It happened once in 3,810 sessions, and that session was - the one that built this test. -9. **Subagents.** Sidechain transcripts are hashed in the source but not - converted. Natural shape: a child graph whose root's parent is the - `tool-call` turn that spawned it. -10. **Spilled tool output** (`tool-results/`) is referenced by path from - content. Inline it, or reference its source blob by hash? -11. **Images** are inline base64 inside content. Separate blob objects would - dedupe and could be deleted independently. -12. **Raw snapshots.** Claude appends to live files, so "immutable raw source" - means snapshotting at ingest. Should `ingest` write `raw/` to a - store? Appending a session and re-ingesting keeps every earlier turn id - (tested), so incremental ingest is safe. -13. **Pin capture.** Historical transcripts record a branch, never a commit. - Capture pins live (a hook in the driving tool), infer them from - `git commit` tool output, or both? And `refs/loch/pins/*` vs git notes. -14. **Envelopes in git** go against the bundle store.s "not git-backed" decision only - in part: envelopes hold kinds, authors, hashes and structure, not text. - Is structure alone sensitive enough to rule git out too? -15. **Conversation identity.** Heads name leaves, but what names "the - conversation" across forks and machines — the root turn id, a - conversation object, or nothing? -16. **Resume from a derived-only share.** Thinking signatures and - `toolUseResult` stay in the raw source, so the emitter (loch → Claude - Code) can resume natively only with the raw source at hand. Otherwise it - synthesizes context. +- **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. | + +## 14. Open + +1. **Salting content hashes.** A deleted low-entropy content object ("yes", + "lgtm", "run the tests") can be confirmed by anyone holding its envelope: + hash the guess and compare. Chaining doesn't help, because content is + hashed on its own so it can be deleted on its own, and the guesser can + see the parents anyway. A salt stored inside the content object goes when + the content goes, which closes the hole. To keep re-ingest idempotent the + salt must be deterministic, so it would be + `HMAC(owner secret, source id + record position)`. + + The cost: re-deriving the same ids then needs the owner's secret, so + losing it means the next converter upgrade changes ids. Awaiting a + decision. +2. **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. From eddb89b70bb6e701f44817fb103db8900added36 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Fri, 6 Nov 2026 10:44:20 -0500 Subject: [PATCH 08/16] Settle content-hash salting: no salt, privacy is not a goal Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HcfcCN7pccwK1zeXf9hZqA --- CLAUDE.md | 6 +++--- SPEC.md | 24 +++++++----------------- 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e568d24..43d3681 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -169,7 +169,7 @@ 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.2). +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 @@ -693,8 +693,8 @@ 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 settled in SPEC.md §13; the one still open is §14.1, salting -content hashes. What it doesn't do yet: write anything to a store (derived +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 diff --git a/SPEC.md b/SPEC.md index 1c3b1c7..3c7cc19 100644 --- a/SPEC.md +++ b/SPEC.md @@ -251,7 +251,7 @@ the environment, because it is part of every id. - 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.2). + already names the destination paths (§14.1). ## 9. Storage: envelope and content (not yet implemented) @@ -266,7 +266,8 @@ The bundle store chose S3 over git because a leaked secret in git can't be delet 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. +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: @@ -341,22 +342,11 @@ These were open in the first draft. Each is settled, with the reason. | 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. | +| 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. Open - -1. **Salting content hashes.** A deleted low-entropy content object ("yes", - "lgtm", "run the tests") can be confirmed by anyone holding its envelope: - hash the guess and compare. Chaining doesn't help, because content is - hashed on its own so it can be deleted on its own, and the guesser can - see the parents anyway. A salt stored inside the content object goes when - the content goes, which closes the hole. To keep re-ingest idempotent the - salt must be deterministic, so it would be - `HMAC(owner secret, source id + record position)`. - - The cost: re-deriving the same ids then needs the owner's secret, so - losing it means the next converter upgrade changes ids. Awaiting a - decision. -2. **Content that names the destination.** A known limit rather than a +## 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. From a0e2482d6b8e9bbe263f63bd2820548e1822b835 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Fri, 6 Nov 2026 15:23:47 -0500 Subject: [PATCH 09/16] Record tombstones over git's rewrite-on-delete in SPEC.md Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HcfcCN7pccwK1zeXf9hZqA --- SPEC.md | 1 + 1 file changed, 1 insertion(+) diff --git a/SPEC.md b/SPEC.md index 3c7cc19..465f793 100644 --- a/SPEC.md +++ b/SPEC.md @@ -342,6 +342,7 @@ These were open in the first draft. Each is settled, with the reason. | 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 From 361428140bfd1776dd8d27f48612a7e92a2552c3 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Fri, 6 Nov 2026 15:37:16 -0500 Subject: [PATCH 10/16] Add loch blame and ask: link commits to the conversations that made them Claude Code hooks note each agent commit on refs/notes/loch with the session and tool call that made it, and snapshot transcripts into the store before Claude's 30-day cleanup can delete them. backfill links earlier commits by exact match only. blame resolves each line to the prompt behind it; ask forks the conversation right after the commit and resumes it in Claude Code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HcfcCN7pccwK1zeXf9hZqA --- CLAUDE.md | 22 ++ README.md | 24 ++ SPEC.md | 21 +- loch/cli.py | 265 ++++++++++++++++++ loch/trace.py | 678 +++++++++++++++++++++++++++++++++++++++++++++ test/test_trace.py | 283 +++++++++++++++++++ 6 files changed, 1292 insertions(+), 1 deletion(-) create mode 100644 loch/trace.py create mode 100644 test/test_trace.py diff --git a/CLAUDE.md b/CLAUDE.md index 43d3681..7fabb13 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -151,6 +151,7 @@ loch/ ├── 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, backfill, ask's fork ├── 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 @@ -485,6 +486,11 @@ never a code. The set today: | `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`/`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 | @@ -682,6 +688,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. + 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 diff --git a/README.md b/README.md index 613b4f0..17105b1 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,28 @@ 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 ask loch/format.py:105 "why not just json.dumps?" +# forks that conversation right after the commit and resumes it in Claude Code +``` + +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 up to that commit, 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 +145,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 diff --git a/SPEC.md b/SPEC.md index 465f793..8936337 100644 --- a/SPEC.md +++ b/SPEC.md @@ -277,7 +277,26 @@ content/ content object turns/ turn core ``` -## 10. Git pins (not yet implemented) +## 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: diff --git a/loch/cli.py b/loch/cli.py index 3052798..c74ce35 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -1,8 +1,10 @@ import argparse import importlib.metadata +import json import os import platform import re +import shutil import socket import sys import time @@ -63,6 +65,22 @@ 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_at_call, + git, + hook_post_tool, + hook_pre_tool, + install_hooks, + repo_root, + snapshot_transcript, +) DEFAULT_DERIVED = os.path.join(str(Path.home()), ".loch", "derived") @@ -78,6 +96,11 @@ loch ingest [--cwd ] [--branch ] [--session ] [--author | --author-key ] [--out ] + loch install [--local] [--command ] + loch blame [--store ] + loch ask [] [--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- @@ -93,6 +116,12 @@ 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; `ask` forks that +conversation at the commit and resumes it in Claude Code. """ @@ -666,6 +695,237 @@ def command_ingest(argv: list[str]) -> Result: ) +@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 _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 = "" + if link.prompt: + flat = " ".join(link.prompt.split()) + flat = flat if len(flat) <= 72 else flat[:71] + "…" + prompt = f' — asked: "{flat}"' + + return f"session {link.session_id[:8]}{title}{prompt}" + + +def command_blame(argv: list[str]) -> Result: + parser = _parser("blame") + parser.add_argument("file") + 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) + + rows: list[dict[str, Any]] = [] + lines = [f"{args.file}\n"] + 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, + "conversation": link.payload() if link is not None else None, + } + ) + 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 {args.file}:\n" + ) + return Result( + command="blame", + payload={"file": args.file, "hunks": rows}, + text="".join(lines), + ) + + +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("--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_at_call( + link.transcript, link.call, root, 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, + }, + "launch": command, + } + text = ( + f"forked session {fork.origin_session[:8]} at {commit[:7]} " + f"({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 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) + 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) @@ -702,6 +962,11 @@ def _platform_name() -> str: "delete": command_delete, "reindex": command_reindex, "ingest": command_ingest, + "install": command_install, + "blame": command_blame, + "ask": command_ask, + "backfill": command_backfill, + "hook": command_hook, "help": command_help, "version": command_version, } diff --git a/loch/trace.py b/loch/trace.py new file mode 100644 index 0000000..cd92195 --- /dev/null +++ b/loch/trace.py @@ -0,0 +1,678 @@ +"""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 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 + + +def blame_hunks(cwd: str, path: str) -> list[Hunk]: + porcelain = git(cwd, "blame", "--porcelain", "--", path) + summaries: dict[str, str] = {} + lines: list[tuple[int, str]] = [] + current = "" + for line in porcelain.splitlines(): + if line.startswith("\t"): + continue + parts = line.split(" ") + if len(parts) >= 3 and len(parts[0]) == 40 and parts[1].isdigit(): + current = parts[0] + lines.append((int(parts[2]), current)) + elif line.startswith("summary "): + summaries[current] = line[len("summary ") :] + + hunks: list[Hunk] = [] + for number, commit 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) + else: + hunks.append(Hunk(number, number, commit, summaries.get(commit, ""))) + return hunks + + +@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") -> 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} + calls: list[Call] = [] + 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 not name.endswith(".jsonl"): + continue + path = os.path.join(directory, name) + try: + raw = Path(path).read_text(encoding="utf-8", errors="replace") + except OSError: + continue + if "git commit" in raw and any(subject in raw for subject in subjects): + calls.extend(commit_calls(path)) + + 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_at_call( + transcript: str, call: str, target_cwd: str, title: str | None = None +) -> Fork: + """A new Claude session holding the conversation up to and including the + result of `call`, filed under `target_cwd` so `claude --resume` finds it. + + The cut is after the whole round of tool results the 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. The original session is never modified.""" + raw = Path(transcript).read_text(encoding="utf-8", errors="surrogateescape") + records = [ + record for record in _records_of(raw) if isinstance(record.get("uuid"), str) + ] + by_uuid = {record["uuid"]: record for record in records} + children: dict[str, list[dict[str, Any]]] = {} + for record in records: + parent = _parent(record) + if parent is not None: + children.setdefault(parent, []).append(record) + + 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] + + 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_trace.py b/test/test_trace.py new file mode 100644 index 0000000..4e51a4d --- /dev/null +++ b/test/test_trace.py @@ -0,0 +1,283 @@ +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_at_call, + 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"') + + linked = backfill(str(repo), "HEAD") + assert [sha for sha, _ in linked] == [inside] + 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_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_at_call(path, CALL, str(target)) + + 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) From 1294b1592c16de70b568d4a3c7d61ba02d9a7592 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Fri, 6 Nov 2026 16:42:11 -0500 Subject: [PATCH 11/16] Make ask resume the whole conversation by default, --at-commit to cut Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HcfcCN7pccwK1zeXf9hZqA --- README.md | 5 +++-- loch/cli.py | 22 +++++++++++++++------- loch/trace.py | 41 +++++++++++++++++++++++++++++++---------- test/test_trace.py | 20 ++++++++++++++++++-- 4 files changed, 67 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 17105b1..1848306 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,8 @@ loch blame loch/format.py # session 37d467e5 "loch-format-v1" — asked: "none of those seem like open questions…" loch ask loch/format.py:105 "why not just json.dumps?" -# forks that conversation right after the commit and resumes it in Claude Code +# 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 ``` With the hooks installed, every commit an agent makes gets a git note on @@ -97,7 +98,7 @@ With the hooks installed, every commit an agent makes gets a git note on 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 up to that commit, filed under +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 diff --git a/loch/cli.py b/loch/cli.py index c74ce35..10f39b4 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -73,7 +73,7 @@ TraceError, backfill, blame_hunks, - fork_at_call, + fork_session, git, hook_post_tool, hook_pre_tool, @@ -98,7 +98,8 @@ [--out ] loch install [--local] [--command ] loch blame [--store ] - loch ask [] [--no-launch] [--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 @@ -121,7 +122,8 @@ 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; `ask` forks that -conversation at the commit and resumes it in Claude Code. +conversation and resumes it in Claude Code — from its end, or with +--at-commit from just after the commit. """ @@ -855,6 +857,7 @@ 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) @@ -872,8 +875,11 @@ def command_ask(argv: list[str]) -> Result: f"session {link.session_id} is linked but its transcript is " "neither in ~/.claude/projects nor in the store", ) - fork = fork_at_call( - link.transcript, link.call, root, title=f"loch ask {commit[:7]}" + 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] @@ -888,11 +894,13 @@ def command_ask(argv: list[str]) -> Result: "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]} at {commit[:7]} " - f"({fork.records} records) as {fork.session_id}\n" + 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( diff --git a/loch/trace.py b/loch/trace.py index cd92195..242f335 100644 --- a/loch/trace.py +++ b/loch/trace.py @@ -594,27 +594,37 @@ def _parent(record: dict[str, Any]) -> str | None: return parent if isinstance(parent, str) else None -def fork_at_call( - transcript: str, call: str, target_cwd: str, title: str | None = 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 up to and including the - result of `call`, filed under `target_cwd` so `claude --resume` finds it. - - The cut is after the whole round of tool results the 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. The original session is never modified.""" + """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) ] - by_uuid = {record["uuid"]: record for record in records} 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 @@ -640,7 +650,18 @@ def fork_at_call( 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: diff --git a/test/test_trace.py b/test/test_trace.py index 4e51a4d..c346d03 100644 --- a/test/test_trace.py +++ b/test/test_trace.py @@ -12,7 +12,7 @@ from loch.trace import ( Resolver, backfill, - fork_at_call, + fork_session, hook_post_tool, hook_pre_tool, install_hooks, @@ -272,7 +272,7 @@ def test_fork_cuts_after_the_whole_round_and_leaves_the_original( target = env["tmp"] / "elsewhere" target.mkdir() - fork = fork_at_call(path, CALL, str(target)) + 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()] @@ -281,3 +281,19 @@ def test_fork_cuts_after_the_whole_round_and_leaves_the_original( 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] From 885200e85ac33ec8587bef82d2d14e9c4d96336e Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Mon, 9 Nov 2026 10:27:45 -0500 Subject: [PATCH 12/16] Show blame as the file itself, each line marked by its conversation The hunk list made you map line ranges back to the file in your head. The default is now every line with a margin mark per request and a key at the top; --hunks keeps the old view, and --json gains the key and each hunk's mark. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HcfcCN7pccwK1zeXf9hZqA --- README.md | 30 +++++++++- loch/cli.py | 143 ++++++++++++++++++++++++++++++++++++++++----- loch/trace.py | 21 ++++--- test/test_trace.py | 24 ++++++++ 4 files changed, 193 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 1848306..78e02fc 100644 --- a/README.md +++ b/README.md @@ -84,15 +84,39 @@ sessions produces a single ref. 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 loch/format.py # every line, marked by the conversation that wrote it +loch blame --hunks loch/format.py # or one row per block of lines 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` prints the file with a mark in the margin for each conversation, and a +key at the top saying what each mark asked for: + +``` +loch/format.py — 2 conversations + + A "I would prefer this tool to be agnostic of the editor that …" 37d467e5 · 45b565e + B "honeslty none of those seem like open questions they all se…" 37d467e5 · 6eb7b0d + +A 1 │ import hashlib +A 2 │ import json +B 3 │ import re +A 4 │ from collections.abc import Iterable, Iterator + ... +A 101 │ def canonical(value: Any) -> bytes: +B 102 │ """RFC 8785 (JSON Canonicalization Scheme): the one encoding every id is +B 103 │ computed over, so a second implementation in any language can reproduce +B 104 │ an id byte for byte. Keys sort by UTF-16 code units, numbers print as +B 105 │ ECMAScript does, and strings escape as JSON.stringify does. +``` + +Marks are per request rather than per session, so one long session that made +many commits for many asks doesn't paint the whole file one letter; `·` is a +commit with no conversation recorded and `+` a line not committed yet. + 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 diff --git a/loch/cli.py b/loch/cli.py index 10f39b4..02d288e 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -97,7 +97,7 @@ [--author | --author-key ] [--out ] loch install [--local] [--command ] - loch blame [--store ] + loch blame [--hunks] [--store ] loch ask [] [--at-commit] [--no-launch] [--store ] loch backfill [--revision ] (default: every branch) @@ -772,24 +772,46 @@ def _store_or_none(uri: str | None) -> Any: 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 = "" - if link.prompt: - flat = " ".join(link.prompt.split()) - flat = flat if len(flat) <= 72 else flat[:71] + "…" - prompt = f' — asked: "{flat}"' - + prompt = f' — asked: "{_flat(link.prompt, 72)}"' if link.prompt else "" return f"session {link.session_id[:8]}{title}{prompt}" +UNLINKED_MARK = "·" +UNCOMMITTED_MARK = "+" + +# Foreground colours for the margin marks, cycled. Only the mark is coloured: +# the code keeps the terminal's own colours, so it reads as code. +MARK_COLOURS = ("36", "33", "35", "32", "34", "31", "96", "93", "95", "92") + + +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 _use_colour() -> bool: + return sys.stdout.isatty() and "NO_COLOR" not in os.environ + + def command_blame(argv: list[str]) -> Result: parser = _parser("blame") parser.add_argument("file") + parser.add_argument("--hunks", action="store_true") parser.add_argument("--store") args = parser.parse_args(argv) @@ -803,8 +825,31 @@ def command_blame(argv: list[str]) -> Result: 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]] = [] - lines = [f"{args.file}\n"] for hunk in hunks: link = links.get(hunk.commit) rows.append( @@ -813,26 +858,94 @@ def command_blame(argv: list[str]) -> Result: "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) + if args.hunks + else _annotated_text(args.file, hunks, legend, mark_of, links) + ) + return Result( + command="blame", + payload={"file": args.file, "conversations": legend, "hunks": rows}, + text=text, + ) + + +def _annotated_text( + file: str, + hunks: list[Any], + legend: list[dict[str, Any]], + mark_of: dict[str, str], + links: dict[str, Link | None], +) -> str: + colour = _use_colour() + colours = { + entry["mark"]: MARK_COLOURS[index % len(MARK_COLOURS)] + for index, entry in enumerate(legend) + } + + def paint(mark: str, text: str) -> str: + code = colours.get(mark, "2") + return f"\033[{code}m{text}\033[0m" if colour else text + + width = max((len(entry["mark"]) for entry in legend), default=1) + count = len(legend) + out = [f"{file} — {count} conversation{'s' if count != 1 else ''}\n\n"] + for entry in legend: + if entry["available"]: + prompt = f'"{_flat(entry["prompt"], 60)}"' if entry["prompt"] else "" + else: + prompt = "(transcript not available)" + commits = ", ".join(commit[:7] for commit in entry["commits"]) + out.append( + f" {paint(entry['mark'], entry['mark'].ljust(width))} " + f"{prompt} {entry['session'][:8]} · {commits}\n" + ) + unlinked = sorted({c[:7] for c, m in mark_of.items() if m == UNLINKED_MARK}) + if unlinked: + out.append( + f" {paint(UNLINKED_MARK, UNLINKED_MARK.ljust(width))} " + f"no conversation recorded {', '.join(unlinked)}\n" + ) + if UNCOMMITTED_MARK in mark_of.values(): + out.append( + f" {paint(UNCOMMITTED_MARK, UNCOMMITTED_MARK.ljust(width))} " + "not committed yet\n" + ) + out.append("\n") + + digits = len(str(hunks[-1].end)) if hunks else 1 + for hunk in hunks: + mark = mark_of[hunk.commit] + for offset, line in enumerate(hunk.lines): + out.append( + f"{paint(mark, mark.ljust(width))} " + f"{hunk.start + offset:>{digits}} │ {line}\n" + ) + if legend: + out.append(f"\nfollow one up with: loch ask {file}:\n") + return "".join(out) + + +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 {args.file}:\n" - ) - return Result( - command="blame", - payload={"file": args.file, "hunks": rows}, - text="".join(lines), + f"follow one up with: loch ask {file}:\n" ) + return "".join(lines) def _resolve_commit(root: str, target: str) -> str: diff --git a/loch/trace.py b/loch/trace.py index 242f335..785821a 100644 --- a/loch/trace.py +++ b/loch/trace.py @@ -342,30 +342,37 @@ class Hunk: 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]] = [] + lines: list[tuple[int, str, str]] = [] current = "" - for line in porcelain.splitlines(): + 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 = parts[0] - lines.append((int(parts[2]), current)) + current, number = parts[0], int(parts[2]) elif line.startswith("summary "): summaries[current] = line[len("summary ") :] hunks: list[Hunk] = [] - for number, commit in sorted(lines): + 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) + hunks[-1] = Hunk( + last.start, number, commit, last.summary, (*last.lines, text) + ) else: - hunks.append(Hunk(number, number, commit, summaries.get(commit, ""))) + hunks.append( + Hunk(number, number, commit, summaries.get(commit, ""), (text,)) + ) return hunks diff --git a/test/test_trace.py b/test/test_trace.py index c346d03..6702f5b 100644 --- a/test/test_trace.py +++ b/test/test_trace.py @@ -297,3 +297,27 @@ def test_fork_without_a_call_runs_to_the_end_of_the_conversation( 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_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 two 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") + + monkeypatch.chdir(repo) + monkeypatch.setattr("sys.argv", ["loch", "blame", "f.txt"]) + main() + out = capsys.readouterr().out + assert ' A "make it two lines"' in out + assert "· 1 │ human line\n" in out + assert "A 2 │ agent line\n" in out + assert "+ 3 │ work in progress\n" in out + assert "\033[" not in out From 7fe700baff4ba4b15452107b074755e281cad5f5 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Mon, 9 Nov 2026 10:31:14 -0500 Subject: [PATCH 13/16] Restore the hunk view for terminal blame and add blame --html The margin-mark terminal view fought the shell. Terminal output is back to one row per block; --html renders every line tinted by its conversation, with a key, click-to-focus, and each line's loch ask command, as one self-contained page. --lines limits it to an excerpt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HcfcCN7pccwK1zeXf9hZqA --- CLAUDE.md | 1 + README.md | 34 ++---- loch/blame_html.py | 273 +++++++++++++++++++++++++++++++++++++++++++++ loch/cli.py | 109 ++++++------------ test/test_trace.py | 22 ++-- 5 files changed, 331 insertions(+), 108 deletions(-) create mode 100644 loch/blame_html.py diff --git a/CLAUDE.md b/CLAUDE.md index 7fabb13..fabe378 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -152,6 +152,7 @@ loch/ ├── 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, 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 diff --git a/README.md b/README.md index 78e02fc..1893b40 100644 --- a/README.md +++ b/README.md @@ -84,38 +84,20 @@ sessions produces a single ref. 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 # every line, marked by the conversation that wrote it -loch blame --hunks loch/format.py # or one row per block of lines +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 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` prints the file with a mark in the margin for each conversation, and a -key at the top saying what each mark asked for: - -``` -loch/format.py — 2 conversations - - A "I would prefer this tool to be agnostic of the editor that …" 37d467e5 · 45b565e - B "honeslty none of those seem like open questions they all se…" 37d467e5 · 6eb7b0d - -A 1 │ import hashlib -A 2 │ import json -B 3 │ import re -A 4 │ from collections.abc import Iterable, Iterator - ... -A 101 │ def canonical(value: Any) -> bytes: -B 102 │ """RFC 8785 (JSON Canonicalization Scheme): the one encoding every id is -B 103 │ computed over, so a second implementation in any language can reproduce -B 104 │ an id byte for byte. Keys sort by UTF-16 code units, numbers print as -B 105 │ ECMAScript does, and strings escape as JSON.stringify does. -``` - -Marks are per request rather than per session, so one long session that made -many commits for many asks doesn't paint the whole file one letter; `·` is a -commit with no conversation recorded and `+` a line not committed yet. +`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 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 02d288e..3a8ceb2 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -7,14 +7,17 @@ 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 pathlib import Path from typing import Any, Callable, NoReturn +from .blame_html import parse_ranges, render from .bundle import ( BUNDLE_VERSION, Bundle, @@ -97,7 +100,8 @@ [--author | --author-key ] [--out ] loch install [--local] [--command ] - loch blame [--hunks] [--store ] + loch blame [--html [] [--lines ] [--no-open]] + [--store ] loch ask [] [--at-commit] [--no-launch] [--store ] loch backfill [--revision ] (default: every branch) @@ -790,10 +794,6 @@ def _link_text(link: Link | None) -> str: UNLINKED_MARK = "·" UNCOMMITTED_MARK = "+" -# Foreground colours for the margin marks, cycled. Only the mark is coloured: -# the code keeps the terminal's own colours, so it reads as code. -MARK_COLOURS = ("36", "33", "35", "32", "34", "31", "96", "93", "95", "92") - def _mark(index: int) -> str: letters = "" @@ -804,14 +804,12 @@ def _mark(index: int) -> str: return letters -def _use_colour() -> bool: - return sys.stdout.isatty() and "NO_COLOR" not in os.environ - - def command_blame(argv: list[str]) -> Result: parser = _parser("blame") parser.add_argument("file") - parser.add_argument("--hunks", action="store_true") + 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) @@ -862,72 +860,37 @@ def command_blame(argv: list[str]) -> Result: "conversation": link.payload() if link is not None else None, } ) - text = ( - _hunks_text(args.file, hunks, links) - if args.hunks - else _annotated_text(args.file, hunks, legend, mark_of, links) - ) - return Result( - command="blame", - payload={"file": args.file, "conversations": legend, "hunks": rows}, - text=text, - ) - - -def _annotated_text( - file: str, - hunks: list[Any], - legend: list[dict[str, Any]], - mark_of: dict[str, str], - links: dict[str, Link | None], -) -> str: - colour = _use_colour() - colours = { - entry["mark"]: MARK_COLOURS[index % len(MARK_COLOURS)] - for index, entry in enumerate(legend) + text = _hunks_text(args.file, hunks, links) + payload: dict[str, Any] = { + "file": args.file, + "conversations": legend, + "hunks": rows, } - - def paint(mark: str, text: str) -> str: - code = colours.get(mark, "2") - return f"\033[{code}m{text}\033[0m" if colour else text - - width = max((len(entry["mark"]) for entry in legend), default=1) - count = len(legend) - out = [f"{file} — {count} conversation{'s' if count != 1 else ''}\n\n"] - for entry in legend: - if entry["available"]: - prompt = f'"{_flat(entry["prompt"], 60)}"' if entry["prompt"] else "" - else: - prompt = "(transcript not available)" - commits = ", ".join(commit[:7] for commit in entry["commits"]) - out.append( - f" {paint(entry['mark'], entry['mark'].ljust(width))} " - f"{prompt} {entry['session'][:8]} · {commits}\n" - ) - unlinked = sorted({c[:7] for c, m in mark_of.items() if m == UNLINKED_MARK}) - if unlinked: - out.append( - f" {paint(UNLINKED_MARK, UNLINKED_MARK.ljust(width))} " - f"no conversation recorded {', '.join(unlinked)}\n" + 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, ) - if UNCOMMITTED_MARK in mark_of.values(): - out.append( - f" {paint(UNCOMMITTED_MARK, UNCOMMITTED_MARK.ljust(width))} " - "not committed yet\n" + target = args.html or os.path.join( + tempfile.gettempdir(), f"loch-blame-{os.path.basename(args.file)}.html" ) - out.append("\n") - - digits = len(str(hunks[-1].end)) if hunks else 1 - for hunk in hunks: - mark = mark_of[hunk.commit] - for offset, line in enumerate(hunk.lines): - out.append( - f"{paint(mark, mark.ljust(width))} " - f"{hunk.start + offset:>{digits}} │ {line}\n" - ) - if legend: - out.append(f"\nfollow one up with: loch ask {file}:\n") - return "".join(out) + 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: diff --git a/test/test_trace.py b/test/test_trace.py index 6702f5b..3992bcb 100644 --- a/test/test_trace.py +++ b/test/test_trace.py @@ -299,25 +299,29 @@ def test_fork_without_a_call_runs_to_the_end_of_the_conversation( assert [r.get("uuid") for r in forked] == ["u1", "a1", "r1", "u2", None] -def test_blame_marks_every_line_with_its_conversation( +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 two lines") + 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"]) + monkeypatch.setattr( + "sys.argv", ["loch", "blame", "f.txt", "--html", str(page), "--no-open"] + ) main() - out = capsys.readouterr().out - assert ' A "make it two lines"' in out - assert "· 1 │ human line\n" in out - assert "A 2 │ agent line\n" in out - assert "+ 3 │ work in progress\n" in out - assert "\033[" not in out + assert capsys.readouterr().out == f"wrote {page}\n" + html = page.read_text() + assert '" not in html.split("