From d1cd26864b6b212b5627b4edd5152aa6d53d37fd Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 15:16:14 -0500 Subject: [PATCH 01/18] Honour CLAUDE_CONFIG_DIR for Claude's state directory Claude Code reads $CLAUDE_CONFIG_DIR/projects when the variable is set; loch always read ~/.claude, so on a machine running a second account it listed, restored and forked into a directory Claude never looks at. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 7 ++++++- loch/claude.py | 16 +++++++++++++++- loch/cli.py | 4 +++- test/conftest.py | 8 ++++++++ test/test_claude.py | 14 ++++++++++++++ 5 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 test/conftest.py diff --git a/CLAUDE.md b/CLAUDE.md index a7bab5c..9c27819 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -92,7 +92,12 @@ These were verified by experiment, not documentation, and are not stable public API. Re-verify if something breaks. - Sessions live at - `~/.claude/projects//.jsonl`. + `~/.claude/projects//.jsonl`, or under + `$CLAUDE_CONFIG_DIR/projects` when that is set (how one machine runs + several accounts). loch follows the same rule and only that rule — + never both places — since a restore filed anywhere Claude doesn't look + is a session `--resume` can't find. `claude.config_dir` is the one place + it's decided. - The encoding is `re.sub(r"[^a-zA-Z0-9]", "-", cwd)` — every non-alphanumeric character, not just slashes. - The cwd is **symlink-resolved first**, so `/tmp/x` is stored as diff --git a/loch/claude.py b/loch/claude.py index 02fd0ab..4695b07 100644 --- a/loch/claude.py +++ b/loch/claude.py @@ -41,8 +41,22 @@ def iso_timestamp(seconds: float) -> str: return f"{moment.strftime('%Y-%m-%dT%H:%M:%S')}.{moment.microsecond // 1000:03d}Z" +def config_dir(home: str | None = None) -> str: + """Where Claude Code keeps its state: `CLAUDE_CONFIG_DIR` when set, which + is how one machine runs several accounts, else `~/.claude`. Only the + variable is consulted, never both places, because that is the rule Claude + itself follows — a restore filed anywhere else is one `--resume` can't + find. An explicit `home` names another machine's layout and ignores it.""" + if home is None: + configured = os.environ.get("CLAUDE_CONFIG_DIR") + if configured: + return configured + home = home_dir() + return os.path.join(home, ".claude") + + def projects_dir(home: str | None = None) -> str: - return os.path.join(home if home is not None else home_dir(), ".claude", "projects") + return os.path.join(config_dir(home), "projects") def resolve_cwd(cwd: str) -> str: diff --git a/loch/cli.py b/loch/cli.py index 853aeec..880ff53 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -34,6 +34,7 @@ home_dir, iso_timestamp, list_sessions, + projects_dir, resolve_cwd, transcript_path_for, ) @@ -122,6 +123,7 @@ LOCH_STORE default store URI LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) LOCH_S3_REGION region override + CLAUDE_CONFIG_DIR Claude Code's state directory (default ~/.claude) Derived conversation files go to ~/.loch/derived unless --out says otherwise. @@ -1038,7 +1040,7 @@ def command_ask(argv: list[str]) -> Result: fail( "transcript-missing", f"session {link.session_id} is linked but its transcript is " - "neither in ~/.claude/projects nor in the store", + f"neither in {projects_dir()} nor in the store", ) fork = fork_session( link.transcript, diff --git a/test/conftest.py b/test/conftest.py new file mode 100644 index 0000000..7aeb3db --- /dev/null +++ b/test/conftest.py @@ -0,0 +1,8 @@ +import pytest + + +@pytest.fixture(autouse=True) +def _no_claude_config_dir(monkeypatch: pytest.MonkeyPatch) -> None: + # Tests point HOME at a temporary directory; a CLAUDE_CONFIG_DIR inherited + # from the developer's shell would send them to the real one instead. + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) diff --git a/test/test_claude.py b/test/test_claude.py index a71bd54..0cbb619 100644 --- a/test/test_claude.py +++ b/test/test_claude.py @@ -9,6 +9,7 @@ encode_cwd, encode_path, list_sessions, + projects_dir, read_session_meta, resolve_cwd, session_dir_for, @@ -262,3 +263,16 @@ def test_lists_and_filters_sessions(tmp_path: Path) -> None: assert [meta.session_id for meta in by_id] == ["one"] assert list_sessions(cwd="/Users/mike/other", home=str(tmp_path)) == [] + + +def test_claude_config_dir_replaces_the_home_default( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "work-account")) + assert projects_dir() == str(tmp_path / "work-account" / "projects") + # An explicit home names some other machine's layout, where this + # machine's variable means nothing. + assert projects_dir("/home/other") == "/home/other/.claude/projects" + monkeypatch.setenv("CLAUDE_CONFIG_DIR", "") + assert projects_dir() == str(tmp_path / "home" / ".claude" / "projects") From e5be892cfd1a360d376a993fbeb904a6cfc9482d Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 15:29:38 -0500 Subject: [PATCH 02/18] Rust build of loch, starting with the hook, and an equivalence harness rust/ holds a single crate whose binary implements `loch hook` (pre-tool, post-tool, stop with a file store) plus --version and help; every other command answers not-ported. HEAD and the git dir are read natively on layouts the fast path fully understands and from git otherwise, which takes a hook call from ~75ms to ~3ms (rust/bench/hook.py). test/test_equivalence.py runs both implementations on identical worlds with pinned git dates and compares stdout, stderr, status, the notes ref, pending state and store bytes, including a pre hook under one and the post hook under the other. LOCH_CORPUS=1 adds call recovery on real transcripts. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 38 +++ release.sh | 20 +- rust/.gitignore | 1 + rust/Cargo.lock | 220 ++++++++++++++ rust/Cargo.toml | 29 ++ rust/bench/hook.py | 89 ++++++ rust/src/claude.rs | 43 +++ rust/src/git.rs | 254 ++++++++++++++++ rust/src/hook.rs | 338 +++++++++++++++++++++ rust/src/main.rs | 112 +++++++ rust/src/output.rs | 314 ++++++++++++++++++++ rust/src/store.rs | 142 +++++++++ test/test_equivalence.py | 583 +++++++++++++++++++++++++++++++++++++ 13 files changed, 2180 insertions(+), 3 deletions(-) create mode 100644 rust/.gitignore create mode 100644 rust/Cargo.lock create mode 100644 rust/Cargo.toml create mode 100644 rust/bench/hook.py create mode 100644 rust/src/claude.rs create mode 100644 rust/src/git.rs create mode 100644 rust/src/hook.rs create mode 100644 rust/src/main.rs create mode 100644 rust/src/output.rs create mode 100644 rust/src/store.rs create mode 100644 test/test_equivalence.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index df13ae2..1cec6fb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -40,3 +40,41 @@ jobs: - run: poetry run ruff format --check - run: poetry run mypy . - run: poetry run pytest + + # The Rust build, held to the Python reference by test/test_equivalence.py. + # Linux and macOS because the hooks' native git fast path is Unix-only and + # its filesystem details (realpath, ownership) differ between the two. + rust: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + defaults: + run: + working-directory: rust + + steps: + - uses: actions/checkout@v7 + + # rustup ships on both runner images; pinned to the crate's + # rust-version so a newer toolchain can't hide an MSRV break. + - run: | + rustup toolchain install 1.83.0 --profile minimal -c clippy,rustfmt + rustup default 1.83.0 + + - run: cargo fmt --check + - run: cargo clippy --release --all-targets -- -D warnings + - run: cargo test --release + - run: cargo build --release + + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + - run: pipx install poetry + - run: poetry env use python && poetry install + working-directory: . + - run: poetry run pytest -q test/test_equivalence.py + working-directory: . + env: + LOCH_RUST: rust/target/release/loch diff --git a/release.sh b/release.sh index bfdc24e..2fa08cf 100755 --- a/release.sh +++ b/release.sh @@ -41,6 +41,17 @@ if count != 1: path.write_text(new) PY grep -q "^version = \"$version\"$" pyproject.toml || die "version bump did not apply" +# The Rust build answers `loch --version` too, and the two must agree. +python3 - "$version" <<'PY' +import pathlib, re, sys +path = pathlib.Path("rust/Cargo.toml") +text = path.read_text() +new, count = re.subn(r'(?m)^version = "[^"]*"$', f'version = "{sys.argv[1]}"', text, count=1) +if count != 1: + raise SystemExit("release: could not find a single version line in rust/Cargo.toml") +path.write_text(new) +PY +(cd rust && cargo update -q -w --offline 2>/dev/null || cargo update -q -w) # Not asserting `loch --version` here: it reads installed package metadata, # which still holds the old number until the bumped project is reinstalled. @@ -50,12 +61,15 @@ poetry run ruff check poetry run ruff format --check poetry run mypy . poetry run pytest -q +(cd rust && cargo fmt --check && cargo clippy -q --release --all-targets -- -D warnings \ + && cargo test -q --release && cargo build -q --release) +LOCH_RUST=rust/target/release/loch poetry run pytest -q test/test_equivalence.py echo "==> tagging $tag" # pyproject may already hold this version — the first release, or a re-cut after # a deleted tag. An empty commit fails under `set -e`, so tag what's there. if [ -n "$(git status --porcelain)" ]; then - run git add pyproject.toml + run git add pyproject.toml rust/Cargo.toml rust/Cargo.lock run git commit -m "release: $tag" else echo " pyproject is already at $version; tagging the current commit" @@ -65,8 +79,8 @@ run git push origin "$BRANCH" run git push origin "$tag" if [ -n "$DRY_RUN" ]; then - git checkout -- pyproject.toml - echo "==> dry run: pyproject.toml restored, nothing pushed" + git checkout -- pyproject.toml rust/Cargo.toml rust/Cargo.lock + echo "==> dry run: versions restored, nothing pushed" exit 0 fi diff --git a/rust/.gitignore b/rust/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/rust/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/rust/Cargo.lock b/rust/Cargo.lock new file mode 100644 index 0000000..d59be59 --- /dev/null +++ b/rust/Cargo.lock @@ -0,0 +1,220 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" + +[[package]] +name = "indexmap" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "loch" +version = "0.1.0" +dependencies = [ + "libc", + "serde_json", + "sha2", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/rust/Cargo.toml b/rust/Cargo.toml new file mode 100644 index 0000000..2567bf4 --- /dev/null +++ b/rust/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "loch" +# Kept equal to pyproject's version by release.sh: both implementations answer +# `loch --version`, and they must not disagree while both ship. +version = "0.1.0" +edition = "2021" +rust-version = "1.83" +license = "MIT" +description = "Save and restore agent coding sessions across machines" +publish = false + +[[bin]] +name = "loch" +path = "src/main.rs" + +[dependencies] +# preserve_order: payload keys come out in insertion order, as Python's dicts do. +serde_json = { version = "1", features = ["preserve_order"] } +sha2 = "0.10" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 +strip = true +panic = "abort" diff --git a/rust/bench/hook.py b/rust/bench/hook.py new file mode 100644 index 0000000..f2b61f1 --- /dev/null +++ b/rust/bench/hook.py @@ -0,0 +1,89 @@ +"""Wall-clock cost of `loch hook` per call, for any number of loch binaries. + + python rust/bench/hook.py [--runs N] [ ...] + +Each binary runs against its own scratch repository with the event Claude Code +sends around a Bash call. Three cases, since they cost different amounts: +`pre-tool`, `post-tool` when the call committed nothing (nearly every call), +and `post-tool` when it made a commit and a note gets written. Reports the +median and p90 in milliseconds. Nothing from a real transcript is used. +""" + +import argparse +import json +import os +import statistics +import subprocess +import sys +import tempfile +import time + +SESSION = "00000000-0000-4000-8000-000000000000" + + +def git(cwd: str, *args: str) -> None: + subprocess.run(["git", "-C", cwd, *args], check=True, capture_output=True) + + +def scratch_repo(root: str) -> str: + repo = os.path.join(root, "repo") + os.makedirs(repo) + git(repo, "init", "-q", "-b", "main") + git(repo, "commit", "-q", "--allow-empty", "-m", "initial") + return repo + + +def run(loch: str, name: str, event: dict, env: dict) -> float: + started = time.perf_counter() + subprocess.run( + [loch, "hook", name], + input=json.dumps(event).encode(), + env=env, + check=True, + capture_output=True, + ) + return (time.perf_counter() - started) * 1000 + + +def bench(loch: str, runs: int) -> dict[str, list[float]]: + times: dict[str, list[float]] = {"pre-tool": [], "post-tool": [], "post-commit": []} + with tempfile.TemporaryDirectory() as root: + repo = scratch_repo(root) + env = {**os.environ, "HOME": root, "GIT_CONFIG_GLOBAL": os.devnull} + env.pop("CLAUDE_CONFIG_DIR", None) + for i in range(runs): + event = { + "session_id": SESSION, + "cwd": repo, + "tool_name": "Bash", + "tool_input": {"command": f"echo {i}"}, + "tool_use_id": f"toolu_{i:08d}", + } + times["pre-tool"].append(run(loch, "pre-tool", event, env)) + if i % 2: + git(repo, "commit", "-q", "--allow-empty", "-m", f"change {i}") + times["post-commit"].append(run(loch, "post-tool", event, env)) + else: + times["post-tool"].append(run(loch, "post-tool", event, env)) + return times + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--runs", type=int, default=40) + parser.add_argument("loch", nargs="+") + args = parser.parse_args() + print(f"{'binary':<48} {'case':<12} {'median':>8} {'p90':>8}") + for loch in args.loch: + for case, samples in bench(loch, args.runs).items(): + samples.sort() + p90 = samples[int(len(samples) * 0.9) - 1] + print( + f"{loch[-48:]:<48} {case:<12} " + f"{statistics.median(samples):>7.1f}ms {p90:>7.1f}ms" + ) + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/rust/src/claude.rs b/rust/src/claude.rs new file mode 100644 index 0000000..cf5376b --- /dev/null +++ b/rust/src/claude.rs @@ -0,0 +1,43 @@ +//! Where Claude Code keeps its state, as in `loch/claude.py`. + +use std::path::{Path, PathBuf}; + +/// `Path.home()`: `HOME` on Unix, `USERPROFILE` on Windows. +pub fn home_dir() -> String { + let name = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; + std::env::var(name).unwrap_or_default() +} + +/// `CLAUDE_CONFIG_DIR` when set, which is how one machine runs several +/// accounts, else `~/.claude`. Only the variable is consulted, never both +/// places, because that is the rule Claude itself follows — a restore filed +/// anywhere else is one `--resume` can't find. An explicit `home` names +/// another machine's layout and ignores it. +#[allow(dead_code)] // read by list/save/restore/ask once they are ported +pub fn config_dir(home: Option<&str>) -> PathBuf { + if home.is_none() { + if let Some(configured) = std::env::var_os("CLAUDE_CONFIG_DIR").filter(|v| !v.is_empty()) { + return PathBuf::from(configured); + } + } + let home = home.map(str::to_string).unwrap_or_else(home_dir); + Path::new(&home).join(".claude") +} + +#[allow(dead_code)] +pub fn projects_dir(home: Option<&str>) -> PathBuf { + config_dir(home).join("projects") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_explicit_home_ignores_the_variable() { + assert_eq!( + projects_dir(Some("/home/other")), + PathBuf::from("/home/other/.claude/projects") + ); + } +} diff --git a/rust/src/git.rs b/rust/src/git.rs new file mode 100644 index 0000000..57a346f --- /dev/null +++ b/rust/src/git.rs @@ -0,0 +1,254 @@ +//! Git, by subprocess — plus a native fast path for the two questions the +//! hooks ask on every Bash call: where the git directory is and what HEAD is. +//! +//! The fast path exists because a `git` process costs ~8ms and the hooks ask +//! both questions twice per agent command; it is what takes `loch hook` from +//! tens of milliseconds to one. It is only trusted on layouts it fully +//! understands. Anything else — an environment variable that changes +//! discovery, reftable, a repository owned by someone else (`safe.directory`), +//! a ref it can't parse, Windows — returns `None` and the caller asks `git`, +//! so the worst a gap here costs is speed, never a different answer. + +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +#[derive(Debug)] +#[allow(dead_code)] // stderr, for the commands that will report it +pub struct GitError(pub String); + +pub fn git(cwd: &str, args: &[&str], stdin: Option<&str>) -> Result { + let (status, stdout, stderr) = run(cwd, args, stdin)?; + if !status { + let message = stderr.trim(); + return Err(GitError(if message.is_empty() { + "git failed".into() + } else { + message.into() + })); + } + Ok(stdout) +} + +/// Runs git and returns its stdout whatever the exit status, as Python's +/// `git(..., check=False)` does. +pub fn git_unchecked(cwd: &str, args: &[&str]) -> Result { + run(cwd, args, None).map(|(_, stdout, _)| stdout) +} + +fn run(cwd: &str, args: &[&str], stdin: Option<&str>) -> Result<(bool, String, String), GitError> { + let mut command = Command::new("git"); + command + .arg("-C") + .arg(cwd) + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }); + let mut child = command + .spawn() + .map_err(|error| GitError(error.to_string()))?; + if let Some(input) = stdin { + if let Some(mut pipe) = child.stdin.take() { + let _ = pipe.write_all(input.as_bytes()); + } + } + let output = child + .wait_with_output() + .map_err(|error| GitError(error.to_string()))?; + Ok(( + output.status.success(), + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + )) +} + +/// `git rev-parse --verify -q HEAD`, or `None` on an unborn branch or outside +/// a repository. +pub fn head(cwd: &str) -> Result, GitError> { + if let Some(layout) = Layout::discover(cwd) { + if let Some(answer) = layout.head() { + return Ok(answer); + } + } + let out = git_unchecked(cwd, &["rev-parse", "--verify", "-q", "HEAD"])?; + let sha = out.trim(); + Ok(if sha.is_empty() { + None + } else { + Some(sha.into()) + }) +} + +/// `git rev-parse --absolute-git-dir`. +pub fn absolute_git_dir(cwd: &str) -> Result { + if let Some(layout) = Layout::discover(cwd) { + return Ok(layout.git_dir.to_string_lossy().into_owned()); + } + Ok(git(cwd, &["rev-parse", "--absolute-git-dir"], None)? + .trim() + .to_string()) +} + +/// Variables that change how git finds or reads a repository. With any of +/// them set the native answer could differ from git's, so it isn't given. +const DISCOVERY_VARIABLES: &[&str] = &[ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_COMMON_DIR", + "GIT_CEILING_DIRECTORIES", + "GIT_DISCOVERY_ACROSS_FILESYSTEM", + "GIT_NAMESPACE", + "GIT_OBJECT_DIRECTORY", + "GIT_INDEX_FILE", + "GIT_CONFIG_PARAMETERS", +]; + +pub struct Layout { + pub git_dir: PathBuf, + common_dir: PathBuf, +} + +impl Layout { + pub fn discover(cwd: &str) -> Option { + if !cfg!(unix) { + return None; + } + if DISCOVERY_VARIABLES + .iter() + .any(|name| std::env::var_os(name).is_some()) + { + return None; + } + let start = fs::canonicalize(cwd).ok()?; + // Inside a git directory itself git behaves as if GIT_DIR were set. + if start.components().any(|part| part.as_os_str() == ".git") { + return None; + } + let mut dir: &Path = &start; + loop { + let dot_git = dir.join(".git"); + if let Ok(meta) = fs::symlink_metadata(&dot_git) { + if !owned_by_us(dir) { + return None; + } + let git_dir = if meta.is_dir() { + dot_git + } else if meta.is_file() { + let text = fs::read_to_string(&dot_git).ok()?; + let target = text + .strip_prefix("gitdir: ")? + .trim_end_matches(['\n', '\r']); + fs::canonicalize(dir.join(target)).ok()? + } else { + return None; + }; + if !git_dir.join("HEAD").is_file() { + return None; + } + let common_dir = match fs::read_to_string(git_dir.join("commondir")) { + Ok(text) => fs::canonicalize(git_dir.join(text.trim_end())).ok()?, + Err(_) => git_dir.clone(), + }; + if git_dir.join("reftable").exists() || common_dir.join("reftable").exists() { + return None; + } + if !common_dir.join("objects").is_dir() { + return None; + } + return Some(Layout { + git_dir, + common_dir, + }); + } + // A bare repository or a filesystem root: leave those to git. + if dir.join("HEAD").is_file() && dir.join("objects").is_dir() { + return None; + } + dir = dir.parent()?; + } + } + + /// `Some(None)` is a definite unborn HEAD; `None` means "ask git". + pub fn head(&self) -> Option> { + let mut text = fs::read_to_string(self.git_dir.join("HEAD")).ok()?; + for _ in 0..5 { + let line = text.trim_end_matches(['\n', '\r']); + let Some(name) = line.strip_prefix("ref: ") else { + return object_id(line).map(Some); + }; + let name = name.trim(); + if !name.starts_with("refs/") || name.contains("..") { + return None; + } + match fs::read_to_string(self.ref_base(name).join(name)) { + Ok(next) => text = next, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return self.packed(name); + } + Err(_) => return None, + } + } + None + } + + /// Per-worktree refs live in the worktree's own git directory; everything + /// else is shared through the common directory. + fn ref_base(&self, name: &str) -> &Path { + let per_worktree = ["refs/bisect/", "refs/worktree/", "refs/rewritten/"]; + if per_worktree.iter().any(|prefix| name.starts_with(prefix)) { + &self.git_dir + } else { + &self.common_dir + } + } + + fn packed(&self, name: &str) -> Option> { + let text = match fs::read_to_string(self.common_dir.join("packed-refs")) { + Ok(text) => text, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(None), + Err(_) => return None, + }; + for line in text.lines() { + if line.starts_with('#') || line.starts_with('^') { + continue; + } + if let Some((sha, refname)) = line.split_once(' ') { + if refname == name { + return object_id(sha).map(Some); + } + } + } + Some(None) + } +} + +fn object_id(text: &str) -> Option { + let valid = (text.len() == 40 || text.len() == 64) + && text + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + valid.then(|| text.to_string()) +} + +/// git's `safe.directory` check refuses a repository owned by another user; +/// answering natively there would answer where git declines to. +#[cfg(unix)] +fn owned_by_us(dir: &Path) -> bool { + use std::os::unix::fs::MetadataExt; + // SAFETY: geteuid has no preconditions and cannot fail. + let uid = unsafe { libc::geteuid() }; + fs::metadata(dir) + .map(|meta| meta.uid() == uid) + .unwrap_or(false) +} + +#[cfg(not(unix))] +fn owned_by_us(_dir: &Path) -> bool { + false +} diff --git a/rust/src/hook.rs b/rust/src/hook.rs new file mode 100644 index 0000000..375098e --- /dev/null +++ b/rust/src/hook.rs @@ -0,0 +1,338 @@ +//! `loch hook`, run by Claude Code around every Bash call and at every stop. +//! A port of the hook half of `loch/trace.py`; the Python is the reference +//! and `test/test_equivalence.py` holds the two to the same side effects. +//! +//! The pending-state file is shared across implementations — a session can +//! start its Bash call under one and finish it under the other while a machine +//! switches over — so its name and JSON shape must stay exactly Python's. + +use crate::git::{self, GitError}; +use crate::output::{python_dumps, python_dumps_compact_sorted}; +use crate::store::{self, Store}; +use serde_json::{json, Map, Value}; +use sha2::{Digest, Sha256}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub const NOTES_REF: &str = "refs/notes/loch"; +pub const NOTE_VERSION: i64 = 1; +pub const AGENT: &str = "claude-code"; + +/// Any failure: the hook swallows them all, so the only thing that matters +/// about one is where it stopped. +pub struct Stop; + +impl From for Stop { + fn from(_: GitError) -> Self { + Stop + } +} + +impl From for Stop { + fn from(_: std::io::Error) -> Self { + Stop + } +} + +fn event_cwd(event: &Map) -> Result { + // Python's `str(event.get("cwd") or os.getcwd())`. A non-string cwd would + // be str()-ed into something git can't enter, so it stops here instead. + match event.get("cwd") { + None | Some(Value::Null) | Some(Value::Bool(false)) => current_dir(), + Some(Value::String(text)) if text.is_empty() => current_dir(), + Some(Value::String(text)) => Ok(text.clone()), + Some(_) => Err(Stop), + } +} + +fn current_dir() -> Result { + Ok(std::env::current_dir()?.to_string_lossy().into_owned()) +} + +fn pending_dir(cwd: &str) -> Result { + let git_dir = git::absolute_git_dir(cwd)?; + Ok(Path::new(&git_dir).join("loch").join("pending")) +} + +/// `(event.get("tool_input") or {}).get("command", "")`, stringified. A truthy +/// non-object tool_input raises in Python, so it stops here. +fn tool_command(event: &Map) -> Result { + let input = match event.get("tool_input") { + None | Some(Value::Null) => return Ok(String::new()), + Some(Value::Object(map)) => map, + Some(value) if !truthy(value) => return Ok(String::new()), + Some(_) => return Err(Stop), + }; + match input.get("command") { + None => Ok(String::new()), + Some(Value::String(text)) => Ok(text.clone()), + // str() of anything else; commands are strings in every real event. + Some(_) => Err(Stop), + } +} + +fn truthy(value: &Value) -> bool { + match value { + Value::Null => false, + Value::Bool(b) => *b, + Value::Number(n) => n.as_f64() != Some(0.0), + Value::String(s) => !s.is_empty(), + Value::Array(a) => !a.is_empty(), + Value::Object(o) => !o.is_empty(), + } +} + +fn tool_use_id(event: &Map) -> Option { + match event.get("tool_use_id") { + Some(Value::String(call)) if !call.is_empty() => Some(call.clone()), + _ => None, + } +} + +fn call_key(event: &Map) -> Result { + if let Some(call) = tool_use_id(event) { + return Ok(call); + } + let digest = Sha256::digest(tool_command(event)?.as_bytes()); + let hex: String = digest[..16] + .iter() + .map(|b| format!("{:02x}", b)) + .collect::>() + .concat(); + Ok(format!("cmd-{}", hex)) +} + +fn now() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0) +} + +/// Remembers HEAD before a Bash call, so the matching post hook can tell +/// exactly which commits the call made rather than guessing from history. +pub fn pre_tool(event: &Map) -> Result<(), Stop> { + let cwd = event_cwd(event)?; + let before = git::head(&cwd)?.unwrap_or_default(); + let directory = pending_dir(&cwd)?; + fs::create_dir_all(&directory)?; + let key = call_key(event)?; + let state = json!({"head": before, "at": now()}); + fs::write(directory.join(key), python_dumps(&state))?; + Ok(()) +} + +pub fn post_tool(event: &Map) -> Result, Stop> { + let cwd = event_cwd(event)?; + let Some(Value::String(session_id)) = event.get("session_id") else { + return Ok(Vec::new()); + }; + let state_path = pending_dir(&cwd)?.join(call_key(event)?); + let state: Value = serde_json::from_slice(&fs::read(&state_path)?).map_err(|_| Stop)?; + fs::remove_file(&state_path)?; + let before = match state.get("head") { + Some(Value::String(head)) => head.clone(), + _ => return Err(Stop), + }; + let since = match state.get("at") { + Some(Value::Number(at)) => at.as_f64().ok_or(Stop)?, + _ => return Err(Stop), + }; + let after = match git::head(&cwd)? { + Some(after) if after != before => after, + _ => return Ok(Vec::new()), + }; + + let call = match tool_use_id(event) { + Some(call) => call, + None => { + let command = tool_command(event)?; + let found = match event.get("transcript_path") { + Some(Value::String(path)) => call_from_transcript(path, &command), + _ => None, + }; + match found { + Some(call) => call, + None => return Ok(Vec::new()), + } + } + }; + + let made = commits_made(&cwd, &before, &after, since)?; + for commit in &made { + write_note(&cwd, commit, &make_note(session_id, &call, "hook"))?; + } + Ok(made) +} + +/// 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. +fn commits_made(cwd: &str, before: &str, after: &str, since: f64) -> Result, Stop> { + let span = if before.is_empty() { + after.to_string() + } else { + format!("{}..{}", before, after) + }; + let listing = git::git(cwd, &["log", "--format=%H %ct", &span], None)?; + // Python's int() truncates toward zero, as `as` does. + let floor = since.trunc() as i64 - 1; + let mut made = Vec::new(); + for line in listing.lines() { + let (sha, stamp) = line.split_once(' ').unwrap_or((line, "")); + if stamp.is_empty() { + continue; + } + let stamp: i64 = stamp.trim().parse().map_err(|_| Stop)?; + if stamp >= floor { + made.push(sha.to_string()); + } + } + Ok(made) +} + +/// 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. +fn call_from_transcript(path: &str, command: &str) -> Option { + let raw = fs::read(path).ok()?; + let mut found: Option = None; + for line in raw.split(|&b| b == b'\n') { + let Ok(Value::Object(record)) = serde_json::from_slice::(line) else { + continue; + }; + let Some(Value::Object(message)) = record.get("message") else { + continue; + }; + let Some(Value::Array(content)) = message.get("content") else { + continue; + }; + for block in content { + let Value::Object(block) = block else { + continue; + }; + let input_command = match block.get("input") { + Some(Value::Object(input)) => input.get("command"), + _ => None, + }; + if block.get("type") == Some(&Value::from("tool_use")) + && block.get("name") == Some(&Value::from("Bash")) + && input_command == Some(&Value::from(command)) + { + found = Some(block.get("id").cloned().unwrap_or(Value::Null)); + } + } + } + match found { + Some(Value::String(id)) => Some(id), + _ => None, + } +} + +pub fn make_note(session_id: &str, call: &str, captured: &str) -> Value { + json!({ + "loch": NOTE_VERSION, + "agent": AGENT, + "session": session_id, + "call": call, + "captured": captured, + }) +} + +fn write_note(cwd: &str, commit: &str, note: &Value) -> Result<(), Stop> { + let body = python_dumps_compact_sorted(note); + git::git( + cwd, + &["notes", "--ref", NOTES_REF, "add", "-f", "-F", "-", commit], + Some(&body), + )?; + Ok(()) +} + +/// 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. +pub fn snapshot_transcript( + event: &Map, + store: &dyn Store, +) -> Result, Stop> { + let (Some(Value::String(path)), Some(Value::String(session_id))) = + (event.get("transcript_path"), event.get("session_id")) + else { + return Ok(None); + }; + let Ok(data) = fs::read(path) else { + return Ok(None); + }; + let key = transcript_key(&project_of(path), session_id); + store.put(&key, &data).map_err(|_| Stop)?; + Ok(Some(key)) +} + +/// `os.path.basename(os.path.dirname(path))`. +fn project_of(path: &str) -> String { + let dir = match path.rfind('/') { + Some(slash) => path[..slash].trim_end_matches('/'), + None => "", + }; + match dir.rfind('/') { + Some(slash) => dir[slash + 1..].to_string(), + None => dir.to_string(), + } +} + +pub fn transcript_key(project: &str, session_id: &str) -> String { + format!("transcripts/{}/{}/{}.jsonl", AGENT, project, session_id) +} + +/// 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. +pub fn run(name: &str, stdin: &[u8]) { + // Strict, as Python's text-mode stdin is: undecodable input raises there. + let Ok(text) = std::str::from_utf8(stdin) else { + return; + }; + let text = if text.is_empty() { "{}" } else { text }; + let Ok(parsed) = serde_json::from_str::(text) else { + return; + }; + let event = match parsed { + Value::Object(map) => map, + _ => Map::new(), + }; + let _ = match name { + "pre-tool" => pre_tool(&event), + "post-tool" => post_tool(&event).map(|_| ()), + "stop" => store::create_store(&store::resolve_store_uri(None)) + .map_err(|_| Stop) + .and_then(|store| snapshot_transcript(&event, store.as_ref()).map(|_| ())), + _ => Ok(()), + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn project_is_the_containing_directory_name() { + assert_eq!(project_of("/h/.claude/projects/-a-b/s.jsonl"), "-a-b"); + assert_eq!(project_of("s.jsonl"), ""); + assert_eq!(project_of("/s.jsonl"), ""); + } + + #[test] + fn command_key_matches_python() { + let event: Map = + serde_json::from_str(r#"{"tool_input": {"command": "git commit"}}"#).unwrap(); + // hashlib.sha256(b"git commit").hexdigest()[:32] + assert_eq!( + call_key(&event).ok().unwrap(), + "cmd-993c9eb42f6efa07b7501be8a0378748" + ); + } +} diff --git a/rust/src/main.rs b/rust/src/main.rs new file mode 100644 index 0000000..844d682 --- /dev/null +++ b/rust/src/main.rs @@ -0,0 +1,112 @@ +//! The Rust build of loch: one static binary for Ness, the VS Code extension +//! and the Claude Code hooks to ship. The Python package is the reference +//! implementation; a command lands here only once `test/test_equivalence.py` +//! holds it to the same output and side effects. + +// The error path is cold and runs once per process; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +mod claude; +mod git; +mod hook; +mod output; +mod store; + +use output::{emit, emit_error, CommandError, Outcome, JSON_FLAG}; +use serde_json::Value; +use std::io::Read; + +/// Commands the Python implementation has and this one doesn't yet. Asking +/// for one is `not-ported` rather than `unknown-command`: the command exists, +/// and the fix is the Python install, not a typo. +const UNPORTED: &[&str] = &[ + "list", "save", "restore", "delete", "reindex", "ingest", "install", "blame", "ask", "log", + "backfill", +]; + +const USAGE: &str = "loch — save and restore agent coding sessions across machines + +This is the Rust build, which so far implements: + + loch hook pre-tool | post-tool | stop (run by Claude Code) + loch --version + +Every other command is still served by the Python implementation (`uv tool +install loch`); asking this build for one fails with code `not-ported`. + +Every command takes --json, which replaces the text below with one machine- +readable document on stdout. + +Environment: + LOCH_STORE default store URI + CLAUDE_CONFIG_DIR Claude Code's state directory (default ~/.claude) +"; + +fn command_hook(argv: &[String]) -> Result { + let name = argv.first().map(String::as_str).unwrap_or(""); + let mut stdin = Vec::new(); + if std::io::stdin().read_to_end(&mut stdin).is_ok() { + hook::run(name, &stdin); + } + Ok(Outcome::new("hook")) +} + +fn command_version(_argv: &[String]) -> Result { + let version = env!("CARGO_PKG_VERSION"); + let mut outcome = Outcome::new("version"); + outcome + .payload + .insert("version".into(), Value::from(version)); + outcome.text = format!("loch {}\n", version); + Ok(outcome) +} + +fn command_help(_argv: &[String]) -> Result { + let mut outcome = Outcome::new("help"); + outcome.payload.insert("usage".into(), Value::from(USAGE)); + outcome.text = USAGE.into(); + Ok(outcome) +} + +fn main() { + let mut argv: Vec = std::env::args().skip(1).collect(); + // Read off argv rather than from a parsed command line: an unknown + // command has to render in the mode the caller asked for. + let as_json = argv.iter().any(|arg| arg == JSON_FLAG); + if argv.first().map(String::as_str) == Some(JSON_FLAG) { + argv.remove(0); + } + let mut command = argv.first().cloned().unwrap_or_else(|| "help".into()); + if command == "--help" || command == "-h" { + command = "help".into(); + } + if command == "--version" || command == "-V" { + command = "version".into(); + } + let rest = if argv.is_empty() { + &argv[..] + } else { + &argv[1..] + }; + + let result = match command.as_str() { + "hook" => command_hook(rest), + "version" => command_version(rest), + "help" => command_help(rest), + name if UNPORTED.contains(&name) => Err(CommandError::new( + "not-ported", + format!( + "'{}' is not in the Rust build yet; use the Python loch", + name + ), + )), + name => Err(CommandError::new( + "unknown-command", + format!("unknown command '{}' (try: loch help)", name), + )), + }; + match result { + Ok(outcome) => emit(outcome, as_json), + Err(error) => emit_error(&command, error, as_json), + } +} diff --git a/rust/src/output.rs b/rust/src/output.rs new file mode 100644 index 0000000..be3d290 --- /dev/null +++ b/rust/src/output.rs @@ -0,0 +1,314 @@ +//! The result envelope and its two renderings, as in `loch/output.py`. +//! +//! JSON is written the way Python's `json.dumps` writes it by default — `", "` +//! and `": "` separators, every non-ASCII character escaped, floats in `repr` +//! form — so the equivalence harness can compare the two implementations' +//! stdout byte for byte rather than only after parsing. + +use serde_json::{Map, Value}; +use std::io::Write; + +pub const SCHEMA: i64 = 1; + +pub const JSON_FLAG: &str = "--json"; + +/// What a command produced, in both renderings. Building the payload and the +/// prose in one place is what keeps them from drifting apart. +pub struct Outcome { + pub command: String, + pub payload: Map, + pub text: String, + pub warnings: Vec, +} + +impl Outcome { + pub fn new(command: &str) -> Self { + Outcome { + command: command.to_string(), + payload: Map::new(), + text: String::new(), + warnings: Vec::new(), + } + } +} + +/// A failure the caller is meant to act on. `code` is a stable token — +/// consumers branch on it, so reword `message` freely but not `code`. +pub struct CommandError { + pub code: &'static str, + pub message: String, + pub payload: Map, + pub exit_status: i32, + pub prose: Option, +} + +impl CommandError { + pub fn new(code: &'static str, message: impl Into) -> Self { + CommandError { + code, + message: message.into(), + payload: Map::new(), + exit_status: 1, + prose: None, + } + } +} + +pub fn document( + command: &str, + ok: bool, + payload: Map, + failure: Option<(&str, &str)>, +) -> Value { + let mut body = Map::new(); + body.insert("schema".into(), Value::from(SCHEMA)); + body.insert("ok".into(), Value::from(ok)); + body.insert("command".into(), Value::from(command)); + if let Some((code, error)) = failure { + body.insert("code".into(), Value::from(code)); + body.insert("error".into(), Value::from(error)); + } + body.extend(payload); + Value::Object(body) +} + +pub fn emit(outcome: Outcome, as_json: bool) { + if as_json { + write_document(&document(&outcome.command, true, outcome.payload, None)); + return; + } + // Warnings are stderr-only prose; JSON carries the same facts as per-item + // status, so nothing but the document is written in that mode. + let mut stderr = std::io::stderr(); + for warning in &outcome.warnings { + let _ = stderr.write_all(warning.as_bytes()); + } + let _ = std::io::stdout().write_all(outcome.text.as_bytes()); +} + +pub fn emit_error(command: &str, error: CommandError, as_json: bool) -> ! { + if as_json { + write_document(&document( + command, + false, + error.payload, + Some((error.code, &error.message)), + )); + } else { + let prose = error + .prose + .unwrap_or_else(|| format!("loch: {}\n", error.message)); + let _ = std::io::stderr().write_all(prose.as_bytes()); + } + let _ = std::io::stdout().flush(); + std::process::exit(error.exit_status); +} + +fn write_document(body: &Value) { + let mut out = python_dumps(body); + out.push('\n'); + let mut stdout = std::io::stdout(); + let _ = stdout.write_all(out.as_bytes()); + let _ = stdout.flush(); +} + +/// `json.dumps(value)` with Python's defaults. +pub fn python_dumps(value: &Value) -> String { + let mut out = String::new(); + write_value(&mut out, value, ", ", ": "); + out +} + +/// `json.dumps(value, sort_keys=True, separators=(",", ":"))`, the form a +/// commit note is stored in. +pub fn python_dumps_compact_sorted(value: &Value) -> String { + let mut out = String::new(); + write_sorted(&mut out, value); + out +} + +fn write_sorted(out: &mut String, value: &Value) { + match value { + Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + // Python sorts str keys by code point; Rust's str order is UTF-8 + // byte order, which is the same thing. + keys.sort(); + out.push('{'); + for (i, key) in keys.into_iter().enumerate() { + if i > 0 { + out.push(','); + } + write_string(out, key); + out.push(':'); + write_sorted(out, &map[key]); + } + out.push('}'); + } + Value::Array(items) => { + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + write_sorted(out, item); + } + out.push(']'); + } + other => write_value(out, other, ",", ":"), + } +} + +fn write_value(out: &mut String, value: &Value, item_sep: &str, key_sep: &str) { + match value { + Value::Null => out.push_str("null"), + Value::Bool(true) => out.push_str("true"), + Value::Bool(false) => out.push_str("false"), + Value::Number(number) => { + if let Some(f) = number.as_f64().filter(|_| number.is_f64()) { + out.push_str(&python_float_repr(f)); + } else { + out.push_str(&number.to_string()); + } + } + Value::String(text) => write_string(out, text), + Value::Array(items) => { + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push_str(item_sep); + } + write_value(out, item, item_sep, key_sep); + } + out.push(']'); + } + Value::Object(map) => { + out.push('{'); + for (i, (key, item)) in map.iter().enumerate() { + if i > 0 { + out.push_str(item_sep); + } + write_string(out, key); + out.push_str(key_sep); + write_value(out, item, item_sep, key_sep); + } + out.push('}'); + } + } +} + +/// `ensure_ascii=True`: everything outside printable ASCII becomes `\uXXXX`, +/// astral characters as a surrogate pair, exactly as Python escapes them. +fn write_string(out: &mut String, text: &str) { + out.push('"'); + for ch in text.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{08}' => out.push_str("\\b"), + '\u{0c}' => out.push_str("\\f"), + ' '..='~' => out.push(ch), + _ => { + let mut units = [0u16; 2]; + for unit in ch.encode_utf16(&mut units) { + out.push_str(&format!("\\u{:04x}", unit)); + } + } + } + } + out.push('"'); +} + +/// Python's `float.__repr__`: the shortest digits that round-trip, written +/// positionally when the exponent is in [-4, 16) and as `d.ddde±XX` outside. +pub fn python_float_repr(value: f64) -> String { + if value.is_nan() { + return "NaN".into(); + } + if value.is_infinite() { + return if value > 0.0 { "Infinity" } else { "-Infinity" }.into(); + } + // `{:e}` gives the shortest round-trip digits in scientific form. + let scientific = format!("{:e}", value); + let (mantissa, exponent) = scientific.split_once('e').expect("{:e} has an e"); + let exponent: i32 = exponent.parse().expect("{:e} exponent is an integer"); + let negative = mantissa.starts_with('-'); + let digits: String = mantissa.chars().filter(|c| c.is_ascii_digit()).collect(); + let sign = if negative { "-" } else { "" }; + + if (-4..16).contains(&exponent) { + let point = exponent + 1; + let body = if point <= 0 { + format!("0.{}{}", "0".repeat((-point) as usize), digits) + } else if point as usize >= digits.len() { + format!("{}{}.0", digits, "0".repeat(point as usize - digits.len())) + } else { + let (whole, fraction) = digits.split_at(point as usize); + format!("{}.{}", whole, fraction) + }; + format!("{}{}", sign, body) + } else { + let (first, rest) = digits.split_at(1); + let fraction = if rest.is_empty() { + String::new() + } else { + format!(".{}", rest) + }; + let exponent_sign = if exponent < 0 { '-' } else { '+' }; + format!( + "{}{}{}e{}{:02}", + sign, + first, + fraction, + exponent_sign, + exponent.abs() + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn floats_match_python_repr() { + let cases = [ + (1.0, "1.0"), + (0.1, "0.1"), + (1731859200.123456, "1731859200.123456"), + (1e16, "1e+16"), + (1.5e16, "1.5e+16"), + (123456789012345.6, "123456789012345.6"), + (0.0001, "0.0001"), + (0.00001, "1e-05"), + (-2.5e-7, "-2.5e-07"), + (0.0, "0.0"), + (1e300, "1e+300"), + ]; + for (value, expected) in cases { + assert_eq!(python_float_repr(value), expected, "{value}"); + } + } + + #[test] + fn strings_escape_like_ensure_ascii() { + let value = json!({"a": "é😀\u{7f}\u{1}\"\\\n", "b": [1, true, null]}); + assert_eq!( + python_dumps(&value), + r#"{"a": "\u00e9\ud83d\ude00\u007f\u0001\"\\\n", "b": [1, true, null]}"# + ); + } + + #[test] + fn notes_are_compact_and_sorted() { + let value = json!({"session": "s", "loch": 1, "agent": "claude-code"}); + assert_eq!( + python_dumps_compact_sorted(&value), + r#"{"agent":"claude-code","loch":1,"session":"s"}"# + ); + } +} diff --git a/rust/src/store.rs b/rust/src/store.rs new file mode 100644 index 0000000..469b4d5 --- /dev/null +++ b/rust/src/store.rs @@ -0,0 +1,142 @@ +//! The store interface, as in `loch/store.py`. Only what the ported commands +//! use is here; the rest arrives with the commands that need it. + +use crate::claude::home_dir; +use std::fs; +use std::path::{Component, Path, PathBuf}; + +/// The message is for the commands that report it; the hook only needs to +/// know that the put failed. +#[derive(Debug)] +#[allow(dead_code)] +pub enum StoreError { + /// The store didn't answer (`store-unreachable`). + Unreachable(String), + Invalid(String), +} + +pub trait Store { + fn put(&self, key: &str, data: &[u8]) -> Result<(), StoreError>; +} + +pub struct FileStore { + root: PathBuf, +} + +impl FileStore { + pub fn new(root: impl Into) -> Self { + FileStore { root: root.into() } + } +} + +impl Store for FileStore { + fn put(&self, key: &str, data: &[u8]) -> Result<(), StoreError> { + let path = self.root.join(key); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|e| StoreError::Unreachable(e.to_string()))?; + } + fs::write(&path, data).map_err(|e| StoreError::Unreachable(e.to_string())) + } +} + +pub fn default_store() -> String { + Path::new(&home_dir()) + .join(".loch") + .join("store") + .to_string_lossy() + .into_owned() +} + +pub fn resolve_store_uri(explicit: Option<&str>) -> String { + if let Some(uri) = explicit { + return uri.to_string(); + } + std::env::var("LOCH_STORE").unwrap_or_else(|_| default_store()) +} + +pub fn create_store(uri: &str) -> Result, StoreError> { + if let Some(rest) = uri.strip_prefix("s3://") { + let bucket = rest.split('/').next().unwrap_or(""); + if bucket.is_empty() { + return Err(StoreError::Invalid(format!( + "invalid S3 store URI: {}", + uri + ))); + } + return Err(StoreError::Unreachable( + "the S3 backend is not ported to the Rust build yet".into(), + )); + } + if let Some(rest) = uri.strip_prefix("file://") { + return Ok(Box::new(FileStore::new(file_uri_path(rest)))); + } + Ok(Box::new(FileStore::new(abspath(uri)))) +} + +/// `unquote(urlparse(uri).path)`: the netloc and any query or fragment are +/// dropped, and percent-escapes decoded as UTF-8 with replacement. +fn file_uri_path(rest: &str) -> String { + let path = match rest.find('/') { + Some(slash) => &rest[slash..], + None => "", + }; + let path = path.split(['?', '#']).next().unwrap_or(""); + let bytes = path.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok(); + if let Some(value) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) { + decoded.push(value); + i += 3; + continue; + } + } + decoded.push(bytes[i]); + i += 1; + } + String::from_utf8_lossy(&decoded).into_owned() +} + +/// `os.path.abspath`: joined onto the working directory and normalised +/// lexically, without touching the filesystem. +pub fn abspath(path: &str) -> String { + let joined = if Path::new(path).is_absolute() { + PathBuf::from(path) + } else { + std::env::current_dir().unwrap_or_default().join(path) + }; + let mut parts: Vec = Vec::new(); + for component in joined.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + if matches!(parts.last(), Some(Component::Normal(_))) { + parts.pop(); + } + } + other => parts.push(other), + } + } + let normal: PathBuf = parts.iter().collect(); + normal.to_string_lossy().into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_uris_decode_like_urllib() { + assert_eq!(file_uri_path("/tmp/a%20b"), "/tmp/a b"); + assert_eq!(file_uri_path("host/tmp/x?q=1#f"), "/tmp/x"); + assert_eq!(file_uri_path("/tmp/%zz%2"), "/tmp/%zz%2"); + } + + #[test] + fn abspath_normalises_lexically() { + assert_eq!(abspath("/a/./b/../c"), "/a/c"); + assert_eq!(abspath("/.."), "/"); + } +} diff --git a/test/test_equivalence.py b/test/test_equivalence.py new file mode 100644 index 0000000..67312d9 --- /dev/null +++ b/test/test_equivalence.py @@ -0,0 +1,583 @@ +"""The Rust build against the Python reference, on the same inputs. + +Opt-in: set LOCH_RUST to a built binary (`cargo build --release` in rust/, then +LOCH_RUST=rust/target/release/loch). Every scenario is built twice at the same +path with pinned git dates, so commit hashes, note objects and the notes ref +come out byte-identical; one copy is driven by `python -m loch.cli`, the other +by the binary, and everything observable is compared: stdout, stderr, exit +status, the notes ref, the pending-state directory and the store. + +With LOCH_CORPUS=1 as well, the transcript-reading path is run against this +machine's real transcripts. Their content only ever exists in a temporary +directory and in memory; failures report session ids and counts, never text. +""" + +import hashlib +import json +import os +import random +import shutil +import subprocess +import sys +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest + +RUST = os.environ.get("LOCH_RUST") + +pytestmark = pytest.mark.skipif(not RUST, reason="set LOCH_RUST to a Rust build") + +SESSION = "11111111-2222-3333-4444-555555555555" +# In the future, so the hook's "committed after the call began" bound admits +# commits made during a call; fixed, so their hashes are too. +NOW = "2031-01-01T00:00:00Z" +PAST = "2020-01-01T00:00:00Z" + + +def implementation(name: str) -> list[str]: + if name == "py": + return [sys.executable, "-m", "loch.cli"] + assert RUST is not None + return [os.path.abspath(RUST)] + + +@dataclass +class Run: + stdout: bytes + stderr: bytes + status: int + + +class World: + """One scratch machine: a HOME, a repository, a store, an environment.""" + + def __init__(self, root: Path) -> None: + self.root = root + self.home = root / "home" + self.repo = root / "repo" + self.store = root / "store" + self.home.mkdir(parents=True) + self.env = { + "PATH": os.environ["PATH"], + "HOME": str(self.home), + "LOCH_STORE": str(self.store), + "GIT_CONFIG_GLOBAL": str(root / "gitconfig"), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_NAME": "Test", + "GIT_AUTHOR_EMAIL": "test@example.com", + "GIT_COMMITTER_NAME": "Test", + "GIT_COMMITTER_EMAIL": "test@example.com", + "GIT_AUTHOR_DATE": NOW, + "GIT_COMMITTER_DATE": NOW, + "PYTHONPATH": str(Path(__file__).resolve().parent.parent), + } + + def git(self, *args: str, cwd: Path | None = None, date: str = NOW) -> str: + env = {**self.env, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} + return subprocess.run( + ["git", "-C", str(cwd or self.repo), *args], + capture_output=True, + text=True, + check=True, + env=env, + ).stdout.strip() + + def init(self, *extra: str) -> None: + self.repo.mkdir(exist_ok=True) + self.git("init", "-q", "-b", "main", *extra) + + def commit(self, message: str, cwd: Path | None = None, date: str = NOW) -> str: + self.git("commit", "-q", "--allow-empty", "-m", message, cwd=cwd, date=date) + return self.git("rev-parse", "HEAD", cwd=cwd) + + def loch( + self, + impl: str, + *args: str, + stdin: Any = None, + env: dict[str, str] | None = None, + cwd: Path | None = None, + ) -> Run: + data = ( + stdin + if isinstance(stdin, bytes) + else b"" + if stdin is None + else json.dumps(stdin).encode() + ) + result = subprocess.run( + [*implementation(impl), *args], + input=data, + capture_output=True, + env={**self.env, **(env or {})}, + cwd=str(cwd or self.root), + ) + return Run(result.stdout, result.stderr, result.returncode) + + def event(self, call: str | None = "toolu_1", **fields: Any) -> dict[str, Any]: + body: dict[str, Any] = { + "session_id": SESSION, + "cwd": str(self.repo), + "tool_name": "Bash", + "tool_input": {"command": "git commit -m work"}, + } + if call is not None: + body["tool_use_id"] = call + body.update(fields) + return body + + def observe(self) -> dict[str, Any]: + """Everything a hook can leave behind, in a form two runs can be + compared on. The one nondeterministic value — the pending state's + timestamp — is reduced to its type.""" + seen: dict[str, Any] = {} + for path in sorted(self.root.rglob("*")): + relative = path.relative_to(self.root).as_posix() + if "/.git/objects/" in f"/{relative}" or relative.startswith("home/.loch/"): + continue + if "/loch/pending/" in relative and path.is_file(): + try: + state = json.loads(path.read_text()) + except ValueError: + state = path.read_text() + seen[relative] = ( + {"head": state.get("head"), "at": type(state.get("at")).__name__} + if isinstance(state, dict) + else state + ) + elif path.is_file() and ( + relative.startswith("store/") or relative.endswith("/NOTES_EDITMSG") + ): + seen[relative] = hashlib.sha256(path.read_bytes()).hexdigest() + elif path.is_dir() and "/loch" in relative: + seen[relative] = "dir" + for repo in {self.repo, *self.root.glob("wt*")}: + if (repo / ".git").exists(): + seen[f"notes:{repo.name}"] = subprocess.run( + [ + "git", + "-C", + str(repo), + "rev-parse", + "-q", + "--verify", + "refs/notes/loch", + ], + capture_output=True, + text=True, + env=self.env, + ).stdout.strip() + return seen + + +Scenario = Callable[[World, Callable[..., Run]], list[Run]] + + +def twin( + tmp_path: Path, scenario: Scenario, mix: tuple[str, str] | None = None +) -> dict[str, Any]: + """Runs `scenario` once per implementation in identical worlds at the same + path, and asserts nothing observable differs. With `mix`, the second run + alternates implementations call by call — pre under one, post under the + other — which is what a machine switching over mid-session does.""" + root = tmp_path / "world" + outcomes = [] + plans: list[tuple[str, ...]] = [("py",), ("rs",)] if mix is None else [("py",), mix] + for plan in plans: + if root.exists(): + shutil.rmtree(root) + world = World(root) + calls = iter(range(10_000)) + + def loch( + *args: str, _w: World = world, _p: tuple[str, ...] = plan, **kw: Any + ) -> Run: + return _w.loch(_p[next(calls) % len(_p)], *args, **kw) + + runs = scenario(world, loch) + outcomes.append(([vars(run) for run in runs], world.observe())) + (py_runs, py_seen), (rs_runs, rs_seen) = outcomes + assert rs_runs == py_runs + assert rs_seen == py_seen + return py_seen + + +# -- scenarios ---------------------------------------------------------------- + + +def no_commit(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + return [ + loch("hook", "pre-tool", stdin=w.event()), + loch("hook", "post-tool", stdin=w.event()), + ] + + +def one_commit(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + pre = loch("hook", "pre-tool", stdin=w.event()) + w.commit("agent work") + return [pre, loch("hook", "post-tool", stdin=w.event())] + + +def two_commits(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + pre = loch("hook", "pre-tool", stdin=w.event()) + w.commit("one") + w.commit("two") + return [pre, loch("hook", "post-tool", stdin=w.event())] + + +def checkout_is_not_committing(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("base", date=PAST) + w.git("checkout", "-q", "-b", "side") + w.commit("someone else", date=PAST) + w.git("checkout", "-q", "main") + pre = loch("hook", "pre-tool", stdin=w.event()) + w.git("checkout", "-q", "side") + return [pre, loch("hook", "post-tool", stdin=w.event())] + + +def unborn_head(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + pre = loch("hook", "pre-tool", stdin=w.event()) + w.commit("root") + return [pre, loch("hook", "post-tool", stdin=w.event())] + + +def call_from_transcript(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + transcript = w.root / "t.jsonl" + lines = [ + { + "type": "assistant", + "message": { + "content": [ + { + "type": "tool_use", + "id": "toolu_old", + "name": "Bash", + "input": {"command": "git commit -m work"}, + } + ] + }, + }, + "not json", + [1, 2], + {"type": "assistant", "message": {"content": "plain"}}, + { + "type": "assistant", + "message": { + "content": [ + { + "type": "tool_use", + "id": "toolu_new", + "name": "Bash", + "input": {"command": "git commit -m work"}, + }, + { + "type": "tool_use", + "id": "toolu_other", + "name": "Bash", + "input": {"command": "ls"}, + }, + ] + }, + }, + ] + transcript.write_text( + "\n".join(x if isinstance(x, str) else json.dumps(x) for x in lines) + "\n" + ) + event = w.event(call=None, transcript_path=str(transcript)) + pre = loch("hook", "pre-tool", stdin=event) + w.commit("agent work") + return [pre, loch("hook", "post-tool", stdin=event)] + + +def no_call_anywhere(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + event = w.event(call=None) + pre = loch("hook", "pre-tool", stdin=event) + w.commit("agent work") + return [pre, loch("hook", "post-tool", stdin=event)] + + +def worktree(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + wt = w.root / "wt1" + w.git("worktree", "add", "-q", "-b", "feature", str(wt)) + event = w.event(cwd=str(wt / ".")) + pre = loch("hook", "pre-tool", stdin=event) + w.commit("in the worktree", cwd=wt) + return [pre, loch("hook", "post-tool", stdin=event)] + + +def packed_refs(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + w.git("pack-refs", "--all") + pre = loch("hook", "pre-tool", stdin=w.event()) + w.commit("after packing") + w.git("pack-refs", "--all") + return [pre, loch("hook", "post-tool", stdin=w.event())] + + +def detached(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + w.git("checkout", "-q", "--detach") + pre = loch("hook", "pre-tool", stdin=w.event()) + w.commit("detached work") + return [pre, loch("hook", "post-tool", stdin=w.event())] + + +def subdirectory_and_symlink(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + (w.repo / "sub" / "deeper").mkdir(parents=True) + os.symlink(w.repo / "sub", w.root / "link") + event = w.event(cwd=str(w.root / "link" / "deeper")) + pre = loch("hook", "pre-tool", stdin=event) + w.commit("from a subdirectory") + return [pre, loch("hook", "post-tool", stdin=event)] + + +def reftable(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init("--ref-format=reftable") + w.commit("first") + pre = loch("hook", "pre-tool", stdin=w.event()) + w.commit("agent work") + return [pre, loch("hook", "post-tool", stdin=w.event())] + + +def git_dir_variable(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + other = w.root / "elsewhere" + other.mkdir() + env = {"GIT_DIR": str(w.repo / ".git")} + event = w.event(cwd=str(other)) + pre = loch("hook", "pre-tool", stdin=event, env=env) + w.commit("agent work") + return [pre, loch("hook", "post-tool", stdin=event, env=env)] + + +def malformed(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + runs = [] + for stdin in [ + b"not json", + b"[1, 2]", + b"\xff\xfe", + b"", + {**w.event(), "tool_input": "a string"}, + {**w.event(call=None), "tool_input": "a string"}, + {**w.event(call=None), "tool_input": {"command": 5}}, + {k: v for k, v in w.event().items() if k != "session_id"}, + {**w.event(), "session_id": 7}, + {**w.event(), "cwd": str(w.root / "missing")}, + {**w.event(), "cwd": str(w.home)}, + {**w.event(), "cwd": 12}, + ]: + for name in ("pre-tool", "post-tool"): + runs.append(loch("hook", name, stdin=stdin)) + runs.append(loch("hook", "bogus", stdin=w.event())) + runs.append(loch("hook", stdin=w.event())) + return runs + + +def stale_state(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + pending = w.repo / ".git" / "loch" / "pending" + pending.mkdir(parents=True) + (pending / "toolu_a").write_text("[]") + (pending / "toolu_b").write_text('{"head": "x"}') + (pending / "toolu_c").write_text("garbage") + runs = [] + w.commit("moved") + for call in ("toolu_a", "toolu_b", "toolu_c", "toolu_missing"): + runs.append(loch("hook", "post-tool", stdin=w.event(call=call))) + return runs + + +def json_mode(w: World, loch: Callable[..., Run]) -> list[Run]: + w.init() + w.commit("first") + return [ + loch("hook", "pre-tool", "--json", stdin=w.event()), + loch("--json", "hook", "post-tool", stdin=w.event()), + loch("--version"), + loch("--version", "--json"), + loch("version", "--json"), + loch("--json", "-V"), + loch("nonsense"), + loch("nonsense", "--json"), + ] + + +def stop(w: World, loch: Callable[..., Run]) -> list[Run]: + project = w.home / ".claude" / "projects" / "-repo" + project.mkdir(parents=True) + transcript = project / f"{SESSION}.jsonl" + transcript.write_bytes(b'{"type": "user"}\n\xff not utf-8\n') + event = {"session_id": SESSION, "transcript_path": str(transcript)} + uri = "file://" + str(w.root / "file store").replace(" ", "%20") + return [ + loch("hook", "stop", stdin=event), + loch("hook", "stop", stdin=event, env={"LOCH_STORE": uri}), + loch("hook", "stop", stdin=event, env={"LOCH_STORE": "relative/store"}), + loch("hook", "stop", stdin={**event, "transcript_path": str(w.root / "gone")}), + loch("hook", "stop", stdin={"session_id": SESSION}), + loch("hook", "stop", stdin={**event, "session_id": 3}), + ] + + +def stop_default_store(w: World, loch: Callable[..., Run]) -> list[Run]: + project = w.home / ".claude" / "projects" / "-repo" + project.mkdir(parents=True) + transcript = project / f"{SESSION}.jsonl" + transcript.write_text('{"type": "user"}\n') + event = {"session_id": SESSION, "transcript_path": str(transcript)} + run = loch("hook", "stop", stdin=event, env={"LOCH_STORE": ""}) + # Moved where observe() compares stores. + snapshot = w.home / ".loch" / "store" + if snapshot.exists(): + shutil.copytree(snapshot, w.store) + return [run] + + +SCENARIOS = [ + no_commit, + one_commit, + two_commits, + checkout_is_not_committing, + unborn_head, + call_from_transcript, + no_call_anywhere, + worktree, + packed_refs, + detached, + subdirectory_and_symlink, + reftable, + git_dir_variable, + malformed, + stale_state, + json_mode, + stop, + stop_default_store, +] + + +@pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda s: s.__name__) +def test_hook_matches_python(tmp_path: Path, scenario: Scenario) -> None: + twin(tmp_path, scenario) + + +@pytest.mark.parametrize( + "mix", [("py", "rs"), ("rs", "py")], ids=["py-then-rs", "rs-then-py"] +) +@pytest.mark.parametrize( + "scenario", + [one_commit, two_commits, unborn_head, call_from_transcript, worktree], + ids=lambda s: s.__name__, +) +def test_switching_over_mid_call( + tmp_path: Path, scenario: Scenario, mix: tuple[str, str] +) -> None: + """A Bash call whose pre hook ran under one implementation and whose post + hook ran under the other, as happens the moment a machine switches.""" + twin(tmp_path, scenario, mix=mix) + + +def test_stop_with_s3_store_differs_only_as_expected(tmp_path: Path) -> None: + """Placeholder until S3 is ported: both must at least leave stdout empty + and exit zero, since a hook may never fail its tool call.""" + world = World(tmp_path / "world") + event = {"session_id": SESSION, "transcript_path": str(tmp_path / "none")} + for impl in ("py", "rs"): + run = world.loch( + impl, "hook", "stop", stdin=event, env={"LOCH_STORE": "s3://bucket/p"} + ) + assert (run.stdout, run.status) == (b"", 0) + + +# -- corpus ------------------------------------------------------------------- + + +def _corpus_cases(limit: int) -> list[tuple[str, str]]: + from loch.claude import projects_dir + + root = Path(projects_dir()) + transcripts = sorted(root.glob("*/*.jsonl")) if root.is_dir() else [] + random.Random(0).shuffle(transcripts) + cases = [] + for path in transcripts: + commands = [] + for line in path.read_bytes().split(b"\n"): + if b'"Bash"' not in line: + continue + try: + record = json.loads(line) + except ValueError: + continue + content = (record.get("message") or {}).get("content") + for block in content if isinstance(content, list) else []: + if ( + isinstance(block, dict) + and block.get("type") == "tool_use" + and block.get("name") == "Bash" + and isinstance((block.get("input") or {}).get("command"), str) + ): + commands.append(block["input"]["command"]) + if commands: + cases.append((str(path), random.Random(path.name).choice(commands))) + if len(cases) >= limit: + break + return cases + + +@pytest.mark.skipif(os.environ.get("LOCH_CORPUS") != "1", reason="set LOCH_CORPUS=1") +def test_call_recovery_matches_on_real_transcripts(tmp_path: Path) -> None: + """The one hook path that reads a transcript, on real ones: a commit made + by a call whose payload lacks tool_use_id must be noted with the same call + id by both implementations.""" + cases = _corpus_cases(int(os.environ.get("LOCH_CORPUS_LIMIT", "150"))) + assert cases, "no transcripts with Bash calls on this machine" + mismatched = [] + unnoted = 0 + for index, (path, command) in enumerate(cases): + session = Path(path).stem + + def scenario( + w: World, loch: Callable[..., Run], _p: str = path, _c: str = command + ) -> list[Run]: + w.init() + w.commit("first") + event = w.event(call=None, transcript_path=_p, tool_input={"command": _c}) + pre = loch("hook", "pre-tool", stdin=event) + w.commit("agent work") + return [pre, loch("hook", "post-tool", stdin=event)] + + try: + seen = twin(tmp_path / str(index), scenario) + except AssertionError: + mismatched.append(session) + continue + # Agreeing that nothing happened would pass vacuously. + unnoted += not seen["notes:repo"] + assert not unnoted, f"{unnoted}/{len(cases)} cases wrote no note" + assert not mismatched, ( + f"{len(mismatched)}/{len(cases)} sessions differ: {mismatched}" + ) From 8fabb1231a41278cf075b968fad7a7c670b35109 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 15:38:58 -0500 Subject: [PATCH 03/18] Rust stop hook writes to S3 too, checked against moto with IAM auth on SigV4 by hand over ureq/rustls rather than the AWS SDK: one signed PUT doesn't justify an async runtime. Credentials come from AWS_* and the shared credentials/config files; SSO, credential_process and instance metadata are not read. The signer is pinned to AWS's published example, and the harness compares both builds against a moto server that refuses a wrong signature. The toolchain is pinned to 1.91.0 in rust/rust-toolchain.toml: 1.83 can't build current url/idna, and the pin is scoped to rust/ so nobody's default changes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 8 +- poetry.lock | 103 ++++++- pyproject.toml | 6 + rust/Cargo.lock | 538 ++++++++++++++++++++++++++++++++++++- rust/Cargo.toml | 6 +- rust/rust-toolchain.toml | 7 + rust/src/main.rs | 1 + rust/src/s3.rs | 395 +++++++++++++++++++++++++++ rust/src/store.rs | 8 +- test/test_equivalence.py | 155 ++++++++++- 10 files changed, 1205 insertions(+), 22 deletions(-) create mode 100644 rust/rust-toolchain.toml create mode 100644 rust/src/s3.rs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1cec6fb..f905c90 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -57,11 +57,9 @@ jobs: steps: - uses: actions/checkout@v7 - # rustup ships on both runner images; pinned to the crate's - # rust-version so a newer toolchain can't hide an MSRV break. - - run: | - rustup toolchain install 1.83.0 --profile minimal -c clippy,rustfmt - rustup default 1.83.0 + # rustup ships on both runner images and installs the version + # rust/rust-toolchain.toml pins on first use; this makes that explicit. + - run: rustup show active-toolchain || rustup toolchain install - run: cargo fmt --check - run: cargo clippy --release --all-targets -- -D warnings diff --git a/poetry.lock b/poetry.lock index b4f7f48..1de2d72 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,5 +1,18 @@ # This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand. +[[package]] +name = "blinker" +version = "1.9.0" +description = "Fast, simple object-to-object and broadcast signaling" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version < \"4.0\"" +files = [ + {file = "blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc"}, + {file = "blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf"}, +] + [[package]] name = "boto3" version = "1.43.71" @@ -815,6 +828,19 @@ files = [ {file = "charset_normalizer-3.5.0.tar.gz", hash = "sha256:49bd5feb59b0bf3cbf6ebcf4352e371c95b9da9bacd4449f8b64d0ad2c10a26e"}, ] +[[package]] +name = "click" +version = "8.5.1" +description = "Composable command line interface toolkit" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +markers = "python_version < \"4.0\"" +files = [ + {file = "click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37"}, + {file = "click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4"}, +] + [[package]] name = "colorama" version = "0.4.6" @@ -910,6 +936,49 @@ typing-extensions = {version = ">=4.6.0", markers = "python_version < \"3.13\""} [package.extras] test = ["pytest (>=6)"] +[[package]] +name = "flask" +version = "3.1.3" +description = "A simple framework for building complex web applications." +optional = false +python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version < \"4.0\"" +files = [ + {file = "flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c"}, + {file = "flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"}, +] + +[package.dependencies] +blinker = ">=1.9.0" +click = ">=8.1.3" +itsdangerous = ">=2.2.0" +jinja2 = ">=3.1.2" +markupsafe = ">=2.1.1" +werkzeug = ">=3.1.0" + +[package.extras] +async = ["asgiref (>=3.2)"] +dotenv = ["python-dotenv"] + +[[package]] +name = "flask-cors" +version = "6.0.5" +description = "A Flask extension simplifying CORS support" +optional = false +python-versions = "<4.0,>=3.9" +groups = ["dev"] +markers = "python_version < \"4.0\"" +files = [ + {file = "flask_cors-6.0.5-py3-none-any.whl", hash = "sha256:68fcf75693e961f3af26683b23c4b9a8fb6b64de17d20d0c37b95e8de7ab2ed8"}, + {file = "flask_cors-6.0.5.tar.gz", hash = "sha256:30c5031552cd59f620ac0c8211dac45b345d3b2df310e7721879e4f46ef9c601"}, +] + +[package.dependencies] +flask = ">=0.9" +typing_extensions = {version = ">=4.6.0", markers = "python_version < \"3.11\""} +Werkzeug = ">=0.7" + [[package]] name = "idna" version = "3.18" @@ -937,6 +1006,38 @@ files = [ {file = "iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730"}, ] +[[package]] +name = "itsdangerous" +version = "2.2.0" +description = "Safely pass data to untrusted environments and back." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version < \"4.0\"" +files = [ + {file = "itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef"}, + {file = "itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173"}, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +description = "A very fast and expressive template engine." +optional = false +python-versions = ">=3.7" +groups = ["dev"] +markers = "python_version < \"4.0\"" +files = [ + {file = "jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67"}, + {file = "jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d"}, +] + +[package.dependencies] +MarkupSafe = ">=2.0" + +[package.extras] +i18n = ["Babel (>=2.7)"] + [[package]] name = "jmespath" version = "1.1.0" @@ -1773,4 +1874,4 @@ s3 = ["boto3"] [metadata] lock-version = "2.1" python-versions = ">=3.10" -content-hash = "0a5327e0095579ffa9380634d5ab43070793163140cba0c2437b005bbad6f8ac" +content-hash = "4dea3fad344979b3ddecee989a6fcefde414bb933970747f35067687ee469521" diff --git a/pyproject.toml b/pyproject.toml index d1dfbc0..9861c41 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,6 +31,12 @@ ruff = "^0.11.2" boto3 = "^1.37.31" boto3-stubs = "^1.34.145" mypy-boto3-s3 = "^1.34.105" +# moto's threaded server, which the Rust S3 client is tested against: a real +# HTTP endpoint rather than boto3's in-process mock. flask-cors caps Python +# below 4; the marker keeps that cap on this dev dependency alone rather than +# on loch's own requires-python. +flask = { version = "^3.0", python = ">=3.10,<4.0" } +flask-cors = { version = ">=4.0", python = ">=3.10,<4.0" } [tool.pytest.ini_options] testpaths = ["test"] diff --git a/rust/Cargo.lock b/rust/Cargo.lock index d59be59..742bb30 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "block-buffer" version = "0.10.4" @@ -11,6 +17,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -44,6 +60,18 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -52,12 +80,27 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -68,17 +111,141 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "hashbrown" -version = "0.15.5" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hmac" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] [[package]] name = "indexmap" -version = "2.7.1" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", @@ -96,21 +263,56 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "loch" version = "0.1.0" dependencies = [ + "hmac", "libc", "serde_json", "sha2", + "ureq", ] +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -129,6 +331,55 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "serde" version = "1.0.229" @@ -184,6 +435,30 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "3.0.10" @@ -195,6 +470,27 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "typenum" version = "1.20.1" @@ -207,12 +503,246 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 2567bf4..7a739bb 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -4,7 +4,7 @@ name = "loch" # `loch --version`, and they must not disagree while both ship. version = "0.1.0" edition = "2021" -rust-version = "1.83" +rust-version = "1.91" license = "MIT" description = "Save and restore agent coding sessions across machines" publish = false @@ -17,6 +17,10 @@ path = "src/main.rs" # preserve_order: payload keys come out in insertion order, as Python's dicts do. serde_json = { version = "1", features = ["preserve_order"] } sha2 = "0.10" +hmac = "0.12" +# Blocking and rustls-only: no async runtime and no system OpenSSL, so the +# binary stays static. Used by the S3 backend alone. +ureq = { version = "2", default-features = false, features = ["tls"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/rust/rust-toolchain.toml b/rust/rust-toolchain.toml new file mode 100644 index 0000000..f1b4387 --- /dev/null +++ b/rust/rust-toolchain.toml @@ -0,0 +1,7 @@ +# Pinned so a build is the same on every machine and in CI, and scoped to this +# directory so it never touches anyone's default toolchain. rustup installs it +# on first use. +[toolchain] +channel = "1.91.0" +profile = "minimal" +components = ["clippy", "rustfmt"] diff --git a/rust/src/main.rs b/rust/src/main.rs index 844d682..6fddd80 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -10,6 +10,7 @@ mod claude; mod git; mod hook; mod output; +mod s3; mod store; use output::{emit, emit_error, CommandError, Outcome, JSON_FLAG}; diff --git a/rust/src/s3.rs b/rust/src/s3.rs new file mode 100644 index 0000000..3b1e402 --- /dev/null +++ b/rust/src/s3.rs @@ -0,0 +1,395 @@ +//! The S3-compatible backend, signed with SigV4 by hand. +//! +//! An SDK would be the whole AWS credential chain in exchange for a static +//! binary several megabytes larger and an async runtime; the hook needs one +//! signed PUT. So the chain is the part people actually use against R2, B2, +//! MinIO, Garage and plain S3: the `AWS_*` variables, then the shared +//! credentials and config files for `AWS_PROFILE` (or `default`). SSO, +//! `credential_process`, assumed roles and instance metadata are not read; +//! boto3 reads them, so a machine relying on one of those needs the Python +//! build until they are. + +use crate::claude::home_dir; +use crate::store::{Store, StoreError}; +use hmac::{Hmac, Mac}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::fs; +use std::path::PathBuf; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +/// A hook has to come back before Claude Code gives up on it, so a store +/// that doesn't answer fails rather than hanging the turn. +const TIMEOUT: Duration = Duration::from_secs(20); + +pub struct S3Store { + bucket: String, + prefix: String, +} + +impl S3Store { + pub fn new(bucket: &str, prefix: &str) -> Self { + S3Store { + bucket: bucket.into(), + prefix: prefix.into(), + } + } + + fn key_for(&self, key: &str) -> String { + if self.prefix.is_empty() { + key.into() + } else { + format!("{}/{}", self.prefix, key) + } + } +} + +impl Store for S3Store { + fn put(&self, key: &str, data: &[u8]) -> Result<(), StoreError> { + let credentials = Credentials::load() + .ok_or_else(|| StoreError::Unreachable("no AWS credentials found".into()))?; + let region = region(); + let target = Target::new(&self.bucket, &self.key_for(key), ®ion); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let headers = sign( + "PUT", + &target, + &[("content-type", "application/gzip")], + data, + &credentials, + ®ion, + now, + ); + let mut request = ureq::AgentBuilder::new() + .timeout(TIMEOUT) + .build() + .put(&target.url()); + for (name, value) in &headers { + if name != "host" { + request = request.set(name, value); + } + } + request + .send_bytes(data) + .map(|_| ()) + .map_err(|error| StoreError::Unreachable(error.to_string())) + } +} + +struct Target { + scheme: String, + host: String, + path: String, +} + +impl Target { + /// Path style under `LOCH_S3_ENDPOINT` — MinIO, R2 and Garage need it — + /// and virtual-hosted against AWS, as boto3 addresses them. A bucket + /// with a dot can't be a TLS hostname, so it goes path style there too. + fn new(bucket: &str, key: &str, region: &str) -> Target { + let encoded = uri_encode_path(key); + match std::env::var("LOCH_S3_ENDPOINT") + .ok() + .filter(|e| !e.is_empty()) + { + Some(endpoint) => { + let (scheme, rest) = endpoint.split_once("://").unwrap_or(("https", &endpoint)); + let (host, base) = match rest.find('/') { + Some(slash) => (&rest[..slash], rest[slash..].trim_end_matches('/')), + None => (rest, ""), + }; + Target { + scheme: scheme.into(), + host: host.into(), + path: format!("{}/{}/{}", base, uri_encode_path(bucket), encoded), + } + } + None if bucket.contains('.') => Target { + scheme: "https".into(), + host: format!("s3.{}.amazonaws.com", region), + path: format!("/{}/{}", bucket, encoded), + }, + None => Target { + scheme: "https".into(), + host: format!("{}.s3.{}.amazonaws.com", bucket, region), + path: format!("/{}", encoded), + }, + } + } + + fn url(&self) -> String { + format!("{}://{}{}", self.scheme, self.host, self.path) + } +} + +/// RFC 3986 unreserved characters pass, `/` separates segments, and +/// everything else is percent-encoded. S3 signs the path encoded once. +fn uri_encode_path(text: &str) -> String { + let mut out = String::new(); + for byte in text.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { + out.push(byte as char) + } + _ => out.push_str(&format!("%{:02X}", byte)), + } + } + out +} + +fn hex(bytes: &[u8]) -> String { + bytes + .iter() + .map(|b| format!("{:02x}", b)) + .collect::>() + .concat() +} + +fn hmac(key: &[u8], data: &str) -> Vec { + let mut mac = Hmac::::new_from_slice(key).expect("HMAC takes any key length"); + mac.update(data.as_bytes()); + mac.finalize().into_bytes().to_vec() +} + +/// The headers of a SigV4-signed request, `authorization` among them. +fn sign( + method: &str, + target: &Target, + extra: &[(&str, &str)], + body: &[u8], + credentials: &Credentials, + region: &str, + now: u64, +) -> Vec<(String, String)> { + let stamp = amz_date(now); + let day = &stamp[..8]; + let payload = hex(&Sha256::digest(body)); + let mut headers: Vec<(String, String)> = vec![ + ("host".into(), target.host.clone()), + ("x-amz-content-sha256".into(), payload.clone()), + ("x-amz-date".into(), stamp.clone()), + ]; + for (name, value) in extra { + headers.push((name.to_string(), value.to_string())); + } + if let Some(token) = &credentials.session_token { + headers.push(("x-amz-security-token".into(), token.clone())); + } + headers.sort(); + let canonical_headers: String = headers + .iter() + .map(|(name, value)| format!("{}:{}\n", name, value.trim())) + .collect(); + let signed: String = headers + .iter() + .map(|(name, _)| name.as_str()) + .collect::>() + .join(";"); + let canonical = format!( + "{}\n{}\n\n{}\n{}\n{}", + method, target.path, canonical_headers, signed, payload + ); + let scope = format!("{}/{}/s3/aws4_request", day, region); + let to_sign = format!( + "AWS4-HMAC-SHA256\n{}\n{}\n{}", + stamp, + scope, + hex(&Sha256::digest(canonical.as_bytes())) + ); + let mut key = hmac(format!("AWS4{}", credentials.secret_key).as_bytes(), day); + for part in [region, "s3", "aws4_request"] { + key = hmac(&key, part); + } + let signature = hex(&hmac(&key, &to_sign)); + headers.push(( + "authorization".into(), + format!( + "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}", + credentials.access_key, scope, signed, signature + ), + )); + headers +} + +/// `YYYYMMDDTHHMMSSZ` from Unix seconds, without a date library. +fn amz_date(seconds: u64) -> String { + let days = (seconds / 86_400) as i64; + let rest = seconds % 86_400; + // Howard Hinnant's civil_from_days. + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{:04}{:02}{:02}T{:02}{:02}{:02}Z", + year, + month, + day, + rest / 3600, + rest % 3600 / 60, + rest % 60 + ) +} + +struct Credentials { + access_key: String, + secret_key: String, + session_token: Option, +} + +fn env(name: &str) -> Option { + std::env::var(name).ok().filter(|v| !v.is_empty()) +} + +fn profile() -> String { + env("AWS_PROFILE") + .or_else(|| env("AWS_DEFAULT_PROFILE")) + .unwrap_or_else(|| "default".into()) +} + +fn aws_file(variable: &str, name: &str) -> PathBuf { + env(variable) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(home_dir()).join(".aws").join(name)) +} + +/// One section of an AWS INI file. The config file names non-default +/// profiles `[profile name]`; the credentials file names them `[name]`. +fn ini_section(path: &PathBuf, section: &str) -> HashMap { + let mut values = HashMap::new(); + let Ok(text) = fs::read_to_string(path) else { + return values; + }; + let mut inside = false; + for line in text.lines() { + let line = line.trim(); + if line.starts_with('#') || line.starts_with(';') || line.is_empty() { + continue; + } + if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + inside = name.trim() == section; + continue; + } + if inside { + if let Some((key, value)) = line.split_once('=') { + values.insert(key.trim().to_lowercase(), value.trim().to_string()); + } + } + } + values +} + +fn config_section() -> HashMap { + let name = profile(); + let section = if name == "default" { + name + } else { + format!("profile {}", name) + }; + ini_section(&aws_file("AWS_CONFIG_FILE", "config"), §ion) +} + +impl Credentials { + fn load() -> Option { + if let (Some(access_key), Some(secret_key)) = + (env("AWS_ACCESS_KEY_ID"), env("AWS_SECRET_ACCESS_KEY")) + { + return Some(Credentials { + access_key, + secret_key, + session_token: env("AWS_SESSION_TOKEN"), + }); + } + let shared = ini_section( + &aws_file("AWS_SHARED_CREDENTIALS_FILE", "credentials"), + &profile(), + ); + for section in [shared, config_section()] { + if let (Some(access_key), Some(secret_key)) = ( + section.get("aws_access_key_id"), + section.get("aws_secret_access_key"), + ) { + return Some(Credentials { + access_key: access_key.clone(), + secret_key: secret_key.clone(), + session_token: section.get("aws_session_token").cloned(), + }); + } + } + None + } +} + +/// `LOCH_S3_REGION`, then what boto3 would read, then us-east-1. +fn region() -> String { + env("LOCH_S3_REGION") + .or_else(|| env("AWS_REGION")) + .or_else(|| env("AWS_DEFAULT_REGION")) + .or_else(|| config_section().get("region").cloned()) + .unwrap_or_else(|| "us-east-1".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dates_are_civil() { + assert_eq!(amz_date(0), "19700101T000000Z"); + assert_eq!(amz_date(951_782_400), "20000229T000000Z"); + assert_eq!(amz_date(1_794_947_157), "20261117T202557Z"); + } + + /// The worked example from AWS's SigV4 documentation for S3: a GET of + /// /test.txt from examplebucket, with its published signature. + #[test] + fn signature_matches_the_aws_example() { + let target = Target { + scheme: "https".into(), + host: "examplebucket.s3.amazonaws.com".into(), + path: "/test.txt".into(), + }; + let credentials = Credentials { + access_key: "AKIAIOSFODNN7EXAMPLE".into(), + secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into(), + session_token: None, + }; + // 2013-05-24T00:00:00Z + let headers = sign( + "GET", + &target, + &[("range", "bytes=0-9")], + b"", + &credentials, + "us-east-1", + 1_369_353_600, + ); + let authorization = &headers + .iter() + .find(|(n, _)| n == "authorization") + .unwrap() + .1; + assert_eq!( + authorization, + "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, \ + SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, \ + Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41" + ); + } + + #[test] + fn keys_are_encoded_once() { + assert_eq!( + uri_encode_path("transcripts/a b/c+d.jsonl"), + "transcripts/a%20b/c%2Bd.jsonl" + ); + } +} diff --git a/rust/src/store.rs b/rust/src/store.rs index 469b4d5..da3beea 100644 --- a/rust/src/store.rs +++ b/rust/src/store.rs @@ -56,16 +56,16 @@ pub fn resolve_store_uri(explicit: Option<&str>) -> String { pub fn create_store(uri: &str) -> Result, StoreError> { if let Some(rest) = uri.strip_prefix("s3://") { - let bucket = rest.split('/').next().unwrap_or(""); + let (bucket, prefix) = rest.split_once('/').unwrap_or((rest, "")); if bucket.is_empty() { return Err(StoreError::Invalid(format!( "invalid S3 store URI: {}", uri ))); } - return Err(StoreError::Unreachable( - "the S3 backend is not ported to the Rust build yet".into(), - )); + // `re.sub(r"/$", "", prefix)`: one trailing slash, not all of them. + let prefix = prefix.strip_suffix('/').unwrap_or(prefix); + return Ok(Box::new(crate::s3::S3Store::new(bucket, prefix))); } if let Some(rest) = uri.strip_prefix("file://") { return Ok(Box::new(FileStore::new(file_uri_path(rest)))); diff --git a/test/test_equivalence.py b/test/test_equivalence.py index 67312d9..fe87e55 100644 --- a/test/test_equivalence.py +++ b/test/test_equivalence.py @@ -501,16 +501,157 @@ def test_switching_over_mid_call( twin(tmp_path, scenario, mix=mix) -def test_stop_with_s3_store_differs_only_as_expected(tmp_path: Path) -> None: - """Placeholder until S3 is ported: both must at least leave stdout empty - and exit zero, since a hook may never fail its tool call.""" +@dataclass +class S3: + signed: bool + endpoint: str + access_key: str + secret_key: str + client: Any + + +@pytest.fixture(params=["signed", "unsigned"]) +def s3(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> Any: + """A real HTTP endpoint rather than boto3's in-process mock, since the Rust + build signs its own requests. "signed" turns moto's IAM auth on, so a + wrong signature is refused rather than waved through; the first four + actions, which create the user who signs everything after, go unchecked. + + "unsigned" exists because moto's verifier rejects boto3's own correct + signature on a key holding a space or `+`, so key encoding — which real + project directories exercise — can only be compared with auth off.""" + import urllib.request + + import boto3 + import moto.settings + from moto.core.responses import ActionAuthenticatorMixin + from moto.server import ThreadedMotoServer + + server = ThreadedMotoServer(ip_address="127.0.0.1", port=0) + server.start() + host, port = server.get_host_and_port() + endpoint = f"http://{host}:{port}" + # moto's state belongs to the process, not the server; start clean. + urllib.request.urlopen(urllib.request.Request(f"{endpoint}/moto-api/reset", b"")) + if request.param == "signed": + monkeypatch.setattr(moto.settings, "INITIAL_NO_AUTH_ACTION_COUNT", 4) + monkeypatch.setattr(ActionAuthenticatorMixin, "request_count", 0) + iam = boto3.client( + "iam", + endpoint_url=endpoint, + region_name="us-east-1", + aws_access_key_id="bootstrap", + aws_secret_access_key="bootstrap", + ) + iam.create_user(UserName="loch") + key = iam.create_access_key(UserName="loch")["AccessKey"] + iam.put_user_policy( + UserName="loch", + PolicyName="s3", + PolicyDocument=json.dumps( + { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}], + } + ), + ) + client = boto3.client( + "s3", + endpoint_url=endpoint, + region_name="us-east-1", + aws_access_key_id=key["AccessKeyId"], + aws_secret_access_key=key["SecretAccessKey"], + ) + client.create_bucket(Bucket="loch-test") + yield S3( + request.param == "signed", + endpoint, + key["AccessKeyId"], + key["SecretAccessKey"], + client, + ) + server.stop() + + +def test_stop_snapshots_into_s3_identically(tmp_path: Path, s3: S3) -> None: + """Each implementation snapshots under its own prefix of one bucket; the + keys and bytes beneath must match, and a bad secret must write nothing.""" world = World(tmp_path / "world") - event = {"session_id": SESSION, "transcript_path": str(tmp_path / "none")} + name = "-Users-x-repo" if s3.signed else "-a b+c%" + project = world.home / ".claude" / "projects" / name + project.mkdir(parents=True) + transcript = project / f"{SESSION}.jsonl" + transcript.write_bytes(b'{"type": "user"}\n\xff raw bytes \xe2\x9c\x93\n') + event = {"session_id": SESSION, "transcript_path": str(transcript)} + signed = { + "AWS_ACCESS_KEY_ID": s3.access_key, + "LOCH_S3_ENDPOINT": s3.endpoint, + "LOCH_S3_REGION": "us-east-1", + "AWS_SHARED_CREDENTIALS_FILE": os.devnull, + "AWS_CONFIG_FILE": os.devnull, + } + + contents: dict[str, dict[str, bytes]] = {} for impl in ("py", "rs"): - run = world.loch( - impl, "hook", "stop", stdin=event, env={"LOCH_STORE": "s3://bucket/p"} + runs = [ + world.loch( + impl, + "hook", + "stop", + stdin=event, + env={ + **signed, + "AWS_SECRET_ACCESS_KEY": s3.secret_key, + "LOCH_STORE": f"s3://loch-test/{impl}/", + }, + ), + world.loch( + impl, + "hook", + "stop", + stdin=event, + env={ + **signed, + "AWS_SECRET_ACCESS_KEY": "wrong", + "LOCH_STORE": f"s3://loch-test/{impl}-badly-signed", + }, + ), + world.loch( + impl, + "hook", + "stop", + stdin=event, + env={ + **{k: v for k, v in signed.items() if k != "AWS_ACCESS_KEY_ID"}, + "LOCH_STORE": f"s3://loch-test/{impl}-anonymous", + }, + ), + ] + # A hook may never fail its tool call, whatever the store says. + assert [(r.stdout, r.stderr, r.status) for r in runs] == [(b"", b"", 0)] * len( + runs ) - assert (run.stdout, run.status) == (b"", 0) + # Unprefixed: moto's verifier also rejects boto3's own signature on a + # listing whose prefix holds a `/`. + listed = s3.client.list_objects_v2(Bucket="loch-test") + contents[impl] = { + item["Key"]: s3.client.get_object(Bucket="loch-test", Key=item["Key"])[ + "Body" + ].read() + for item in listed.get("Contents", []) + if item["Key"].startswith(f"{impl}/") + } + assert list(contents["py"]) == [ + f"py/transcripts/claude-code/{name}/{SESSION}.jsonl" + ] + assert list(contents["py"].values()) == [transcript.read_bytes()] + assert {k.replace("rs/", "py/", 1): v for k, v in contents["rs"].items()} == ( + contents["py"] + ) + if s3.signed: + # Neither the bad secret nor the absent key got anything in. + every = s3.client.list_objects_v2(Bucket="loch-test").get("Contents", []) + assert sorted(item["Key"].split("/")[0] for item in every) == ["py", "rs"] # -- corpus ------------------------------------------------------------------- From baebba3a661f764585678e611b8717ce38403145 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 15:43:06 -0500 Subject: [PATCH 04/18] npm packaging sketch for the Rust build, and CLAUDE.md for all of it @ness-dev/loch with per-platform optionalDependencies, as Claude Code ships: a target map, an assembler, a postinstall that puts the native binary itself on PATH, and binaryPath() for embedders. Dry-run locally for darwin-arm64; the Node shim costs ~24ms a call, which is why embedders must spawn the binary directly. rust-binaries.yml builds the six targets and assembles the packages, manually and without publishing. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/rust-binaries.yml | 73 ++++++++++++++ CLAUDE.md | 148 +++++++++++++++++++++++++++- npm/assemble.mjs | 50 ++++++++++ npm/loch/bin/loch | 13 +++ npm/loch/index.js | 30 ++++++ npm/loch/install.js | 29 ++++++ npm/loch/package.json | 12 +++ npm/platforms.json | 8 ++ 8 files changed, 362 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/rust-binaries.yml create mode 100644 npm/assemble.mjs create mode 100755 npm/loch/bin/loch create mode 100644 npm/loch/index.js create mode 100644 npm/loch/install.js create mode 100644 npm/loch/package.json create mode 100644 npm/platforms.json diff --git a/.github/workflows/rust-binaries.yml b/.github/workflows/rust-binaries.yml new file mode 100644 index 0000000..11d9c89 --- /dev/null +++ b/.github/workflows/rust-binaries.yml @@ -0,0 +1,73 @@ +name: rust-binaries + +# Builds the Rust binary for every npm platform and assembles the npm packages +# as an artifact. Manual and publish-free on purpose: it has never run, and the +# release path it will eventually join must not inherit an untested job. Fold +# it into release.yml once a run has produced binaries that pass the harness. +on: + workflow_dispatch: + inputs: + version: + description: "version to stamp into the npm packages" + required: true + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - { target: aarch64-apple-darwin, os: macos-latest } + - { target: x86_64-apple-darwin, os: macos-latest } + # musl, statically linked: one binary per architecture runs on any + # distribution, glibc or not, which is why npm has no -musl packages. + - { target: x86_64-unknown-linux-musl, os: ubuntu-latest, musl: true } + - { target: aarch64-unknown-linux-musl, os: ubuntu-24.04-arm, musl: true } + - { target: x86_64-pc-windows-msvc, os: windows-latest } + - { target: aarch64-pc-windows-msvc, os: windows-11-arm } + runs-on: ${{ matrix.os }} + defaults: + run: + working-directory: rust + shell: bash + + steps: + - uses: actions/checkout@v7 + # ring compiles C, and a static musl build needs musl's own compiler. + - if: matrix.musl + run: sudo apt-get update && sudo apt-get install -y musl-tools + - run: rustup target add ${{ matrix.target }} + - run: cargo build --release --locked --target ${{ matrix.target }} + + - name: Check a Linux binary really is static + if: matrix.musl + run: | + file target/${{ matrix.target }}/release/loch + file target/${{ matrix.target }}/release/loch | grep -q "statically linked" + + - uses: actions/upload-artifact@v4 + with: + name: loch-${{ matrix.target }} + path: rust/target/${{ matrix.target }}/release/loch${{ contains(matrix.target, 'windows') && '.exe' || '' }} + + npm: + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v4 + with: + path: binaries + - name: Assemble the npm packages + run: | + args=() + for dir in binaries/loch-*; do + target=${dir#binaries/loch-} + args+=("$target=$(ls "$dir"/loch*)") + done + node npm/assemble.mjs "${{ inputs.version }}" dist/npm "${args[@]}" + for pkg in dist/npm/@ness-dev/*; do (cd "$pkg" && npm pack --pack-destination ../../..); done + - uses: actions/upload-artifact@v4 + with: + name: npm-packages + path: dist/*.tgz diff --git a/CLAUDE.md b/CLAUDE.md index 9c27819..16c5fd5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -165,7 +165,13 @@ loch/ └── store.py # Store interface + local-fs and S3-compatible backends test/ ├── test_corpus.py # opt-in, against this machine's transcripts (LOCH_CORPUS=1) +├── test_equivalence.py # opt-in, Rust build vs Python (LOCH_RUST=) └── test_*.py # one module per source module +rust/ # the Rust build: one crate, binary `loch` (see "The Rust build") +├── src/ # main, output, hook, git, store, s3, claude +├── bench/hook.py # per-call wall clock of `loch hook`, any number of binaries +└── rust-toolchain.toml +npm/ # @ness-dev/loch and its per-platform packages ``` `ingest.py` normalizes with `rewrite.py`'s machinery rather than its own: @@ -499,6 +505,7 @@ never a code. The set today: | `git-failed` | a git command failed | | `unknown-command` | no such subcommand | | `usage` | argparse rejected the arguments (exit status 2) | +| `not-ported` | the Rust build was asked for a command only the Python one has yet | | `internal` | an unexpected exception | The four store-facing codes — `bundle-not-found`, `store-unreachable`, @@ -602,6 +609,131 @@ both are attached to the GitHub release. The build is byte-reproducible; don't introduce anything timestamp-dependent into it. There is deliberately no PyPI publishing. +## The Rust build + +The goal is one static binary that Ness, a VS Code extension and the Claude +Code hooks can ship and run, with no Python on the machine. **The Python +package stays the reference implementation** until the port is complete: a +command moves to Rust only once `test/test_equivalence.py` holds the two to +the same output and side effects, and the Python suite has to keep passing +on its own throughout. + +**Layout: `rust/`, one crate, not a root workspace.** The repository root +belongs to Poetry (pyproject, the `loch` package, `release.sh`), and a root +`Cargo.toml` would mean two build systems claiming the same directory and a +`target/` beside the wheel's sources. One crate with modules mirroring the +Python ones (`hook.rs` ↔ the hook half of `trace.py`, `output.rs` ↔ +`output.py`, …) is enough until something needs splitting into a library a +second binary links; that is the point to make `rust/` a workspace, and +nothing outside it would have to move. + +The toolchain is pinned in `rust/rust-toolchain.toml` (1.91.0), scoped to +`rust/` so it never changes anyone's default. 1.83, which was installed, +can't build today's `url`/`idna`, and pinning half the dependency tree +backwards to stay on it would have been a standing cost for nothing. + +Unported commands answer `not-ported` rather than `unknown-command`: the +command exists, and the fix is the Python install, not a typo. + +**The equivalence harness** builds each scenario twice at the same path with +pinned git dates, so commit hashes, note blobs and even the notes-ref commit +come out byte-identical, then drives one copy with `python -m loch.cli` and +the other with the binary. It compares stdout, stderr and exit status +byte-for-byte — `output.rs` reproduces `json.dumps` exactly, `", "` +separators, `ensure_ascii` and float `repr` included, so that a comparison +can be on bytes rather than on parsed values — plus the notes ref, the +pending-state directory and the store. It also runs *mixed*: pre hook under +one build, post hook under the other, which is what happens the moment a +machine switches over mid-session; that is why the pending file's name and +JSON shape are part of the contract between the two. With `LOCH_CORPUS=1` +it adds the one hook path that reads a transcript (recovering a call id +when the payload lacks one) on 150 of this machine's real sessions by +default; their content exists only in a temp directory, failures name +session ids, and it asserts a note was written so that two builds agreeing +on nothing can't pass. Mutating the Rust (a wrong `captured` value, a +loosened time bound, a corrupted signing key) fails it; that was checked. + +**`loch hook` is ported, and costs 3ms a call instead of ~73ms.** Measured +with `rust/bench/hook.py` against the `uv tool` install: pre-tool 72.9 → +3.1ms, post-tool with no commit 72.4 → 3.1ms, post-tool writing a note +98.5 → 27.3ms (median of 60). The hooks run twice per agent shell command, +so that is ~145ms of every Bash call down to ~6ms. Python's cost was ~50ms +of imports — `importlib.metadata` alone is 19ms — and ~8ms per `git` +process, of which the hot path ran two. + +Getting under the git floor is the fast path in `git.rs`: the two +questions asked on every call — where is the git directory, what is HEAD — +are answered by reading `.git` (including a worktree's `gitdir:` file, +`commondir`, loose and packed refs) instead of spawning git. It answers +only on layouts it fully understands and returns "ask git" for anything +else: any discovery-changing `GIT_*` variable, reftable, a repository owned +by another user (git's `safe.directory` would refuse it), a cwd inside +`.git`, an unparseable ref, and Windows outright. **A gap there may only +ever cost speed, never a different answer**, which the harness checks by +having reftable, `GIT_DIR`, worktree, packed-refs, detached, unborn and +symlinked-subdirectory scenarios. The note-writing path still runs `git log` +and `git notes`, which is the remaining 24ms; it runs only when a call +actually committed. + +**S3 in Rust is SigV4 by hand over `ureq`/rustls**, not the AWS SDK — one +signed PUT doesn't justify an async runtime and several MB. Its credential +chain is `AWS_*` variables, then the shared credentials and config files for +`AWS_PROFILE`; **SSO, `credential_process`, assumed roles and instance +metadata are not read**, so a machine relying on them keeps the Python +hook for now. The signer is pinned to AWS's published worked example, and +the harness runs both builds against a moto server with IAM auth on, so a +bad signature is refused rather than waved through. moto's verifier itself +rejects boto3's correct signatures on keys holding a space or `+`, and on a +`ListObjectsV2` prefix holding `/`; the test works around both, and a +failure that looks like a signing bug in exactly those cases is moto's. +A stop hook against a store that doesn't answer gives up after 20s rather +than holding the turn. + +### Packaging + +**npm, the way Claude Code is shipped:** `@ness-dev/loch` with +`optionalDependencies` on `@ness-dev/loch-{darwin,linux,win32}-{arm64,x64}`, +each declaring `os`/`cpu` and holding one binary, so npm installs only the +host's. `npm/platforms.json` is the target-triple → package map, +`npm/assemble.mjs` lays out a release's packages from built binaries, and +`.github/workflows/rust-binaries.yml` (manual, publish-free, **never run**) +builds all six targets and assembles them. Assembling, `npm pack` and a +global install were dry-run locally for darwin-arm64. + +Linux binaries are static musl, so one package per architecture serves +glibc and musl alike. That is a deliberate difference from Claude Code's +packages, and Ness's resolver adds `-musl` on musl hosts, so it must not do +that for loch. + +**Embedders spawn the platform binary, never a Node shim.** Measured: going +through the wrapper's Node launcher costs ~24ms a call (27ms against 3ms), +which hands most of the port's win back on every hook. So `index.js` +exports `binaryPath()` — the same `createRequire` + `app.asar` → +`app.asar.unpacked` resolution Ness already uses for Claude Code — and an +Electron app must `asarUnpack` `**/node_modules/@ness-dev/loch-*/**`. For a +global `npm install -g`, the postinstall replaces `bin/loch` with a hardlink +to the native binary, so the `loch` on PATH is the binary itself; with +`--ignore-scripts`, or on Windows where npm runs bins through a `.cmd` +wrapper anyway, the shim remains and still works. For hooks, Ness +should write the binary's absolute path with `loch install --local +--command ` (settings.local.json, since the path is machine-specific) +rather than rely on PATH. + +**`uv tool install` users** have a working install of the reference, so +nothing changes for them until the port is complete. The intended switch is +to ship the Rust binary as platform wheels too — maturin's `bindings = +"bin"`, the way ruff and uv ship — attached to the GitHub release next to +today's pure-Python wheel, so the switch is the same `uv tool install +--force ` people already run. Platform wheels make that URL +per-platform. `uv tool install loch --find-links +https://github.com/ness-dev/loch/releases/expanded_assets/` would let uv +pick the right one without PyPI, **but it hasn't been tried** against a real +release page. Until then, a `uv tool` install and an npm global install both +put a `loch` on PATH and whichever comes first wins; the settings files +written by `install` name `loch`, so it is PATH order that decides which +build the hooks run. That is fine while the two are equivalent, which is +what the harness is for. + ## State Working and verified end to end: a session was created on a feature @@ -710,6 +842,14 @@ 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. +**Squash merges drop every note today**, and that is a requirement to fix, +not a workflow to avoid: loch has to support squash transparently in any +repository that installs it. It bit #2 — its commits' notes now annotate +commits `main` doesn't contain. A note annotates one object id, and a +squash makes a new commit from many, so nothing carries them. The design is +pending review: see the squash proposal in the conversation of the +`rust-rewrite` branch, which is to be recorded here once settled. + The rename from lochy carried no compatibility shim: `LOCHY_STORE`, `LOCHY_S3_ENDPOINT`, `LOCHY_S3_REGION` and the `~/.lochy/store` default are simply no longer read. That was chosen because nothing had been released and @@ -749,7 +889,13 @@ agree is a one-line property test. - Verify before committing: `poetry run ruff check`, `poetry run ruff format --check`, `poetry run mypy .`, and - `poetry run pytest`. + `poetry run pytest`. Touching `rust/` adds `cargo fmt --check`, + `cargo clippy --release --all-targets -- -D warnings`, `cargo test` there, + and `LOCH_RUST=rust/target/release/loch poetry run pytest + test/test_equivalence.py` after a `cargo build --release`. +- A command is ported when the harness covers it, not when it compiles. Port + behaviour exactly, quirks included, and fix a quirk in Python first if it + is a bug, so the reference stays the reference. - Commit coherent changes as you go rather than batching. - **Every command must be fully drivable by a program that never reads the human text.** A new command isn't finished until `--json` covers it — diff --git a/npm/assemble.mjs b/npm/assemble.mjs new file mode 100644 index 0000000..74eaa44 --- /dev/null +++ b/npm/assemble.mjs @@ -0,0 +1,50 @@ +// Lays out the npm packages for one release from built binaries: +// +// node npm/assemble.mjs = [...] +// +// e.g. aarch64-apple-darwin=rust/target/aarch64-apple-darwin/release/loch. +// Writes // for the wrapper and each platform given; the +// wrapper's optionalDependencies always name every platform, pinned to this +// exact version, so npm installs the one matching the host and only that. +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const platforms = JSON.parse(fs.readFileSync(path.join(here, "platforms.json"), "utf8")); +const [version, out, ...binaries] = process.argv.slice(2); +if (!version || !out) { + console.error("usage: assemble.mjs = ..."); + process.exit(2); +} + +const wrapper = JSON.parse(fs.readFileSync(path.join(here, "loch", "package.json"), "utf8")); +const wrapperDir = path.join(out, wrapper.name); +fs.cpSync(path.join(here, "loch"), wrapperDir, { recursive: true }); +fs.copyFileSync(path.join(here, "platforms.json"), path.join(wrapperDir, "platforms.json")); +wrapper.version = version; +wrapper.optionalDependencies = Object.fromEntries( + Object.values(platforms).map((p) => [p.package, version]), +); +fs.writeFileSync(path.join(wrapperDir, "package.json"), JSON.stringify(wrapper, null, 2) + "\n"); + +for (const spec of binaries) { + const [target, binary] = spec.split("="); + const platform = platforms[target]; + if (!platform) throw new Error(`no npm platform for ${target}`); + const dir = path.join(out, platform.package); + fs.mkdirSync(dir, { recursive: true }); + fs.copyFileSync(binary, path.join(dir, platform.bin)); + fs.chmodSync(path.join(dir, platform.bin), 0o755); + const manifest = { + name: platform.package, + version, + description: `The ${platform.os}-${platform.cpu} binary for @ness-dev/loch`, + license: "MIT", + repository: wrapper.repository, + os: [platform.os], + cpu: [platform.cpu], + files: [platform.bin], + }; + fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify(manifest, null, 2) + "\n"); +} diff --git a/npm/loch/bin/loch b/npm/loch/bin/loch new file mode 100755 index 0000000..9ca2c18 --- /dev/null +++ b/npm/loch/bin/loch @@ -0,0 +1,13 @@ +#!/usr/bin/env node +// Only used until install.js swaps in the native binary, or on Windows. +"use strict"; + +const { spawnSync } = require("child_process"); +const { binaryPath } = require("../index.js"); + +const result = spawnSync(binaryPath(), process.argv.slice(2), { stdio: "inherit" }); +if (result.error) { + process.stderr.write(`loch: ${result.error.message}\n`); + process.exit(1); +} +process.exit(result.status === null ? 1 : result.status); diff --git a/npm/loch/index.js b/npm/loch/index.js new file mode 100644 index 0000000..5f682f1 --- /dev/null +++ b/npm/loch/index.js @@ -0,0 +1,30 @@ +// Where this platform's loch binary is, for programs that embed loch (Ness, +// the VS Code extension). Spawn the path this returns rather than the `loch` +// on PATH or this package's bin/loch: the hooks run twice per agent shell +// command, and going through Node first would put its startup back on every +// call. Electron apps must also asarUnpack "**/node_modules/@ness-dev/loch-*/**" +// — a native binary can't be executed from inside an asar archive. +"use strict"; + +const { dirname, join, sep } = require("path"); +const platforms = require("./platforms.json"); + +function platformEntry() { + const key = `${process.platform}-${process.arch}`; + // Linux builds are static musl binaries, so one package per architecture + // serves glibc and musl alike — unlike Claude Code, there is no -musl split. + const entry = Object.values(platforms).find((p) => `${p.os}-${p.cpu}` === key); + if (!entry) throw new Error(`loch has no build for ${key}`); + return entry; +} + +function binaryPath() { + const entry = platformEntry(); + const manifest = require.resolve(`${entry.package}/package.json`); + return join(dirname(manifest), entry.bin).replace( + `${sep}app.asar${sep}`, + `${sep}app.asar.unpacked${sep}`, + ); +} + +module.exports = { binaryPath, platformEntry }; diff --git a/npm/loch/install.js b/npm/loch/install.js new file mode 100644 index 0000000..d82a614 --- /dev/null +++ b/npm/loch/install.js @@ -0,0 +1,29 @@ +// Replaces bin/loch, a Node shim, with the native binary itself, so that a +// `loch` on PATH from `npm install -g` costs nothing but loch. Hardlinked +// where possible and copied where not. Windows keeps the shim: npm reaches +// bins there through a .cmd wrapper that runs Node either way. +// +// If this never runs (--ignore-scripts), the shim still works, just slower. +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const { binaryPath } = require("./index.js"); + +if (process.platform !== "win32") { + try { + const native = binaryPath(); + const target = path.join(__dirname, "bin", "loch"); + const staged = `${target}.native`; + fs.rmSync(staged, { force: true }); + try { + fs.linkSync(native, staged); + } catch { + fs.copyFileSync(native, staged); + } + fs.chmodSync(staged, 0o755); + fs.renameSync(staged, target); + } catch (error) { + process.stderr.write(`loch: keeping the Node shim (${error.message})\n`); + } +} diff --git a/npm/loch/package.json b/npm/loch/package.json new file mode 100644 index 0000000..384a105 --- /dev/null +++ b/npm/loch/package.json @@ -0,0 +1,12 @@ +{ + "name": "@ness-dev/loch", + "version": "0.0.0", + "description": "Save and restore agent coding sessions across machines", + "license": "MIT", + "repository": { "type": "git", "url": "git+https://github.com/ness-dev/loch.git" }, + "main": "index.js", + "bin": { "loch": "bin/loch" }, + "scripts": { "postinstall": "node install.js" }, + "files": ["index.js", "install.js", "platforms.json", "bin/loch"], + "optionalDependencies": {} +} diff --git a/npm/platforms.json b/npm/platforms.json new file mode 100644 index 0000000..9b92c9f --- /dev/null +++ b/npm/platforms.json @@ -0,0 +1,8 @@ +{ + "aarch64-apple-darwin": { "package": "@ness-dev/loch-darwin-arm64", "os": "darwin", "cpu": "arm64", "bin": "loch" }, + "x86_64-apple-darwin": { "package": "@ness-dev/loch-darwin-x64", "os": "darwin", "cpu": "x64", "bin": "loch" }, + "aarch64-unknown-linux-musl": { "package": "@ness-dev/loch-linux-arm64", "os": "linux", "cpu": "arm64", "bin": "loch" }, + "x86_64-unknown-linux-musl": { "package": "@ness-dev/loch-linux-x64", "os": "linux", "cpu": "x64", "bin": "loch" }, + "aarch64-pc-windows-msvc": { "package": "@ness-dev/loch-win32-arm64", "os": "win32", "cpu": "arm64", "bin": "loch.exe" }, + "x86_64-pc-windows-msvc": { "package": "@ness-dev/loch-win32-x64", "os": "win32", "cpu": "x64", "bin": "loch.exe" } +} From 0dfee97d631272237c5469a5a96f1d6e4f98004e Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 15:43:13 -0500 Subject: [PATCH 05/18] CLAUDE.md: don't point at a conversation for the squash design Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 16c5fd5..c59c7b2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -847,8 +847,7 @@ not a workflow to avoid: loch has to support squash transparently in any repository that installs it. It bit #2 — its commits' notes now annotate commits `main` doesn't contain. A note annotates one object id, and a squash makes a new commit from many, so nothing carries them. The design is -pending review: see the squash proposal in the conversation of the -`rust-rewrite` branch, which is to be recorded here once settled. +pending review and gets recorded here once settled. The rename from lochy carried no compatibility shim: `LOCHY_STORE`, `LOCHY_S3_ENDPOINT`, `LOCHY_S3_REGION` and the `~/.lochy/store` default are From 3dc9c1a3d0221947ca78527a4a898ebe055d02da Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 16:53:06 -0500 Subject: [PATCH 06/18] Bundle refs no longer depend on the Python version or platform From 3.11 gzip.compress hands the header to zlib, which writes its own OS byte (19 on macOS, 3 on Linux) where 3.10 wrote 255, so the same sessions packed to different bytes and therefore different refs. The header is now written by hand, byte-identical to 3.10's on every platform. Bundles already saved keep their refs; a re-save of the same sessions from 3.11+ gets a new one. Co-Authored-By: Claude Opus 5.5 --- loch/bundle.py | 19 ++++++++++++++++++- test/test_bundle.py | 15 +++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/loch/bundle.py b/loch/bundle.py index 0a9aa6f..42eae78 100644 --- a/loch/bundle.py +++ b/loch/bundle.py @@ -1,6 +1,8 @@ import gzip import hashlib import json +import struct +import zlib from dataclasses import dataclass from typing import Any @@ -60,11 +62,26 @@ def _bundle_to_json(bundle: Bundle) -> dict[str, Any]: } +# The gzip header, written out rather than left to gzip.compress: from 3.11 +# that delegates to zlib, which stamps its own OS byte (19 on macOS, 3 on +# Linux) where 3.10 wrote 255. The ref is a hash of these bytes, so the same +# sessions got a different ref per platform and per Python. Fixed at 255 +# ("unknown"), which is what 3.10 always produced; XFL 2 is level 9. +GZIP_HEADER = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff" + + +def gzip_deterministic(data: bytes) -> bytes: + compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, 8, 0) + body = compressor.compress(data) + compressor.flush() + trailer = struct.pack(" bytes: encoded = json.dumps( _bundle_to_json(bundle), separators=(",", ":"), ensure_ascii=False ).encode("utf-8") - return gzip.compress(encoded, compresslevel=9, mtime=0) + return gzip_deterministic(encoded) def unpack_bundle(data: bytes) -> Bundle: diff --git a/test/test_bundle.py b/test/test_bundle.py index 8fb9b8c..074d9a9 100644 --- a/test/test_bundle.py +++ b/test/test_bundle.py @@ -1,3 +1,6 @@ +import gzip +import hashlib + import pytest from loch.bundle import ( @@ -71,3 +74,15 @@ def test_rejects_an_unsupported_version() -> None: ) with pytest.raises(ValueError, match="unsupported bundle version 2"): unpack_bundle(packed) + + +def test_packing_matches_python_310_on_every_platform() -> None: + from loch.bundle import gzip_deterministic + + data = b'{"a":"' + b"xyz" * 5000 + b'"}' + packed = gzip_deterministic(data) + # What 3.10's gzip.compress(data, 9, mtime=0) produced, OS byte 255 + # included; 3.12 on macOS writes 19 there and Linux 3. + assert packed[:10].hex() == "1f8b08000000000002ff" + assert hashlib.sha256(packed).hexdigest()[:16] == "405552bff938ef58" + assert gzip.decompress(packed) == data From 47a12d73da5002c8b7bcb5159660f009b76b2f9f Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 17:03:41 -0500 Subject: [PATCH 07/18] An undecodable transcript no longer takes down list, or save read_session_meta caught OSError only, so one transcript with a bad byte raised out of list and hid every session in the directory. Metadata now decodes with replacement; save refuses that session with a new code, transcript-unreadable, instead of a traceback. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + loch/claude.py | 6 +- loch/cli.py | 9 +- rust/Cargo.lock | 128 ++++-- rust/Cargo.toml | 12 +- rust/src/argparse.rs | 915 +++++++++++++++++++++++++++++++++++++++++++ rust/src/json.rs | 817 ++++++++++++++++++++++++++++++++++++++ rust/src/output.rs | 274 +++---------- rust/src/py.rs | 175 +++++++++ test/test_cli.py | 30 ++ 10 files changed, 2107 insertions(+), 260 deletions(-) create mode 100644 rust/src/argparse.rs create mode 100644 rust/src/json.rs create mode 100644 rust/src/py.rs diff --git a/CLAUDE.md b/CLAUDE.md index c59c7b2..d486de7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -491,6 +491,7 @@ never a code. The set today: | --- | --- | | `no-sessions` | `save` matched nothing | | `redaction-failed` | a secret survived redaction; nothing was uploaded | +| `transcript-unreadable` | `save` found a transcript that isn't UTF-8; nothing was uploaded | | `missing-ref` | `restore`/`delete` called without a ref | | `bundle-not-found` | the store answered and the ref isn't there | | `store-unreachable` | the store didn't answer | diff --git a/loch/claude.py b/loch/claude.py index 4695b07..68a111a 100644 --- a/loch/claude.py +++ b/loch/claude.py @@ -171,7 +171,11 @@ def _display_summary(text: str | None) -> str | None: def read_session_meta(path: str) -> SessionMeta | None: try: stat = os.stat(path) - raw = Path(path).read_text(encoding="utf-8") + # Replacing rather than strict: one undecodable byte (a file truncated + # mid-character) used to raise out of `list` and lose every session in + # the directory. Only metadata is read here; `save` decides separately + # whether the transcript can be packed. + raw = Path(path).read_text(encoding="utf-8", errors="replace") except OSError: return None diff --git a/loch/cli.py b/loch/cli.py index 880ff53..c87804f 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -347,7 +347,14 @@ def command_save(argv: list[str]) -> Result: for meta in sessions: # In memory only — the agent's own transcript on disk stays verbatim. try: - scrubbed = redact(Path(meta.path).read_text(encoding="utf-8")) + raw = Path(meta.path).read_bytes().decode("utf-8") + except UnicodeDecodeError as error: + fail( + "transcript-unreadable", + f"refusing to pack {meta.session_id}: not UTF-8 at byte {error.start}", + ) + try: + scrubbed = redact(raw) except RedactionError as error: fail("redaction-failed", f"refusing to pack {meta.session_id}: {error}") packed_sessions.append( diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 742bb30..6cf0381 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -2,12 +2,36 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "block-buffer" version = "0.10.4" @@ -42,6 +66,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -80,6 +113,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "fancy-regex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -87,10 +131,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] -name = "foldhash" -version = "0.2.0" +name = "flate2" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "libz-sys", +] [[package]] name = "form_urlencoded" @@ -251,18 +299,24 @@ dependencies = [ "hashbrown", ] -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libz-sys" +version = "1.1.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "litemap" version = "0.8.3" @@ -273,9 +327,13 @@ checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" name = "loch" version = "0.1.0" dependencies = [ + "fancy-regex", + "flate2", + "getrandom", "hmac", + "indexmap", "libc", - "serde_json", + "libz-sys", "sha2", "ureq", ] @@ -304,6 +362,12 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "potential_utf" version = "0.1.6" @@ -331,6 +395,23 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "ring" version = "0.17.14" @@ -409,21 +490,6 @@ dependencies = [ "syn", ] -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "foldhash", - "indexmap", - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - [[package]] name = "sha2" version = "0.10.9" @@ -551,6 +617,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -742,9 +814,3 @@ dependencies = [ "quote", "syn", ] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 7a739bb..3106694 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -14,8 +14,16 @@ name = "loch" path = "src/main.rs" [dependencies] -# preserve_order: payload keys come out in insertion order, as Python's dicts do. -serde_json = { version = "1", features = ["preserve_order"] } +indexmap = "2" +# Python's `re` has lookarounds, which the `regex` crate deliberately lacks; +# fancy-regex adds them and hands everything else to `regex`. +fancy-regex = "0.14" +# zlib itself, built from source and linked statically: the ref is a hash of +# the gzip bytes, and only zlib's own deflate reproduces zlib's output. +# miniz_oxide (flate2's default) compresses differently. +flate2 = { version = "1", default-features = false, features = ["zlib"] } +libz-sys = { version = "1", default-features = false, features = ["static", "libc"] } +getrandom = "0.2" sha2 = "0.10" hmac = "0.12" # Blocking and rustls-only: no async runtime and no system OpenSSL, so the diff --git a/rust/src/argparse.rs b/rust/src/argparse.rs new file mode 100644 index 0000000..9051cac --- /dev/null +++ b/rust/src/argparse.rs @@ -0,0 +1,915 @@ +//! The subset of Python's argparse that loch's commands use, ported from +//! CPython 3.12.10 closely enough that usage errors and `-h` come out byte for +//! byte the same: abbreviated long options, `--opt=value`, `--`, the +//! A/O/- pattern matching that decides which strings a `nargs="?"` positional +//! takes, and the help formatter's wrapping. The harness diffs both builds +//! over a spread of bad command lines to keep it that way. + +use std::collections::HashMap; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Nargs { + /// Exactly one value; a positional so declared is required. + One, + /// `nargs="?"`. + Optional, + /// A flag: store_true or help. + Zero, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Store, + StoreTrue, + Help, +} + +#[derive(Clone)] +struct Action { + options: Vec<&'static str>, + dest: String, + nargs: Nargs, + kind: Kind, + metavar: Option<&'static str>, + constant: Option<&'static str>, + default: Option<&'static str>, + help: Option<&'static str>, +} + +impl Action { + fn required(&self) -> bool { + self.options.is_empty() && self.nargs == Nargs::One + } + + fn name(&self) -> String { + if !self.options.is_empty() { + self.options.join("/") + } else if let Some(metavar) = self.metavar { + metavar.into() + } else { + self.dest.clone() + } + } + + fn metavar(&self) -> String { + match self.metavar { + Some(metavar) => metavar.into(), + None if self.options.is_empty() => self.dest.clone(), + None => self.dest.to_uppercase(), + } + } + + fn format_args(&self) -> String { + match self.nargs { + Nargs::One => self.metavar(), + Nargs::Optional => format!("[{}]", self.metavar()), + Nargs::Zero => String::new(), + } + } + + fn invocation(&self) -> String { + if self.options.is_empty() { + return self.metavar(); + } + if self.nargs == Nargs::Zero { + return self.options.join(", "); + } + let args = self.format_args(); + self.options + .iter() + .map(|option| format!("{} {}", option, args)) + .collect::>() + .join(", ") + } + + fn usage(&self) -> String { + if self.options.is_empty() { + return self.format_args(); + } + let part = if self.nargs == Nargs::Zero { + self.options[0].to_string() + } else { + format!("{} {}", self.options[0], self.format_args()) + }; + format!("[{}]", part) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Val { + Str(Option), + Flag(bool), +} + +pub struct Args { + values: HashMap, +} + +impl Args { + pub fn str(&self, dest: &str) -> Option { + match self.values.get(dest) { + Some(Val::Str(value)) => value.clone(), + _ => None, + } + } + + pub fn flag(&self, dest: &str) -> bool { + matches!(self.values.get(dest), Some(Val::Flag(true))) + } +} + +pub enum Exit { + /// `-h`: the help text, which main renders as the command's result. + Help(String), + /// An argparse error: the message, and the prose argparse would print. + Usage { message: String, prose: String }, +} + +pub struct Parser { + prog: String, + actions: Vec, +} + +impl Parser { + /// `argparse.ArgumentParser(prog=...)`, with `-h` first as argparse adds + /// it, then `--json` as `cli._parser` registers it. + pub fn new(prog: &str) -> Parser { + let mut parser = Parser { + prog: prog.into(), + actions: Vec::new(), + }; + parser.actions.push(Action { + options: vec!["-h", "--help"], + dest: "help".into(), + nargs: Nargs::Zero, + kind: Kind::Help, + metavar: None, + constant: None, + default: None, + help: Some("show this help message and exit"), + }); + parser.flag("--json", None); + parser + } + + fn dest_of(option: &str) -> String { + option.trim_start_matches('-').replace('-', "_") + } + + /// `add_argument("--name")`. + pub fn option(&mut self, option: &'static str) -> &mut Self { + self.push(option, Nargs::One, None, None, None) + } + + /// `add_argument("--name", default=...)`. + pub fn option_default(&mut self, option: &'static str, default: &'static str) -> &mut Self { + self.push(option, Nargs::One, None, None, Some(default)) + } + + /// `add_argument("--name", metavar=...)`. + pub fn option_metavar(&mut self, option: &'static str, metavar: &'static str) -> &mut Self { + self.push(option, Nargs::One, Some(metavar), None, None) + } + + /// `add_argument("--name", nargs="?", const=..., metavar=...)`. + pub fn option_optional( + &mut self, + option: &'static str, + constant: &'static str, + metavar: &'static str, + ) -> &mut Self { + self.push(option, Nargs::Optional, Some(metavar), Some(constant), None) + } + + fn push( + &mut self, + option: &'static str, + nargs: Nargs, + metavar: Option<&'static str>, + constant: Option<&'static str>, + default: Option<&'static str>, + ) -> &mut Self { + self.actions.push(Action { + options: vec![option], + dest: Self::dest_of(option), + nargs, + kind: Kind::Store, + metavar, + constant, + default, + help: None, + }); + self + } + + /// `add_argument("--name", action="store_true"[, dest=...])`. + pub fn flag(&mut self, option: &'static str, dest: Option<&str>) -> &mut Self { + self.actions.push(Action { + options: vec![option], + dest: dest.map(str::to_string).unwrap_or_else(|| Self::dest_of(option)), + nargs: Nargs::Zero, + kind: Kind::StoreTrue, + metavar: None, + constant: None, + default: None, + help: None, + }); + self + } + + /// `add_argument("name"[, nargs="?"])`. + pub fn positional(&mut self, name: &'static str, nargs: Nargs) -> &mut Self { + self.actions.push(Action { + options: Vec::new(), + dest: name.into(), + nargs, + kind: Kind::Store, + metavar: None, + constant: None, + default: None, + help: None, + }); + self + } + + fn error(&self, message: String) -> Exit { + let prose = format!("{}{}: error: {}\n", self.format_usage(), self.prog, message); + Exit::Usage { message, prose } + } + + fn argument_error(&self, action: Option<&Action>, message: &str) -> Exit { + match action { + Some(action) => self.error(format!("argument {}: {}", action.name(), message)), + None => self.error(message.into()), + } + } + + fn lookup(&self, option: &str) -> Option { + self.actions + .iter() + .position(|action| action.options.contains(&option)) + } + + /// The option strings in registration order, as `_option_string_actions` + /// iterates them. + fn option_strings(&self) -> Vec<(&'static str, usize)> { + self.actions + .iter() + .enumerate() + .flat_map(|(index, action)| action.options.iter().map(move |o| (*o, index))) + .collect() + } + + /// `_parse_optional`: None for a positional, else every interpretation. + fn parse_optional(&self, arg: &str) -> Option> { + if arg.is_empty() || !arg.starts_with('-') { + return None; + } + if let Some(index) = self.lookup(arg) { + return Some(vec![Tuple { + action: Some(index), + option: arg.into(), + sep: None, + explicit: None, + }]); + } + if arg.chars().count() == 1 { + return None; + } + if let Some((option, explicit)) = arg.split_once('=') { + if let Some(index) = self.lookup(option) { + return Some(vec![Tuple { + action: Some(index), + option: option.into(), + sep: Some("=".into()), + explicit: Some(explicit.into()), + }]); + } + } + let tuples = self.option_tuples(arg); + if !tuples.is_empty() { + return Some(tuples); + } + if is_negative_number(arg) { + return None; + } + if arg.contains(' ') { + return None; + } + Some(vec![Tuple { + action: None, + option: arg.into(), + sep: None, + explicit: None, + }]) + } + + fn option_tuples(&self, arg: &str) -> Vec { + let mut result = Vec::new(); + let second_dash = arg.chars().nth(1) == Some('-'); + let (prefix, sep, explicit) = match arg.split_once('=') { + Some((prefix, explicit)) => (prefix, Some("=".to_string()), Some(explicit.to_string())), + None => (arg, None, None), + }; + if second_dash { + for (option, index) in self.option_strings() { + if option.starts_with(prefix) { + result.push(Tuple { + action: Some(index), + option: option.into(), + sep: sep.clone(), + explicit: explicit.clone(), + }); + } + } + } else { + let split = arg.char_indices().nth(2).map(|(i, _)| i).unwrap_or(arg.len()); + let (short, short_explicit) = arg.split_at(split); + for (option, index) in self.option_strings() { + if option == short { + result.push(Tuple { + action: Some(index), + option: option.into(), + sep: Some(String::new()), + explicit: Some(short_explicit.into()), + }); + } else if option.starts_with(prefix) { + result.push(Tuple { + action: Some(index), + option: option.into(), + sep: sep.clone(), + explicit: explicit.clone(), + }); + } + } + } + result + } + + pub fn parse(&self, argv: &[String]) -> Result { + let mut pattern = String::new(); + let mut options: HashMap> = HashMap::new(); + let mut after_dashes = false; + for (i, arg) in argv.iter().enumerate() { + if after_dashes { + pattern.push('A'); + } else if arg == "--" { + pattern.push('-'); + after_dashes = true; + } else { + match self.parse_optional(arg) { + None => pattern.push('A'), + Some(tuples) => { + options.insert(i, tuples); + pattern.push('O'); + } + } + } + } + let pattern: Vec = pattern.chars().collect(); + + let mut state = State { + values: HashMap::new(), + seen: vec![false; self.actions.len()], + extras: Vec::new(), + }; + for action in &self.actions { + let default = match action.kind { + Kind::StoreTrue => Val::Flag(false), + Kind::Help => continue, + Kind::Store => Val::Str(action.default.map(str::to_string)), + }; + state.values.insert(action.dest.clone(), default); + } + let mut positionals: Vec = (0..self.actions.len()) + .filter(|&i| self.actions[i].options.is_empty()) + .collect(); + + let max_option = options.keys().copied().max(); + let mut start = 0usize; + if let Some(max_option) = max_option { + while start <= max_option { + let next = *options.keys().filter(|&&i| i >= start).min().expect("an option remains"); + if start != next { + let end = self.consume_positionals(&mut state, &mut positionals, argv, &pattern, start); + if end > start { + start = end; + continue; + } + start = end; + } + if !options.contains_key(&start) { + state.extras.extend(argv[start..next].iter().cloned()); + start = next; + } + start = self.consume_optional(&mut state, argv, &pattern, &options, start)?; + } + } + let stop = self.consume_positionals(&mut state, &mut positionals, argv, &pattern, start); + state.extras.extend(argv[stop.min(argv.len())..].iter().cloned()); + + let missing: Vec = self + .actions + .iter() + .enumerate() + .filter(|(i, action)| !state.seen[*i] && action.required()) + .map(|(_, action)| action.name()) + .collect(); + if !missing.is_empty() { + return Err(self.error(format!( + "the following arguments are required: {}", + missing.join(", ") + ))); + } + if !state.extras.is_empty() { + return Err(self.error(format!("unrecognized arguments: {}", state.extras.join(" ")))); + } + Ok(Args { + values: state.values, + }) + } + + fn take(&self, state: &mut State, index: usize, mut args: Vec) -> Result<(), Exit> { + state.seen[index] = true; + let action = &self.actions[index]; + match action.kind { + Kind::Help => Err(Exit::Help(self.format_help())), + Kind::StoreTrue => { + state.values.insert(action.dest.clone(), Val::Flag(true)); + Ok(()) + } + Kind::Store => { + let value = if args.is_empty() { + if action.options.is_empty() { + action.default.map(str::to_string) + } else { + action.constant.map(str::to_string) + } + } else { + Some(args.remove(0)) + }; + state.values.insert(action.dest.clone(), Val::Str(value)); + Ok(()) + } + } + } + + /// `_match_argument` for an optional: how many of the following strings + /// it takes, or argparse's error. + fn match_option(&self, index: usize, following: &[char]) -> Result { + let action = &self.actions[index]; + match action.nargs { + Nargs::Zero => Ok(0), + Nargs::Optional => Ok(usize::from(following.first() == Some(&'A'))), + Nargs::One if following.first() == Some(&'A') => Ok(1), + Nargs::One => Err(self.argument_error(Some(action), "expected one argument")), + } + } + + fn consume_optional( + &self, + state: &mut State, + argv: &[String], + pattern: &[char], + options: &HashMap>, + start: usize, + ) -> Result { + let tuples = &options[&start]; + if tuples.len() > 1 { + let matches: Vec<&str> = tuples.iter().map(|t| t.option.as_str()).collect(); + return Err(self.argument_error( + None, + &format!( + "ambiguous option: {} could match {}", + argv[start], + matches.join(", ") + ), + )); + } + let Tuple { + action, + mut option, + mut sep, + mut explicit, + } = tuples[0].clone(); + let mut action = action; + let mut taken: Vec<(usize, Vec)> = Vec::new(); + let stop; + loop { + let Some(index) = action else { + state.extras.push(argv[start].clone()); + // Actions gathered so far from a -xyz cluster still apply. + for (index, args) in taken { + self.take(state, index, args)?; + } + return Ok(start + 1); + }; + if let Some(arg) = explicit.clone() { + let count = self.match_option(index, &['A'])?; + let single_dash = option.chars().nth(1) != Some('-'); + if count == 0 && single_dash && !arg.is_empty() { + if sep.as_deref().is_some_and(|s| !s.is_empty()) || arg.starts_with('-') { + return Err(self.argument_error( + Some(&self.actions[index]), + &format!("ignored explicit argument {}", py_repr(&arg)), + )); + } + taken.push((index, Vec::new())); + let first: String = arg.chars().next().into_iter().collect(); + option = format!("-{}", first); + let rest: String = arg.chars().skip(1).collect(); + match self.lookup(&option) { + Some(next) => { + action = Some(next); + if rest.is_empty() { + sep = None; + explicit = None; + } else if let Some(after) = rest.strip_prefix('=') { + sep = Some("=".into()); + explicit = Some(after.into()); + } else { + sep = Some(String::new()); + explicit = Some(rest); + } + } + None => { + state.extras.push(format!("-{}", arg)); + stop = start + 1; + break; + } + } + } else if count == 1 { + taken.push((index, vec![arg])); + stop = start + 1; + break; + } else { + return Err(self.argument_error( + Some(&self.actions[index]), + &format!("ignored explicit argument {}", py_repr(&arg)), + )); + } + } else { + let from = start + 1; + let count = self.match_option(index, &pattern[from.min(pattern.len())..])?; + taken.push((index, argv[from..from + count].to_vec())); + stop = from + count; + break; + } + } + for (index, args) in taken { + self.take(state, index, args)?; + } + Ok(stop) + } + + fn consume_positionals( + &self, + state: &mut State, + positionals: &mut Vec, + argv: &[String], + pattern: &[char], + start: usize, + ) -> usize { + let selected = &pattern[start.min(pattern.len())..]; + let counts = self.match_partial(positionals, selected); + let mut index = start; + for (&action, &count) in positionals.iter().zip(&counts) { + let mut args = argv[index..index + count].to_vec(); + if pattern[index..index + count].contains(&'-') { + if let Some(at) = args.iter().position(|a| a == "--") { + args.remove(at); + } + } + index += count; + // Positionals never raise: they are plain stores. + let _ = self.take(state, action, args); + } + positionals.drain(..counts.len()); + index + } + + /// `_match_arguments_partial`: the longest prefix of positionals that + /// matches, each one's count, then trailing empties trimmed when an + /// option follows — the 3.12.10 behaviour that stops a `nargs="?"` + /// positional being consumed empty ahead of an option. + fn match_partial(&self, positionals: &[usize], pattern: &[char]) -> Vec { + for i in (1..=positionals.len()).rev() { + let shapes: Vec = positionals[..i] + .iter() + .map(|&p| self.actions[p].nargs) + .collect(); + if let Some(mut counts) = match_groups(&shapes, pattern, 0) { + let end: usize = counts.iter().sum(); + if end < pattern.len() && pattern[end] == 'O' { + while counts.last() == Some(&0) { + counts.pop(); + } + } + return counts; + } + } + Vec::new() + } + + // -- formatting ----------------------------------------------------------- + + fn width() -> usize { + terminal_columns().saturating_sub(2) + } + + pub fn format_usage(&self) -> String { + format!("{}\n", self.usage_block(Self::width()).trim_end_matches('\n')) + } + + fn usage_block(&self, width: usize) -> String { + let prefix = "usage: "; + let optionals: Vec<&Action> = self.actions.iter().filter(|a| !a.options.is_empty()).collect(); + let positionals: Vec<&Action> = self.actions.iter().filter(|a| a.options.is_empty()).collect(); + let opt_parts: Vec = optionals.iter().map(|a| a.usage()).collect(); + let pos_parts: Vec = positionals.iter().map(|a| a.usage()).collect(); + let all: Vec = opt_parts.iter().chain(&pos_parts).cloned().collect(); + let mut usage = self.prog.clone(); + if !all.is_empty() { + usage = format!("{} {}", usage, all.join(" ")); + } + let text_width = width; + if prefix.len() + usage.chars().count() > text_width { + let get_lines = |parts: &[String], indent: &str, prefix: Option<&str>| -> Vec { + let mut lines = Vec::new(); + let mut line: Vec<&str> = Vec::new(); + let indent_length = indent.chars().count(); + let mut line_len = match prefix { + Some(p) => p.chars().count() as isize - 1, + None => indent_length as isize - 1, + }; + for part in parts { + let part_len = part.chars().count() as isize; + if line_len + 1 + part_len > text_width as isize && !line.is_empty() { + lines.push(format!("{}{}", indent, line.join(" "))); + line.clear(); + line_len = indent_length as isize - 1; + } + line.push(part); + line_len += part_len + 1; + } + if !line.is_empty() { + lines.push(format!("{}{}", indent, line.join(" "))); + } + if prefix.is_some() { + lines[0] = lines[0].chars().skip(indent_length).collect(); + } + lines + }; + let prog_len = self.prog.chars().count(); + let lines: Vec = if (prefix.len() + prog_len) as f64 <= 0.75 * text_width as f64 { + let indent = " ".repeat(prefix.len() + prog_len + 1); + let mut head = vec![self.prog.clone()]; + if !opt_parts.is_empty() { + head.extend(opt_parts.iter().cloned()); + let mut lines = get_lines(&head, &indent, Some(prefix)); + lines.extend(get_lines(&pos_parts, &indent, None)); + lines + } else if !pos_parts.is_empty() { + head.extend(pos_parts.iter().cloned()); + get_lines(&head, &indent, Some(prefix)) + } else { + head + } + } else { + let indent = " ".repeat(prefix.len()); + let parts: Vec = opt_parts.iter().chain(&pos_parts).cloned().collect(); + let mut lines = get_lines(&parts, &indent, None); + if lines.len() > 1 { + lines = get_lines(&opt_parts, &indent, None); + lines.extend(get_lines(&pos_parts, &indent, None)); + } + let mut all = vec![self.prog.clone()]; + all.extend(lines); + all + }; + usage = lines.join("\n"); + } + format!("{}{}\n\n", prefix, usage) + } + + pub fn format_help(&self) -> String { + let width = Self::width(); + let max_help_position = 24usize.min(width.saturating_sub(20).max(4)); + let indent = 2usize; + let action_max = self + .actions + .iter() + .map(|a| a.invocation().chars().count() + indent) + .max() + .unwrap_or(0); + let help_position = (action_max + 2).min(max_help_position); + let help_width = width.saturating_sub(help_position).max(11); + let action_width = help_position as isize - indent as isize - 2; + + let format_action = |action: &Action| -> String { + let header = action.invocation(); + let mut out = String::new(); + match action.help { + None => out.push_str(&format!("{}{}\n", " ".repeat(indent), header)), + Some(help) => { + let first_indent; + if header.chars().count() as isize <= action_width { + let pad = action_width as usize - header.chars().count(); + out.push_str(&format!("{}{}{} ", " ".repeat(indent), header, " ".repeat(pad))); + first_indent = 0; + } else { + out.push_str(&format!("{}{}\n", " ".repeat(indent), header)); + first_indent = help_position; + } + let lines = wrap(help, help_width); + out.push_str(&format!("{}{}\n", " ".repeat(first_indent), lines[0])); + for line in &lines[1..] { + out.push_str(&format!("{}{}\n", " ".repeat(help_position), line)); + } + } + } + out + }; + let section = |heading: &str, actions: Vec<&Action>| -> String { + if actions.is_empty() { + return String::new(); + } + let body: String = actions.into_iter().map(&format_action).collect(); + format!("\n{}:\n{}\n", heading, body) + }; + let mut help = self.usage_block(width); + help.push_str(§ion( + "positional arguments", + self.actions.iter().filter(|a| a.options.is_empty()).collect(), + )); + help.push_str(§ion( + "options", + self.actions.iter().filter(|a| !a.options.is_empty()).collect(), + )); + // _long_break_matcher, then strip('\n') + '\n'. + while help.contains("\n\n\n") { + help = help.replace("\n\n\n", "\n\n"); + } + format!("{}\n", help.trim_matches('\n')) + } +} + +#[derive(Clone)] +struct Tuple { + action: Option, + option: String, + sep: Option, + explicit: Option, +} + +struct State { + values: HashMap, + seen: Vec, + extras: Vec, +} + +/// `re.match` of the concatenated positional patterns — each `(-*A-*)` or +/// `(-*A?-*)` — with the backtracking order a regex engine uses: greedy +/// first, shorter on failure. +fn match_groups(shapes: &[Nargs], pattern: &[char], at: usize) -> Option> { + let Some((&shape, rest)) = shapes.split_first() else { + return Some(Vec::new()); + }; + let dashes = |from: usize| pattern[from..].iter().take_while(|&&c| c == '-').count(); + let lead_max = dashes(at); + for lead in (0..=lead_max).rev() { + let after_lead = at + lead; + let a_options: &[usize] = match shape { + Nargs::One => &[1], + Nargs::Optional => &[1, 0], + Nargs::Zero => &[0], + }; + for &a in a_options { + if a == 1 && pattern.get(after_lead) != Some(&'A') { + continue; + } + let after_a = after_lead + a; + let trail_max = dashes(after_a); + for trail in (0..=trail_max).rev() { + let end = after_a + trail; + if let Some(mut counts) = match_groups(rest, pattern, end) { + counts.insert(0, end - at); + return Some(counts); + } + } + } + } + None +} + +/// `^-\d+$|^-\d*\.\d+$`. +fn is_negative_number(arg: &str) -> bool { + let Some(body) = arg.strip_prefix('-') else { + return false; + }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + if digits(body) { + return true; + } + match body.split_once('.') { + Some((whole, fraction)) => (whole.is_empty() || digits(whole)) && digits(fraction), + None => false, + } +} + +/// Python's `repr()` of a str, as `%r` puts it in "ignored explicit argument". +fn py_repr(text: &str) -> String { + let quote = if text.contains('\'') && !text.contains('"') { '"' } else { '\'' }; + let mut out = String::new(); + out.push(quote); + for c in text.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if c == quote => { + out.push('\\'); + out.push(c); + } + c if (c as u32) < 0x20 || c as u32 == 0x7f => out.push_str(&format!("\\x{:02x}", c as u32)), + c => out.push(c), + } + } + out.push(quote); + out +} + +/// `textwrap.wrap` for help text made of short words. +fn wrap(text: &str, width: usize) -> Vec { + let mut lines = Vec::new(); + let mut line = String::new(); + for word in text.split_whitespace() { + if !line.is_empty() && line.chars().count() + 1 + word.chars().count() > width { + lines.push(std::mem::take(&mut line)); + } + if !line.is_empty() { + line.push(' '); + } + line.push_str(word); + } + if !line.is_empty() || lines.is_empty() { + lines.push(line); + } + lines +} + +/// `shutil.get_terminal_size().columns`: COLUMNS if it is a positive integer, +/// else the size of the terminal on stdout, else 80. +pub fn terminal_columns() -> usize { + if let Some(columns) = std::env::var("COLUMNS") + .ok() + .and_then(|value| value.trim().parse::().ok()) + .filter(|&columns| columns > 0) + { + return columns as usize; + } + stdout_columns().filter(|&c| c > 0).unwrap_or(80) +} + +#[cfg(unix)] +fn stdout_columns() -> Option { + let mut size: libc::winsize = unsafe { std::mem::zeroed() }; + // SAFETY: TIOCGWINSZ writes a winsize into the pointer it is given. + let result = unsafe { libc::ioctl(1, libc::TIOCGWINSZ, &mut size) }; + (result == 0).then_some(size.ws_col as usize) +} + +#[cfg(not(unix))] +fn stdout_columns() -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn argv(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn a_trailing_optional_positional_is_not_swallowed_before_an_option() { + let mut parser = Parser::new("loch ask"); + parser + .positional("target", Nargs::One) + .positional("question", Nargs::Optional) + .flag("--at-commit", None); + let args = parser.parse(&argv(&["t", "--at-commit", "q"])).ok().unwrap(); + assert_eq!(args.str("target").as_deref(), Some("t")); + assert_eq!(args.str("question").as_deref(), Some("q")); + assert!(args.flag("at_commit")); + } + + #[test] + fn negative_numbers() { + assert!(is_negative_number("-5")); + assert!(is_negative_number("-.5")); + assert!(!is_negative_number("-x")); + } +} diff --git a/rust/src/json.rs b/rust/src/json.rs new file mode 100644 index 0000000..c115323 --- /dev/null +++ b/rust/src/json.rs @@ -0,0 +1,817 @@ +//! JSON as Python's `json` module reads and writes it. +//! +//! serde_json can't stand in: it refuses lone surrogates (five transcripts on +//! one machine hold them), rounds integers wider than 64 bits, and rejects the +//! `NaN`/`Infinity` Python accepts. Every id in the loch format, every bundle +//! ref and every byte of `--json` output depends on agreeing with Python +//! exactly, so this is a small parser and writer written to its rules: +//! duplicate keys keep their first position and last value, integers stay +//! exact, and strings hold surrogates in the mapping `py.rs` describes. + +use crate::py; +use indexmap::IndexMap; + +pub type Map = IndexMap; + +#[derive(Clone, Debug, PartialEq)] +pub enum Value { + Null, + Bool(bool), + /// Exact decimal, as Python's arbitrary-precision int prints. + Int(String), + Float(f64), + Str(String), + Array(Vec), + Object(Map), +} + +impl Value { + pub fn str(text: impl Into) -> Value { + Value::Str(text.into()) + } + + pub fn int(value: i64) -> Value { + Value::Int(value.to_string()) + } + + pub fn opt_str(value: Option<&str>) -> Value { + value.map(Value::str).unwrap_or(Value::Null) + } + + pub fn as_str(&self) -> Option<&str> { + match self { + Value::Str(text) => Some(text), + _ => None, + } + } + + pub fn as_object(&self) -> Option<&Map> { + match self { + Value::Object(map) => Some(map), + _ => None, + } + } + + pub fn as_array(&self) -> Option<&Vec> { + match self { + Value::Array(items) => Some(items), + _ => None, + } + } + + pub fn as_i64(&self) -> Option { + match self { + Value::Int(digits) => digits.parse().ok(), + _ => None, + } + } + + /// `obj.get(key)` on something that may not be a dict. + pub fn get(&self, key: &str) -> Option<&Value> { + self.as_object().and_then(|map| map.get(key)) + } + + /// Python truthiness. + pub fn truthy(&self) -> bool { + match self { + Value::Null => false, + Value::Bool(b) => *b, + Value::Int(digits) => digits != "0", + Value::Float(f) => *f != 0.0, + Value::Str(s) => !s.is_empty(), + Value::Array(a) => !a.is_empty(), + Value::Object(o) => !o.is_empty(), + } + } + + pub fn is_str(&self, text: &str) -> bool { + self.as_str() == Some(text) + } +} + +impl From<&str> for Value { + fn from(text: &str) -> Value { + Value::Str(text.to_string()) + } +} + +impl From for Value { + fn from(text: String) -> Value { + Value::Str(text) + } +} + +impl From for Value { + fn from(b: bool) -> Value { + Value::Bool(b) + } +} + +impl From for Value { + fn from(n: i64) -> Value { + Value::int(n) + } +} + +impl From for Value { + fn from(n: usize) -> Value { + Value::Int(n.to_string()) + } +} + +impl From for Value { + fn from(map: Map) -> Value { + Value::Object(map) + } +} + +impl From> for Value { + fn from(items: Vec) -> Value { + Value::Array(items) + } +} + +/// Builds a `Map` in insertion order: `object! { "a" => 1, "b" => "x" }`. +#[macro_export] +macro_rules! object { + () => { $crate::json::Map::new() }; + ($($key:expr => $value:expr),+ $(,)?) => {{ + let mut map = $crate::json::Map::new(); + $( map.insert(String::from($key), $crate::json::Value::from($value)); )+ + map + }}; +} + +// -- parsing ----------------------------------------------------------------- + +#[derive(Debug)] +pub struct ParseError; + +/// Nesting deeper than this fails rather than overflowing the stack; Python +/// would have raised RecursionError somewhat earlier. +const MAX_DEPTH: usize = 2000; + +/// `json.loads(text)`. +pub fn loads(text: &str) -> Result { + let mut parser = Parser { + bytes: text.as_bytes(), + text, + pos: 0, + depth: 0, + }; + parser.skip_ws(); + let value = parser.value()?; + parser.skip_ws(); + if parser.pos != parser.bytes.len() { + return Err(ParseError); + } + Ok(value) +} + +/// `json.loads(line)` for a line that is UTF-8 bytes, which is how transcript +/// lines arrive. Undecodable input fails, as `bytes.decode` would first. +pub fn loads_bytes(bytes: &[u8]) -> Result { + loads(std::str::from_utf8(bytes).map_err(|_| ParseError)?) +} + +struct Parser<'a> { + bytes: &'a [u8], + text: &'a str, + pos: usize, + depth: usize, +} + +impl Parser<'_> { + fn skip_ws(&mut self) { + while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.bytes.get(self.pos) { + self.pos += 1; + } + } + + fn eat(&mut self, literal: &str) -> bool { + if self.bytes[self.pos..].starts_with(literal.as_bytes()) { + self.pos += literal.len(); + true + } else { + false + } + } + + fn value(&mut self) -> Result { + match self.bytes.get(self.pos).copied().ok_or(ParseError)? { + b'"' => { + self.pos += 1; + Ok(Value::Str(self.string()?)) + } + b'{' => self.object(), + b'[' => self.array(), + b'n' if self.eat("null") => Ok(Value::Null), + b't' if self.eat("true") => Ok(Value::Bool(true)), + b'f' if self.eat("false") => Ok(Value::Bool(false)), + b'N' if self.eat("NaN") => Ok(Value::Float(f64::NAN)), + b'I' if self.eat("Infinity") => Ok(Value::Float(f64::INFINITY)), + b'-' if self.eat("-Infinity") => Ok(Value::Float(f64::NEG_INFINITY)), + b'-' | b'0'..=b'9' => self.number(), + _ => Err(ParseError), + } + } + + fn nest(&mut self) -> Result<(), ParseError> { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err(ParseError); + } + Ok(()) + } + + fn object(&mut self) -> Result { + self.nest()?; + self.pos += 1; + let mut map = Map::new(); + self.skip_ws(); + if self.bytes.get(self.pos) == Some(&b'}') { + self.pos += 1; + self.depth -= 1; + return Ok(Value::Object(map)); + } + loop { + if self.bytes.get(self.pos) != Some(&b'"') { + return Err(ParseError); + } + self.pos += 1; + let key = self.string()?; + self.skip_ws(); + if self.bytes.get(self.pos) != Some(&b':') { + return Err(ParseError); + } + self.pos += 1; + self.skip_ws(); + let value = self.value()?; + // dict assignment: a repeated key keeps its first position. + map.insert(key, value); + self.skip_ws(); + match self.bytes.get(self.pos) { + Some(b',') => { + self.pos += 1; + self.skip_ws(); + } + Some(b'}') => { + self.pos += 1; + self.depth -= 1; + return Ok(Value::Object(map)); + } + _ => return Err(ParseError), + } + } + } + + fn array(&mut self) -> Result { + self.nest()?; + self.pos += 1; + let mut items = Vec::new(); + self.skip_ws(); + if self.bytes.get(self.pos) == Some(&b']') { + self.pos += 1; + self.depth -= 1; + return Ok(Value::Array(items)); + } + loop { + items.push(self.value()?); + self.skip_ws(); + match self.bytes.get(self.pos) { + Some(b',') => { + self.pos += 1; + self.skip_ws(); + } + Some(b']') => { + self.pos += 1; + self.depth -= 1; + return Ok(Value::Array(items)); + } + _ => return Err(ParseError), + } + } + } + + fn number(&mut self) -> Result { + let start = self.pos; + if self.bytes[self.pos] == b'-' { + self.pos += 1; + } + let digits = |p: &mut Self| { + let from = p.pos; + while p.bytes.get(p.pos).is_some_and(u8::is_ascii_digit) { + p.pos += 1; + } + p.pos - from + }; + match self.bytes.get(self.pos) { + Some(b'0') => self.pos += 1, + Some(b'1'..=b'9') => { + digits(self); + } + _ => return Err(ParseError), + } + let mut float = false; + if self.bytes.get(self.pos) == Some(&b'.') + && self.bytes.get(self.pos + 1).is_some_and(u8::is_ascii_digit) + { + self.pos += 1; + digits(self); + float = true; + } + if let Some(b'e' | b'E') = self.bytes.get(self.pos) { + let save = self.pos; + self.pos += 1; + if let Some(b'+' | b'-') = self.bytes.get(self.pos) { + self.pos += 1; + } + if digits(self) == 0 { + self.pos = save; + } else { + float = true; + } + } + let literal = &self.text[start..self.pos]; + if float { + literal + .parse::() + .map(Value::Float) + .map_err(|_| ParseError) + } else { + let trimmed = literal.trim_start_matches('-'); + let negative = literal.starts_with('-') && trimmed != "0"; + Ok(Value::Int(if negative { + literal.to_string() + } else { + trimmed.to_string() + })) + } + } + + fn hex4(&self, at: usize) -> Option { + let slice = self.bytes.get(at..at + 4)?; + if !slice.iter().all(u8::is_ascii_hexdigit) { + return None; + } + u32::from_str_radix(std::str::from_utf8(slice).ok()?, 16).ok() + } + + fn string(&mut self) -> Result { + let mut out = String::new(); + loop { + let run_start = self.pos; + while let Some(&b) = self.bytes.get(self.pos) { + if b == b'"' || b == b'\\' || b < 0x20 { + break; + } + self.pos += 1; + } + out.push_str(&self.text[run_start..self.pos]); + match self.bytes.get(self.pos).copied() { + Some(b'"') => { + self.pos += 1; + return Ok(out); + } + Some(b'\\') => { + let escape = *self.bytes.get(self.pos + 1).ok_or(ParseError)?; + self.pos += 2; + match escape { + b'"' => out.push('"'), + b'\\' => out.push('\\'), + b'/' => out.push('/'), + b'b' => out.push('\u{08}'), + b'f' => out.push('\u{0c}'), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), + b'u' => { + let unit = self.hex4(self.pos).ok_or(ParseError)?; + self.pos += 4; + if (0xD800..=0xDBFF).contains(&unit) + && self.bytes.get(self.pos..self.pos + 2) == Some(b"\\u") + { + if let Some(low @ 0xDC00..=0xDFFF) = self.hex4(self.pos + 2) { + let code = 0x10000 + ((unit - 0xD800) << 10) + (low - 0xDC00); + out.push(char::from_u32(code).ok_or(ParseError)?); + self.pos += 6; + continue; + } + } + if (0xD800..=0xDFFF).contains(&unit) { + out.push(py::surrogate(unit)); + } else { + out.push(char::from_u32(unit).ok_or(ParseError)?); + } + } + _ => return Err(ParseError), + } + } + // A raw control character, or the end: both errors under + // Python's default strict=True. + _ => return Err(ParseError), + } + } + } +} + +// -- writing ----------------------------------------------------------------- + +#[derive(Clone, Copy)] +pub struct Style { + pub ensure_ascii: bool, + pub item_sep: &'static str, + pub key_sep: &'static str, + pub sort_keys: bool, + pub indent: Option, +} + +/// `json.dumps(value)`. +pub const DEFAULT: Style = Style { + ensure_ascii: true, + item_sep: ", ", + key_sep: ": ", + sort_keys: false, + indent: None, +}; + +/// `json.dumps(value, separators=(",", ":"), ensure_ascii=False)`. +pub const COMPACT_UNICODE: Style = Style { + ensure_ascii: false, + item_sep: ",", + key_sep: ":", + sort_keys: false, + indent: None, +}; + +/// `json.dumps(value, sort_keys=True, separators=(",", ":"))`. +pub const COMPACT_SORTED: Style = Style { + ensure_ascii: true, + item_sep: ",", + key_sep: ":", + sort_keys: true, + indent: None, +}; + +/// `json.dumps(value, ensure_ascii=False)`. +pub const UNICODE: Style = Style { + ensure_ascii: false, + ..DEFAULT +}; + +/// `json.dumps(value, indent=2)`, whose item separator is a bare comma. +pub const INDENTED: Style = Style { + ensure_ascii: true, + item_sep: ",", + key_sep: ": ", + sort_keys: false, + indent: Some(2), +}; + +pub fn dumps(value: &Value, style: Style) -> String { + let mut out = String::new(); + write(&mut out, value, style, 0); + out +} + +fn newline(out: &mut String, style: Style, level: usize) { + if let Some(width) = style.indent { + out.push('\n'); + out.push_str(&" ".repeat(width * level)); + } +} + +fn write(out: &mut String, value: &Value, style: Style, level: usize) { + match value { + Value::Null => out.push_str("null"), + Value::Bool(true) => out.push_str("true"), + Value::Bool(false) => out.push_str("false"), + Value::Int(digits) => out.push_str(digits), + Value::Float(f) => out.push_str(&float_repr(*f)), + Value::Str(text) => write_str(out, text, style.ensure_ascii), + Value::Array(items) => { + if items.is_empty() { + out.push_str("[]"); + return; + } + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push_str(style.item_sep); + } + newline(out, style, level + 1); + write(out, item, style, level + 1); + } + newline(out, style, level); + out.push(']'); + } + Value::Object(map) => { + if map.is_empty() { + out.push_str("{}"); + return; + } + out.push('{'); + let mut entries: Vec<(&String, &Value)> = map.iter().collect(); + if style.sort_keys { + entries.sort_by(|a, b| py::cmp(a.0, b.0)); + } + for (i, (key, item)) in entries.into_iter().enumerate() { + if i > 0 { + out.push_str(style.item_sep); + } + newline(out, style, level + 1); + write_str(out, key, style.ensure_ascii); + out.push_str(style.key_sep); + write(out, item, style, level + 1); + } + newline(out, style, level); + out.push('}'); + } + } +} + +/// Python's string escaping. With `ensure_ascii` everything outside printable +/// ASCII is `\uXXXX`; without it, only `"`, `\` and control characters are +/// escaped and a surrogate is written as itself — which Python then fails to +/// encode, so callers encode with `py::encode_strict` and treat that the same. +pub fn write_str(out: &mut String, text: &str, ensure_ascii: bool) { + out.push('"'); + for c in text.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{08}' => out.push_str("\\b"), + '\u{0c}' => out.push_str("\\f"), + '\u{00}'..='\u{1f}' => out.push_str(&format!("\\u{:04x}", c as u32)), + ' '..='~' => out.push(c), + _ if !ensure_ascii => out.push(c), + _ => match py::as_surrogate(c) { + Some(unit) => out.push_str(&format!("\\u{:04x}", unit)), + None => { + let mut units = [0u16; 2]; + for unit in c.encode_utf16(&mut units) { + out.push_str(&format!("\\u{:04x}", unit)); + } + } + }, + } + } + out.push('"'); +} + +/// The shortest round-trip digits of a finite, positive double, and the +/// decimal exponent of the first: 0.00123 is ("123", -3). +fn shortest_digits(value: f64) -> (String, i32) { + let scientific = format!("{:e}", value); + let (mantissa, exponent) = scientific.split_once('e').expect("{:e} has an e"); + let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); + let digits = digits.trim_end_matches('0'); + let digits = if digits.is_empty() { "0" } else { digits }; + (digits.to_string(), exponent.parse().expect("integer exponent")) +} + +/// Python's `float.__repr__`, which `json.dumps` writes: positional when the +/// exponent is in [-4, 16), `d.ddde±XX` outside. +pub fn float_repr(value: f64) -> String { + if value.is_nan() { + return "NaN".into(); + } + if value.is_infinite() { + return if value > 0.0 { "Infinity" } else { "-Infinity" }.into(); + } + let sign = if value.is_sign_negative() { "-" } else { "" }; + if value == 0.0 { + return format!("{}0.0", sign); + } + let (digits, exponent) = shortest_digits(value.abs()); + if (-4..16).contains(&exponent) { + let point = exponent + 1; + let body = if point <= 0 { + format!("0.{}{}", "0".repeat((-point) as usize), digits) + } else if point as usize >= digits.len() { + format!("{}{}.0", digits, "0".repeat(point as usize - digits.len())) + } else { + let (whole, fraction) = digits.split_at(point as usize); + format!("{}.{}", whole, fraction) + }; + format!("{}{}", sign, body) + } else { + let (first, rest) = digits.split_at(1); + let fraction = if rest.is_empty() { + String::new() + } else { + format!(".{}", rest) + }; + let exponent_sign = if exponent < 0 { '-' } else { '+' }; + format!( + "{}{}{}e{}{:02}", + sign, + first, + fraction, + exponent_sign, + exponent.abs() + ) + } +} + +// -- RFC 8785 ------------------------------------------------------------------- + +#[derive(Debug)] +pub struct NotJson; + +/// RFC 8785, exactly as `format.canonical` writes it: keys by UTF-16 code +/// unit, strings escaped as JSON.stringify does (a lone surrogate as +/// `\uXXXX`), numbers as ECMAScript prints them — except that an integer +/// prints exactly at any size, the departure format.py documents. +pub fn canonical(value: &Value) -> Result, NotJson> { + let mut out = String::new(); + write_canonical(&mut out, value)?; + Ok(out.into_bytes()) +} + +fn canonical_str(out: &mut String, text: &str) { + out.push('"'); + for c in text.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{08}' => out.push_str("\\b"), + '\u{0c}' => out.push_str("\\f"), + '\u{00}'..='\u{1f}' => out.push_str(&format!("\\u{:04x}", c as u32)), + _ => match py::as_surrogate(c) { + Some(unit) => out.push_str(&format!("\\u{:04x}", unit)), + None => out.push(c), + }, + } + } + out.push('"'); +} + +fn utf16_units(text: &str) -> Vec { + let mut units = Vec::with_capacity(text.len()); + let mut buffer = [0u16; 2]; + for c in text.chars() { + match py::as_surrogate(c) { + Some(unit) => units.push(unit as u16), + None => units.extend_from_slice(c.encode_utf16(&mut buffer)), + } + } + units +} + +fn write_canonical(out: &mut String, value: &Value) -> Result<(), NotJson> { + match value { + Value::Null => out.push_str("null"), + Value::Bool(true) => out.push_str("true"), + Value::Bool(false) => out.push_str("false"), + Value::Int(digits) => out.push_str(digits), + Value::Float(f) => out.push_str(&ecma_number(*f)?), + Value::Str(text) => canonical_str(out, text), + Value::Array(items) => { + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + write_canonical(out, item)?; + } + out.push(']'); + } + Value::Object(map) => { + let mut keys: Vec<(Vec, &String)> = + map.keys().map(|key| (utf16_units(key), key)).collect(); + keys.sort_by(|a, b| a.0.cmp(&b.0)); + out.push('{'); + for (i, (_, key)) in keys.into_iter().enumerate() { + if i > 0 { + out.push(','); + } + canonical_str(out, key); + out.push(':'); + write_canonical(out, &map[key])?; + } + out.push('}'); + } + } + Ok(()) +} + +/// ECMAScript Number-to-String. +fn ecma_number(value: f64) -> Result { + if !value.is_finite() { + return Err(NotJson); + } + if value == 0.0 { + return Ok("0".into()); + } + let sign = if value < 0.0 { "-" } else { "" }; + let (digits, exponent) = shortest_digits(value.abs()); + let k = digits.len() as i32; + let n = exponent + 1; + Ok(if k <= n && n <= 21 { + format!("{}{}{}", sign, digits, "0".repeat((n - k) as usize)) + } else if 0 < n && n <= 21 { + format!("{}{}.{}", sign, &digits[..n as usize], &digits[n as usize..]) + } else if -6 < n && n <= 0 { + format!("{}0.{}{}", sign, "0".repeat((-n) as usize), digits) + } else { + let mantissa = if k > 1 { + format!("{}.{}", &digits[..1], &digits[1..]) + } else { + digits.clone() + }; + let power = n - 1; + format!( + "{}{}e{}{}", + sign, + mantissa, + if power >= 0 { '+' } else { '-' }, + power.abs() + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn floats_match_python_repr() { + for (value, expected) in [ + (1.0, "1.0"), + (0.1, "0.1"), + (1731859200.123456, "1731859200.123456"), + (1e16, "1e+16"), + (1.5e16, "1.5e+16"), + (123456789012345.6, "123456789012345.6"), + (0.0001, "0.0001"), + (0.00001, "1e-05"), + (-2.5e-7, "-2.5e-07"), + (0.0, "0.0"), + (-0.0, "-0.0"), + (1e300, "1e+300"), + (100.0, "100.0"), + ] { + assert_eq!(float_repr(value), expected, "{value}"); + } + } + + #[test] + fn numbers_match_ecmascript() { + for (value, expected) in [ + (1e16, "10000000000000000"), + (0.00001, "0.00001"), + (1e21, "1e+21"), + (1e-7, "1e-7"), + (1.5, "1.5"), + (100.0, "100"), + (-0.0, "0"), + ] { + assert_eq!(ecma_number(value).unwrap(), expected, "{value}"); + } + } + + #[test] + fn parses_what_python_parses() { + let value = loads(r#" {"a": 1, "b": [1.5, -0, 123456789012345678901234567890], "a": NaN, "s": "😀\ud83d x"} "#).unwrap(); + let map = value.as_object().unwrap(); + assert_eq!(map.keys().collect::>(), ["a", "b", "s"]); + assert!(matches!(map["a"], Value::Float(f) if f.is_nan())); + assert_eq!( + dumps(&map["b"], DEFAULT), + "[1.5, 0, 123456789012345678901234567890]" + ); + assert_eq!(dumps(&map["s"], DEFAULT), r#""😀\ud83d x""#); + assert!(loads("[1] x").is_err()); + assert!(loads("\"a\nb\"").is_err()); + assert!(loads("01").is_err()); + } + + #[test] + fn strings_escape_like_ensure_ascii() { + let value = Value::Object(object! {"a" => "é😀\u{7f}\u{1}\"\\\n", "b" => Value::Array(vec![Value::int(1), Value::Bool(true), Value::Null])}); + assert_eq!( + dumps(&value, DEFAULT), + "{\"a\": \"\\u00e9\\ud83d\\ude00\\u007f\\u0001\\\"\\\\\\n\", \"b\": [1, true, null]}" + ); + assert_eq!( + dumps(&value, COMPACT_UNICODE), + "{\"a\":\"é😀\u{7f}\\u0001\\\"\\\\\\n\",\"b\":[1,true,null]}" + ); + } + + #[test] + fn indent_matches_python() { + let value = Value::Object(object! {"a" => Value::Array(vec![]), "b" => Value::Object(object!{"c" => 1i64})}); + assert_eq!( + dumps(&value, INDENTED), + "{\n \"a\": [],\n \"b\": {\n \"c\": 1\n }\n}" + ); + } +} diff --git a/rust/src/output.rs b/rust/src/output.rs index be3d290..87714e0 100644 --- a/rust/src/output.rs +++ b/rust/src/output.rs @@ -1,11 +1,6 @@ //! The result envelope and its two renderings, as in `loch/output.py`. -//! -//! JSON is written the way Python's `json.dumps` writes it by default — `", "` -//! and `": "` separators, every non-ASCII character escaped, floats in `repr` -//! form — so the equivalence harness can compare the two implementations' -//! stdout byte for byte rather than only after parsing. -use serde_json::{Map, Value}; +use crate::json::{self, Map, Value}; use std::io::Write; pub const SCHEMA: i64 = 1; @@ -16,7 +11,7 @@ pub const JSON_FLAG: &str = "--json"; /// prose in one place is what keeps them from drifting apart. pub struct Outcome { pub command: String, - pub payload: Map, + pub payload: Map, pub text: String, pub warnings: Vec, } @@ -30,14 +25,25 @@ impl Outcome { warnings: Vec::new(), } } + + pub fn with(command: &str, payload: Map, text: String) -> Self { + Outcome { + command: command.into(), + payload, + text, + warnings: Vec::new(), + } + } } /// A failure the caller is meant to act on. `code` is a stable token — /// consumers branch on it, so reword `message` freely but not `code`. +#[derive(Debug)] pub struct CommandError { pub code: &'static str, pub message: String, - pub payload: Map, + pub payload: Map, + pub warnings: Vec, pub exit_status: i32, pub prose: Option, } @@ -48,30 +54,43 @@ impl CommandError { code, message: message.into(), payload: Map::new(), + warnings: Vec::new(), exit_status: 1, prose: None, } } } -pub fn document( - command: &str, - ok: bool, - payload: Map, - failure: Option<(&str, &str)>, -) -> Value { +pub type Result = std::result::Result; + +pub fn fail(code: &'static str, message: impl Into) -> Result { + Err(CommandError::new(code, message)) +} + +pub fn document(command: &str, ok: bool, payload: Map, failure: Option<(&str, &str)>) -> Value { let mut body = Map::new(); - body.insert("schema".into(), Value::from(SCHEMA)); - body.insert("ok".into(), Value::from(ok)); - body.insert("command".into(), Value::from(command)); + body.insert("schema".into(), Value::int(SCHEMA)); + body.insert("ok".into(), Value::Bool(ok)); + body.insert("command".into(), Value::str(command)); if let Some((code, error)) = failure { - body.insert("code".into(), Value::from(code)); - body.insert("error".into(), Value::from(error)); + body.insert("code".into(), Value::str(code)); + body.insert("error".into(), Value::str(error)); + } + for (key, value) in payload { + body.insert(key, value); } - body.extend(payload); Value::Object(body) } +/// Text that Python would write to a text-mode stream. A surrogate is +/// unencodable there, so Python would raise; writing it with escaping +/// replaced keeps the stream valid instead. +fn write_text(stream: &mut dyn Write, text: &str) { + let bytes = crate::py::encode_strict(text) + .unwrap_or_else(|_| crate::py::decode_replace(text.as_bytes()).into_bytes()); + let _ = stream.write_all(&bytes); +} + pub fn emit(outcome: Outcome, as_json: bool) { if as_json { write_document(&document(&outcome.command, true, outcome.payload, None)); @@ -81,9 +100,11 @@ pub fn emit(outcome: Outcome, as_json: bool) { // status, so nothing but the document is written in that mode. let mut stderr = std::io::stderr(); for warning in &outcome.warnings { - let _ = stderr.write_all(warning.as_bytes()); + write_text(&mut stderr, warning); } - let _ = std::io::stdout().write_all(outcome.text.as_bytes()); + let mut stdout = std::io::stdout(); + write_text(&mut stdout, &outcome.text); + let _ = stdout.flush(); } pub fn emit_error(command: &str, error: CommandError, as_json: bool) -> ! { @@ -95,220 +116,23 @@ pub fn emit_error(command: &str, error: CommandError, as_json: bool) -> ! { Some((error.code, &error.message)), )); } else { + let mut stderr = std::io::stderr(); + for warning in &error.warnings { + write_text(&mut stderr, warning); + } let prose = error .prose .unwrap_or_else(|| format!("loch: {}\n", error.message)); - let _ = std::io::stderr().write_all(prose.as_bytes()); + write_text(&mut stderr, &prose); } let _ = std::io::stdout().flush(); std::process::exit(error.exit_status); } fn write_document(body: &Value) { - let mut out = python_dumps(body); + let mut out = json::dumps(body, json::DEFAULT); out.push('\n'); let mut stdout = std::io::stdout(); let _ = stdout.write_all(out.as_bytes()); let _ = stdout.flush(); } - -/// `json.dumps(value)` with Python's defaults. -pub fn python_dumps(value: &Value) -> String { - let mut out = String::new(); - write_value(&mut out, value, ", ", ": "); - out -} - -/// `json.dumps(value, sort_keys=True, separators=(",", ":"))`, the form a -/// commit note is stored in. -pub fn python_dumps_compact_sorted(value: &Value) -> String { - let mut out = String::new(); - write_sorted(&mut out, value); - out -} - -fn write_sorted(out: &mut String, value: &Value) { - match value { - Value::Object(map) => { - let mut keys: Vec<&String> = map.keys().collect(); - // Python sorts str keys by code point; Rust's str order is UTF-8 - // byte order, which is the same thing. - keys.sort(); - out.push('{'); - for (i, key) in keys.into_iter().enumerate() { - if i > 0 { - out.push(','); - } - write_string(out, key); - out.push(':'); - write_sorted(out, &map[key]); - } - out.push('}'); - } - Value::Array(items) => { - out.push('['); - for (i, item) in items.iter().enumerate() { - if i > 0 { - out.push(','); - } - write_sorted(out, item); - } - out.push(']'); - } - other => write_value(out, other, ",", ":"), - } -} - -fn write_value(out: &mut String, value: &Value, item_sep: &str, key_sep: &str) { - match value { - Value::Null => out.push_str("null"), - Value::Bool(true) => out.push_str("true"), - Value::Bool(false) => out.push_str("false"), - Value::Number(number) => { - if let Some(f) = number.as_f64().filter(|_| number.is_f64()) { - out.push_str(&python_float_repr(f)); - } else { - out.push_str(&number.to_string()); - } - } - Value::String(text) => write_string(out, text), - Value::Array(items) => { - out.push('['); - for (i, item) in items.iter().enumerate() { - if i > 0 { - out.push_str(item_sep); - } - write_value(out, item, item_sep, key_sep); - } - out.push(']'); - } - Value::Object(map) => { - out.push('{'); - for (i, (key, item)) in map.iter().enumerate() { - if i > 0 { - out.push_str(item_sep); - } - write_string(out, key); - out.push_str(key_sep); - write_value(out, item, item_sep, key_sep); - } - out.push('}'); - } - } -} - -/// `ensure_ascii=True`: everything outside printable ASCII becomes `\uXXXX`, -/// astral characters as a surrogate pair, exactly as Python escapes them. -fn write_string(out: &mut String, text: &str) { - out.push('"'); - for ch in text.chars() { - match ch { - '"' => out.push_str("\\\""), - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - '\u{08}' => out.push_str("\\b"), - '\u{0c}' => out.push_str("\\f"), - ' '..='~' => out.push(ch), - _ => { - let mut units = [0u16; 2]; - for unit in ch.encode_utf16(&mut units) { - out.push_str(&format!("\\u{:04x}", unit)); - } - } - } - } - out.push('"'); -} - -/// Python's `float.__repr__`: the shortest digits that round-trip, written -/// positionally when the exponent is in [-4, 16) and as `d.ddde±XX` outside. -pub fn python_float_repr(value: f64) -> String { - if value.is_nan() { - return "NaN".into(); - } - if value.is_infinite() { - return if value > 0.0 { "Infinity" } else { "-Infinity" }.into(); - } - // `{:e}` gives the shortest round-trip digits in scientific form. - let scientific = format!("{:e}", value); - let (mantissa, exponent) = scientific.split_once('e').expect("{:e} has an e"); - let exponent: i32 = exponent.parse().expect("{:e} exponent is an integer"); - let negative = mantissa.starts_with('-'); - let digits: String = mantissa.chars().filter(|c| c.is_ascii_digit()).collect(); - let sign = if negative { "-" } else { "" }; - - if (-4..16).contains(&exponent) { - let point = exponent + 1; - let body = if point <= 0 { - format!("0.{}{}", "0".repeat((-point) as usize), digits) - } else if point as usize >= digits.len() { - format!("{}{}.0", digits, "0".repeat(point as usize - digits.len())) - } else { - let (whole, fraction) = digits.split_at(point as usize); - format!("{}.{}", whole, fraction) - }; - format!("{}{}", sign, body) - } else { - let (first, rest) = digits.split_at(1); - let fraction = if rest.is_empty() { - String::new() - } else { - format!(".{}", rest) - }; - let exponent_sign = if exponent < 0 { '-' } else { '+' }; - format!( - "{}{}{}e{}{:02}", - sign, - first, - fraction, - exponent_sign, - exponent.abs() - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn floats_match_python_repr() { - let cases = [ - (1.0, "1.0"), - (0.1, "0.1"), - (1731859200.123456, "1731859200.123456"), - (1e16, "1e+16"), - (1.5e16, "1.5e+16"), - (123456789012345.6, "123456789012345.6"), - (0.0001, "0.0001"), - (0.00001, "1e-05"), - (-2.5e-7, "-2.5e-07"), - (0.0, "0.0"), - (1e300, "1e+300"), - ]; - for (value, expected) in cases { - assert_eq!(python_float_repr(value), expected, "{value}"); - } - } - - #[test] - fn strings_escape_like_ensure_ascii() { - let value = json!({"a": "é😀\u{7f}\u{1}\"\\\n", "b": [1, true, null]}); - assert_eq!( - python_dumps(&value), - r#"{"a": "\u00e9\ud83d\ude00\u007f\u0001\"\\\n", "b": [1, true, null]}"# - ); - } - - #[test] - fn notes_are_compact_and_sorted() { - let value = json!({"session": "s", "loch": 1, "agent": "claude-code"}); - assert_eq!( - python_dumps_compact_sorted(&value), - r#"{"agent":"claude-code","loch":1,"session":"s"}"# - ); - } -} diff --git a/rust/src/py.rs b/rust/src/py.rs new file mode 100644 index 0000000..b36b426 --- /dev/null +++ b/rust/src/py.rs @@ -0,0 +1,175 @@ +//! The handful of Python string semantics loch's behaviour depends on. +//! +//! **Lone surrogates.** A Python `str` can hold an unpaired surrogate — a +//! `\ud83d` cut from its pair by truncation decodes to one, and +//! `surrogateescape` turns every undecodable byte into one — and real +//! transcripts contain both. A Rust `String` can't. So the port maps each +//! surrogate U+D800..U+DFFF onto U+10F800..U+10FFFF, the top of plane 16's +//! private-use area, and maps it back wherever Python would write it. The +//! cost is that a transcript holding those private-use code points literally +//! would be read as holding surrogates; the corpus check asserts no transcript +//! on this machine does, and `has_reserved` lets a caller find out. + +/// `str.isspace()`, which is also what `\s` matches in a `str` pattern. +/// Broader than Rust's: it includes the file/group/record/unit separators. +pub fn is_space(c: char) -> bool { + matches!( + c, + '\t' | '\n' + | '\u{0b}' + | '\u{0c}' + | '\r' + | '\u{1c}'..='\u{1f}' + | ' ' + | '\u{85}' + | '\u{a0}' + | '\u{1680}' + | '\u{2000}'..='\u{200a}' + | '\u{2028}' + | '\u{2029}' + | '\u{202f}' + | '\u{205f}' + | '\u{3000}' + ) +} + +/// The same set as a regex character-class body, for patterns ported from +/// Python that say `\s`. +pub const SPACE_CLASS: &str = + r"\t\n\x0b\x0c\r\x1c-\x1f \x{85}\x{a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}"; + +/// `str.split()` with no argument. +pub fn split(text: &str) -> Vec<&str> { + text.split(is_space).filter(|part| !part.is_empty()).collect() +} + +/// `str.strip()` with no argument. +pub fn strip(text: &str) -> &str { + text.trim_matches(is_space) +} + +const SURROGATE_BASE: u32 = 0x10F800; + +pub fn surrogate(unit: u32) -> char { + debug_assert!((0xD800..=0xDFFF).contains(&unit)); + char::from_u32(SURROGATE_BASE + (unit - 0xD800)).expect("plane 16 is valid") +} + +/// The surrogate a mapped character stands for, if it is one. +pub fn as_surrogate(c: char) -> Option { + let code = c as u32; + (code >= SURROGATE_BASE).then(|| code - SURROGATE_BASE + 0xD800) +} + +/// The code point Python would see: the surrogate for a mapped character. +pub fn code_point(c: char) -> u32 { + as_surrogate(c).unwrap_or(c as u32) +} + +pub fn has_reserved(text: &str) -> bool { + text.chars().any(|c| as_surrogate(c).is_some()) +} + +/// `bytes.decode("utf-8", "surrogateescape")`: each byte of an invalid +/// sequence becomes U+DC80..U+DCFF. Python and Rust agree on where an invalid +/// sequence ends (the Unicode "maximal subpart" rule), and since every byte is +/// escaped on its own, that is all that has to agree. +pub fn decode_surrogateescape(mut bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len()); + loop { + match std::str::from_utf8(bytes) { + Ok(valid) => { + out.push_str(valid); + return out; + } + Err(error) => { + let (valid, rest) = bytes.split_at(error.valid_up_to()); + out.push_str(std::str::from_utf8(valid).expect("checked valid")); + let bad = error.error_len().unwrap_or(rest.len()); + for &byte in &rest[..bad] { + out.push(surrogate(0xDC00 + byte as u32)); + } + bytes = &rest[bad..]; + } + } + } +} + +/// `bytes.decode("utf-8", "replace")`, which also follows maximal subparts. +pub fn decode_replace(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes).into_owned() +} + +/// `str.encode("utf-8")`: fails, as Python does, on any surrogate. +pub fn encode_strict(text: &str) -> Result, char> { + match text.chars().find(|&c| as_surrogate(c).is_some()) { + Some(c) => Err(c), + None => Ok(text.as_bytes().to_vec()), + } +} + +/// `str.encode("utf-8", "surrogateescape")`: an escaped byte goes back to +/// itself; any other surrogate is unencodable, as in Python. +pub fn encode_surrogateescape(text: &str) -> Result, char> { + if !has_reserved(text) { + return Ok(text.as_bytes().to_vec()); + } + let mut out = Vec::with_capacity(text.len()); + let mut buffer = [0u8; 4]; + for c in text.chars() { + match as_surrogate(c) { + Some(unit @ 0xDC80..=0xDCFF) => out.push((unit - 0xDC00) as u8), + Some(_) => return Err(c), + None => out.extend_from_slice(c.encode_utf8(&mut buffer).as_bytes()), + } + } + Ok(out) +} + +/// Python's `str` ordering: by code point, with a mapped surrogate in the +/// place of the surrogate it stands for. +pub fn cmp(a: &str, b: &str) -> std::cmp::Ordering { + if !has_reserved(a) && !has_reserved(b) { + return a.cmp(b); + } + a.chars().map(code_point).cmp(b.chars().map(code_point)) +} + +/// `len(text)` in code points. +pub fn len(text: &str) -> usize { + text.chars().count() +} + +/// `text[:limit]` in code points. +pub fn truncate(text: &str, limit: usize) -> &str { + match text.char_indices().nth(limit) { + Some((index, _)) => &text[..index], + None => text, + } +} + +/// `str.isdigit()` for the ASCII digits loch's callers can actually pass. +pub fn is_digits(text: &str) -> bool { + !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn surrogateescape_round_trips() { + let bytes = b"ok \xff\xfe \xed\xa0\x80 \xe2\x9c\x93 \xe2\x9c"; + let text = decode_surrogateescape(bytes); + assert_eq!(text.chars().filter(|&c| as_surrogate(c).is_some()).count(), 7); + assert_eq!(encode_surrogateescape(&text).unwrap(), bytes); + assert!(encode_strict(&text).is_err()); + } + + #[test] + fn ordering_places_surrogates_where_python_does() { + let lone = surrogate(0xD83D).to_string(); + assert_eq!(cmp(&lone, "\u{E000}"), std::cmp::Ordering::Less); + assert_eq!(cmp(&lone, "\u{D7FF}"), std::cmp::Ordering::Greater); + } +} diff --git a/test/test_cli.py b/test/test_cli.py index 932f149..2daa0f0 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -1129,3 +1129,33 @@ def test_ingest_rejects_an_unreadable_author_key( ) assert (code, document["code"]) == (1, "author-key-unreadable") + + +def test_an_undecodable_transcript_is_listed_but_not_packed( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path +) -> None: + home = tmp_path / "home" + project = tmp_path / "proj" + project.mkdir() + path = write_session(home, str(project), "abc") + path.write_bytes(path.read_bytes() + b'{"type": "user", "x": "\xff"}\n') + + listed, _, _ = invoke_json( + monkeypatch, capsys, home, "list", "--json", "--cwd", str(project) + ) + assert [s["sessionId"] for s in listed["sessions"]] == ["abc"] + + saved, _, code = invoke_json( + monkeypatch, + capsys, + home, + "save", + "--json", + "--cwd", + str(project), + "--store", + str(tmp_path / "store"), + ) + assert code == 1 + assert saved["code"] == "transcript-unreadable" + assert not (tmp_path / "store").exists() From 84659be82f49ef0655ddacd71b4510479956094a Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 17:23:29 -0500 Subject: [PATCH 08/18] Port every command to Rust (harness coverage for the new ones follows) Ported module for module: argparse (3.12.10's parse loop, nargs patterns and help formatter), json (Python's parser and writers, lone surrogates, exact integers, RFC 8785), claude, redact (fancy-regex, Python's \s set spelled out), rewrite (the single-pass alternation run by hand), bundle (zlib's own deflate via flate2), index, store and S3 (signed get, list, delete), format, ingest, trace, blame_html (template extracted verbatim) and cli. Only the hook is held to the reference by the harness so far. Co-Authored-By: Claude Opus 5.5 --- rust/Cargo.toml | 2 +- rust/src/argparse.rs | 95 ++- rust/src/blame_html.rs | 263 ++++++ rust/src/blame_template.html | 143 ++++ rust/src/bundle.rs | 249 ++++++ rust/src/claude.rs | 236 +++++- rust/src/cli.rs | 1551 ++++++++++++++++++++++++++++++++++ rust/src/format.rs | 124 +++ rust/src/hook.rs | 241 ++---- rust/src/index.rs | 280 ++++++ rust/src/ingest.rs | 652 ++++++++++++++ rust/src/json.rs | 28 +- rust/src/main.rs | 113 +-- rust/src/py.rs | 12 +- rust/src/redact.rs | 202 +++++ rust/src/rewrite.rs | 197 +++++ rust/src/s3.rs | 354 ++++++-- rust/src/store.rs | 192 +++-- rust/src/sys.rs | 472 +++++++++++ rust/src/trace.rs | 921 ++++++++++++++++++++ rust/src/usage.txt | 44 + 21 files changed, 5955 insertions(+), 416 deletions(-) create mode 100644 rust/src/blame_html.rs create mode 100644 rust/src/blame_template.html create mode 100644 rust/src/bundle.rs create mode 100644 rust/src/cli.rs create mode 100644 rust/src/format.rs create mode 100644 rust/src/index.rs create mode 100644 rust/src/ingest.rs create mode 100644 rust/src/redact.rs create mode 100644 rust/src/rewrite.rs create mode 100644 rust/src/sys.rs create mode 100644 rust/src/trace.rs create mode 100644 rust/src/usage.txt diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 3106694..3850cb9 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -22,7 +22,7 @@ fancy-regex = "0.14" # the gzip bytes, and only zlib's own deflate reproduces zlib's output. # miniz_oxide (flate2's default) compresses differently. flate2 = { version = "1", default-features = false, features = ["zlib"] } -libz-sys = { version = "1", default-features = false, features = ["static", "libc"] } +libz-sys = { version = "1", default-features = false, features = ["static", "libc"] } # flate2's backend, built from source and linked statically getrandom = "0.2" sha2 = "0.10" hmac = "0.12" diff --git a/rust/src/argparse.rs b/rust/src/argparse.rs index 9051cac..3492a5a 100644 --- a/rust/src/argparse.rs +++ b/rust/src/argparse.rs @@ -206,7 +206,9 @@ impl Parser { pub fn flag(&mut self, option: &'static str, dest: Option<&str>) -> &mut Self { self.actions.push(Action { options: vec![option], - dest: dest.map(str::to_string).unwrap_or_else(|| Self::dest_of(option)), + dest: dest + .map(str::to_string) + .unwrap_or_else(|| Self::dest_of(option)), nargs: Nargs::Zero, kind: Kind::StoreTrue, metavar: None, @@ -323,7 +325,11 @@ impl Parser { } } } else { - let split = arg.char_indices().nth(2).map(|(i, _)| i).unwrap_or(arg.len()); + let split = arg + .char_indices() + .nth(2) + .map(|(i, _)| i) + .unwrap_or(arg.len()); let (short, short_explicit) = arg.split_at(split); for (option, index) in self.option_strings() { if option == short { @@ -389,9 +395,19 @@ impl Parser { let mut start = 0usize; if let Some(max_option) = max_option { while start <= max_option { - let next = *options.keys().filter(|&&i| i >= start).min().expect("an option remains"); + let next = *options + .keys() + .filter(|&&i| i >= start) + .min() + .expect("an option remains"); if start != next { - let end = self.consume_positionals(&mut state, &mut positionals, argv, &pattern, start); + let end = self.consume_positionals( + &mut state, + &mut positionals, + argv, + &pattern, + start, + ); if end > start { start = end; continue; @@ -406,7 +422,9 @@ impl Parser { } } let stop = self.consume_positionals(&mut state, &mut positionals, argv, &pattern, start); - state.extras.extend(argv[stop.min(argv.len())..].iter().cloned()); + state + .extras + .extend(argv[stop.min(argv.len())..].iter().cloned()); let missing: Vec = self .actions @@ -422,7 +440,10 @@ impl Parser { ))); } if !state.extras.is_empty() { - return Err(self.error(format!("unrecognized arguments: {}", state.extras.join(" ")))); + return Err(self.error(format!( + "unrecognized arguments: {}", + state.extras.join(" ") + ))); } Ok(Args { values: state.values, @@ -618,13 +639,24 @@ impl Parser { } pub fn format_usage(&self) -> String { - format!("{}\n", self.usage_block(Self::width()).trim_end_matches('\n')) + format!( + "{}\n", + self.usage_block(Self::width()).trim_end_matches('\n') + ) } fn usage_block(&self, width: usize) -> String { let prefix = "usage: "; - let optionals: Vec<&Action> = self.actions.iter().filter(|a| !a.options.is_empty()).collect(); - let positionals: Vec<&Action> = self.actions.iter().filter(|a| a.options.is_empty()).collect(); + let optionals: Vec<&Action> = self + .actions + .iter() + .filter(|a| !a.options.is_empty()) + .collect(); + let positionals: Vec<&Action> = self + .actions + .iter() + .filter(|a| a.options.is_empty()) + .collect(); let opt_parts: Vec = optionals.iter().map(|a| a.usage()).collect(); let pos_parts: Vec = positionals.iter().map(|a| a.usage()).collect(); let all: Vec = opt_parts.iter().chain(&pos_parts).cloned().collect(); @@ -661,7 +693,8 @@ impl Parser { lines }; let prog_len = self.prog.chars().count(); - let lines: Vec = if (prefix.len() + prog_len) as f64 <= 0.75 * text_width as f64 { + let lines: Vec = if (prefix.len() + prog_len) as f64 <= 0.75 * text_width as f64 + { let indent = " ".repeat(prefix.len() + prog_len + 1); let mut head = vec![self.prog.clone()]; if !opt_parts.is_empty() { @@ -712,15 +745,20 @@ impl Parser { match action.help { None => out.push_str(&format!("{}{}\n", " ".repeat(indent), header)), Some(help) => { - let first_indent; - if header.chars().count() as isize <= action_width { + let fits = header.chars().count() as isize <= action_width; + let first_indent = if fits { let pad = action_width as usize - header.chars().count(); - out.push_str(&format!("{}{}{} ", " ".repeat(indent), header, " ".repeat(pad))); - first_indent = 0; + out.push_str(&format!( + "{}{}{} ", + " ".repeat(indent), + header, + " ".repeat(pad) + )); + 0 } else { out.push_str(&format!("{}{}\n", " ".repeat(indent), header)); - first_indent = help_position; - } + help_position + }; let lines = wrap(help, help_width); out.push_str(&format!("{}{}\n", " ".repeat(first_indent), lines[0])); for line in &lines[1..] { @@ -740,11 +778,17 @@ impl Parser { let mut help = self.usage_block(width); help.push_str(§ion( "positional arguments", - self.actions.iter().filter(|a| a.options.is_empty()).collect(), + self.actions + .iter() + .filter(|a| a.options.is_empty()) + .collect(), )); help.push_str(§ion( "options", - self.actions.iter().filter(|a| !a.options.is_empty()).collect(), + self.actions + .iter() + .filter(|a| !a.options.is_empty()) + .collect(), )); // _long_break_matcher, then strip('\n') + '\n'. while help.contains("\n\n\n") { @@ -819,7 +863,11 @@ fn is_negative_number(arg: &str) -> bool { /// Python's `repr()` of a str, as `%r` puts it in "ignored explicit argument". fn py_repr(text: &str) -> String { - let quote = if text.contains('\'') && !text.contains('"') { '"' } else { '\'' }; + let quote = if text.contains('\'') && !text.contains('"') { + '"' + } else { + '\'' + }; let mut out = String::new(); out.push(quote); for c in text.chars() { @@ -832,7 +880,9 @@ fn py_repr(text: &str) -> String { out.push('\\'); out.push(c); } - c if (c as u32) < 0x20 || c as u32 == 0x7f => out.push_str(&format!("\\x{:02x}", c as u32)), + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + out.push_str(&format!("\\x{:02x}", c as u32)) + } c => out.push(c), } } @@ -900,7 +950,10 @@ mod tests { .positional("target", Nargs::One) .positional("question", Nargs::Optional) .flag("--at-commit", None); - let args = parser.parse(&argv(&["t", "--at-commit", "q"])).ok().unwrap(); + let args = parser + .parse(&argv(&["t", "--at-commit", "q"])) + .ok() + .unwrap(); assert_eq!(args.str("target").as_deref(), Some("t")); assert_eq!(args.str("question").as_deref(), Some("q")); assert!(args.flag("at_commit")); diff --git a/rust/src/blame_html.rs b/rust/src/blame_html.rs new file mode 100644 index 0000000..c5ea7a4 --- /dev/null +++ b/rust/src/blame_html.rs @@ -0,0 +1,263 @@ +//! `loch blame --html`, as in `loch/blame_html.py`: the annotated file as one +//! self-contained page. `blame_template.html` is the Python module's +//! `TEMPLATE`, extracted verbatim, so it is filled the way `str.format` would +//! fill it: `{{`/`}}` are literal braces and `{name}` a field. + +use crate::json::{self, Value}; +use crate::object; +use crate::py; + +const PALETTE: [&str; 8] = [ + "#4f8cc9", "#d08a3a", "#8e6cc2", "#4a9e6b", "#c75b7a", "#3a9ea5", "#a8913a", "#6b7fd1", +]; +const NONE_COLOUR: &str = "#9aa0a6"; +const TEMPLATE: &str = include_str!("blame_template.html"); + +/// `html.escape(text)`, quotes included. +pub fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +fn short(text: &str, limit: usize) -> String { + let flat = py::split(text).join(" "); + if py::len(&flat) <= limit { + flat + } else { + format!("{}…", py::truncate(&flat, limit - 1)) + } +} + +fn format_template(fields: &[(&str, &str)]) -> String { + let mut out = String::with_capacity(TEMPLATE.len() * 2); + let mut rest = TEMPLATE; + while let Some(i) = rest.find(['{', '}']) { + out.push_str(&rest[..i]); + let tail = &rest[i..]; + if tail.starts_with("{{") || tail.starts_with("}}") { + out.push_str(&tail[..1]); + rest = &tail[2..]; + } else if let Some(end) = tail.find('}').filter(|_| tail.starts_with('{')) { + let name = &tail[1..end]; + let value = fields + .iter() + .find(|(field, _)| *field == name) + .map(|(_, value)| *value) + .expect("every template field is supplied"); + out.push_str(value); + rest = &tail[end + 1..]; + } else { + out.push_str(&tail[..1]); + rest = &tail[1..]; + } + } + out.push_str(rest); + out +} + +/// One conversation or hunk as `cli.py` builds it, in JSON form. +pub fn render( + file: &str, + conversations: &[Value], + hunks: &[Value], + lines: &std::collections::HashMap, + visible: Option<&[(i64, i64)]>, +) -> String { + let mark_of = |v: &Value| { + v.get("mark") + .and_then(Value::as_str) + .unwrap_or("") + .to_string() + }; + let order: std::collections::HashMap = conversations + .iter() + .enumerate() + .map(|(i, c)| (mark_of(c), i)) + .collect(); + let by_mark: std::collections::HashMap = + conversations.iter().map(|c| (mark_of(c), c)).collect(); + let colour = |mark: &str| match order.get(mark) { + Some(index) => PALETTE[index % PALETTE.len()], + None => NONE_COLOUR, + }; + let shown = |number: i64| { + visible.is_none_or(|ranges| ranges.iter().any(|&(a, b)| a <= number && number <= b)) + }; + + let mut rows: Vec = Vec::new(); + let mut previous_mark: Option = None; + let mut previous_number: Option = None; + for hunk in hunks { + let mark = mark_of(hunk); + let colour = colour(&mark); + let start = hunk.get("start").and_then(Value::as_i64).unwrap_or(0); + let end = hunk.get("end").and_then(Value::as_i64).unwrap_or(0); + for number in start..=end { + if !shown(number) { + continue; + } + if previous_number.is_some_and(|p| number != p + 1) { + rows.push("⋯".into()); + previous_mark = None; + } + let mut label = String::new(); + if previous_mark.as_deref() != Some(mark.as_str()) { + label = match by_mark.get(&mark) { + Some(entry) => { + let asked = match entry.get("prompt") { + Some(Value::Str(p)) if !p.is_empty() => p.clone(), + _ => "(no prompt recorded)".into(), + }; + format!( + "{} · {}", + escape(&mark), + escape(&short(&asked, 70)) + ) + } + None if mark == "+" => "not committed yet".into(), + None => "no conversation recorded".into(), + }; + } + let text = escape( + lines + .get(&(number as usize)) + .map(String::as_str) + .unwrap_or(""), + ); + let text = if text.is_empty() { + " ".to_string() + } else { + text + }; + rows.push(format!( + "{}{}{}", + escape(&mark), + number, + colour, + number, + text, + label + )); + previous_mark = Some(mark.clone()); + previous_number = Some(number); + } + } + + let mut key = String::new(); + for entry in conversations { + let mark = mark_of(entry); + let asked = match entry.get("prompt") { + Some(Value::Str(p)) if !p.is_empty() => p.clone(), + _ if !entry.get("available").is_some_and(Value::truthy) => { + "(transcript not available)".into() + } + _ => "(no prompt recorded)".into(), + }; + let commits: Vec = entry + .get("commits") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(|c| py::truncate(c, 7).to_string()) + .collect(); + let session = entry.get("session").and_then(Value::as_str).unwrap_or(""); + key.push_str(&format!( + "
  • {}“{}”session {} · {}
  • ", + escape(&mark), + colour(&mark), + escape(&mark), + escape(&asked), + escape(py::truncate(session, 8)), + escape(&commits.join(", ")) + )); + } + + let data = json::dumps( + &Value::Object(object! {"file" => file, "conversations" => conversations.to_vec()}), + json::UNICODE, + ) + .replace(" Option { + let text = py::strip(text); + let (negative, digits) = match text.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, text.strip_prefix('+').unwrap_or(text)), + }; + if digits.is_empty() + || digits.starts_with('_') + || digits.ends_with('_') + || digits.contains("__") + { + return None; + } + let cleaned: String = digits.chars().filter(|&c| c != '_').collect(); + if !cleaned.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let value: i64 = cleaned.parse().ok()?; + Some(if negative { -value } else { value }) +} + +/// `1-12,99-110` → [(1, 12), (99, 110)]; a bare number is one line. +pub fn parse_ranges(spec: &str) -> Option> { + let mut ranges = Vec::new(); + for part in spec.split(',') { + let part = py::strip(part); + if part.is_empty() { + continue; + } + let (start, end) = part.split_once('-').unwrap_or((part, "")); + let first = py_int(start)?; + let last = if end.is_empty() { first } else { py_int(end)? }; + ranges.push((first, last)); + } + Some(ranges) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn template_braces_unescape() { + let page = format_template(&[ + ("title", "T"), + ("file", "F"), + ("key", ""), + ("rows", ""), + ("data", "{}"), + ]); + assert!(page.contains(".loch-blame {\n")); + assert!(page.contains("${line}")); + assert!(page.contains("const data = {};")); + } +} diff --git a/rust/src/blame_template.html b/rust/src/blame_template.html new file mode 100644 index 0000000..5129a77 --- /dev/null +++ b/rust/src/blame_template.html @@ -0,0 +1,143 @@ + + + + + + +{title} + + + +
    +
    {file}loch blame
    +
    {rows}
    + +
    + + + diff --git a/rust/src/bundle.rs b/rust/src/bundle.rs new file mode 100644 index 0000000..3ec7cc8 --- /dev/null +++ b/rust/src/bundle.rs @@ -0,0 +1,249 @@ +//! The bundle format, as in `loch/bundle.py`. The ref is the SHA-256 of the +//! packed bytes, so two things here must never drift: the JSON is compact and +//! unescaped (`separators=(",", ":")`, `ensure_ascii=False`) with absent +//! metadata omitted rather than null, and the gzip stream is zlib's own +//! output at level 9 behind a fixed header. + +use crate::json::{self, Map, Value}; +use crate::object; +use crate::py; +use crate::sys; +use sha2::{Digest, Sha256}; +use std::io::Read; + +pub const BUNDLE_VERSION: i64 = 1; + +#[derive(Clone)] +pub struct BundleOrigin { + pub home: String, + pub platform: String, + pub hostname: String, +} + +#[derive(Clone)] +pub struct BundleSession { + pub session_id: String, + pub cwd: String, + pub git_branch: Option, + pub claude_version: Option, + pub modified_at: String, + pub transcript: String, +} + +#[derive(Clone)] +pub struct Bundle { + pub version: i64, + pub agent: String, + pub created_at: String, + pub origin: BundleOrigin, + pub sessions: Vec, +} + +fn session_json(session: &BundleSession) -> Value { + let mut record = + object! {"sessionId" => session.session_id.as_str(), "cwd" => session.cwd.as_str()}; + // Omitted rather than null: the ref is a hash of these bytes. + if let Some(branch) = &session.git_branch { + record.insert("gitBranch".into(), branch.as_str().into()); + } + if let Some(version) = &session.claude_version { + record.insert("claudeVersion".into(), version.as_str().into()); + } + record.insert("modifiedAt".into(), session.modified_at.as_str().into()); + record.insert("transcript".into(), session.transcript.as_str().into()); + Value::Object(record) +} + +fn bundle_json(bundle: &Bundle) -> Value { + Value::Object(object! { + "version" => bundle.version, + "agent" => bundle.agent.as_str(), + "createdAt" => bundle.created_at.as_str(), + "origin" => object! { + "home" => bundle.origin.home.as_str(), + "platform" => bundle.origin.platform.as_str(), + "hostname" => bundle.origin.hostname.as_str(), + }, + "sessions" => bundle.sessions.iter().map(session_json).collect::>(), + }) +} + +/// bundle.py's fixed header: OS byte 255 whatever the platform, XFL 2 for +/// level 9, mtime 0. +const GZIP_HEADER: [u8; 10] = [0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x02, 0xff]; + +/// Raw deflate at level 9, window 15, memLevel 8, default strategy — the +/// `zlib.compressobj(9, DEFLATED, -15, 8, 0)` bundle.py uses — through zlib +/// itself (flate2's zlib backend initialises exactly that), since no other +/// deflate reproduces zlib's bytes. zlib's output doesn't depend on how the +/// input is chunked, so streaming it is the same as one call. +fn deflate_raw(data: &[u8]) -> Vec { + use std::io::Write; + let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::new(9)); + encoder.write_all(data).expect("writing to a Vec"); + encoder.finish().expect("finishing into a Vec") +} + +fn crc32(data: &[u8]) -> u32 { + let mut crc = flate2::Crc::new(); + crc.update(data); + crc.sum() +} + +pub fn gzip_deterministic(data: &[u8]) -> Vec { + let mut out = GZIP_HEADER.to_vec(); + out.extend(deflate_raw(data)); + out.extend(crc32(data).to_le_bytes()); + out.extend((data.len() as u32).to_le_bytes()); + out +} + +#[derive(Debug)] +pub struct PackError(pub String); + +pub fn pack_bundle(bundle: &Bundle) -> Result, PackError> { + let encoded = json::dumps(&bundle_json(bundle), json::COMPACT_UNICODE); + let bytes = py::encode_strict(&encoded) + .map_err(|_| PackError("'utf-8' codec can't encode a surrogate".into()))?; + Ok(gzip_deterministic(&bytes)) +} + +pub fn bundle_ref(data: &[u8]) -> String { + Sha256::digest(data) + .iter() + .map(|b| format!("{:02x}", b)) + .collect() +} + +/// `str()` of a JSON value as Python would print it in an f-string. +fn py_str(value: Option<&Value>) -> String { + match value { + None | Some(Value::Null) => "None".into(), + Some(Value::Bool(true)) => "True".into(), + Some(Value::Bool(false)) => "False".into(), + Some(Value::Int(digits)) => digits.clone(), + Some(Value::Float(f)) => json::float_repr(*f), + Some(Value::Str(text)) => text.clone(), + Some(other) => json::dumps(other, json::DEFAULT), + } +} + +/// What `gzip.decompress` raises for the inputs worth telling apart. An empty +/// input is not an error to it: it decompresses to nothing, and the JSON +/// parse then fails. +fn gunzip(data: &[u8]) -> Result, String> { + if data.is_empty() { + return Ok(Vec::new()); + } + let magic = &data[..data.len().min(2)]; + if magic != [0x1f, 0x8b] { + return Err(format!("Not a gzipped file ({})", sys::bytes_repr(magic))); + } + let mut out = Vec::new(); + flate2::read::MultiGzDecoder::new(data) + .read_to_end(&mut out) + .map_err(|_| { + "Compressed file ended before the end-of-stream marker was reached".to_string() + })?; + Ok(out) +} + +/// The error string is what bundle.py's exception would print, for the +/// failures the harness exercises; anything stranger reads generically. +pub fn unpack_bundle(data: &[u8]) -> Result { + let raw = gunzip(data)?; + let text = std::str::from_utf8(&raw).map_err(|e| { + format!( + "'utf-8' codec can't decode byte 0x{:02x} in position {}: invalid start byte", + raw[e.valid_up_to()], + e.valid_up_to() + ) + })?; + let value = json::loads(text).map_err(|_| { + if py::strip(text).is_empty() { + "Expecting value: line 1 column 1 (char 0)".to_string() + } else { + "the bundle is not valid JSON".to_string() + } + })?; + let root = value.as_object().ok_or("the bundle is not a JSON object")?; + let version = root.get("version"); + let current = matches!(version, Some(Value::Int(d)) if d == "1") + || matches!(version, Some(Value::Bool(true))) + || matches!(version, Some(Value::Float(f)) if *f == 1.0); + if !current { + return Err(format!( + "unsupported bundle version {} (this build reads {})", + py_str(version), + BUNDLE_VERSION + )); + } + let empty = Map::new(); + let origin = match root.get("origin") { + None => &empty, + Some(Value::Object(map)) => map, + Some(_) => return Err("the bundle's origin is not an object".into()), + }; + let text_of = |map: &Map, key: &str| -> String { + map.get(key) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }; + let mut sessions = Vec::new(); + for session in root + .get("sessions") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let session = session.as_object().ok_or("a session is not an object")?; + let required = |key: &str| -> Result { + session + .get(key) + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| format!("'{}'", key)) + }; + sessions.push(BundleSession { + session_id: required("sessionId")?, + cwd: required("cwd")?, + git_branch: session + .get("gitBranch") + .and_then(Value::as_str) + .map(str::to_string), + claude_version: session + .get("claudeVersion") + .and_then(Value::as_str) + .map(str::to_string), + modified_at: text_of(session, "modifiedAt"), + transcript: required("transcript")?, + }); + } + Ok(Bundle { + version: BUNDLE_VERSION, + agent: text_of(root, "agent"), + created_at: text_of(root, "createdAt"), + origin: BundleOrigin { + home: text_of(origin, "home"), + platform: text_of(origin, "platform"), + hostname: text_of(origin, "hostname"), + }, + sessions, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The same check bundle.py's test makes: 3.10's gzip.compress output. + #[test] + fn packing_matches_python_310() { + let mut data = b"{\"a\":\"".to_vec(); + data.extend(b"xyz".repeat(5000)); + data.extend(b"\"}"); + let packed = gzip_deterministic(&data); + assert_eq!(&bundle_ref(&packed)[..16], "405552bff938ef58"); + } +} diff --git a/rust/src/claude.rs b/rust/src/claude.rs index cf5376b..5fa38ff 100644 --- a/rust/src/claude.rs +++ b/rust/src/claude.rs @@ -1,6 +1,31 @@ -//! Where Claude Code keeps its state, as in `loch/claude.py`. +//! The Claude Code adapter, as in `loch/claude.py`: where sessions live, how +//! their directory is named, and what a session's metadata is. -use std::path::{Path, PathBuf}; +use crate::json::{self, Value}; +use crate::py; +use crate::redact; +use crate::sys; +use std::fs; + +pub const AGENT: &str = "claude-code"; + +pub const SUMMARY_LIMIT: usize = 120; + +#[derive(Clone, Debug)] +pub struct SessionMeta { + pub session_id: String, + pub path: String, + pub cwd: String, + pub git_branch: Option, + pub claude_version: Option, + pub bytes: u64, + pub modified_at: String, + pub summary: Option, + /// Directories the session also worked in before it moved. A restore has + /// one target cwd, so records naming these cannot be made correct on the + /// far side; surfacing them is the only honest option. + pub other_cwds: Vec, +} /// `Path.home()`: `HOME` on Unix, `USERPROFILE` on Windows. pub fn home_dir() -> String { @@ -13,31 +38,204 @@ pub fn home_dir() -> String { /// places, because that is the rule Claude itself follows — a restore filed /// anywhere else is one `--resume` can't find. An explicit `home` names /// another machine's layout and ignores it. -#[allow(dead_code)] // read by list/save/restore/ask once they are ported -pub fn config_dir(home: Option<&str>) -> PathBuf { +pub fn config_dir(home: Option<&str>) -> String { if home.is_none() { - if let Some(configured) = std::env::var_os("CLAUDE_CONFIG_DIR").filter(|v| !v.is_empty()) { - return PathBuf::from(configured); + if let Ok(configured) = std::env::var("CLAUDE_CONFIG_DIR") { + if !configured.is_empty() { + return configured; + } } } let home = home.map(str::to_string).unwrap_or_else(home_dir); - Path::new(&home).join(".claude") + sys::join(&home, ".claude") +} + +pub fn projects_dir(home: Option<&str>) -> String { + sys::join(&config_dir(home), "projects") +} + +/// Claude resolves symlinks before deriving the directory name, so /tmp +/// becomes /private/tmp on macOS. Resolving here keeps lookups matching. +pub fn resolve_cwd(cwd: &str) -> String { + sys::realpath_strict(cwd).unwrap_or_else(|| cwd.to_string()) +} + +/// `re.sub(r"[^a-zA-Z0-9]", "-", path)`: every code point, a surrogate +/// included, that isn't an ASCII letter or digit. +pub fn encode_path(path: &str) -> String { + path.chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect() +} + +pub fn encode_cwd(cwd: &str) -> String { + encode_path(&resolve_cwd(cwd)) +} + +pub fn session_dir_for(cwd: &str, home: Option<&str>) -> String { + sys::join(&projects_dir(home), &encode_cwd(cwd)) +} + +pub fn transcript_path_for(cwd: &str, session_id: &str, home: Option<&str>) -> String { + sys::join( + &session_dir_for(cwd, home), + &format!("{}.jsonl", session_id), + ) +} + +fn first_string(value: Option<&Value>) -> Option { + match value { + Some(Value::Str(text)) if !text.is_empty() && text != "-" => Some(text.clone()), + _ => None, + } +} + +/// claude.py's `_records`: each line stripped, then parsed; dicts only. +pub fn records(raw: &str) -> impl Iterator + '_ { + raw.split('\n').filter_map(|line| { + let line = py::strip(line); + if line.is_empty() { + return None; + } + match json::loads(line) { + Ok(Value::Object(map)) => Some(map), + _ => None, + } + }) +} + +/// 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 — loch's own --json output among them — +/// where it names some other process's directory. +pub fn transcript_cwds(raw: &str) -> Vec<(String, usize)> { + let mut counts: indexmap::IndexMap = indexmap::IndexMap::new(); + for record in records(raw) { + if let Some(cwd) = first_string(record.get("cwd")) { + *counts.entry(cwd).or_insert(0) += 1; + } + } + counts.into_iter().collect() } -#[allow(dead_code)] -pub fn projects_dir(home: Option<&str>) -> PathBuf { - config_dir(home).join("projects") +/// Which of a session's cwd values the transcript is actually filed under. +/// The encoding is only ever compared here, never decoded: a match is strong +/// evidence, a mismatch is conclusive. Nothing matching falls back to the +/// first cwd. +pub fn cwd_for_directory(cwds: &[String], directory: &str) -> String { + cwds.iter() + .find(|cwd| encode_path(cwd) == directory) + .unwrap_or(&cwds[0]) + .clone() } -#[cfg(test)] -mod tests { - use super::*; +fn extract_summary(record: &json::Map) -> Option { + if !record.get("type").is_some_and(|t| t.is_str("user")) { + return None; + } + let content = record.get("message")?.get("content")?; + match content { + Value::Str(text) => Some(text.clone()), + Value::Array(blocks) => blocks.iter().find_map(|block| match block.get("text") { + Some(Value::Str(text)) if !text.is_empty() => Some(text.clone()), + _ => None, + }), + _ => None, + } +} + +/// The one piece of transcript content that travels as metadata, so it is +/// scrubbed here, before truncation, since a cut can leave a secret's tail +/// matching no rule. A summary that won't come clean is dropped whole. +pub fn display_summary(text: Option<&str>) -> Option { + let text = text?; + Some(match redact::redact(text) { + Ok(redaction) => py::truncate(&redaction.text, SUMMARY_LIMIT).to_string(), + Err(_) => "[REDACTED]".into(), + }) +} - #[test] - fn an_explicit_home_ignores_the_variable() { - assert_eq!( - projects_dir(Some("/home/other")), - PathBuf::from("/home/other/.claude/projects") - ); +pub fn read_session_meta(path: &str) -> Option { + let meta = fs::metadata(path).ok()?; + // Replacing rather than strict, as claude.py now does: one undecodable + // byte must not take down a listing. + let raw = py::decode_replace(&fs::read(path).ok()?); + let file = path.rsplit('/').next().unwrap_or(path); + let session_id = file.strip_suffix(".jsonl").unwrap_or(file).to_string(); + + let mut counts: indexmap::IndexMap = indexmap::IndexMap::new(); + let mut branches: std::collections::HashMap = Default::default(); + let mut versions: indexmap::IndexMap = indexmap::IndexMap::new(); + let mut summary: Option = None; + // Whole file rather than a bounded window: the cwd the session is filed + // under can first appear hundreds of records in. + for record in records(&raw) { + if let Some(cwd) = first_string(record.get("cwd")) { + *counts.entry(cwd.clone()).or_insert(0) += 1; + if let Some(branch) = first_string(record.get("gitBranch")) { + branches.entry(cwd.clone()).or_insert(branch); + } + if let Some(version) = first_string(record.get("version")) { + versions.entry(cwd).or_insert(version); + } + } + if summary.is_none() { + summary = extract_summary(&record); + } + } + if counts.is_empty() { + return None; + } + let ordered: Vec = counts.keys().cloned().collect(); + let cwd = cwd_for_directory(&ordered, &sys::basename(&sys::dirname(path))); + Some(SessionMeta { + session_id, + path: path.into(), + git_branch: branches.get(&cwd).cloned(), + claude_version: versions + .get(&cwd) + .or_else(|| versions.values().next()) + .cloned(), + bytes: meta.len(), + modified_at: sys::iso_timestamp(sys::mtime(&meta)), + summary: display_summary(summary.as_deref()), + other_cwds: ordered.iter().filter(|o| **o != cwd).cloned().collect(), + cwd, + }) +} + +pub fn list_sessions( + cwd: &str, + branch: Option<&str>, + session_id: Option<&str>, + home: Option<&str>, +) -> Vec { + let directory = session_dir_for(cwd, home); + let Ok(entries) = fs::read_dir(&directory) else { + return Vec::new(); + }; + let mut metas = Vec::new(); + for entry in entries.flatten() { + let file = entry.file_name().to_string_lossy().into_owned(); + if !file.ends_with(".jsonl") { + continue; + } + if let Some(id) = session_id.filter(|s| !s.is_empty()) { + if file != format!("{}.jsonl", id) { + continue; + } + } + let Some(meta) = read_session_meta(&sys::join(&directory, &file)) else { + continue; + }; + if let Some(branch) = branch.filter(|b| !b.is_empty()) { + if meta.git_branch.as_deref() != Some(branch) { + continue; + } + } + metas.push(meta); } + // sorted(..., reverse=True) is stable, as sort_by is. + metas.sort_by(|a, b| py::cmp(&b.modified_at, &a.modified_at)); + metas } diff --git a/rust/src/cli.rs b/rust/src/cli.rs new file mode 100644 index 0000000..e1179c5 --- /dev/null +++ b/rust/src/cli.rs @@ -0,0 +1,1551 @@ +//! Every command, as in `loch/cli.py`: each builds one `Outcome` — payload +//! and prose together — and `main` renders it. + +use crate::argparse::{Exit, Nargs, Parser}; +use crate::blame_html; +use crate::bundle::{self, Bundle, BundleOrigin, BundleSession, BUNDLE_VERSION}; +use crate::claude::{ + self, home_dir, list_sessions, resolve_cwd, transcript_path_for, SessionMeta, AGENT, +}; +use crate::format; +use crate::index::{self, IndexEntry, IndexError, BRANCH}; +use crate::ingest::{self, Origin}; +use crate::json::{Map, Value}; +use crate::object; +use crate::output::{fail, CommandError, Outcome, JSON_FLAG}; +use crate::py; +use crate::redact; +use crate::rewrite::{self, ForeignCwd, RewriteSpec}; +use crate::store::{create_store, resolve_store_uri, Store, StoreError}; +use crate::sys; +use crate::trace::{self, Link, Resolver, TraceError, UNCOMMITTED}; +use std::collections::HashMap; +use std::fs; +use std::path::Path; + +pub const USAGE: &str = include_str!("usage.txt"); + +/// Whether `--json` appears anywhere in argv — `JSON_FLAG in sys.argv`. +pub fn json_requested() -> bool { + std::env::args().skip(1).any(|a| a == JSON_FLAG) +} + +pub enum Failure { + Error(CommandError), + Help(String), + /// What Python's uncaught exception would say: `internal` in JSON mode. + Internal(String), +} + +impl From for Failure { + fn from(error: CommandError) -> Self { + Failure::Error(error) + } +} + +impl From for Failure { + fn from(exit: Exit) -> Self { + match exit { + Exit::Help(text) => Failure::Help(text), + Exit::Usage { message, prose } => { + let mut error = CommandError::new("usage", message); + error.prose = Some(prose); + error.exit_status = 2; + Failure::Error(error) + } + } + } +} + +impl From for Failure { + fn from(error: TraceError) -> Self { + Failure::Error(CommandError::new(error.code, error.message)) + } +} + +type Run = std::result::Result; + +fn err(code: &'static str, message: impl Into) -> std::result::Result { + fail(code, message).map_err(Failure::Error) +} + +/// `store_errors`: absent is terminal, unreachable is worth retrying. +fn store_error(description: &str, error: StoreError) -> Failure { + match error { + StoreError::Missing(m) => Failure::Error(CommandError::new( + "bundle-not-found", + format!("{}: {}", description, m), + )), + StoreError::Unreachable(m) => Failure::Error(CommandError::new( + "store-unreachable", + format!("{}: {}", description, m), + )), + } +} + +/// Inside store_errors in Python a parse failure is just another exception, +/// so it lands as store-unreachable; kept, since it is the reference's answer. +fn index_error(description: &str, error: IndexError) -> Failure { + match error { + IndexError::Store(e) => store_error(description, e), + IndexError::Unreadable(m) => Failure::Error(CommandError::new( + "store-unreachable", + format!("{}: {}", description, m), + )), + } +} + +fn open_store(uri: Option<&str>) -> std::result::Result, Failure> { + create_store(&resolve_store_uri(uri)).map_err(|e| Failure::Internal(e.0)) +} + +pub fn format_bytes(count: u64) -> String { + if count < 1024 { + format!("{}B", count) + } else if count < 1024 * 1024 { + format!("{:.0}K", count as f64 / 1024.0) + } else { + format!("{:.1}M", count as f64 / (1024.0 * 1024.0)) + } +} + +/// `f"{text:>width}"`. +fn right(text: &str, width: usize) -> String { + let len = py::len(text); + format!("{}{}", " ".repeat(width.saturating_sub(len)), text) +} + +fn left(text: &str, width: usize) -> String { + let len = py::len(text); + format!("{}{}", text, " ".repeat(width.saturating_sub(len))) +} + +fn describe(meta: &SessionMeta) -> String { + let branch = match &meta.git_branch { + Some(b) if !b.is_empty() => format!("[{}]", b), + _ => "[no branch]".into(), + }; + let collapsed = meta + .summary + .as_deref() + .map(collapse_whitespace) + .unwrap_or_default(); + let summary = if collapsed.is_empty() { + String::new() + } else { + format!(" {}", collapsed) + }; + let when = py::truncate(&meta.modified_at, 16).replace('T', " "); + format!( + "{} {} {} {}{}", + meta.session_id, + when, + right(&format_bytes(meta.bytes), 5), + branch, + summary + ) +} + +/// `re.sub(r"\s+", " ", text)`. +fn collapse_whitespace(text: &str) -> String { + let mut out = String::new(); + let mut in_space = false; + for c in text.chars() { + if py::is_space(c) { + if !in_space { + out.push(' '); + } + in_space = true; + } else { + out.push(c); + in_space = false; + } + } + out +} + +fn describe_entry(entry: &IndexEntry) -> String { + let branch = match &entry.value { + Some(v) if !v.is_empty() => format!("[{}]", v), + _ => "[no branch]".into(), + }; + let when = py::truncate(&entry.created_at, 16).replace('T', " "); + let version = match &entry.claude_version { + Some(v) if !v.is_empty() => format!(" claude {}", v), + _ => String::new(), + }; + format!( + "{} {} {} session(s) {}{} {}", + when, + right(&format_bytes(entry.bytes.max(0) as u64), 5), + entry.sessions, + branch, + version, + entry.cwd + ) +} + +fn collect( + cwd: Option<&str>, + branch: Option<&str>, + session: Option<&str>, +) -> (String, Vec) { + let resolved = resolve_cwd(&cwd.map(str::to_string).unwrap_or_else(sys::getcwd)); + let sessions = list_sessions(&resolved, branch, session, None); + (resolved, sessions) +} + +fn parser(command: &str) -> Parser { + Parser::new(&format!("loch {}", command)) +} + +fn strings(items: &[String]) -> Value { + Value::Array(items.iter().map(|s| Value::str(s.as_str())).collect()) +} + +fn session_payload(meta: &SessionMeta) -> Value { + Value::Object(object! { + "sessionId" => meta.session_id.as_str(), + "path" => meta.path.as_str(), + "cwd" => meta.cwd.as_str(), + "otherCwds" => strings(&meta.other_cwds), + "branch" => Value::opt_str(meta.git_branch.as_deref()), + "claudeVersion" => Value::opt_str(meta.claude_version.as_deref()), + "bytes" => meta.bytes as i64, + "modifiedAt" => meta.modified_at.as_str(), + "summary" => Value::opt_str(meta.summary.as_deref()), + }) +} + +/// Deliberately not index.py's stored shape: a storage format and a wire +/// contract change for different reasons. +fn entry_payload(entry: &IndexEntry) -> Value { + Value::Object(object! { + "ref" => entry.ref_.as_str(), + "dimension" => entry.dimension.as_str(), + "value" => Value::opt_str(entry.value.as_deref()), + "agent" => entry.agent.as_str(), + "createdAt" => entry.created_at.as_str(), + "bytes" => entry.bytes, + "sessions" => entry.sessions, + "cwd" => entry.cwd.as_str(), + "claudeVersion" => Value::opt_str(entry.claude_version.as_deref()), + }) +} + +// -- list --------------------------------------------------------------------- + +pub fn command_list(argv: &[String]) -> Run { + let mut p = parser("list"); + p.option("--cwd") + .option("--branch") + .flag("--remote", None) + .flag("--all", Some("every")) + .option("--store"); + let args = p.parse(argv)?; + let (cwd, branch, store) = (args.str("cwd"), args.str("branch"), args.str("store")); + if args.flag("remote") || args.flag("every") || store.is_some() { + return list_remote(cwd, branch, store, args.flag("every")); + } + let (cwd, sessions) = collect(cwd.as_deref(), branch.as_deref(), None); + let text = if sessions.is_empty() { + format!("no {} sessions found for {}\n", AGENT, cwd) + } else { + let mut text = format!("{} session(s) for {}\n", sessions.len(), cwd); + for meta in &sessions { + text.push_str(&format!(" {}\n", describe(meta))); + } + text + }; + Ok(Outcome::with( + "list", + object! { + "remote" => false, + "cwd" => cwd.as_str(), + "branch" => Value::opt_str(branch.as_deref()), + "sessions" => sessions.iter().map(session_payload).collect::>(), + }, + text, + )) +} + +fn current_branch(cwd: &str) -> Option { + let out = trace::git_unchecked(cwd, &["symbolic-ref", "--short", "HEAD"]); + let branch = py::strip(&out); + (!branch.is_empty()).then(|| branch.to_string()) +} + +fn list_remote( + cwd: Option, + branch: Option, + uri: Option, + every: bool, +) -> Run { + let store = open_store(uri.as_deref())?; + let cwd = resolve_cwd(&cwd.unwrap_or_else(sys::getcwd)); + let branch = branch.or_else(|| current_branch(&cwd)); + let prefix = if every { + index::dimension_prefix(BRANCH) + } else { + index::value_prefix(BRANCH, branch.as_deref()) + }; + let described = store.describe(); + let entries = index::load_entries(store.as_ref(), &prefix) + .map_err(|e| index_error(&format!("could not list {}", described), e))?; + let mut refs: Vec<&str> = entries.iter().map(|e| e.ref_.as_str()).collect(); + refs.sort(); + refs.dedup(); + let scope = if every { + String::new() + } else { + format!( + " for [{}]", + branch + .as_deref() + .filter(|b| !b.is_empty()) + .unwrap_or("no branch") + ) + }; + let text = if entries.is_empty() { + format!("no bundles{} in {}\n", scope, described) + } else { + let mut text = format!("{} bundle(s){} in {}\n", refs.len(), scope, described); + for entry in &entries { + text.push_str(&format!( + " {}\n {}\n", + entry.ref_, + describe_entry(entry) + )); + } + text + }; + Ok(Outcome::with( + "list", + object! { + "remote" => true, + "store" => described.as_str(), + "all" => every, + "branch" => if every { Value::Null } else { Value::opt_str(branch.as_deref()) }, + "bundles" => refs.len(), + "entries" => entries.iter().map(entry_payload).collect::>(), + }, + text, + )) +} + +// -- save --------------------------------------------------------------------- + +fn counts_value(counts: &indexmap::IndexMap) -> Value { + Value::Object( + counts + .iter() + .map(|(k, v)| (k.clone(), Value::from(*v))) + .collect(), + ) +} + +pub fn command_save(argv: &[String]) -> Run { + let mut p = parser("save"); + p.option("--cwd") + .option("--branch") + .option("--session") + .option("--store"); + let args = p.parse(argv)?; + let (cwd, sessions) = collect( + args.str("cwd").as_deref(), + args.str("branch").as_deref(), + args.str("session").as_deref(), + ); + if sessions.is_empty() { + return err( + "no-sessions", + format!("no {} sessions found for {}", AGENT, cwd), + ); + } + let mut packed_sessions = Vec::new(); + let mut redactions = Vec::new(); + for meta in &sessions { + // In memory only — the agent's own transcript on disk stays verbatim. + let bytes = + fs::read(&meta.path).map_err(|e| Failure::Internal(sys::os_error(&e, &meta.path)))?; + let raw = match std::str::from_utf8(&bytes) { + Ok(raw) => raw, + Err(error) => { + return err( + "transcript-unreadable", + format!( + "refusing to pack {}: not UTF-8 at byte {}", + meta.session_id, + error.valid_up_to() + ), + ) + } + }; + let scrubbed = match redact::redact(raw) { + Ok(scrubbed) => scrubbed, + Err(error) => { + return err( + "redaction-failed", + format!("refusing to pack {}: {}", meta.session_id, error.0), + ) + } + }; + packed_sessions.push(BundleSession { + session_id: meta.session_id.clone(), + cwd: meta.cwd.clone(), + git_branch: meta.git_branch.clone(), + claude_version: meta.claude_version.clone(), + modified_at: meta.modified_at.clone(), + transcript: scrubbed.text, + }); + redactions.push(scrubbed.counts); + } + let bundle = Bundle { + version: BUNDLE_VERSION, + agent: AGENT.into(), + created_at: sys::iso_timestamp(sys::now()), + origin: BundleOrigin { + home: home_dir(), + platform: sys::platform_name().into(), + hostname: sys::hostname(), + }, + sessions: packed_sessions, + }; + let packed = bundle::pack_bundle(&bundle).map_err(|e| Failure::Internal(e.0))?; + let ref_ = bundle::bundle_ref(&packed); + let store = open_store(args.str("store").as_deref())?; + let described = format!("could not write to {}", store.describe()); + // Bundle first: an index entry is derived from it. + store + .put(&index::bundle_key(&ref_), &packed) + .map_err(|e| store_error(&described, e))?; + let entries = index::index_bundle(store.as_ref(), &bundle, &ref_, packed.len()) + .map_err(|e| store_error(&described, e))?; + + let total: usize = redactions.iter().map(|c| c.values().sum::()).sum(); + let mut text = String::new(); + for (session, counts) in bundle.sessions.iter().zip(&redactions) { + let note = if counts.is_empty() { + String::new() + } else { + format!(" — {}", redact::summarize(counts)) + }; + text.push_str(&format!( + " packed {} [{}]{}\n", + session.session_id, + session + .git_branch + .as_deref() + .filter(|b| !b.is_empty()) + .unwrap_or("no branch"), + note + )); + } + let indexed: Vec = entries + .iter() + .map(|e| { + format!( + "[{}]", + e.value + .as_deref() + .filter(|v| !v.is_empty()) + .unwrap_or("no branch") + ) + }) + .collect(); + text.push_str(&format!( + "\nstored {} in {}\n", + format_bytes(packed.len() as u64), + store.describe() + )); + text.push_str(&format!("indexed under {}\n", indexed.join(", "))); + text.push_str(&format!("ref {}\n", ref_)); + + Ok(Outcome::with( + "save", + object! { + "ref" => ref_.as_str(), + "bytes" => packed.len(), + "store" => store.describe(), + "cwd" => cwd.as_str(), + "createdAt" => bundle.created_at.as_str(), + // Counts by rule name only. The matched text never leaves this + // process: save's stdout lands in the next agent's transcript. + "redacted" => total, + "sessions" => bundle.sessions.iter().zip(&redactions).map(|(s, counts)| Value::Object(object! { + "sessionId" => s.session_id.as_str(), + "branch" => Value::opt_str(s.git_branch.as_deref()), + "cwd" => s.cwd.as_str(), + "claudeVersion" => Value::opt_str(s.claude_version.as_deref()), + "modifiedAt" => s.modified_at.as_str(), + "redactions" => counts_value(counts), + })).collect::>(), + "indexed" => entries.iter().map(|e| Value::Object(object! { + "dimension" => e.dimension.as_str(), + "value" => Value::opt_str(e.value.as_deref()), + "key" => index::index_key(&e.dimension, e.value.as_deref(), &e.ref_), + })).collect::>(), + }, + text, + )) +} + +// -- restore ------------------------------------------------------------------ + +struct Restored { + session_id: String, + origin_session_id: String, + branch: Option, + status: &'static str, + path: String, + residual: Vec, + resume_command: Option, + foreign: Vec<(String, ForeignCwd)>, +} + +fn restored_payload(session: &Restored) -> Value { + Value::Object(object! { + "sessionId" => session.session_id.as_str(), + "originSessionId" => session.origin_session_id.as_str(), + "branch" => Value::opt_str(session.branch.as_deref()), + "status" => session.status, + "path" => session.path.as_str(), + "residualOriginPaths" => strings(&session.residual), + // Keyed by the origin path, the left-hand side a caller states a + // mapping with; `restored` is what the file on disk actually says. + "foreignCwds" => Value::Object(session.foreign.iter().map(|(origin, f)| (origin.clone(), Value::Object(object! { + "count" => f.count, + "restored" => f.restored.as_str(), + }))).collect()), + "resumeCommand" => Value::opt_str(session.resume_command.as_deref()), + }) +} + +pub fn command_restore(argv: &[String]) -> Run { + let mut p = parser("restore"); + p.positional("ref", Nargs::Optional) + .option("--into") + .option("--store") + .flag("--force", None) + .flag("--new-id", Some("new_id")); + let args = p.parse(argv)?; + let Some(ref_) = args.str("ref").filter(|r| !r.is_empty()) else { + return err("missing-ref", "restore requires a bundle ref"); + }; + let store = open_store(args.str("store").as_deref())?; + let described = format!("could not read {} from {}", ref_, store.describe()); + let packed = store + .get(&index::bundle_key(&ref_)) + .map_err(|e| store_error(&described, e))?; + let bundle = match bundle::unpack_bundle(&packed) { + Ok(bundle) => bundle, + // Fetched fine and still unusable: neither absent nor unreachable. + Err(error) => return err("bundle-unreadable", format!("{}: {}", described, error)), + }; + let target_cwd = resolve_cwd(&args.str("into").unwrap_or_else(sys::getcwd)); + let target_home = home_dir(); + let mut restored = Vec::new(); + for session in &bundle.sessions { + let target_session_id = if args.flag("new_id") { + sys::uuid4() + } else { + session.session_id.clone() + }; + let spec = RewriteSpec { + origin_cwd: session.cwd.clone(), + origin_home: bundle.origin.home.clone(), + target_cwd: target_cwd.clone(), + target_home: target_home.clone(), + origin_session_id: Some(session.session_id.clone()), + target_session_id: Some(target_session_id.clone()), + }; + let transcript = rewrite::rewrite_transcript(&session.transcript, &spec); + let destination = transcript_path_for(&target_cwd, &target_session_id, None); + if Path::new(&destination).exists() && !args.flag("force") { + restored.push(Restored { + session_id: target_session_id, + origin_session_id: session.session_id.clone(), + branch: session.git_branch.clone(), + status: "skipped", + path: destination, + residual: Vec::new(), + resume_command: None, + foreign: Vec::new(), + }); + continue; + } + let parent = sys::dirname(&destination); + fs::create_dir_all(&parent).map_err(|e| Failure::Internal(sys::os_error(&e, &parent)))?; + fs::write(&destination, transcript.as_bytes()) + .map_err(|e| Failure::Internal(sys::os_error(&e, &destination)))?; + restored.push(Restored { + session_id: target_session_id.clone(), + origin_session_id: session.session_id.clone(), + branch: session.git_branch.clone(), + status: "restored", + path: destination, + residual: rewrite::residual_origin_paths(&transcript, &spec), + resume_command: Some(format!( + "cd {} && claude --resume {}", + target_cwd, target_session_id + )), + // Pre-rewrite: the origin path only exists losslessly here. + foreign: rewrite::foreign_cwds(&session.transcript, &spec), + }); + } + + let payload = object! { + "ref" => ref_.as_str(), + "store" => store.describe(), + "cwd" => target_cwd.as_str(), + "origin" => object! { + "hostname" => bundle.origin.hostname.as_str(), + "home" => bundle.origin.home.as_str(), + "platform" => bundle.origin.platform.as_str(), + }, + "sessions" => restored.iter().map(restored_payload).collect::>(), + }; + let mut warnings: Vec = restored + .iter() + .filter(|s| s.status == "skipped") + .map(|s| { + format!( + " skipped {} (already exists; --force to overwrite)\n", + s.session_id + ) + }) + .collect(); + for session in &restored { + for (origin, foreign) in &session.foreign { + warnings.push(format!( + " {} worked in {} for {} record(s), which no rewrite into {} can satisfy\n", + session.session_id, origin, foreign.count, target_cwd + )); + } + } + if !restored.iter().any(|s| s.status == "restored") { + let mut error = CommandError::new("nothing-restored", "nothing restored"); + error.payload = payload; + error.warnings = warnings; + return Err(Failure::Error(error)); + } + + let mut text = String::new(); + for session in restored.iter().filter(|s| s.status == "restored") { + let note = if session.residual.is_empty() { + String::new() + } else { + format!(" (residual origin paths: {})", session.residual.join(", ")) + }; + text.push_str(&format!( + " restored {} [{}]{}\n", + session.session_id, + session + .branch + .as_deref() + .filter(|b| !b.is_empty()) + .unwrap_or("no branch"), + note + )); + for (origin, foreign) in &session.foreign { + text.push_str(&format!( + " {} record(s) worked in {}, now {}\n", + foreign.count, origin, foreign.restored + )); + } + } + text.push_str(&format!( + "\nfrom {} ({})\nresume with:\n", + bundle.origin.hostname, bundle.origin.home + )); + for session in &restored { + if let Some(command) = &session.resume_command { + text.push_str(&format!(" {}\n", command)); + } + } + let mut outcome = Outcome::with("restore", payload, text); + outcome.warnings = warnings; + Ok(outcome) +} + +// -- delete / reindex ----------------------------------------------------------- + +pub fn command_delete(argv: &[String]) -> Run { + let mut p = parser("delete"); + p.positional("ref", Nargs::Optional).option("--store"); + let args = p.parse(argv)?; + let Some(ref_) = args.str("ref").filter(|r| !r.is_empty()) else { + return err("missing-ref", "delete requires a bundle ref"); + }; + let store = open_store(args.str("store").as_deref())?; + let removed = index::delete_bundle(store.as_ref(), &ref_).map_err(|e| { + index_error( + &format!("could not delete {} from {}", ref_, store.describe()), + e, + ) + })?; + let mut text: String = removed + .iter() + .map(|k| format!(" removed {}\n", k)) + .collect(); + text.push_str(&format!("\ndeleted {} from {}\n", ref_, store.describe())); + Ok(Outcome::with( + "delete", + object! {"ref" => ref_.as_str(), "store" => store.describe(), "removed" => strings(&removed)}, + text, + )) +} + +pub fn command_reindex(argv: &[String]) -> Run { + let mut p = parser("reindex"); + p.option("--store"); + let args = p.parse(argv)?; + let store = open_store(args.str("store").as_deref())?; + let result = index::reindex(store.as_ref()) + .map_err(|e| index_error(&format!("could not reindex {}", store.describe()), e))?; + Ok(Outcome::with( + "reindex", + object! { + "store" => store.describe(), + "bundles" => result.bundles, + "entries" => result.entries, + "removed" => result.removed, + }, + format!( + "scanned {} bundle(s) in {}\nwrote {} index entries, removed {} stale\n", + result.bundles, + store.describe(), + result.entries, + result.removed + ), + )) +} + +// -- ingest ------------------------------------------------------------------------- + +fn default_derived() -> String { + sys::join(&sys::join(&home_dir(), ".loch"), "derived") +} + +pub fn command_ingest(argv: &[String]) -> Run { + let mut p = parser("ingest"); + p.option("--cwd") + .option("--branch") + .option("--session") + .option("--author") + .option("--author-key") + .option("--out"); + let args = p.parse(argv)?; + let mut author = args.str("author"); + if let Some(key_path) = args.str("author_key") { + if author.is_some() { + return err("usage", "pass --author or --author-key, not both"); + } + let text = match fs::read(&key_path) { + Ok(bytes) => String::from_utf8(bytes) + .map_err(|_| Failure::Internal(format!("{} is not UTF-8", key_path)))?, + Err(error) => { + return err( + "author-key-unreadable", + format!("{}: {}", key_path, sys::os_error(&error, &key_path)), + ) + } + }; + match ingest::ssh_author_id(&text) { + Ok(id) => author = Some(id), + Err(error) => { + return err( + "author-key-unreadable", + format!("{}: {}", key_path, error.0), + ) + } + } + } + let (cwd, sessions) = collect( + args.str("cwd").as_deref(), + args.str("branch").as_deref(), + args.str("session").as_deref(), + ); + if sessions.is_empty() { + return err( + "no-sessions", + format!("no {} sessions found for {}", AGENT, cwd), + ); + } + let out = args.str("out").unwrap_or_else(default_derived); + fs::create_dir_all(&out).map_err(|e| Failure::Internal(sys::os_error(&e, &out)))?; + let home = home_dir(); + let mut results = Vec::new(); + let mut text = String::new(); + for meta in &sessions { + let origin = Origin { + cwd: meta.cwd.clone(), + home: home.clone(), + session_id: meta.session_id.clone(), + }; + let derived = ingest::ingest(&meta.path, &origin, author.as_deref()) + .map_err(|e| Failure::Internal(format!("{:?}", e)))?; + let path = sys::join(&out, &ingest::derived_name(&derived)); + let packed = + format::pack_derived(&derived).map_err(|_| Failure::Internal("not JSON".into()))?; + fs::write(&path, packed).map_err(|e| Failure::Internal(sys::os_error(&e, &path)))?; + let leaves = derived + .heads + .get("leaves") + .and_then(Value::as_array) + .map_or(0, Vec::len); + results.push(Value::Object(object! { + "sessionId" => meta.session_id.as_str(), + "source" => derived.header["source"].get("id").cloned().unwrap_or(Value::Null), + "path" => path.as_str(), + "turns" => derived.turns.len(), + "heads" => derived.heads.clone(), + })); + text.push_str(&format!( + " {} {} turns {} head(s)\n", + meta.session_id, + derived.turns.len(), + leaves + )); + } + text.push_str(&format!( + "\ningested {} session(s) into {}\n", + sessions.len(), + out + )); + Ok(Outcome::with( + "ingest", + object! { + "cwd" => cwd.as_str(), + "out" => out.as_str(), + "converter" => ingest::converter(), + "sessions" => results, + }, + text, + )) +} + +// -- hook / install ------------------------------------------------------------- + +pub fn command_hook(argv: &[String]) -> Run { + use std::io::Read; + let name = argv.first().map(String::as_str).unwrap_or(""); + let mut stdin = Vec::new(); + if std::io::stdin().read_to_end(&mut stdin).is_ok() { + crate::hook::run(name, &stdin); + } + Ok(Outcome::new("hook")) +} + +/// `shutil.which(name)`. +fn which(name: &str) -> Option { + let path = std::env::var("PATH").ok()?; + for dir in path.split(':') { + let candidate = sys::join(dir, name); + let Ok(meta) = fs::metadata(&candidate) else { + continue; + }; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if meta.is_file() && meta.permissions().mode() & 0o111 != 0 { + return Some(candidate); + } + } + #[cfg(not(unix))] + if meta.is_file() { + return Some(candidate); + } + } + None +} + +pub fn command_install(argv: &[String]) -> Run { + let mut p = parser("install"); + p.option("--cwd").flag("--local", None).option("--command"); + let args = p.parse(argv)?; + let root = trace::repo_root( + &args + .str("cwd") + .filter(|c| !c.is_empty()) + .unwrap_or_else(sys::getcwd), + )?; + let command = match args.str("command") { + Some(command) => command, + // A machine-specific path, which is why it only goes in the + // uncommitted settings file. + None if args.flag("local") => which("loch") + .unwrap_or_else(|| sys::abspath(&std::env::args().next().unwrap_or_default())), + None => "loch".into(), + }; + let name = if args.flag("local") { + "settings.local.json" + } else { + "settings.json" + }; + let settings = sys::join(&sys::join(&root, ".claude"), name); + let added = trace::install_hooks(&settings, &command) + .map_err(|trace::InstallError::Internal(m)| Failure::Internal(m))?; + // 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. + trace::git(&root, &["config", "notes.rewriteRef", trace::NOTES_REF])?; + let mut text = if added.is_empty() { + format!("loch hooks already installed in {}\n", settings) + } else { + format!( + "installed loch hooks ({}) in {}\n", + added.join(", "), + settings + ) + }; + text.push_str(&format!( + "restart Claude Code sessions in this repository to pick them up\nshare links with: git push {}\n", + trace::NOTES_REF + )); + Ok(Outcome::with( + "install", + object! {"settings" => settings.as_str(), "command" => command.as_str(), "added" => strings(&added)}, + text, + )) +} + +// -- blame / log / ask ------------------------------------------------------------- + +fn store_or_none(uri: Option<&str>) -> Option> { + create_store(&resolve_store_uri(uri)).ok() +} + +fn flat(text: &str, limit: usize) -> String { + let flat = py::split(text).join(" "); + if py::len(&flat) <= limit { + flat + } else { + format!("{}…", py::truncate(&flat, limit - 1)) + } +} + +fn link_text(link: Option<&Link>) -> String { + let Some(link) = link else { + return "no conversation recorded".into(); + }; + if link.transcript.is_none() { + return format!( + "session {} (transcript not available)", + py::truncate(&link.session_id, 8) + ); + } + let title = match &link.title { + Some(t) if !t.is_empty() => format!(" \"{}\"", t), + _ => String::new(), + }; + let prompt = match &link.prompt { + Some(p) if !p.is_empty() => format!(" — asked: \"{}\"", flat(p, 72)), + _ => String::new(), + }; + format!( + "session {}{}{}", + py::truncate(&link.session_id, 8), + title, + prompt + ) +} + +fn mark(index: usize) -> String { + let mut letters = String::new(); + let mut index = index + 1; + while index > 0 { + let remainder = (index - 1) % 26; + index = (index - 1) / 26; + letters.insert(0, (b'A' + remainder as u8) as char); + } + letters +} + +fn resolve(resolver: &mut Resolver, commit: &str) -> std::result::Result, Failure> { + resolver.resolve(commit).map_err(Failure::Internal) +} + +pub fn command_blame(argv: &[String]) -> Run { + let mut p = parser("blame"); + p.positional("file", Nargs::One) + .option_optional("--html", "", "PATH") + .option_metavar("--lines", "RANGES") + .flag("--no-open", None) + .option("--store"); + let args = p.parse(argv)?; + let file = args.str("file").unwrap_or_default(); + let absolute = sys::abspath(&file); + let cwd = { + let dir = sys::dirname(&absolute); + if dir.is_empty() { + sys::getcwd() + } else { + dir + } + }; + let root = trace::repo_root(&cwd)?; + let hunks = trace::blame_hunks(&root, &sys::relpath(&absolute, &root))?; + let store = store_or_none(args.str("store").as_deref()); + let mut resolver = Resolver::new(&root, store.as_deref()); + let mut links: indexmap::IndexMap> = indexmap::IndexMap::new(); + for hunk in &hunks { + if !links.contains_key(&hunk.commit) && hunk.commit != UNCOMMITTED { + let link = resolve(&mut resolver, &hunk.commit)?; + links.insert(hunk.commit.clone(), link); + } + } + + // One mark per request rather than per session, handed out in order of + // first appearance, so A is always the first conversation you read. + let mut marks: HashMap<(String, String), String> = HashMap::new(); + let mut legend: Vec = Vec::new(); + let mut mark_of: HashMap = HashMap::new(); + for hunk in &hunks { + if hunk.commit == UNCOMMITTED { + mark_of.insert(hunk.commit.clone(), "+".into()); + continue; + } + let Some(Some(link)) = links.get(&hunk.commit) else { + mark_of.insert(hunk.commit.clone(), "·".into()); + continue; + }; + let key = ( + link.session_id.clone(), + link.prompt + .clone() + .filter(|p| !p.is_empty()) + .unwrap_or_else(|| link.call.clone()), + ); + if !marks.contains_key(&key) { + let letter = mark(marks.len()); + marks.insert(key.clone(), letter.clone()); + let mut entry = object! {"mark" => letter}; + entry.extend(link.payload()); + entry.insert("commits".into(), Value::Array(Vec::new())); + legend.push(entry); + } + let letter = marks[&key].clone(); + let entry = legend + .iter_mut() + .find(|e| e.get("mark").is_some_and(|m| m.is_str(&letter))) + .expect("the mark was just added"); + if let Some(Value::Array(commits)) = entry.get_mut("commits") { + if !commits.iter().any(|c| c.is_str(&hunk.commit)) { + commits.push(hunk.commit.as_str().into()); + } + } + mark_of.insert(hunk.commit.clone(), letter); + } + + let rows: Vec = hunks + .iter() + .map(|hunk| { + let link = links.get(&hunk.commit).and_then(Option::as_ref); + Value::Object(object! { + "start" => hunk.start, + "end" => hunk.end, + "commit" => if hunk.commit == UNCOMMITTED { Value::Null } else { hunk.commit.as_str().into() }, + "summary" => hunk.summary.as_str(), + "mark" => mark_of[&hunk.commit].as_str(), + "conversation" => link.map_or(Value::Null, |l| Value::Object(l.payload())), + }) + }) + .collect(); + + let mut text = format!("{}\n", file); + for hunk in &hunks { + let span = if hunk.end > hunk.start { + format!("{}-{}", hunk.start, hunk.end) + } else { + hunk.start.to_string() + }; + if hunk.commit == UNCOMMITTED { + text.push_str(&format!(" {} uncommitted\n", right(&span, 9))); + continue; + } + let link = links.get(&hunk.commit).and_then(Option::as_ref); + text.push_str(&format!( + " {} {} {}\n", + right(&span, 9), + py::truncate(&hunk.commit, 7), + py::truncate(&hunk.summary, 60) + )); + text.push_str(&format!( + " {} {} {}\n", + right("", 9), + left("", 7), + link_text(link) + )); + } + let linked = links.values().filter(|l| l.is_some()).count(); + text.push_str(&format!( + "\n{} of {} commit(s) linked to a conversation; follow one up with: loch ask {}:\n", + linked, + links.len(), + file + )); + + let legend_values: Vec = legend.into_iter().map(Value::Object).collect(); + let mut payload = object! { + "file" => file.as_str(), + "conversations" => legend_values.clone(), + "hunks" => rows.clone(), + }; + if let Some(html) = args.str("html") { + let visible = match args.str("lines").filter(|l| !l.is_empty()) { + Some(spec) => match blame_html::parse_ranges(&spec) { + Some(ranges) => Some(ranges), + None => { + return err( + "usage", + format!("--lines takes ranges like 1-12,99-110, not {}", spec), + ) + } + }, + None => None, + }; + let mut lines: HashMap = HashMap::new(); + for hunk in &hunks { + for (offset, line) in hunk.lines.iter().enumerate() { + lines.insert(hunk.start + offset, line.clone()); + } + } + let page = blame_html::render(&file, &legend_values, &rows, &lines, visible.as_deref()); + let target = if html.is_empty() { + sys::join( + &sys::gettempdir(), + &format!("loch-blame-{}.html", sys::basename(&file)), + ) + } else { + html + }; + let bytes = + py::encode_strict(&page).map_err(|_| Failure::Internal("unencodable page".into()))?; + fs::write(&target, bytes).map_err(|e| Failure::Internal(sys::os_error(&e, &target)))?; + let absolute = sys::abspath(&target); + text = format!("wrote {}\n", absolute); + payload.insert("html".into(), absolute.as_str().into()); + if !args.flag("no_open") && !json_requested() { + open_in_browser(&sys::realpath_strict(&target).unwrap_or(absolute)); + } + } + Ok(Outcome::with("blame", payload, text)) +} + +fn open_in_browser(path: &str) { + let uri = format!("file://{}", path.replace(' ', "%20")); + let opener = if cfg!(target_os = "macos") { + "open" + } else if cfg!(windows) { + "explorer" + } else { + "xdg-open" + }; + let _ = std::process::Command::new(opener) + .arg(uri) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn(); +} + +/// `file`, `file:105` or `file:100-120`; a path that exists wins outright. +fn history_target(target: &str) -> std::result::Result<(String, Option<(usize, usize)>), Failure> { + if Path::new(target).exists() { + return Ok((target.into(), None)); + } + let (file, span) = target.rsplit_once(':').unwrap_or(("", target)); + let (start, end) = span.split_once('-').unwrap_or((span, "")); + if file.is_empty() || !py::is_digits(start) || (!end.is_empty() && !py::is_digits(end)) { + return err( + "usage", + format!("{} is neither a file nor :[-]", target), + ); + } + let first: usize = start.parse().unwrap_or(0); + let last: usize = if end.is_empty() { + first + } else { + end.parse().unwrap_or(0) + }; + if first < 1 || last < first { + return err("usage", format!("{} is not a line range", span)); + } + Ok((file.into(), Some((first, last)))) +} + +pub fn command_log(argv: &[String]) -> Run { + let mut p = parser("log"); + p.positional("target", Nargs::One).option("--store"); + let args = p.parse(argv)?; + let (file, lines) = history_target(&args.str("target").unwrap_or_default())?; + let absolute = sys::abspath(&file); + let cwd = { + let dir = sys::dirname(&absolute); + if dir.is_empty() { + sys::getcwd() + } else { + dir + } + }; + let root = trace::repo_root(&cwd)?; + let relative = sys::relpath(&absolute, &root); + if let Some((_, last)) = lines { + // -L past the end is a fatal git error with a worse message. + let length = trace::blame_hunks(&root, &relative)? + .iter() + .map(|h| h.end) + .max() + .unwrap_or(0); + if last > length { + return err( + "usage", + format!("{} has {} lines, not {}", file, length, last), + ); + } + } + let changes = trace::history(&root, &relative, lines)?; + let store = store_or_none(args.str("store").as_deref()); + let mut resolver = Resolver::new(&root, store.as_deref()); + + let mut conversations: Vec = Vec::new(); + let mut keyed: HashMap<(String, String), usize> = HashMap::new(); + let mut entries = Vec::new(); + let mut text = String::new(); + for change in &changes { + let link = resolve(&mut resolver, &change.commit)?; + let when = sys::utc_seconds(change.time); + entries.push(Value::Object(object! { + "commit" => change.commit.as_str(), + "time" => when.as_str(), + "summary" => change.summary.as_str(), + "conversation" => link.as_ref().map_or(Value::Null, |l| Value::Object(l.payload())), + })); + text.push_str(&format!( + " {} {} {}\n {} {} {}\n", + py::truncate(&change.commit, 7), + &when[..10], + py::truncate(&change.summary, 60), + left("", 7), + left("", 10), + link_text(link.as_ref()) + )); + let Some(link) = link else { continue }; + let key = ( + link.session_id.clone(), + link.prompt + .clone() + .filter(|p| !p.is_empty()) + .unwrap_or_else(|| link.call.clone()), + ); + let index = *keyed.entry(key).or_insert_with(|| { + let mut entry = link.payload(); + entry.insert("commits".into(), Value::Array(Vec::new())); + conversations.push(entry); + conversations.len() - 1 + }); + if let Some(Value::Array(commits)) = conversations[index].get_mut("commits") { + commits.push(change.commit.as_str().into()); + } + } + let span = match lines { + None => String::new(), + Some((a, b)) if a == b => format!(":{}", a), + Some((a, b)) => format!(":{}-{}", a, b), + }; + let header = format!( + "{}{}: {} commit(s) from {} conversation(s), newest first\n", + file, + span, + changes.len(), + conversations.len() + ); + let footer = if conversations.is_empty() { + "" + } else { + "\nfollow one up with: loch ask \n" + }; + Ok(Outcome::with( + "log", + object! { + "file" => file.as_str(), + "lines" => lines.map_or(Value::Null, |(a, b)| Value::Object(object! {"start" => a, "end" => b})), + "conversations" => conversations.into_iter().map(Value::Object).collect::>(), + "commits" => entries, + }, + format!("{}{}{}", header, text, footer), + )) +} + +fn resolve_commit(root: &str, target: &str) -> std::result::Result { + if let Some((file, line)) = target.rsplit_once(':') { + if !file.is_empty() && py::is_digits(line) && Path::new(file).exists() { + let relative = sys::relpath(&sys::abspath(file), root); + let number: usize = line.parse().unwrap_or(0); + for hunk in trace::blame_hunks(root, &relative)? { + if hunk.start <= number && number <= hunk.end { + if hunk.commit == UNCOMMITTED { + return err("not-linked", format!("{} is not committed yet", target)); + } + return Ok(hunk.commit); + } + } + return err("usage", format!("{} has no line {}", file, line)); + } + } + let output = trace::git_unchecked( + root, + &[ + "rev-parse", + "--verify", + "-q", + &format!("{}^{{commit}}", target), + ], + ); + let commit = py::strip(&output); + if commit.is_empty() { + return err( + "usage", + format!("{} is neither a commit nor :", target), + ); + } + Ok(commit.into()) +} + +pub fn command_ask(argv: &[String]) -> Run { + let mut p = parser("ask"); + p.positional("target", Nargs::One) + .positional("question", Nargs::Optional) + .flag("--at-commit", None) + .flag("--no-launch", None) + .option("--store"); + let args = p.parse(argv)?; + let as_json = json_requested(); + let root = trace::repo_root(&sys::getcwd())?; + let target = args.str("target").unwrap_or_default(); + let commit = resolve_commit(&root, &target)?; + let store = store_or_none(args.str("store").as_deref()); + let mut resolver = Resolver::new(&root, store.as_deref()); + let Some(link) = resolve(&mut resolver, &commit)? else { + return err( + "not-linked", + format!( + "no conversation is recorded for {}", + py::truncate(&commit, 7) + ), + ); + }; + let Some(transcript) = &link.transcript else { + return err( + "transcript-missing", + format!( + "session {} is linked but its transcript is neither in {} nor in the store", + link.session_id, + claude::projects_dir(None) + ), + ); + }; + let fork = trace::fork_session( + transcript, + &root, + if args.flag("at_commit") { + Some(link.call.as_str()) + } else { + None + }, + Some(&format!("loch ask {}", py::truncate(&commit, 7))), + ) + .map_err(|e| match e { + trace::ForkError::Trace(t) => Failure::from(t), + trace::ForkError::Internal(m) => Failure::Internal(m), + })?; + + let mut command = vec![ + "claude".to_string(), + "--resume".into(), + fork.session_id.clone(), + ]; + if let Some(question) = args.str("question").filter(|q| !q.is_empty()) { + command.push(question); + } + let payload = object! { + "commit" => commit.as_str(), + "conversation" => link.payload(), + "fork" => object! { + "sessionId" => fork.session_id.as_str(), + "path" => fork.path.as_str(), + "cwd" => fork.cwd.as_str(), + "records" => fork.records, + }, + "at" => if args.flag("at_commit") { "commit" } else { "end" }, + "launch" => strings(&command), + }; + let text = format!( + "forked session {}, which made {}, {}: {} records, as {}\n", + py::truncate(&fork.origin_session, 8), + py::truncate(&commit, 7), + if args.flag("at_commit") { + "just after it" + } else { + "to its end" + }, + fork.records, + fork.session_id + ); + if args.flag("no_launch") || as_json { + return Ok(Outcome::with( + "ask", + payload, + format!( + "{}resume with: cd {} && {}\n", + text, + root, + command.join(" ") + ), + )); + } + eprint!("{}", text); + exec_claude(&root, &command) +} + +#[cfg(unix)] +fn exec_claude(root: &str, command: &[String]) -> Run { + use std::os::unix::process::CommandExt; + let _ = std::env::set_current_dir(root); + let error = std::process::Command::new(&command[0]) + .args(&command[1..]) + .exec(); + Err(Failure::Internal(format!( + "[Errno {}] {}: '{}'", + error.raw_os_error().unwrap_or(0), + sys::strerror(error.raw_os_error().unwrap_or(0)), + command[0] + ))) +} + +#[cfg(not(unix))] +fn exec_claude(root: &str, command: &[String]) -> Run { + let status = std::process::Command::new(&command[0]) + .args(&command[1..]) + .current_dir(root) + .status() + .map_err(|e| Failure::Internal(e.to_string()))?; + std::process::exit(status.code().unwrap_or(1)); +} + +// -- backfill ------------------------------------------------------------------------- + +fn stderr_is_tty() -> bool { + #[cfg(unix)] + { + // SAFETY: isatty only inspects the descriptor. + unsafe { libc::isatty(2) == 1 } + } + #[cfg(not(unix))] + { + false + } +} + +pub fn command_backfill(argv: &[String]) -> Run { + let mut p = parser("backfill"); + // Branches rather than --all, which would walk refs/notes/loch too. + p.option("--cwd").option_default("--revision", "--branches"); + let args = p.parse(argv)?; + let root = trace::repo_root( + &args + .str("cwd") + .filter(|c| !c.is_empty()) + .unwrap_or_else(sys::getcwd), + )?; + let revision = args.str("revision").unwrap_or_default(); + + // A one-line counter for a person watching a terminal only; JSON mode and + // a pipe both get nothing. + let mut last = std::time::Instant::now() - std::time::Duration::from_secs(1); + let mut meter = |done: usize, total: usize, read: u64, size: u64| { + let now = std::time::Instant::now(); + if done < total && now.duration_since(last).as_secs_f64() < 0.1 { + return; + } + last = now; + let percent = if size > 0 { 100 * read / size } else { 100 }; + eprint!( + "\rscanning transcripts {}/{} ({} of {}, {}%)\x1b[K", + done, + total, + format_bytes(read), + format_bytes(size), + percent + ); + if done == total { + eprintln!(); + } + }; + let progress: Option = if json_requested() || !stderr_is_tty() { + None + } else { + Some(&mut meter) + }; + let linked = trace::backfill(&root, &revision, progress)?; + let rows: Vec = linked + .iter() + .map(|(sha, call)| { + Value::Object(object! { + "commit" => sha.as_str(), + "session" => call.session_id.as_str(), + "call" => call.call.as_str(), + }) + }) + .collect(); + let mut text: String = linked + .iter() + .map(|(sha, call)| { + format!( + " {} session {}\n", + py::truncate(sha, 7), + py::truncate(&call.session_id, 8) + ) + }) + .collect(); + text.push_str(&format!("linked {} commit(s)\n", linked.len())); + Ok(Outcome::with("backfill", object! {"linked" => rows}, text)) +} + +// -- help / version ----------------------------------------------------------------- + +pub fn command_help(_argv: &[String]) -> Run { + Ok(Outcome::with( + "help", + object! {"usage" => USAGE}, + USAGE.into(), + )) +} + +pub fn command_version(_argv: &[String]) -> Run { + let version = env!("CARGO_PKG_VERSION"); + Ok(Outcome::with( + "version", + object! {"version" => version}, + format!("loch {}\n", version), + )) +} + +pub fn dispatch(command: &str, argv: &[String]) -> Option { + Some(match command { + "list" => command_list(argv), + "save" => command_save(argv), + "restore" => command_restore(argv), + "delete" => command_delete(argv), + "reindex" => command_reindex(argv), + "ingest" => command_ingest(argv), + "install" => command_install(argv), + "blame" => command_blame(argv), + "ask" => command_ask(argv), + "log" => command_log(argv), + "backfill" => command_backfill(argv), + "hook" => command_hook(argv), + "help" => command_help(argv), + "version" => command_version(argv), + _ => return None, + }) +} diff --git a/rust/src/format.rs b/rust/src/format.rs new file mode 100644 index 0000000..01363c8 --- /dev/null +++ b/rust/src/format.rs @@ -0,0 +1,124 @@ +//! The loch format's ids and derived files, as in `loch/format.py`. Every id +//! is a SHA-256 over `json::canonical` (RFC 8785, integers exact). + +use crate::json::{self, Map, Value}; +use crate::object; +use sha2::{Digest, Sha256}; + +pub const FORMAT_VERSION: i64 = 1; +pub const HASH_PREFIX: &str = "sha256:"; + +#[derive(Debug)] +pub struct NotJson; + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{:02x}", b)).collect() +} + +pub fn digest(value: &Value) -> Result { + let bytes = json::canonical(value).map_err(|_| NotJson)?; + Ok(format!("{}{}", HASH_PREFIX, hex(&Sha256::digest(bytes)))) +} + +pub fn digest_bytes(data: &[u8]) -> String { + format!("{}{}", HASH_PREFIX, hex(&Sha256::digest(data))) +} + +/// One node of the conversation graph. `core` is the hashed envelope, which +/// holds the content's hash and never the content; `facts` are what the +/// converter knew that is not part of the turn's identity. +#[derive(Clone, Debug)] +pub struct Turn { + pub id: String, + pub core: Map, + pub blocks: Option>, + pub facts: Map, +} + +pub fn content_id(blocks: &[Value]) -> Result { + digest(&Value::Object(object! {"blocks" => blocks.to_vec()})) +} + +pub fn make_turn( + kind: &str, + author: &Map, + parents: Vec, + blocks: Vec, + facts: Map, +) -> Result { + let core = object! { + "loch" => FORMAT_VERSION, + "kind" => kind, + "author" => author.clone(), + "parents" => parents.into_iter().map(Value::Str).collect::>(), + "content" => content_id(&blocks)?, + }; + Ok(Turn { + id: digest(&Value::Object(core.clone()))?, + core, + blocks: Some(blocks), + facts, + }) +} + +impl Turn { + pub fn parents(&self) -> Vec { + self.core + .get("parents") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() + } + + pub fn kind(&self) -> &str { + self.core.get("kind").and_then(Value::as_str).unwrap_or("") + } + + pub fn author_kind(&self) -> Option<&str> { + self.core.get("author")?.get("kind")?.as_str() + } +} + +pub struct Derived { + pub header: Map, + pub turns: Vec, + pub heads: Map, +} + +pub fn pack_derived(derived: &Derived) -> Result, NotJson> { + let mut out = Vec::new(); + let mut line = |value: Value| -> Result<(), NotJson> { + out.extend(json::canonical(&value).map_err(|_| NotJson)?); + out.push(b'\n'); + Ok(()) + }; + let mut header = object! {"type" => "header"}; + header.extend(derived.header.clone()); + line(Value::Object(header))?; + for turn in &derived.turns { + let mut record = object! { + "type" => "turn", + "id" => turn.id.as_str(), + "turn" => turn.core.clone(), + }; + if let Some(blocks) = &turn.blocks { + record.insert( + "content".into(), + Value::Object(object! {"blocks" => blocks.clone()}), + ); + } + if !turn.facts.is_empty() { + record.insert("facts".into(), Value::Object(turn.facts.clone())); + } + line(Value::Object(record))?; + } + let mut heads = object! {"type" => "heads"}; + heads.extend(derived.heads.clone()); + line(Value::Object(heads))?; + Ok(out) +} diff --git a/rust/src/hook.rs b/rust/src/hook.rs index 375098e..47c8e4a 100644 --- a/rust/src/hook.rs +++ b/rust/src/hook.rs @@ -1,23 +1,17 @@ -//! `loch hook`, run by Claude Code around every Bash call and at every stop. -//! A port of the hook half of `loch/trace.py`; the Python is the reference -//! and `test/test_equivalence.py` holds the two to the same side effects. +//! `loch hook`, run by Claude Code around every Bash call and at every stop — +//! the hook half of `loch/trace.py`. //! //! The pending-state file is shared across implementations — a session can //! start its Bash call under one and finish it under the other while a machine //! switches over — so its name and JSON shape must stay exactly Python's. use crate::git::{self, GitError}; -use crate::output::{python_dumps, python_dumps_compact_sorted}; +use crate::json::{self, Map, Value}; +use crate::object; use crate::store::{self, Store}; -use serde_json::{json, Map, Value}; +use crate::trace::{self, content, make_note, read_records, write_note}; use sha2::{Digest, Sha256}; use std::fs; -use std::path::{Path, PathBuf}; -use std::time::{SystemTime, UNIX_EPOCH}; - -pub const NOTES_REF: &str = "refs/notes/loch"; -pub const NOTE_VERSION: i64 = 1; -pub const AGENT: &str = "claude-code"; /// Any failure: the hook swallows them all, so the only thing that matters /// about one is where it stopped. @@ -35,108 +29,89 @@ impl From for Stop { } } -fn event_cwd(event: &Map) -> Result { - // Python's `str(event.get("cwd") or os.getcwd())`. A non-string cwd would - // be str()-ed into something git can't enter, so it stops here instead. - match event.get("cwd") { - None | Some(Value::Null) | Some(Value::Bool(false)) => current_dir(), - Some(Value::String(text)) if text.is_empty() => current_dir(), - Some(Value::String(text)) => Ok(text.clone()), - Some(_) => Err(Stop), +impl From for Stop { + fn from(_: trace::TraceError) -> Self { + Stop } } -fn current_dir() -> Result { - Ok(std::env::current_dir()?.to_string_lossy().into_owned()) +fn event_cwd(event: &Map) -> Result { + // `str(event.get("cwd") or os.getcwd())`. A non-string cwd would be + // str()-ed into something git can't enter, so it stops here instead. + match event.get("cwd") { + None => Ok(crate::sys::getcwd()), + Some(v) if !v.truthy() => Ok(crate::sys::getcwd()), + Some(Value::Str(text)) => Ok(text.clone()), + Some(_) => Err(Stop), + } } -fn pending_dir(cwd: &str) -> Result { +fn pending_dir(cwd: &str) -> Result { let git_dir = git::absolute_git_dir(cwd)?; - Ok(Path::new(&git_dir).join("loch").join("pending")) + Ok(crate::sys::join( + &crate::sys::join(&git_dir, "loch"), + "pending", + )) } -/// `(event.get("tool_input") or {}).get("command", "")`, stringified. A truthy -/// non-object tool_input raises in Python, so it stops here. -fn tool_command(event: &Map) -> Result { - let input = match event.get("tool_input") { - None | Some(Value::Null) => return Ok(String::new()), - Some(Value::Object(map)) => map, - Some(value) if !truthy(value) => return Ok(String::new()), - Some(_) => return Err(Stop), - }; - match input.get("command") { +/// `(event.get("tool_input") or {}).get("command", "")`, stringified. A +/// truthy non-object raises in Python, so it stops here. +fn tool_command(event: &Map) -> Result { + match event.get("tool_input") { None => Ok(String::new()), - Some(Value::String(text)) => Ok(text.clone()), - // str() of anything else; commands are strings in every real event. + Some(v) if !v.truthy() => Ok(String::new()), + Some(Value::Object(input)) => match input.get("command") { + None => Ok(String::new()), + Some(Value::Str(text)) => Ok(text.clone()), + other => Ok(trace::py_str(other)), + }, Some(_) => Err(Stop), } } -fn truthy(value: &Value) -> bool { - match value { - Value::Null => false, - Value::Bool(b) => *b, - Value::Number(n) => n.as_f64() != Some(0.0), - Value::String(s) => !s.is_empty(), - Value::Array(a) => !a.is_empty(), - Value::Object(o) => !o.is_empty(), - } -} - -fn tool_use_id(event: &Map) -> Option { +fn tool_use_id(event: &Map) -> Option { match event.get("tool_use_id") { - Some(Value::String(call)) if !call.is_empty() => Some(call.clone()), + Some(Value::Str(call)) if !call.is_empty() => Some(call.clone()), _ => None, } } -fn call_key(event: &Map) -> Result { +fn call_key(event: &Map) -> Result { if let Some(call) = tool_use_id(event) { return Ok(call); } let digest = Sha256::digest(tool_command(event)?.as_bytes()); - let hex: String = digest[..16] - .iter() - .map(|b| format!("{:02x}", b)) - .collect::>() - .concat(); + let hex: String = digest[..16].iter().map(|b| format!("{:02x}", b)).collect(); Ok(format!("cmd-{}", hex)) } -fn now() -> f64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs_f64()) - .unwrap_or(0.0) -} - /// Remembers HEAD before a Bash call, so the matching post hook can tell /// exactly which commits the call made rather than guessing from history. -pub fn pre_tool(event: &Map) -> Result<(), Stop> { +pub fn pre_tool(event: &Map) -> Result<(), Stop> { let cwd = event_cwd(event)?; let before = git::head(&cwd)?.unwrap_or_default(); let directory = pending_dir(&cwd)?; fs::create_dir_all(&directory)?; let key = call_key(event)?; - let state = json!({"head": before, "at": now()}); - fs::write(directory.join(key), python_dumps(&state))?; + let state = Value::Object(object! {"head" => before, "at" => Value::Float(crate::sys::now())}); + fs::write( + crate::sys::join(&directory, &key), + json::dumps(&state, json::DEFAULT), + )?; Ok(()) } -pub fn post_tool(event: &Map) -> Result, Stop> { +pub fn post_tool(event: &Map) -> Result, Stop> { let cwd = event_cwd(event)?; - let Some(Value::String(session_id)) = event.get("session_id") else { + let Some(Value::Str(session_id)) = event.get("session_id") else { return Ok(Vec::new()); }; - let state_path = pending_dir(&cwd)?.join(call_key(event)?); - let state: Value = serde_json::from_slice(&fs::read(&state_path)?).map_err(|_| Stop)?; + let state_path = crate::sys::join(&pending_dir(&cwd)?, &call_key(event)?); + let text = String::from_utf8(fs::read(&state_path)?).map_err(|_| Stop)?; + let state = json::loads(&text).map_err(|_| Stop)?; fs::remove_file(&state_path)?; let before = match state.get("head") { - Some(Value::String(head)) => head.clone(), - _ => return Err(Stop), - }; - let since = match state.get("at") { - Some(Value::Number(at)) => at.as_f64().ok_or(Stop)?, + Some(Value::Str(head)) => head.clone(), _ => return Err(Stop), }; let after = match git::head(&cwd)? { @@ -149,7 +124,7 @@ pub fn post_tool(event: &Map) -> Result, Stop> { None => { let command = tool_command(event)?; let found = match event.get("transcript_path") { - Some(Value::String(path)) => call_from_transcript(path, &command), + Some(Value::Str(path)) => call_from_transcript(path, &command)?, _ => None, }; match found { @@ -159,6 +134,11 @@ pub fn post_tool(event: &Map) -> Result, Stop> { } }; + let since = match state.get("at") { + Some(Value::Float(at)) => *at, + Some(Value::Int(at)) => at.parse::().map_err(|_| Stop)?, + _ => return Err(Stop), + }; let made = commits_made(&cwd, &before, &after, since)?; for commit in &made { write_note(&cwd, commit, &make_note(session_id, &call, "hook"))?; @@ -176,11 +156,11 @@ fn commits_made(cwd: &str, before: &str, after: &str, since: f64) -> Result Result Option { - let raw = fs::read(path).ok()?; +fn call_from_transcript(path: &str, command: &str) -> Result, Stop> { let mut found: Option = None; - for line in raw.split(|&b| b == b'\n') { - let Ok(Value::Object(record)) = serde_json::from_slice::(line) else { - continue; - }; - let Some(Value::Object(message)) = record.get("message") else { - continue; - }; - let Some(Value::Array(content)) = message.get("content") else { - continue; - }; - for block in content { - let Value::Object(block) = block else { + for record in read_records(path) { + for block in content(&record) { + if !(block.get("type").is_some_and(|t| t.is_str("tool_use")) + && block.get("name").is_some_and(|n| n.is_str("Bash"))) + { continue; - }; + } + // `(block.get("input") or {}).get("command")`, which raises on a + // truthy non-object and so ends the hook. let input_command = match block.get("input") { + None => None, + Some(v) if !v.truthy() => None, Some(Value::Object(input)) => input.get("command"), - _ => None, + Some(_) => return Err(Stop), }; - if block.get("type") == Some(&Value::from("tool_use")) - && block.get("name") == Some(&Value::from("Bash")) - && input_command == Some(&Value::from(command)) - { + if input_command.is_some_and(|c| c.is_str(command)) { found = Some(block.get("id").cloned().unwrap_or(Value::Null)); } } } - match found { - Some(Value::String(id)) => Some(id), + Ok(match found { + Some(Value::Str(id)) => Some(id), _ => None, - } -} - -pub fn make_note(session_id: &str, call: &str, captured: &str) -> Value { - json!({ - "loch": NOTE_VERSION, - "agent": AGENT, - "session": session_id, - "call": call, - "captured": captured, }) } -fn write_note(cwd: &str, commit: &str, note: &Value) -> Result<(), Stop> { - let body = python_dumps_compact_sorted(note); - git::git( - cwd, - &["notes", "--ref", NOTES_REF, "add", "-f", "-F", "-", commit], - Some(&body), - )?; - Ok(()) -} - /// 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. -pub fn snapshot_transcript( - event: &Map, - store: &dyn Store, -) -> Result, Stop> { - let (Some(Value::String(path)), Some(Value::String(session_id))) = +pub fn snapshot_transcript(event: &Map, store: &dyn Store) -> Result, Stop> { + let (Some(Value::Str(path)), Some(Value::Str(session_id))) = (event.get("transcript_path"), event.get("session_id")) else { return Ok(None); @@ -267,27 +217,17 @@ pub fn snapshot_transcript( let Ok(data) = fs::read(path) else { return Ok(None); }; - let key = transcript_key(&project_of(path), session_id); + let project = crate::sys::basename(&crate::sys::dirname(path)); + let key = format!( + "{}{}/{}.jsonl", + trace::transcripts_prefix(), + project, + session_id + ); store.put(&key, &data).map_err(|_| Stop)?; Ok(Some(key)) } -/// `os.path.basename(os.path.dirname(path))`. -fn project_of(path: &str) -> String { - let dir = match path.rfind('/') { - Some(slash) => path[..slash].trim_end_matches('/'), - None => "", - }; - match dir.rfind('/') { - Some(slash) => dir[slash + 1..].to_string(), - None => dir.to_string(), - } -} - -pub fn transcript_key(project: &str, session_id: &str) -> String { - format!("transcripts/{}/{}/{}.jsonl", AGENT, project, session_id) -} - /// 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. @@ -297,7 +237,7 @@ pub fn run(name: &str, stdin: &[u8]) { return; }; let text = if text.is_empty() { "{}" } else { text }; - let Ok(parsed) = serde_json::from_str::(text) else { + let Ok(parsed) = json::loads(text) else { return; }; let event = match parsed { @@ -307,9 +247,10 @@ pub fn run(name: &str, stdin: &[u8]) { let _ = match name { "pre-tool" => pre_tool(&event), "post-tool" => post_tool(&event).map(|_| ()), - "stop" => store::create_store(&store::resolve_store_uri(None)) - .map_err(|_| Stop) - .and_then(|store| snapshot_transcript(&event, store.as_ref()).map(|_| ())), + "stop" => match store::create_store(&store::resolve_store_uri(None)) { + Ok(store) => snapshot_transcript(&event, store.as_ref()).map(|_| ()), + Err(_) => Err(Stop), + }, _ => Ok(()), }; } @@ -318,20 +259,12 @@ pub fn run(name: &str, stdin: &[u8]) { mod tests { use super::*; - #[test] - fn project_is_the_containing_directory_name() { - assert_eq!(project_of("/h/.claude/projects/-a-b/s.jsonl"), "-a-b"); - assert_eq!(project_of("s.jsonl"), ""); - assert_eq!(project_of("/s.jsonl"), ""); - } - #[test] fn command_key_matches_python() { - let event: Map = - serde_json::from_str(r#"{"tool_input": {"command": "git commit"}}"#).unwrap(); + let event = json::loads(r#"{"tool_input": {"command": "git commit"}}"#).unwrap(); // hashlib.sha256(b"git commit").hexdigest()[:32] assert_eq!( - call_key(&event).ok().unwrap(), + call_key(event.as_object().unwrap()).ok().unwrap(), "cmd-993c9eb42f6efa07b7501be8a0378748" ); } diff --git a/rust/src/index.rs b/rust/src/index.rs new file mode 100644 index 0000000..4ad12f3 --- /dev/null +++ b/rust/src/index.rs @@ -0,0 +1,280 @@ +//! Store key layout and derived index entries, as in `loch/index.py`. + +use crate::bundle::{unpack_bundle, Bundle, BundleSession}; +use crate::json::{self, Value}; +use crate::object; +use crate::store::{Store, StoreError}; +use std::collections::BTreeSet; + +pub const BUNDLES_PREFIX: &str = "bundles/"; +pub const INDEX_PREFIX: &str = "index/"; +pub const BRANCH: &str = "branch"; + +/// Percent-encoding rather than Claude's lossy scheme, which would file +/// feature/foo and feature-foo together. A value can't hold a control +/// character, so this can't collide with one. +pub const UNSET_SEGMENT: &str = "%00"; + +#[derive(Clone, Debug)] +pub struct IndexEntry { + pub ref_: String, + pub dimension: String, + pub value: Option, + pub agent: String, + pub created_at: String, + pub bytes: i64, + pub sessions: i64, + pub cwd: String, + pub claude_version: Option, +} + +pub struct ReindexResult { + pub bundles: usize, + pub entries: usize, + pub removed: usize, +} + +pub fn bundle_key(ref_: &str) -> String { + format!("{}{}.loch", BUNDLES_PREFIX, ref_) +} + +fn ref_from_key(key: &str) -> String { + key[BUNDLES_PREFIX.len()..key.len() - ".loch".len()].into() +} + +/// `urllib.parse.quote(value, safe="")`. +pub fn quote(value: &str) -> String { + let mut out = String::new(); + for byte in + crate::py::encode_surrogateescape(value).unwrap_or_else(|_| value.as_bytes().to_vec()) + { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_' | b'.' | b'-' | b'~' => { + out.push(byte as char) + } + _ => out.push_str(&format!("%{:02X}", byte)), + } + } + out +} + +/// `urllib.parse.unquote`: valid `%XX` escapes become bytes, decoded as UTF-8 +/// with replacement in runs broken by any literal character. +pub fn unquote(value: &str) -> String { + if !value.contains('%') { + return value.into(); + } + let bytes = value.as_bytes(); + let mut out = String::new(); + let mut pending: Vec = Vec::new(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' + && i + 2 < bytes.len() + && bytes[i + 1].is_ascii_hexdigit() + && bytes[i + 2].is_ascii_hexdigit() + { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).expect("ASCII hex"); + pending.push(u8::from_str_radix(hex, 16).expect("checked hex")); + i += 3; + continue; + } + out.push_str(&String::from_utf8_lossy(&pending)); + pending.clear(); + let c = value[i..].chars().next().expect("in bounds"); + out.push(c); + i += c.len_utf8(); + } + out.push_str(&String::from_utf8_lossy(&pending)); + out +} + +pub fn encode_segment(value: Option<&str>) -> String { + match value { + None => UNSET_SEGMENT.into(), + Some(value) => quote(value), + } +} + +pub fn dimension_prefix(dimension: &str) -> String { + format!("{}{}/", INDEX_PREFIX, dimension) +} + +pub fn value_prefix(dimension: &str, value: Option<&str>) -> String { + format!("{}{}/", dimension_prefix(dimension), encode_segment(value)) +} + +pub fn index_key(dimension: &str, value: Option<&str>, ref_: &str) -> String { + format!("{}{}", value_prefix(dimension, value), ref_) +} + +fn entry_json(entry: &IndexEntry) -> Value { + Value::Object(object! { + "ref" => entry.ref_.as_str(), + "dimension" => entry.dimension.as_str(), + "value" => Value::opt_str(entry.value.as_deref()), + "agent" => entry.agent.as_str(), + "createdAt" => entry.created_at.as_str(), + "bytes" => entry.bytes, + "sessions" => entry.sessions, + "cwd" => entry.cwd.as_str(), + "claudeVersion" => Value::opt_str(entry.claude_version.as_deref()), + }) +} + +fn entry_from_json(raw: &Value) -> Option { + let text = |key: &str| raw.get(key).and_then(Value::as_str).map(str::to_string); + let number = |key: &str| raw.get(key).and_then(Value::as_i64).unwrap_or(0); + Some(IndexEntry { + ref_: text("ref")?, + dimension: text("dimension")?, + value: text("value"), + agent: text("agent").unwrap_or_default(), + created_at: text("createdAt").unwrap_or_default(), + bytes: number("bytes"), + sessions: number("sessions"), + cwd: text("cwd").unwrap_or_default(), + claude_version: text("claudeVersion"), + }) +} + +/// One entry per (branch, ref): a save without --branch can pack sessions +/// from several branches, so a bundle may be indexed under each of them. +pub fn entries_for(bundle: &Bundle, ref_: &str, size: usize) -> Vec { + let mut grouped: indexmap::IndexMap, Vec<&BundleSession>> = Default::default(); + for session in &bundle.sessions { + grouped + .entry(session.git_branch.clone()) + .or_default() + .push(session); + } + let mut groups: Vec<(Option, Vec<&BundleSession>)> = grouped.into_iter().collect(); + groups.sort_by(|a, b| { + crate::py::cmp( + &encode_segment(a.0.as_deref()), + &encode_segment(b.0.as_deref()), + ) + }); + groups + .into_iter() + .map(|(branch, sessions)| IndexEntry { + ref_: ref_.into(), + dimension: BRANCH.into(), + value: branch, + agent: bundle.agent.clone(), + created_at: bundle.created_at.clone(), + bytes: size as i64, + sessions: sessions.len() as i64, + cwd: sessions[0].cwd.clone(), + claude_version: sessions + .iter() + .find_map(|s| s.claude_version.clone().filter(|v| !v.is_empty())), + }) + .collect() +} + +pub fn write_entries(store: &dyn Store, entries: &[IndexEntry]) -> Result, StoreError> { + let mut keys = Vec::new(); + for entry in entries { + let key = index_key(&entry.dimension, entry.value.as_deref(), &entry.ref_); + store.put( + &key, + json::dumps(&entry_json(entry), json::DEFAULT).as_bytes(), + )?; + keys.push(key); + } + Ok(keys) +} + +pub fn index_bundle( + store: &dyn Store, + bundle: &Bundle, + ref_: &str, + size: usize, +) -> Result, StoreError> { + let entries = entries_for(bundle, ref_, size); + write_entries(store, &entries)?; + Ok(entries) +} + +#[derive(Debug)] +pub enum IndexError { + Store(StoreError), + /// Bytes that arrived and won't parse: an entry or a bundle. + Unreadable(String), +} + +impl From for IndexError { + fn from(error: StoreError) -> Self { + IndexError::Store(error) + } +} + +pub fn load_entries(store: &dyn Store, prefix: &str) -> Result, IndexError> { + let mut entries = Vec::new(); + for key in store.list(prefix)? { + let data = store.get(&key)?; + let entry = std::str::from_utf8(&data) + .ok() + .and_then(|text| json::loads(text).ok()) + .and_then(|value| entry_from_json(&value)) + .ok_or_else(|| IndexError::Unreadable(format!("unreadable index entry {}", key)))?; + entries.push(entry); + } + entries.sort_by(|a, b| crate::py::cmp(&b.created_at, &a.created_at)); + Ok(entries) +} + +/// Entries first: they are derived from the bundle, so removing it before +/// them would strand any that a failure here left behind. +pub fn delete_bundle(store: &dyn Store, ref_: &str) -> Result, IndexError> { + let packed = store.get(&bundle_key(ref_))?; + let bundle = unpack_bundle(&packed).map_err(IndexError::Unreadable)?; + let mut removed = Vec::new(); + for entry in entries_for(&bundle, ref_, packed.len()) { + let key = index_key(&entry.dimension, entry.value.as_deref(), &entry.ref_); + store.delete(&key)?; + removed.push(key); + } + store.delete(&bundle_key(ref_))?; + removed.push(bundle_key(ref_)); + Ok(removed) +} + +pub fn reindex(store: &dyn Store) -> Result { + let stale: BTreeSet = store.list(INDEX_PREFIX)?.into_iter().collect(); + let mut bundles = 0; + let mut written: BTreeSet = BTreeSet::new(); + for key in store.list(BUNDLES_PREFIX)? { + if !key.ends_with(".loch") { + continue; + } + let packed = store.get(&key)?; + let bundle = unpack_bundle(&packed).map_err(IndexError::Unreadable)?; + let entries = entries_for(&bundle, &ref_from_key(&key), packed.len()); + written.extend(write_entries(store, &entries)?); + bundles += 1; + } + let mut removed: Vec<&String> = stale.difference(&written).collect(); + removed.sort_by(|a, b| crate::py::cmp(a, b)); + for key in &removed { + store.delete(key)?; + } + Ok(ReindexResult { + bundles, + entries: written.len(), + removed: removed.len(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn segments_round_trip_like_urllib() { + assert_eq!(quote("feature/foo bar~é"), "feature%2Ffoo%20bar~%C3%A9"); + assert_eq!(unquote("feature%2Ffoo%20bar~%C3%A9"), "feature/foo bar~é"); + assert_eq!(unquote("%E2x%zz%4"), "\u{fffd}x%zz%4"); + } +} diff --git a/rust/src/ingest.rs b/rust/src/ingest.rs new file mode 100644 index 0000000..88388b5 --- /dev/null +++ b/rust/src/ingest.rs @@ -0,0 +1,652 @@ +//! Claude Code JSONL → loch turns, as in `loch/ingest.py` (the converter). +//! +//! Normalizing goes through `rewrite::compile`, the same single pass with the +//! same guards restore uses, fed placeholders instead of another machine's +//! paths: that sharing is what makes a turn id survive `restore`. + +use crate::claude::{encode_path, AGENT}; +use crate::format::{self, digest, digest_bytes, Derived, NotJson, Turn, FORMAT_VERSION}; +use crate::json::{self, Map, Value}; +use crate::object; +use crate::py; +use crate::rewrite::{self, Guard, Replacer}; +use crate::sys; +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap, HashSet}; +use std::fs; + +pub const CONVERTER_VERSION: i64 = 1; + +pub fn converter() -> Map { + object! {"id" => AGENT, "version" => CONVERTER_VERSION} +} + +const PLACEHOLDER_PREFIX: &str = "{{loch:"; +const ESCAPE: &str = "{{loch:esc}}"; +const ROOT: &str = "{{loch:root}}"; +const HOME: &str = "{{loch:home}}"; +const ROOT_SLUG: &str = "{{loch:root-slug}}"; +const SESSION: &str = "{{loch:session}}"; + +/// Record fields that place a record rather than say anything; excluded from +/// the hashed payload of system and attachment turns. +const ENVELOPE_FIELDS: &[&str] = &[ + "type", + "uuid", + "parentUuid", + "logicalParentUuid", + "sessionId", + "session_id", + "timestamp", + "cwd", + "gitBranch", + "version", + "entrypoint", + "userType", + "slug", + "isSidechain", + "agentId", + "requestId", + "promptId", +]; + +fn author(kind: &str) -> Map { + object! {"kind" => kind, "agent" => AGENT} +} + +pub struct Origin { + pub cwd: String, + pub home: String, + pub session_id: String, +} + +pub fn normalizer(origin: &Origin) -> Replacer { + let mut pairs = vec![ + ( + PLACEHOLDER_PREFIX.to_string(), + ESCAPE.to_string(), + Guard::None, + ), + (origin.cwd.clone(), ROOT.to_string(), Guard::Path), + ( + encode_path(&origin.cwd), + ROOT_SLUG.to_string(), + Guard::EncodedComponent, + ), + (origin.session_id.clone(), SESSION.to_string(), Guard::None), + ]; + // A session run from the home directory itself is a root, not a home. + if origin.home != origin.cwd { + pairs.push((origin.home.clone(), HOME.to_string(), Guard::Path)); + } + rewrite::compile(&pairs) +} + +/// 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. +pub fn normalize_value(value: &Value, text: &Replacer) -> Value { + match value { + Value::Str(s) => Value::Str(text.apply(s)), + Value::Array(items) => { + Value::Array(items.iter().map(|v| normalize_value(v, text)).collect()) + } + Value::Object(map) => { + let mut out = Map::new(); + for (key, item) in map { + out.insert(text.apply(key), normalize_value(item, text)); + } + Value::Object(out) + } + other => other.clone(), + } +} + +/// `block.get(key, default)`: present-with-null stays null. +fn get_or(block: &Map, key: &str, default: Value) -> Value { + block.get(key).cloned().unwrap_or(default) +} + +fn get_none(block: &Map, key: &str) -> Value { + get_or(block, key, Value::Null) +} + +fn blocks_from_content(content: Option<&Value>) -> Vec { + match content { + Some(Value::Str(text)) => vec![Value::Object( + object! {"type" => "text", "text" => text.as_str()}, + )], + Some(Value::Array(items)) => items.iter().map(block).collect(), + _ => Vec::new(), + } +} + +fn passthrough(value: &Value) -> Value { + Value::Object(object! {"type" => "x-claude-code:block", "block" => value.clone()}) +} + +fn block(value: &Value) -> Value { + let Value::Object(b) = value else { + return passthrough(value); + }; + let kind = b.get("type").and_then(Value::as_str); + match kind { + Some("text") => { + Value::Object(object! {"type" => "text", "text" => get_or(b, "text", "".into())}) + } + // The signature is Anthropic's attestation for resuming, not content. + Some("thinking") => Value::Object( + object! {"type" => "thinking", "text" => get_or(b, "thinking", "".into())}, + ), + Some("redacted_thinking") => Value::Object(object! {"type" => "redacted-thinking"}), + Some("tool_use") => Value::Object(object! { + "type" => "tool-call", + "call" => get_none(b, "id"), + "name" => get_none(b, "name"), + "input" => get_none(b, "input"), + }), + Some("tool_result") => { + let mut normalized = object! { + "type" => "tool-result", + "call" => get_none(b, "tool_use_id"), + "content" => blocks_from_content(b.get("content")), + }; + if b.get("is_error").is_some_and(Value::truthy) { + normalized.insert("error".into(), Value::Bool(true)); + } + Value::Object(normalized) + } + Some("image") => { + Value::Object(object! {"type" => "image", "source" => get_none(b, "source")}) + } + // Unknown block types pass through whole rather than being dropped. + _ => passthrough(value), + } +} + +fn payload(record: &Map) -> Map { + record + .iter() + .filter(|(key, _)| !ENVELOPE_FIELDS.contains(&key.as_str())) + .map(|(k, v)| (k.clone(), v.clone())) + .collect() +} + +/// (kind, author, blocks) for a chain record, or None for one outside the +/// conversation graph. The human author is filled in by the caller. +fn classify(record: &Map) -> Option<(&'static str, Map, Vec)> { + let kind = record.get("type").and_then(Value::as_str); + let content = match record.get("message") { + Some(Value::Object(message)) => message.get("content"), + _ => None, + }; + match kind { + Some("assistant") => Some(("message", author("agent"), blocks_from_content(content))), + Some("user") => { + let blocks = blocks_from_content(content); + if record.get("isCompactSummary").is_some_and(Value::truthy) + || record.get("isMeta").is_some_and(Value::truthy) + { + return Some(("context", author("system"), blocks)); + } + if blocks + .iter() + .any(|b| b.get("type").is_some_and(|t| t.is_str("tool-result"))) + { + return Some(("tool-result", author("tool"), blocks)); + } + Some(("message", object! {"kind" => "human"}, blocks)) + } + Some("attachment") => { + let b = object! {"type" => "x-claude-code:attachment", "attachment" => payload(record)}; + Some(("context", author("system"), vec![Value::Object(b)])) + } + Some("system") => { + let b = Value::Object( + object! {"type" => "x-claude-code:system", "system" => payload(record)}, + ); + if record + .get("subtype") + .is_some_and(|s| s.is_str("compact_boundary")) + { + Some(("compaction", author("system"), vec![b])) + } else { + Some(("event", author("system"), vec![b])) + } + } + _ => None, + } +} + +/// A compaction boundary has no parent by design and names the record it +/// logically follows instead; following that link keeps a compacted session +/// one connected graph. +fn parent_uuid(record: &Map) -> Option { + let parent = match record.get("parentUuid") { + None | Some(Value::Null) => record.get("logicalParentUuid"), + other => other, + }; + parent.and_then(Value::as_str).map(str::to_string) +} + +fn parse(raw: &str) -> Vec<(usize, Map)> { + let mut records = Vec::new(); + for (index, line) in raw.split('\n').enumerate() { + if py::strip(line).is_empty() { + continue; + } + if let Ok(Value::Object(record)) = json::loads(line) { + records.push((index + 1, record)); + } + } + records +} + +fn uuid_of(record: &Map) -> &str { + record + .get("uuid") + .and_then(Value::as_str) + .expect("chain records have a uuid") +} + +/// File order wherever it already respects parentage. Dangling parents make +/// a root; a cycle is broken the same way rather than looping. +fn topological(chain: Vec<(usize, Map)>) -> (Vec<(usize, Map)>, HashSet) { + let present: HashSet = chain.iter().map(|(_, r)| uuid_of(r).to_string()).collect(); + let mut children: HashMap> = HashMap::new(); + let mut waiting: Vec = vec![0; chain.len()]; + for (index, (_, record)) in chain.iter().enumerate() { + if let Some(parent) = parent_uuid(record) { + if present.contains(&parent) && parent != uuid_of(record) { + children.entry(parent).or_default().push(index); + waiting[index] = 1; + } + } + } + let mut ready: BinaryHeap> = waiting + .iter() + .enumerate() + .filter(|(_, &w)| w == 0) + .map(|(i, _)| Reverse(i)) + .collect(); + let mut done = vec![false; chain.len()]; + let mut order: Vec = Vec::with_capacity(chain.len()); + while order.len() < chain.len() { + if ready.is_empty() { + let stuck = done + .iter() + .position(|d| !d) + .expect("something is unfinished"); + waiting[stuck] = 0; + ready.push(Reverse(stuck)); + } + let Reverse(index) = ready.pop().expect("ready is non-empty"); + if done[index] { + continue; + } + done[index] = true; + order.push(index); + if let Some(kids) = children.get(uuid_of(&chain[index].1)) { + for &child in kids { + if !done[child] { + waiting[child] -= 1; + if waiting[child] <= 0 { + ready.push(Reverse(child)); + } + } + } + } + } + let mut slots: Vec> = chain.into_iter().map(Some).collect(); + let ordered = order + .into_iter() + .map(|i| slots[i].take().expect("each once")) + .collect(); + (ordered, present) +} + +fn facts(number: usize, record: &Map, text: &Replacer) -> Map { + let mut facts = object! {"line" => number, "uuid" => uuid_of(record)}; + if let Some(Value::Object(message)) = record.get("message") { + for (source, name) in [("id", "messageId"), ("model", "model")] { + if let Some(Value::Str(value)) = message.get(source) { + facts.insert(name.into(), value.as_str().into()); + } + } + } + for name in ["timestamp", "gitBranch", "version", "subtype"] { + if let Some(Value::Str(value)) = record.get(name) { + facts.insert(name.into(), value.as_str().into()); + } + } + if let Some(Value::Str(cwd)) = record.get("cwd") { + facts.insert("cwd".into(), text.apply(cwd).into()); + } + facts.insert("record".into(), get_none(record, "type")); + facts +} + +fn append(map: &mut Map, key: &str, item: Value) { + match map + .entry(key.to_string()) + .or_insert_with(|| Value::Array(Vec::new())) + { + Value::Array(items) => items.push(item), + _ => unreachable!("only ever an array"), + } +} + +pub struct Converted { + pub turns: Vec, + pub heads: Map, + pub session: Map, +} + +pub fn convert(raw: &str, origin: &Origin, human: &Map) -> Result { + let text = normalizer(origin); + let records = parse(raw); + let chain: Vec<(usize, Map)> = records + .iter() + .filter(|(_, r)| matches!(r.get("uuid"), Some(Value::Str(_)))) + .cloned() + .collect(); + let (ordered, present) = topological(chain); + + let mut turn_of: HashMap = HashMap::new(); + let mut turns: indexmap::IndexMap = indexmap::IndexMap::new(); + let mut has_children: HashSet = HashSet::new(); + let mut last_turn: Option = None; + let mut session = Map::new(); + + for (number, record) in &ordered { + let Some((kind, mut who, blocks)) = classify(record) else { + continue; + }; + let uuid = uuid_of(record).to_string(); + if kind == "event" { + // Claude Code's own bookkeeping, folded into the facts of the + // turn it follows rather than made a turn. + let mut event = object! {"line" => *number}; + if let Value::Object(normalized) = normalize_value(&blocks[0], &text) { + event.extend(normalized); + } + if let Some(Value::Str(stamp)) = record.get("timestamp") { + event.insert("timestamp".into(), stamp.as_str().into()); + } + let parent = parent_uuid(record).and_then(|p| turn_of.get(&p).cloned()); + match parent { + None => append(&mut session, "events", Value::Object(event)), + Some(parent) => { + turn_of.insert(uuid, parent.clone()); + append(&mut turns[&parent].facts, "events", Value::Object(event)); + } + } + continue; + } + if who.get("kind").is_some_and(|k| k.is_str("human")) { + who = human.clone(); + } + let parent = parent_uuid(record); + let mut turn_facts = facts(*number, record, &text); + let mut parents = Vec::new(); + if let Some(parent) = parent { + if let Some(turn) = turn_of.get(&parent) { + parents.push(turn.clone()); + } else if !present.contains(&parent) { + turn_facts.insert("danglingParent".into(), parent.into()); + } + } + let normalized: Vec = blocks.iter().map(|b| normalize_value(b, &text)).collect(); + let turn = format::make_turn(kind, &who, parents.clone(), normalized, turn_facts)?; + turn_of.insert(uuid.clone(), turn.id.clone()); + last_turn = Some(turn.id.clone()); + match turns.get_mut(&turn.id) { + Some(existing) => append(&mut existing.facts, "alsoUuids", uuid.into()), + None => { + turns.insert(turn.id.clone(), turn); + } + } + has_children.extend(parents); + } + + let mut current = last_turn; + for (_, record) in &records { + match record.get("type").and_then(Value::as_str) { + Some("last-prompt") => { + if let Some(Value::Str(leaf)) = record.get("leafUuid") { + if let Some(turn) = turn_of.get(leaf) { + current = Some(turn.clone()); + } + } + } + Some("ai-title") => { + if let Some(Value::Str(title)) = record.get("aiTitle") { + session.insert("aiTitle".into(), title.as_str().into()); + } + } + Some("custom-title") => { + if let Some(Value::Str(title)) = record.get("customTitle") { + session.insert("title".into(), title.as_str().into()); + } + } + _ => {} + } + } + + let leaves: Vec = turns + .keys() + .filter(|id| !has_children.contains(*id)) + .map(|id| Value::str(id.as_str())) + .collect(); + let mut heads = object! {"leaves" => leaves}; + if let Some(current) = current { + heads.insert("current".into(), current.into()); + } + let session = match normalize_value(&Value::Object(session), &text) { + Value::Object(map) => map, + _ => unreachable!("an object normalizes to an object"), + }; + Ok(Converted { + turns: turns.into_values().collect(), + heads, + session, + }) +} + +/// The transcript and everything Claude files beside it for the session: +/// subagent transcripts and spilled tool output under `/`. +pub fn source_files(transcript_path: &str) -> Vec<(String, String)> { + let mut files = vec![("transcript.jsonl".to_string(), transcript_path.to_string())]; + let sidecar = &transcript_path[..transcript_path.len().saturating_sub(".jsonl".len())]; + if std::path::Path::new(sidecar).is_dir() { + let mut stack = vec![sidecar.to_string()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = sys::join(&dir, &entry.file_name().to_string_lossy()); + // os.walk files a symlink to a directory with the directories + // and, without followlinks, never descends it: it is in + // neither list. + let real_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false); + if real_dir { + stack.push(path); + } else if std::path::Path::new(&path).is_dir() { + continue; + } else { + let relative = sys::relpath(&path, sidecar); + files.push((format!("sidecar/{}", relative), path)); + } + } + } + } + files.sort_by(|a, b| py::cmp(&a.0, &b.0).then_with(|| py::cmp(&a.1, &b.1))); + files +} + +#[derive(Debug)] +pub enum IngestError { + /// str(OSError), which Debug carries into the `internal` message. + #[allow(dead_code)] + Io(String), + NotJson, +} + +impl From for IngestError { + fn from(_: NotJson) -> Self { + IngestError::NotJson + } +} + +/// The content-addressed identity of the raw source, and the transcript text. +pub fn source_manifest(transcript_path: &str) -> Result<(Map, String), IngestError> { + let mut entries = Vec::new(); + let mut transcript = String::new(); + for (relative, path) in source_files(transcript_path) { + let data = fs::read(&path).map_err(|e| IngestError::Io(sys::os_error(&e, &path)))?; + entries.push(Value::Object(object! { + "path" => relative.as_str(), + "sha256" => digest_bytes(&data), + "bytes" => data.len(), + })); + if relative == "transcript.jsonl" { + transcript = py::decode_surrogateescape(&data); + } + } + let manifest = object! {"agent" => AGENT, "files" => entries}; + let mut source = object! {"id" => digest(&Value::Object(manifest.clone()))?}; + source.extend(manifest); + Ok((source, transcript)) +} + +pub fn ingest( + transcript_path: &str, + origin: &Origin, + author_id: Option<&str>, +) -> Result { + let mut human = object! {"kind" => "human"}; + // Omitted rather than null: the encoding of "unknown" is part of every id. + if let Some(id) = author_id { + human.insert("id".into(), id.into()); + } + let (source, transcript) = source_manifest(transcript_path)?; + let converted = convert(&transcript, origin, &human)?; + let mut header = object! { + "loch" => FORMAT_VERSION, + "converter" => converter(), + "source" => source, + "origin" => object! { + "cwd" => origin.cwd.as_str(), + "home" => origin.home.as_str(), + "sessionId" => origin.session_id.as_str(), + }, + "author" => human, + }; + if !converted.session.is_empty() { + header.insert("session".into(), Value::Object(converted.session)); + } + Ok(Derived { + header, + turns: converted.turns, + heads: converted.heads, + }) +} + +pub fn derived_name(derived: &Derived) -> String { + let id = derived.header["source"] + .get("id") + .and_then(Value::as_str) + .unwrap_or(""); + let source = id.split_once(':').map(|(_, hex)| hex).unwrap_or(id); + format!("{}.{}-v{}.jsonl", source, AGENT, CONVERTER_VERSION) +} + +#[derive(Debug)] +pub struct AuthorKeyError(pub String); + +const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +fn b64encode(data: &[u8]) -> String { + let mut out = String::new(); + for chunk in data.chunks(3) { + let n = chunk + .iter() + .enumerate() + .fold(0u32, |acc, (i, &b)| acc | (b as u32) << (16 - 8 * i)); + for i in 0..4 { + if i <= chunk.len() { + out.push(B64[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +/// `base64.b64decode(text, validate=True)`, with binascii's messages. +fn b64decode_strict(text: &str) -> Result, String> { + if !text.is_ascii() { + return Err("string argument should contain only ASCII characters".into()); + } + let body = text.trim_end_matches('='); + let pad = text.len() - body.len(); + if pad > 2 || !body.bytes().all(|b| B64.contains(&b)) { + return Err("Non-base64 digit found".into()); + } + let data_chars = body.len(); + if data_chars % 4 == 1 { + return Err(format!( + "Invalid base64-encoded string: number of data characters ({}) cannot be 1 more than a multiple of 4", + data_chars + )); + } + if !(data_chars + pad).is_multiple_of(4) { + return Err("Incorrect padding".into()); + } + let mut out = Vec::new(); + let mut buffer = 0u32; + let mut bits = 0; + for b in body.bytes() { + let value = B64.iter().position(|&c| c == b).expect("checked alphabet") as u32; + buffer = buffer << 6 | value; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((buffer >> bits & 0xff) as u8); + } + } + Ok(out) +} + +/// `ssh:SHA256:`, the fingerprint `ssh-keygen -l` prints. +pub fn ssh_author_id(public_key: &str) -> Result { + let fields = py::split(public_key); + if fields.len() < 2 { + return Err(AuthorKeyError("not an OpenSSH public key line".into())); + } + let blob = b64decode_strict(fields[1]) + .map_err(|e| AuthorKeyError(format!("key body is not base64: {}", e)))?; + use sha2::{Digest, Sha256}; + let fingerprint = b64encode(&Sha256::digest(&blob)); + Ok(format!("ssh:SHA256:{}", fingerprint.trim_end_matches('='))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base64_matches_binascii() { + assert_eq!(b64encode(b"hello"), "aGVsbG8="); + assert_eq!(b64decode_strict("aGVsbG8=").unwrap(), b"hello"); + assert_eq!( + b64decode_strict("aGVsbG8").unwrap_err(), + "Incorrect padding" + ); + assert_eq!( + b64decode_strict("a!").unwrap_err(), + "Non-base64 digit found" + ); + } +} diff --git a/rust/src/json.rs b/rust/src/json.rs index c115323..f8d3102 100644 --- a/rust/src/json.rs +++ b/rust/src/json.rs @@ -168,12 +168,6 @@ pub fn loads(text: &str) -> Result { Ok(value) } -/// `json.loads(line)` for a line that is UTF-8 bytes, which is how transcript -/// lines arrive. Undecodable input fails, as `bytes.decode` would first. -pub fn loads_bytes(bytes: &[u8]) -> Result { - loads(std::str::from_utf8(bytes).map_err(|_| ParseError)?) -} - struct Parser<'a> { bytes: &'a [u8], text: &'a str, @@ -570,7 +564,10 @@ fn shortest_digits(value: f64) -> (String, i32) { let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); let digits = digits.trim_end_matches('0'); let digits = if digits.is_empty() { "0" } else { digits }; - (digits.to_string(), exponent.parse().expect("integer exponent")) + ( + digits.to_string(), + exponent.parse().expect("integer exponent"), + ) } /// Python's `float.__repr__`, which `json.dumps` writes: positional when the @@ -717,7 +714,12 @@ fn ecma_number(value: f64) -> Result { Ok(if k <= n && n <= 21 { format!("{}{}{}", sign, digits, "0".repeat((n - k) as usize)) } else if 0 < n && n <= 21 { - format!("{}{}.{}", sign, &digits[..n as usize], &digits[n as usize..]) + format!( + "{}{}.{}", + sign, + &digits[..n as usize], + &digits[n as usize..] + ) } else if -6 < n && n <= 0 { format!("{}0.{}{}", sign, "0".repeat((-n) as usize), digits) } else { @@ -787,7 +789,7 @@ mod tests { dumps(&map["b"], DEFAULT), "[1.5, 0, 123456789012345678901234567890]" ); - assert_eq!(dumps(&map["s"], DEFAULT), r#""😀\ud83d x""#); + assert_eq!(dumps(&map["s"], DEFAULT), r#""\ud83d\ude00\ud83d x""#); assert!(loads("[1] x").is_err()); assert!(loads("\"a\nb\"").is_err()); assert!(loads("01").is_err()); @@ -795,7 +797,9 @@ mod tests { #[test] fn strings_escape_like_ensure_ascii() { - let value = Value::Object(object! {"a" => "é😀\u{7f}\u{1}\"\\\n", "b" => Value::Array(vec![Value::int(1), Value::Bool(true), Value::Null])}); + let value = Value::Object( + object! {"a" => "é😀\u{7f}\u{1}\"\\\n", "b" => Value::Array(vec![Value::int(1), Value::Bool(true), Value::Null])}, + ); assert_eq!( dumps(&value, DEFAULT), "{\"a\": \"\\u00e9\\ud83d\\ude00\\u007f\\u0001\\\"\\\\\\n\", \"b\": [1, true, null]}" @@ -808,7 +812,9 @@ mod tests { #[test] fn indent_matches_python() { - let value = Value::Object(object! {"a" => Value::Array(vec![]), "b" => Value::Object(object!{"c" => 1i64})}); + let value = Value::Object( + object! {"a" => Value::Array(vec![]), "b" => Value::Object(object!{"c" => 1i64})}, + ); assert_eq!( dumps(&value, INDENTED), "{\n \"a\": [],\n \"b\": {\n \"c\": 1\n }\n}" diff --git a/rust/src/main.rs b/rust/src/main.rs index 6fddd80..8722715 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -1,78 +1,39 @@ //! The Rust build of loch: one static binary for Ness, the VS Code extension -//! and the Claude Code hooks to ship. The Python package is the reference -//! implementation; a command lands here only once `test/test_equivalence.py` -//! holds it to the same output and side effects. +//! and the Claude Code hooks to ship. The Python package is the reference; +//! `test/test_equivalence.py` holds every command here to its output and side +//! effects. // The error path is cold and runs once per process; boxing it buys nothing. #![allow(clippy::result_large_err)] +mod argparse; +mod blame_html; +mod bundle; mod claude; +mod cli; +mod format; mod git; mod hook; +mod index; +mod ingest; +mod json; mod output; +mod py; +mod redact; +mod rewrite; mod s3; mod store; +mod sys; +mod trace; +use cli::Failure; use output::{emit, emit_error, CommandError, Outcome, JSON_FLAG}; -use serde_json::Value; -use std::io::Read; - -/// Commands the Python implementation has and this one doesn't yet. Asking -/// for one is `not-ported` rather than `unknown-command`: the command exists, -/// and the fix is the Python install, not a typo. -const UNPORTED: &[&str] = &[ - "list", "save", "restore", "delete", "reindex", "ingest", "install", "blame", "ask", "log", - "backfill", -]; - -const USAGE: &str = "loch — save and restore agent coding sessions across machines - -This is the Rust build, which so far implements: - - loch hook pre-tool | post-tool | stop (run by Claude Code) - loch --version - -Every other command is still served by the Python implementation (`uv tool -install loch`); asking this build for one fails with code `not-ported`. - -Every command takes --json, which replaces the text below with one machine- -readable document on stdout. - -Environment: - LOCH_STORE default store URI - CLAUDE_CONFIG_DIR Claude Code's state directory (default ~/.claude) -"; - -fn command_hook(argv: &[String]) -> Result { - let name = argv.first().map(String::as_str).unwrap_or(""); - let mut stdin = Vec::new(); - if std::io::stdin().read_to_end(&mut stdin).is_ok() { - hook::run(name, &stdin); - } - Ok(Outcome::new("hook")) -} - -fn command_version(_argv: &[String]) -> Result { - let version = env!("CARGO_PKG_VERSION"); - let mut outcome = Outcome::new("version"); - outcome - .payload - .insert("version".into(), Value::from(version)); - outcome.text = format!("loch {}\n", version); - Ok(outcome) -} - -fn command_help(_argv: &[String]) -> Result { - let mut outcome = Outcome::new("help"); - outcome.payload.insert("usage".into(), Value::from(USAGE)); - outcome.text = USAGE.into(); - Ok(outcome) -} fn main() { let mut argv: Vec = std::env::args().skip(1).collect(); // Read off argv rather than from a parsed command line: an unknown - // command has to render in the mode the caller asked for. + // command, or a parser rejecting a flag, has to render in the mode the + // caller asked for, and neither has a namespace by the time it fails. let as_json = argv.iter().any(|arg| arg == JSON_FLAG); if argv.first().map(String::as_str) == Some(JSON_FLAG) { argv.remove(0); @@ -90,24 +51,30 @@ fn main() { &argv[1..] }; - let result = match command.as_str() { - "hook" => command_hook(rest), - "version" => command_version(rest), - "help" => command_help(rest), - name if UNPORTED.contains(&name) => Err(CommandError::new( - "not-ported", - format!( - "'{}' is not in the Rust build yet; use the Python loch", - name - ), - )), - name => Err(CommandError::new( + let result = match cli::dispatch(&command, rest) { + Some(result) => result, + None => Err(Failure::Error(CommandError::new( "unknown-command", - format!("unknown command '{}' (try: loch help)", name), - )), + format!("unknown command '{}' (try: loch help)", command), + ))), }; match result { Ok(outcome) => emit(outcome, as_json), - Err(error) => emit_error(&command, error, as_json), + Err(Failure::Help(text)) => { + let mut outcome = Outcome::new(&command); + outcome.payload.insert("usage".into(), text.as_str().into()); + outcome.text = text; + emit(outcome, as_json); + } + Err(Failure::Error(error)) => emit_error(&command, error, as_json), + // Python prints a traceback here, which is the one thing a consumer + // can't parse; JSON mode gets the same `internal` document. + Err(Failure::Internal(message)) => { + let mut error = CommandError::new("internal", message.clone()); + if !as_json { + error.prose = Some(format!("loch: internal error: {}\n", message)); + } + emit_error(&command, error, as_json) + } } } diff --git a/rust/src/py.rs b/rust/src/py.rs index b36b426..1b827ab 100644 --- a/rust/src/py.rs +++ b/rust/src/py.rs @@ -35,12 +35,13 @@ pub fn is_space(c: char) -> bool { /// The same set as a regex character-class body, for patterns ported from /// Python that say `\s`. -pub const SPACE_CLASS: &str = - r"\t\n\x0b\x0c\r\x1c-\x1f \x{85}\x{a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}"; +pub const SPACE_CLASS: &str = r"\t\n\x0b\x0c\r\x1c-\x1f \x{85}\x{a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}"; /// `str.split()` with no argument. pub fn split(text: &str) -> Vec<&str> { - text.split(is_space).filter(|part| !part.is_empty()).collect() + text.split(is_space) + .filter(|part| !part.is_empty()) + .collect() } /// `str.strip()` with no argument. @@ -161,7 +162,10 @@ mod tests { fn surrogateescape_round_trips() { let bytes = b"ok \xff\xfe \xed\xa0\x80 \xe2\x9c\x93 \xe2\x9c"; let text = decode_surrogateescape(bytes); - assert_eq!(text.chars().filter(|&c| as_surrogate(c).is_some()).count(), 7); + assert_eq!( + text.chars().filter(|&c| as_surrogate(c).is_some()).count(), + 7 + ); assert_eq!(encode_surrogateescape(&text).unwrap(), bytes); assert!(encode_strict(&text).is_err()); } diff --git a/rust/src/redact.rs b/rust/src/redact.rs new file mode 100644 index 0000000..3eef372 --- /dev/null +++ b/rust/src/redact.rs @@ -0,0 +1,202 @@ +//! Secret scrubbing, as in `loch/redact.py` — best-effort pattern matching +//! and nothing more. The patterns are the Python ones with one translation: +//! Python's `\s` (`str.isspace`, which includes U+001C..U+001F) is spelled out, +//! since the `regex` crate's `\s` is Unicode White_Space and differs from it. +//! fancy-regex supplies the lookarounds; it backtracks like Python's `re`, so +//! leftmost-first alternation picks the same rule at the same place. + +use crate::py::SPACE_CLASS; +use fancy_regex::{Regex, RegexBuilder}; +use indexmap::IndexMap; +use std::sync::OnceLock; + +const START: &str = r"(? Vec<(&'static str, String)> { + let env_assignment = format!( + concat!( + r"(?P", + r"[A-Z0-9_]*", + r"(?:AWS_SECRET_ACCESS_KEY|SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)", + r"[A-Z0-9_]*", + r#"["']?[{s}]*[=:][{s}]*["']?"#, + r")", + r#"(?!\[REDACTED:)(?![/~.])[^{s}"',;\\]{{8,}}"# + ), + s = SPACE_CLASS + ); + vec![ + ( + "aws-access-key", + format!(r"{START}(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{{16}}{END}"), + ), + ( + "github-token", + format!(r"{START}gh[pousr]_[A-Za-z0-9]{{36,}}"), + ), + ( + "slack-token", + format!(r"{START}xox[abprs]-[A-Za-z0-9-]{{10,}}"), + ), + ("stripe-key", format!(r"{START}sk_live_[A-Za-z0-9]{{24,}}")), + ( + "anthropic-key", + format!(r"{START}sk-ant-[A-Za-z0-9_-]{{20,}}"), + ), + ( + "openai-key", + format!(r"{START}sk-(?:proj-)?[A-Za-z0-9_-]{{20,}}"), + ), + ( + "google-api-key", + format!(r"{START}AIza[0-9A-Za-z_-]{{35}}{END}"), + ), + // The body excludes the double quote so a BEGIN and an END in two + // different JSONL records can't be joined into one match. + ( + "private-key-block", + r#"-----BEGIN [A-Z ]*PRIVATE KEY-----[^"]*?-----END [A-Z ]*PRIVATE KEY-----"#.into(), + ), + ( + "jwt", + format!(r"{START}eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"), + ), + ("env-assignment", env_assignment), + ] +} + +struct Compiled { + regex: Regex, + names: Vec<&'static str>, +} + +fn compiled() -> &'static Compiled { + static COMPILED: OnceLock = OnceLock::new(); + COMPILED.get_or_init(|| { + let rules = rules(); + let pattern = rules + .iter() + .map(|(name, pattern)| format!("(?P<{}>{})", name.replace('-', "_"), pattern)) + .collect::>() + .join("|"); + Compiled { + // Python's `re` has no backtracking limit; a high one keeps a + // pathological transcript slow rather than failing it. + regex: RegexBuilder::new(&pattern) + .backtrack_limit(usize::MAX / 2) + .build() + .expect("the redaction rules compile"), + names: rules.iter().map(|(name, _)| *name).collect(), + } + }) +} + +#[derive(Debug)] +pub struct RedactionError(pub String); + +pub struct Redaction { + pub text: String, + /// Rule name → count, in order of each rule's first match. + pub counts: IndexMap, +} + +fn matched_rule(captures: &fancy_regex::Captures, names: &[&'static str]) -> &'static str { + names + .iter() + .find(|name| captures.name(&name.replace('-', "_")).is_some()) + .expect("a match belongs to a rule") +} + +pub fn scan(text: &str) -> IndexMap { + let compiled = compiled(); + let mut counts = IndexMap::new(); + for captures in compiled.regex.captures_iter(text).flatten() { + *counts + .entry(matched_rule(&captures, &compiled.names).to_string()) + .or_insert(0) += 1; + } + counts +} + +pub fn redact(text: &str) -> Result { + let compiled = compiled(); + let mut counts: IndexMap = IndexMap::new(); + let mut out = String::with_capacity(text.len()); + let mut last = 0; + for captures in compiled.regex.captures_iter(text).flatten() { + let whole = captures.get(0).expect("group 0 exists"); + let name = matched_rule(&captures, &compiled.names); + *counts.entry(name.to_string()).or_insert(0) += 1; + let kept = captures + .name(&format!("{}_keep", name.replace('-', "_"))) + .map(|m| m.as_str()) + .unwrap_or(""); + out.push_str(&text[last..whole.start()]); + out.push_str(kept); + out.push_str(&format!("[REDACTED:{}]", name)); + last = whole.end(); + } + out.push_str(&text[last..]); + + let leftover = scan(&out); + if !leftover.is_empty() { + return Err(RedactionError(format!( + "secrets still match after redaction: {}", + detail(&leftover) + ))); + } + Ok(Redaction { text: out, counts }) +} + +fn detail(counts: &IndexMap) -> String { + let mut items: Vec<(&String, &usize)> = counts.iter().collect(); + items.sort(); + items + .iter() + .map(|(name, count)| format!("{} ×{}", name, count)) + .collect::>() + .join(", ") +} + +pub fn summarize(counts: &IndexMap) -> String { + if counts.is_empty() { + return String::new(); + } + let total: usize = counts.values().sum(); + format!( + "redacted {} secret{} ({})", + total, + if total == 1 { "" } else { "s" }, + detail(counts) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn redacts_and_keeps_the_assignment_name() { + let secret = format!("ghp_{}", "a1B2c3D4e5".repeat(4)); + let text = format!("x {} AWS_SECRET_ACCESS_KEY=abcdefgh12345678 y", secret); + let result = redact(&text).ok().unwrap(); + assert_eq!( + result.text, + "x [REDACTED:github-token] AWS_SECRET_ACCESS_KEY=[REDACTED:env-assignment] y" + ); + assert_eq!( + summarize(&result.counts), + "redacted 2 secrets (env-assignment ×1, github-token ×1)" + ); + assert!(redact(&result.text).ok().unwrap().counts.is_empty()); + } + + #[test] + fn a_word_boundary_is_required() { + assert!(scan(&format!("xAKIA{}", "ABCDEFGHIJKLMNOP")).is_empty()); + assert_eq!(scan(&format!("AKIA{}", "ABCDEFGHIJKLMNOP")).len(), 1); + } +} diff --git a/rust/src/rewrite.rs b/rust/src/rewrite.rs new file mode 100644 index 0000000..e6c9beb --- /dev/null +++ b/rust/src/rewrite.rs @@ -0,0 +1,197 @@ +//! Path rewriting, as in `loch/rewrite.py` — the load-bearing logic. +//! +//! Python builds one alternation regex of escaped literals, each followed by a +//! zero-width guard, and runs one `re.sub`. This is that regex executed by +//! hand: at each position the sources are tried longest first (a stable sort, +//! so equal lengths keep caller order), the first whose text matches *and* +//! whose guard holds wins, and scanning resumes after it, so no substitution's +//! output is ever re-matched. A source that fails its guard falls through to a +//! shorter one at the same position, which is how `/Users/mike/projector` +//! still gets its home rewritten after the cwd pair declines. + +use crate::claude::{encode_path, transcript_cwds}; +use std::collections::HashMap; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Guard { + /// `(?![A-Za-z0-9._-])`: a path only matches where it ends on a + /// component boundary, so a sibling that extends the origin's last + /// component is left alone. Erring strict is safe: an unsubstituted path + /// shows up in residual_origin_paths, an over-eager one corrupts silently. + Path, + /// `(?![A-Za-z0-9-])`: the encoded slug maps every non-alphanumeric to + /// `-`, so `/sub` and `-sub` encode identically and no + /// lookahead can tell them apart; it is only rewritten as a whole + /// component, declining `-worktrees-...`. + EncodedComponent, + /// The session id is a UUID, not a path. + None, +} + +impl Guard { + fn holds(self, next: Option) -> bool { + let Some(c) = next else { return true }; + match self { + Guard::Path => !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')), + Guard::EncodedComponent => !(c.is_ascii_alphanumeric() || c == '-'), + Guard::None => true, + } + } +} + +pub struct Replacer { + ordered: Vec<(String, Guard)>, + lookup: HashMap, + first_bytes: [bool; 256], +} + +/// `compile_replacements`. Sorted by length, never by caller order: the +/// single-pass guarantee depends on a nested path matching before the prefix +/// that contains it. +pub fn compile(pairs: &[(String, String, Guard)]) -> Replacer { + let mut ordered: Vec<(String, Guard)> = Vec::new(); + let mut lookup = HashMap::new(); + let mut first_bytes = [false; 256]; + for (source, dest, guard) in pairs { + if source.is_empty() || source == dest { + continue; + } + ordered.push((source.clone(), *guard)); + // `{source: dest for ...}`: a repeated source maps to its last dest. + lookup.insert(source.clone(), dest.clone()); + first_bytes[source.as_bytes()[0] as usize] = true; + } + ordered.sort_by_key(|(source, _)| std::cmp::Reverse(source.chars().count())); + Replacer { + ordered, + lookup, + first_bytes, + } +} + +impl Replacer { + pub fn apply(&self, text: &str) -> String { + if self.ordered.is_empty() { + return text.to_string(); + } + let bytes = text.as_bytes(); + let mut out = String::with_capacity(text.len()); + let mut copied = 0; + let mut i = 0; + while i < bytes.len() { + if self.first_bytes[bytes[i] as usize] && text.is_char_boundary(i) { + let rest = &text[i..]; + let found = self.ordered.iter().find(|(source, guard)| { + rest.starts_with(source.as_str()) + && guard.holds(rest[source.len()..].chars().next()) + }); + if let Some((source, _)) = found { + out.push_str(&text[copied..i]); + out.push_str(&self.lookup[source]); + i += source.len(); + copied = i; + continue; + } + } + i += 1; + } + out.push_str(&text[copied..]); + out + } +} + +#[derive(Clone, Debug)] +pub struct RewriteSpec { + pub origin_cwd: String, + pub origin_home: String, + pub target_cwd: String, + pub target_home: String, + pub origin_session_id: Option, + pub target_session_id: Option, +} + +pub fn rewrite_transcript(raw: &str, spec: &RewriteSpec) -> String { + let mut pairs = vec![ + ( + spec.origin_cwd.clone(), + spec.target_cwd.clone(), + Guard::Path, + ), + ( + spec.origin_home.clone(), + spec.target_home.clone(), + Guard::Path, + ), + ( + encode_path(&spec.origin_cwd), + encode_path(&spec.target_cwd), + Guard::EncodedComponent, + ), + ]; + if let (Some(origin), Some(target)) = (&spec.origin_session_id, &spec.target_session_id) { + if !origin.is_empty() && !target.is_empty() { + pairs.push((origin.clone(), target.clone(), Guard::None)); + } + } + compile(&pairs).apply(raw) +} + +/// Occurrences of the origin's paths that survived a rewrite. Necessary and +/// nowhere near sufficient — see foreign_cwds. +pub fn residual_origin_paths(text: &str, spec: &RewriteSpec) -> Vec { + let mut found: Vec = Vec::new(); + for needle in [&spec.origin_cwd, &spec.origin_home] { + if !needle.is_empty() + && *needle != spec.target_cwd + && *needle != spec.target_home + && text.contains(needle.as_str()) + && !found.contains(needle) + { + found.push(needle.clone()); + } + } + found +} + +pub struct ForeignCwd { + pub count: usize, + pub restored: String, +} + +/// Directories a transcript works in that no rewrite into `target_cwd` can +/// satisfy, keyed by their path on the *origin* machine. Takes the transcript +/// before rewriting, the only place the origin path still exists losslessly. +pub fn foreign_cwds(raw: &str, spec: &RewriteSpec) -> Vec<(String, ForeignCwd)> { + transcript_cwds(raw) + .into_iter() + .filter_map(|(cwd, count)| { + let restored = rewrite_transcript(&cwd, spec); + (restored != spec.target_cwd).then_some((cwd, ForeignCwd { count, restored })) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec() -> RewriteSpec { + RewriteSpec { + origin_cwd: "/Users/mike/code/repo".into(), + origin_home: "/Users/mike".into(), + target_cwd: "/home/alice/work/repo".into(), + target_home: "/home/alice".into(), + origin_session_id: None, + target_session_id: None, + } + } + + #[test] + fn nested_paths_rewrite_in_one_pass() { + let text = "/Users/mike/code/repo/a /Users/mike/.zshrc /Users/mike/code/repo-worktrees/x /Users/mike/projector"; + assert_eq!( + rewrite_transcript(text, &spec()), + "/home/alice/work/repo/a /home/alice/.zshrc /home/alice/code/repo-worktrees/x /home/alice/projector" + ); + } +} diff --git a/rust/src/s3.rs b/rust/src/s3.rs index 3b1e402..8d3077d 100644 --- a/rust/src/s3.rs +++ b/rust/src/s3.rs @@ -1,13 +1,15 @@ //! The S3-compatible backend, signed with SigV4 by hand. //! //! An SDK would be the whole AWS credential chain in exchange for a static -//! binary several megabytes larger and an async runtime; the hook needs one -//! signed PUT. So the chain is the part people actually use against R2, B2, -//! MinIO, Garage and plain S3: the `AWS_*` variables, then the shared +//! binary several megabytes larger and an async runtime; loch needs four +//! signed requests. So the chain is the part people actually use against R2, +//! B2, MinIO, Garage and plain S3: the `AWS_*` variables, then the shared //! credentials and config files for `AWS_PROFILE` (or `default`). SSO, -//! `credential_process`, assumed roles and instance metadata are not read; -//! boto3 reads them, so a machine relying on one of those needs the Python -//! build until they are. +//! `credential_process`, assumed roles and instance metadata are not read. +//! +//! Failures read the way botocore words them, since that text reaches the +//! `error` field: `An error occurred (Code) when calling the Op operation: +//! Message`. use crate::claude::home_dir; use crate::store::{Store, StoreError}; @@ -15,11 +17,12 @@ use hmac::{Hmac, Mac}; use sha2::{Digest, Sha256}; use std::collections::HashMap; use std::fs; +use std::io::Read; use std::path::PathBuf; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -/// A hook has to come back before Claude Code gives up on it, so a store -/// that doesn't answer fails rather than hanging the turn. +/// A hook has to come back before Claude Code gives up on it, so a store that +/// doesn't answer fails rather than hanging the turn. const TIMEOUT: Duration = Duration::from_secs(20); pub struct S3Store { @@ -27,6 +30,11 @@ pub struct S3Store { prefix: String, } +struct Response { + status: u16, + body: Vec, +} + impl S3Store { pub fn new(bucket: &str, prefix: &str) -> Self { S3Store { @@ -42,43 +50,228 @@ impl S3Store { format!("{}/{}", self.prefix, key) } } -} -impl Store for S3Store { - fn put(&self, key: &str, data: &[u8]) -> Result<(), StoreError> { + fn relative_key(&self, key: &str) -> String { + if self.prefix.is_empty() { + key.into() + } else { + key.get(self.prefix.len() + 1..).unwrap_or_default().into() + } + } + + fn request( + &self, + method: &str, + key: Option<&str>, + query: &[(&str, &str)], + body: &[u8], + operation: &str, + ) -> Result { let credentials = Credentials::load() - .ok_or_else(|| StoreError::Unreachable("no AWS credentials found".into()))?; + .ok_or_else(|| StoreError::Unreachable("Unable to locate credentials".into()))?; let region = region(); - let target = Target::new(&self.bucket, &self.key_for(key), ®ion); + let target = Target::new(&self.bucket, key, ®ion); let now = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); + let extra: &[(&str, &str)] = if method == "PUT" { + &[("content-type", "application/gzip")] + } else { + &[] + }; + let query_string = canonical_query(query); let headers = sign( - "PUT", + method, &target, - &[("content-type", "application/gzip")], - data, + &query_string, + extra, + body, &credentials, ®ion, now, ); + let url = if query_string.is_empty() { + target.url() + } else { + format!("{}?{}", target.url(), query_string) + }; let mut request = ureq::AgentBuilder::new() .timeout(TIMEOUT) .build() - .put(&target.url()); + .request(method, &url); for (name, value) in &headers { if name != "host" { request = request.set(name, value); } } - request - .send_bytes(data) + let result = if method == "PUT" { + request.send_bytes(body) + } else { + request.call() + }; + let response = match result { + Ok(response) => response, + Err(ureq::Error::Status(_, response)) => response, + Err(ureq::Error::Transport(_)) => { + return Err(StoreError::Unreachable(format!( + "Could not connect to the endpoint URL: \"{}\"", + url + ))) + } + }; + let status = response.status(); + let mut data = Vec::new(); + let _ = response.into_reader().read_to_end(&mut data); + if status >= 300 { + let text = String::from_utf8_lossy(&data); + let code = xml_values(&text, "Code") + .into_iter() + .next() + .unwrap_or_else(|| status.to_string()); + if code == "NoSuchKey" + || (status == 404 && operation == "GetObject" && !text.contains("NoSuchBucket")) + { + return Err(StoreError::Missing(format!( + "no object at {}", + key.map(|k| self.relative_key(k)).unwrap_or_default() + ))); + } + let message = xml_values(&text, "Message") + .into_iter() + .next() + .unwrap_or_else(|| reason(status).into()); + return Err(StoreError::Unreachable(format!( + "An error occurred ({}) when calling the {} operation: {}", + code, operation, message + ))); + } + Ok(Response { status, body: data }) + } +} + +fn reason(status: u16) -> &'static str { + match status { + 403 => "Forbidden", + 404 => "Not Found", + _ => "Unknown", + } +} + +impl Store for S3Store { + fn describe(&self) -> String { + format!("s3://{}/{}", self.bucket, self.prefix) + } + + fn put(&self, key: &str, data: &[u8]) -> Result<(), StoreError> { + self.request("PUT", Some(&self.key_for(key)), &[], data, "PutObject") .map(|_| ()) - .map_err(|error| StoreError::Unreachable(error.to_string())) + } + + fn get(&self, key: &str) -> Result, StoreError> { + let full = self.key_for(key); + match self.request("GET", Some(&full), &[], b"", "GetObject") { + Err(StoreError::Missing(_)) => { + Err(StoreError::Missing(format!("no object at {}", key))) + } + other => other.map(|r| r.body), + } + } + + /// Paginated: ListObjectsV2 truncates at 1000 keys. + fn list(&self, prefix: &str) -> Result, StoreError> { + let full = self.key_for(prefix); + let mut keys = Vec::new(); + let mut token: Option = None; + loop { + let mut query = vec![("list-type", "2"), ("prefix", full.as_str())]; + if let Some(token) = &token { + query.push(("continuation-token", token.as_str())); + } + let response = self.request("GET", None, &query, b"", "ListObjectsV2")?; + let text = String::from_utf8_lossy(&response.body).into_owned(); + let _ = response.status; + for contents in xml_blocks(&text, "Contents") { + for key in xml_values(contents, "Key") { + keys.push(self.relative_key(&key)); + } + } + let truncated = + xml_values(&text, "IsTruncated").first().map(String::as_str) == Some("true"); + token = xml_values(&text, "NextContinuationToken") + .into_iter() + .next(); + if !truncated || token.is_none() { + break; + } + } + keys.sort_by(|a, b| crate::py::cmp(a, b)); + Ok(keys) + } + + fn delete(&self, key: &str) -> Result<(), StoreError> { + match self.request("DELETE", Some(&self.key_for(key)), &[], b"", "DeleteObject") { + Ok(_) | Err(StoreError::Missing(_)) => Ok(()), + Err(error) => Err(error), + } } } +/// The text of every `` element, entities decoded. +fn xml_values(text: &str, tag: &str) -> Vec { + xml_blocks(text, tag) + .into_iter() + .map(xml_unescape) + .collect() +} + +fn xml_blocks<'a>(text: &'a str, tag: &str) -> Vec<&'a str> { + let open = format!("<{}>", tag); + let close = format!("", tag); + let mut out = Vec::new(); + let mut rest = text; + while let Some(start) = rest.find(&open) { + let after = &rest[start + open.len()..]; + let Some(end) = after.find(&close) else { break }; + out.push(&after[..end]); + rest = &after[end + close.len()..]; + } + out +} + +fn xml_unescape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(amp) = rest.find('&') { + out.push_str(&rest[..amp]); + let after = &rest[amp..]; + let Some(semi) = after.find(';') else { + out.push_str(after); + return out; + }; + let entity = &after[1..semi]; + let decoded = match entity { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + _ => entity + .strip_prefix("#x") + .and_then(|h| u32::from_str_radix(h, 16).ok()) + .or_else(|| entity.strip_prefix('#').and_then(|d| d.parse().ok())) + .and_then(char::from_u32), + }; + match decoded { + Some(c) => out.push(c), + None => out.push_str(&after[..=semi]), + } + rest = &after[semi + 1..]; + } + out.push_str(rest); + out +} + struct Target { scheme: String, host: String, @@ -87,10 +280,10 @@ struct Target { impl Target { /// Path style under `LOCH_S3_ENDPOINT` — MinIO, R2 and Garage need it — - /// and virtual-hosted against AWS, as boto3 addresses them. A bucket - /// with a dot can't be a TLS hostname, so it goes path style there too. - fn new(bucket: &str, key: &str, region: &str) -> Target { - let encoded = uri_encode_path(key); + /// and virtual-hosted against AWS, as boto3 addresses them. A bucket with + /// a dot can't be a TLS hostname, so it goes path style there too. + fn new(bucket: &str, key: Option<&str>, region: &str) -> Target { + let encoded = key.map(|k| format!("/{}", uri_encode(k, false))); match std::env::var("LOCH_S3_ENDPOINT") .ok() .filter(|e| !e.is_empty()) @@ -104,18 +297,23 @@ impl Target { Target { scheme: scheme.into(), host: host.into(), - path: format!("{}/{}/{}", base, uri_encode_path(bucket), encoded), + path: format!( + "{}/{}{}", + base, + uri_encode(bucket, true), + encoded.unwrap_or_default() + ), } } None if bucket.contains('.') => Target { scheme: "https".into(), host: format!("s3.{}.amazonaws.com", region), - path: format!("/{}/{}", bucket, encoded), + path: format!("/{}{}", bucket, encoded.unwrap_or_default()), }, None => Target { scheme: "https".into(), host: format!("{}.s3.{}.amazonaws.com", bucket, region), - path: format!("/{}", encoded), + path: encoded.unwrap_or_else(|| "/".into()), }, } } @@ -125,27 +323,37 @@ impl Target { } } -/// RFC 3986 unreserved characters pass, `/` separates segments, and -/// everything else is percent-encoded. S3 signs the path encoded once. -fn uri_encode_path(text: &str) -> String { +/// RFC 3986 unreserved characters pass and everything else is +/// percent-encoded; `/` passes in a path and is encoded in a query value. +fn uri_encode(text: &str, encode_slash: bool) -> String { let mut out = String::new(); for byte in text.bytes() { match byte { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { out.push(byte as char) } + b'/' if !encode_slash => out.push('/'), _ => out.push_str(&format!("%{:02X}", byte)), } } out } -fn hex(bytes: &[u8]) -> String { - bytes +fn canonical_query(query: &[(&str, &str)]) -> String { + let mut pairs: Vec<(String, String)> = query + .iter() + .map(|(k, v)| (uri_encode(k, true), uri_encode(v, true))) + .collect(); + pairs.sort(); + pairs .iter() - .map(|b| format!("{:02x}", b)) + .map(|(k, v)| format!("{}={}", k, v)) .collect::>() - .concat() + .join("&") +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{:02x}", b)).collect() } fn hmac(key: &[u8], data: &str) -> Vec { @@ -155,9 +363,11 @@ fn hmac(key: &[u8], data: &str) -> Vec { } /// The headers of a SigV4-signed request, `authorization` among them. +#[allow(clippy::too_many_arguments)] fn sign( method: &str, target: &Target, + query: &str, extra: &[(&str, &str)], body: &[u8], credentials: &Credentials, @@ -189,8 +399,8 @@ fn sign( .collect::>() .join(";"); let canonical = format!( - "{}\n{}\n\n{}\n{}\n{}", - method, target.path, canonical_headers, signed, payload + "{}\n{}\n{}\n{}\n{}\n{}", + method, target.path, query, canonical_headers, signed, payload ); let scope = format!("{}/{}/s3/aws4_request", day, region); let to_sign = format!( @@ -214,28 +424,12 @@ fn sign( headers } -/// `YYYYMMDDTHHMMSSZ` from Unix seconds, without a date library. +/// `YYYYMMDDTHHMMSSZ` from Unix seconds. fn amz_date(seconds: u64) -> String { - let days = (seconds / 86_400) as i64; - let rest = seconds % 86_400; - // Howard Hinnant's civil_from_days. - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let day = doy - (153 * mp + 2) / 5 + 1; - let month = if mp < 10 { mp + 3 } else { mp - 9 }; - let year = yoe + era * 400 + i64::from(month <= 2); + let c = crate::sys::civil(seconds as i64); format!( "{:04}{:02}{:02}T{:02}{:02}{:02}Z", - year, - month, - day, - rest / 3600, - rest % 3600 / 60, - rest % 60 + c.year, c.month, c.day, c.hour, c.minute, c.second ) } @@ -261,8 +455,8 @@ fn aws_file(variable: &str, name: &str) -> PathBuf { .unwrap_or_else(|| PathBuf::from(home_dir()).join(".aws").join(name)) } -/// One section of an AWS INI file. The config file names non-default -/// profiles `[profile name]`; the credentials file names them `[name]`. +/// One section of an AWS INI file. The config file names non-default profiles +/// `[profile name]`; the credentials file names them `[name]`. fn ini_section(path: &PathBuf, section: &str) -> HashMap { let mut values = HashMap::new(); let Ok(text) = fs::read_to_string(path) else { @@ -362,10 +556,10 @@ mod tests { secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into(), session_token: None, }; - // 2013-05-24T00:00:00Z let headers = sign( "GET", &target, + "", &[("range", "bytes=0-9")], b"", &credentials, @@ -385,11 +579,51 @@ mod tests { ); } + /// AWS's published example for a signed query string: a ListObjects of + /// examplebucket with max-keys and prefix. + #[test] + fn query_signature_matches_the_aws_example() { + let target = Target { + scheme: "https".into(), + host: "examplebucket.s3.amazonaws.com".into(), + path: "/".into(), + }; + let credentials = Credentials { + access_key: "AKIAIOSFODNN7EXAMPLE".into(), + secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into(), + session_token: None, + }; + let query = canonical_query(&[("prefix", "J"), ("max-keys", "2")]); + assert_eq!(query, "max-keys=2&prefix=J"); + let headers = sign( + "GET", + &target, + &query, + &[], + b"", + &credentials, + "us-east-1", + 1_369_353_600, + ); + let authorization = &headers + .iter() + .find(|(n, _)| n == "authorization") + .unwrap() + .1; + assert!(authorization.ends_with( + "Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7" + )); + } + #[test] fn keys_are_encoded_once() { assert_eq!( - uri_encode_path("transcripts/a b/c+d.jsonl"), + uri_encode("transcripts/a b/c+d.jsonl", false), "transcripts/a%20b/c%2Bd.jsonl" ); + assert_eq!( + xml_unescape("a&bAB&bogus;"), + "a&bA B&bogus;".replace(' ', "") + ); } } diff --git a/rust/src/store.rs b/rust/src/store.rs index da3beea..668dcb7 100644 --- a/rust/src/store.rs +++ b/rust/src/store.rs @@ -1,50 +1,139 @@ -//! The store interface, as in `loch/store.py`. Only what the ported commands -//! use is here; the rest arrives with the commands that need it. +//! The store interface, as in `loch/store.py`: a local directory or any +//! S3-compatible endpoint behind the same five operations. use crate::claude::home_dir; +use crate::sys; use std::fs; -use std::path::{Component, Path, PathBuf}; +use std::path::Path; -/// The message is for the commands that report it; the hook only needs to -/// know that the put failed. +/// The failures a caller can act on, kept apart for the reasons +/// `cli.store_errors` gives. There is no "missing dependency": the Rust build +/// carries its S3 client, so `s3-extra-missing` can't arise. #[derive(Debug)] -#[allow(dead_code)] pub enum StoreError { - /// The store didn't answer (`store-unreachable`). + /// The store answered and the object isn't there (`bundle-not-found`). + Missing(String), + /// The store didn't answer, or refused (`store-unreachable`). Unreachable(String), - Invalid(String), +} + +impl std::fmt::Display for StoreError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + StoreError::Missing(m) | StoreError::Unreachable(m) => f.write_str(m), + } + } } pub trait Store { + fn describe(&self) -> String; fn put(&self, key: &str, data: &[u8]) -> Result<(), StoreError>; + fn get(&self, key: &str) -> Result, StoreError>; + fn list(&self, prefix: &str) -> Result, StoreError>; + /// Deleting an absent key succeeds: index entries are derived, so a repair + /// pass has to be able to remove ones a half-finished save never wrote. + fn delete(&self, key: &str) -> Result<(), StoreError>; } pub struct FileStore { - root: PathBuf, + root: String, } impl FileStore { - pub fn new(root: impl Into) -> Self { + pub fn new(root: impl Into) -> Self { FileStore { root: root.into() } } + + /// `Path(root) / key`, which collapses repeated and trailing slashes. + fn path(&self, key: &str) -> String { + let mut path = self.root.trim_end_matches('/').to_string(); + if path.is_empty() && self.root.starts_with('/') { + path.push('/'); + } + for part in key.split('/').filter(|p| !p.is_empty() && *p != ".") { + if !path.ends_with('/') { + path.push('/'); + } + path.push_str(part); + } + path + } +} + +fn unreachable(error: &std::io::Error, path: &str) -> StoreError { + StoreError::Unreachable(sys::os_error(error, path)) } impl Store for FileStore { + fn describe(&self) -> String { + self.root.clone() + } + fn put(&self, key: &str, data: &[u8]) -> Result<(), StoreError> { - let path = self.root.join(key); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|e| StoreError::Unreachable(e.to_string()))?; + let path = self.path(key); + let parent = sys::dirname(&path); + fs::create_dir_all(&parent).map_err(|e| unreachable(&e, &parent))?; + fs::write(&path, data).map_err(|e| unreachable(&e, &path)) + } + + fn get(&self, key: &str) -> Result, StoreError> { + let path = self.path(key); + fs::read(&path).map_err(|error| match error.kind() { + std::io::ErrorKind::NotFound => StoreError::Missing(format!("no object at {}", key)), + _ => unreachable(&error, &path), + }) + } + + /// String prefix rather than directory descent, so both backends answer + /// the same question for a prefix that stops mid-segment. + fn list(&self, prefix: &str) -> Result, StoreError> { + let root = self.path(""); + if !Path::new(&root).is_dir() { + return Ok(Vec::new()); + } + let mut keys = Vec::new(); + walk(Path::new(&root), "", &mut keys); + keys.retain(|key| key.starts_with(prefix)); + keys.sort_by(|a, b| crate::py::cmp(a, b)); + Ok(keys) + } + + fn delete(&self, key: &str) -> Result<(), StoreError> { + let path = self.path(key); + match fs::remove_file(&path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(unreachable(&error, &path)), + } + } +} + +/// `root.rglob("*")` keeping files: directories are descended without +/// following symlinks, and a symlink to a file counts as a file. +fn walk(dir: &Path, relative: &str, keys: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let key = if relative.is_empty() { + name.clone() + } else { + format!("{}/{}", relative, name) + }; + let Ok(kind) = entry.file_type() else { + continue; + }; + if kind.is_dir() { + walk(&entry.path(), &key, keys); + } else if entry.path().is_file() { + keys.push(key); } - fs::write(&path, data).map_err(|e| StoreError::Unreachable(e.to_string())) } } pub fn default_store() -> String { - Path::new(&home_dir()) - .join(".loch") - .join("store") - .to_string_lossy() - .into_owned() + sys::join(&sys::join(&home_dir(), ".loch"), "store") } pub fn resolve_store_uri(explicit: Option<&str>) -> String { @@ -54,14 +143,14 @@ pub fn resolve_store_uri(explicit: Option<&str>) -> String { std::env::var("LOCH_STORE").unwrap_or_else(|_| default_store()) } -pub fn create_store(uri: &str) -> Result, StoreError> { +#[derive(Debug)] +pub struct InvalidUri(pub String); + +pub fn create_store(uri: &str) -> Result, InvalidUri> { if let Some(rest) = uri.strip_prefix("s3://") { let (bucket, prefix) = rest.split_once('/').unwrap_or((rest, "")); if bucket.is_empty() { - return Err(StoreError::Invalid(format!( - "invalid S3 store URI: {}", - uri - ))); + return Err(InvalidUri(format!("invalid S3 store URI: {}", uri))); } // `re.sub(r"/$", "", prefix)`: one trailing slash, not all of them. let prefix = prefix.strip_suffix('/').unwrap_or(prefix); @@ -70,57 +159,20 @@ pub fn create_store(uri: &str) -> Result, StoreError> { if let Some(rest) = uri.strip_prefix("file://") { return Ok(Box::new(FileStore::new(file_uri_path(rest)))); } - Ok(Box::new(FileStore::new(abspath(uri)))) + if uri.starts_with('/') { + return Ok(Box::new(FileStore::new(uri))); + } + Ok(Box::new(FileStore::new(sys::abspath(uri)))) } -/// `unquote(urlparse(uri).path)`: the netloc and any query or fragment are -/// dropped, and percent-escapes decoded as UTF-8 with replacement. +/// `unquote(urlparse(uri).path)`. fn file_uri_path(rest: &str) -> String { let path = match rest.find('/') { Some(slash) => &rest[slash..], None => "", }; let path = path.split(['?', '#']).next().unwrap_or(""); - let bytes = path.as_bytes(); - let mut decoded = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - if bytes[i] == b'%' && i + 2 < bytes.len() { - let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok(); - if let Some(value) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) { - decoded.push(value); - i += 3; - continue; - } - } - decoded.push(bytes[i]); - i += 1; - } - String::from_utf8_lossy(&decoded).into_owned() -} - -/// `os.path.abspath`: joined onto the working directory and normalised -/// lexically, without touching the filesystem. -pub fn abspath(path: &str) -> String { - let joined = if Path::new(path).is_absolute() { - PathBuf::from(path) - } else { - std::env::current_dir().unwrap_or_default().join(path) - }; - let mut parts: Vec = Vec::new(); - for component in joined.components() { - match component { - Component::CurDir => {} - Component::ParentDir => { - if matches!(parts.last(), Some(Component::Normal(_))) { - parts.pop(); - } - } - other => parts.push(other), - } - } - let normal: PathBuf = parts.iter().collect(); - normal.to_string_lossy().into_owned() + crate::index::unquote(path) } #[cfg(test)] @@ -133,10 +185,4 @@ mod tests { assert_eq!(file_uri_path("host/tmp/x?q=1#f"), "/tmp/x"); assert_eq!(file_uri_path("/tmp/%zz%2"), "/tmp/%zz%2"); } - - #[test] - fn abspath_normalises_lexically() { - assert_eq!(abspath("/a/./b/../c"), "/a/c"); - assert_eq!(abspath("/.."), "/"); - } } diff --git a/rust/src/sys.rs b/rust/src/sys.rs new file mode 100644 index 0000000..2f04c5a --- /dev/null +++ b/rust/src/sys.rs @@ -0,0 +1,472 @@ +//! Python's `os.path`, `datetime` and `OSError` behaviour, where loch's output +//! depends on the exact string they produce. + +use std::fs; +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// `os.getcwd()`. +pub fn getcwd() -> String { + std::env::current_dir() + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +/// `posixpath.normpath`. +pub fn normpath(path: &str) -> String { + if path.is_empty() { + return ".".into(); + } + let mut initial = usize::from(path.starts_with('/')); + if path.starts_with("//") && !path.starts_with("///") { + initial = 2; + } + let mut parts: Vec<&str> = Vec::new(); + for part in path.split('/') { + if part.is_empty() || part == "." { + continue; + } + if part != ".." || (initial == 0 && parts.is_empty()) || parts.last() == Some(&"..") { + parts.push(part); + } else if !parts.is_empty() { + parts.pop(); + } + } + let joined = format!("{}{}", "/".repeat(initial), parts.join("/")); + if joined.is_empty() { + ".".into() + } else { + joined + } +} + +/// `os.path.join(a, b)`. +pub fn join(a: &str, b: &str) -> String { + if b.starts_with('/') || a.is_empty() { + b.into() + } else if a.ends_with('/') { + format!("{}{}", a, b) + } else { + format!("{}/{}", a, b) + } +} + +/// `os.path.abspath`. +pub fn abspath(path: &str) -> String { + if path.starts_with('/') { + normpath(path) + } else { + normpath(&join(&getcwd(), path)) + } +} + +/// `os.path.dirname`. +pub fn dirname(path: &str) -> String { + let cut = path.rfind('/').map(|i| i + 1).unwrap_or(0); + let head = &path[..cut]; + if !head.is_empty() && !head.chars().all(|c| c == '/') { + head.trim_end_matches('/').into() + } else { + head.into() + } +} + +/// `os.path.basename`. +pub fn basename(path: &str) -> String { + path[path.rfind('/').map(|i| i + 1).unwrap_or(0)..].into() +} + +/// `os.path.relpath(path, start)`. +pub fn relpath(path: &str, start: &str) -> String { + let path = abspath(path); + let start = abspath(start); + let path_parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect(); + let start_parts: Vec<&str> = start.split('/').filter(|p| !p.is_empty()).collect(); + let common = path_parts + .iter() + .zip(&start_parts) + .take_while(|(a, b)| a == b) + .count(); + let mut parts: Vec<&str> = vec![".."; start_parts.len() - common]; + parts.extend(&path_parts[common..]); + if parts.is_empty() { + ".".into() + } else { + parts.join("/") + } +} + +/// `os.path.realpath(path, strict=True)`, or None where it would raise. +pub fn realpath_strict(path: &str) -> Option { + fs::canonicalize(path) + .ok() + .map(|p| p.to_string_lossy().into_owned()) +} + +/// `str(OSError)` for an error on a path: `[Errno 2] No such file or +/// directory: '/x'`. +pub fn os_error(error: &std::io::Error, path: &str) -> String { + match error.raw_os_error() { + Some(code) => format!("[Errno {}] {}: {}", code, strerror(code), py_repr(path)), + None => error.to_string(), + } +} + +pub fn strerror(code: i32) -> String { + let text = std::io::Error::from_raw_os_error(code).to_string(); + // Rust appends " (os error N)"; Python's strerror is the bare message. + match text.rfind(" (os error") { + Some(cut) => text[..cut].into(), + None => text, + } +} + +/// `repr()` of a str. +pub fn py_repr(text: &str) -> String { + let quote = if text.contains('\'') && !text.contains('"') { + '"' + } else { + '\'' + }; + let mut out = String::new(); + out.push(quote); + for c in text.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if c == quote => { + out.push('\\'); + out.push(c); + } + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + out.push_str(&format!("\\x{:02x}", c as u32)) + } + c => match crate::py::as_surrogate(c) { + Some(unit) => out.push_str(&format!("\\u{:04x}", unit)), + None => out.push(c), + }, + } + } + out.push(quote); + out +} + +/// `repr()` of bytes. +pub fn bytes_repr(bytes: &[u8]) -> String { + let quote = if bytes.contains(&b'\'') && !bytes.contains(&b'"') { + '"' + } else { + '\'' + }; + let mut out = format!("b{}", quote); + for &b in bytes { + match b { + b'\\' => out.push_str("\\\\"), + b'\n' => out.push_str("\\n"), + b'\r' => out.push_str("\\r"), + b'\t' => out.push_str("\\t"), + b if b as char == quote => { + out.push('\\'); + out.push(b as char); + } + 0x20..=0x7e => out.push(b as char), + _ => out.push_str(&format!("\\x{:02x}", b)), + } + } + out.push(quote); + out +} + +/// `time.time()`. +pub fn now() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0) +} + +/// `os.stat(path).st_mtime`, computed as CPython computes it: the seconds +/// plus `nsec * 1e-9`, in double arithmetic. +pub fn mtime(meta: &fs::Metadata) -> f64 { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + meta.mtime() as f64 + meta.mtime_nsec() as f64 * 1e-9 + } + #[cfg(not(unix))] + { + meta.modified() + .ok() + .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) + .map(|d| d.as_secs() as f64 + d.subsec_nanos() as f64 * 1e-9) + .unwrap_or(0.0) + } +} + +/// `_PyTime_ObjectToTimeval(..., _PyTime_ROUND_HALF_EVEN)`, which +/// `datetime.fromtimestamp` uses: whole seconds and microseconds. +pub fn split_timestamp(value: f64) -> (i64, i64) { + let mut whole = value.trunc(); + let mut micros = (value - whole) * 1e6; + let rounded = micros.round(); + micros = if (micros - rounded).abs() == 0.5 { + 2.0 * (micros / 2.0).round() + } else { + rounded + }; + if micros >= 1e6 { + micros -= 1e6; + whole += 1.0; + } else if micros < 0.0 { + micros += 1e6; + whole -= 1.0; + } + (whole as i64, micros as i64) +} + +pub struct Civil { + pub year: i64, + pub month: i64, + pub day: i64, + pub hour: i64, + pub minute: i64, + pub second: i64, +} + +/// UTC calendar fields of Unix seconds (Howard Hinnant's civil_from_days). +pub fn civil(seconds: i64) -> Civil { + let days = seconds.div_euclid(86_400); + let rest = seconds.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + Civil { + year, + month, + day, + hour: rest / 3600, + minute: rest % 3600 / 60, + second: rest % 60, + } +} + +/// Days since the epoch of a proleptic Gregorian date. +pub fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (month + 9) % 12; + let doy = (153 * mp + 2) / 5 + day - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +/// `claude.iso_timestamp`: millisecond-precision UTC with a Z suffix. +pub fn iso_timestamp(seconds: f64) -> String { + let (whole, micros) = split_timestamp(seconds); + let c = civil(whole); + format!( + "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", + c.year, + c.month, + c.day, + c.hour, + c.minute, + c.second, + micros / 1000 + ) +} + +/// `datetime.fromtimestamp(t, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")`. +pub fn utc_seconds(seconds: i64) -> String { + let c = civil(seconds); + format!( + "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", + c.year, c.month, c.day, c.hour, c.minute, c.second + ) +} + +/// `datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp()` for the +/// shapes transcripts carry. A naive stamp is local time to Python; it is +/// read as UTC here, and no transcript writes one. +pub fn iso_seconds(stamp: &str) -> Option { + let stamp = stamp.replace('Z', "+00:00"); + let b = stamp.as_bytes(); + let num = |from: usize, len: usize| -> Option { + let part = stamp.get(from..from + len)?; + part.bytes() + .all(|c| c.is_ascii_digit()) + .then(|| part.parse().ok())? + }; + if b.len() < 10 || b[4] != b'-' || b[7] != b'-' { + return None; + } + let (year, month, day) = (num(0, 4)?, num(5, 2)?, num(8, 2)?); + if !(1..=12).contains(&month) || !(1..=31).contains(&day) { + return None; + } + let mut pos = 10; + let (mut hour, mut minute, mut second, mut micros) = (0, 0, 0, 0i64); + if pos < b.len() && (b[pos] == b'T' || b[pos] == b' ') { + pos += 1; + hour = num(pos, 2)?; + pos += 2; + if b.get(pos) == Some(&b':') { + minute = num(pos + 1, 2)?; + pos += 3; + if b.get(pos) == Some(&b':') { + second = num(pos + 1, 2)?; + pos += 3; + if let Some(b'.' | b',') = b.get(pos) { + pos += 1; + let start = pos; + while b.get(pos).is_some_and(u8::is_ascii_digit) { + pos += 1; + } + let digits = &stamp[start..pos]; + if digits.is_empty() { + return None; + } + let six: String = digits.chars().chain("000000".chars()).take(6).collect(); + micros = six.parse().ok()?; + } + } + } + } + let mut offset = 0i64; + if pos < b.len() { + let sign = match b[pos] { + b'+' => 1, + b'-' => -1, + _ => return None, + }; + let hours = num(pos + 1, 2)?; + let minutes = if b.get(pos + 3) == Some(&b':') { + num(pos + 4, 2)? + } else { + num(pos + 3, 2)? + }; + offset = sign * (hours * 3600 + minutes * 60); + } + if hour > 23 || minute > 59 || second > 59 { + return None; + } + let seconds = + days_from_civil(year, month, day) * 86_400 + hour * 3600 + minute * 60 + second - offset; + Some((seconds * 1_000_000 + micros) as f64 / 1e6) +} + +/// `socket.gethostname()`. +pub fn hostname() -> String { + #[cfg(unix)] + { + let mut buffer = [0u8; 256]; + // SAFETY: gethostname writes at most len bytes into the buffer. + let result = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) }; + if result == 0 { + let end = buffer.iter().position(|&b| b == 0).unwrap_or(buffer.len()); + return String::from_utf8_lossy(&buffer[..end]).into_owned(); + } + String::new() + } + #[cfg(not(unix))] + { + std::env::var("COMPUTERNAME").unwrap_or_default() + } +} + +/// `cli._platform_name`. +pub fn platform_name() -> &'static str { + if cfg!(target_os = "macos") { + "darwin" + } else if cfg!(target_os = "linux") { + "linux" + } else if cfg!(windows) { + "win32" + } else { + std::env::consts::OS + } +} + +/// `str(uuid.uuid4())`. +pub fn uuid4() -> String { + let mut bytes = [0u8; 16]; + getrandom::getrandom(&mut bytes).expect("the OS has a random source"); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + let hex: String = bytes.iter().map(|b| format!("{:02x}", b)).collect(); + format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ) +} + +/// `tempfile.gettempdir()`: the first of TMPDIR, TEMP, TMP, then the +/// platform's usual places, made absolute. +pub fn gettempdir() -> String { + for name in ["TMPDIR", "TEMP", "TMP"] { + if let Ok(dir) = std::env::var(name) { + if !dir.is_empty() && Path::new(&dir).is_dir() { + return abspath(&dir); + } + } + } + for dir in ["/tmp", "/var/tmp", "/usr/tmp"] { + if Path::new(dir).is_dir() { + return dir.into(); + } + } + getcwd() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_follow_posixpath() { + assert_eq!(normpath("//a//b/../c/."), "//a/c"); + assert_eq!(normpath("///a"), "/a"); + assert_eq!(normpath("../x/.."), ".."); + assert_eq!(dirname("/a/b/"), "/a/b"); + assert_eq!(dirname("///"), "///"); + assert_eq!(dirname("x"), ""); + assert_eq!(relpath("/a/b/c", "/a/d"), "../b/c"); + assert_eq!(relpath("/a", "/a"), "."); + } + + #[test] + fn timestamps_round_like_datetime() { + assert_eq!(iso_timestamp(0.0), "1970-01-01T00:00:00.000Z"); + assert_eq!( + iso_timestamp(1_794_947_157.999_6), + "2026-11-17T20:25:57.999Z" + ); + assert_eq!( + iso_timestamp(1_794_947_157.999_999_6), + "2026-11-17T20:25:58.000Z" + ); + assert_eq!(iso_seconds("2026-01-01T00:00:10.5Z"), Some(1_767_225_610.5)); + } + + #[test] + fn os_errors_read_like_python() { + let error = std::fs::read("/nonexistent/x").unwrap_err(); + assert_eq!( + os_error(&error, "/nonexistent/x"), + "[Errno 2] No such file or directory: '/nonexistent/x'" + ); + } +} diff --git a/rust/src/trace.rs b/rust/src/trace.rs new file mode 100644 index 0000000..b6bf087 --- /dev/null +++ b/rust/src/trace.rs @@ -0,0 +1,921 @@ +//! Which conversation made which commit, and getting back into it — as in +//! `loch/trace.py`, less the hooks, which live in `hook.rs`. +//! +//! A commit is linked to the turn that made it by a git note on +//! `refs/notes/loch` naming the session and the tool call that ran +//! `git commit`. It holds no transcript text. + +use crate::claude::{self, display_summary, home_dir, projects_dir, read_session_meta, AGENT}; +use crate::format::Turn; +use crate::git as gitio; +use crate::ingest::{self, Origin}; +use crate::json::{self, Map, Value}; +use crate::object; +use crate::py; +use crate::rewrite::{rewrite_transcript, RewriteSpec}; +use crate::store::{Store, StoreError}; +use crate::sys; +use std::collections::{HashMap, HashSet}; +use std::fs; +use std::path::Path; + +pub const NOTES_REF: &str = "refs/notes/loch"; +pub const NOTE_VERSION: i64 = 1; +pub const UNCOMMITTED: &str = "0000000000000000000000000000000000000000"; + +/// How far a commit's committer time may sit outside the tool call that made +/// it: one second for git's truncation, the rest for a slow hook process. +const CLOCK_SLACK: f64 = 2.0; + +pub fn transcripts_prefix() -> String { + format!("transcripts/{}/", AGENT) +} + +#[derive(Debug)] +pub struct TraceError { + pub code: &'static str, + pub message: String, +} + +impl TraceError { + pub fn new(code: &'static str, message: impl Into) -> Self { + TraceError { + code, + message: message.into(), + } + } +} + +pub type Result = std::result::Result; + +/// trace.git: stdout, or `git-failed` with git's stderr. +pub fn git(cwd: &str, args: &[&str]) -> Result { + gitio::git(cwd, args, None).map_err(|e| TraceError::new("git-failed", e.0)) +} + +fn git_stdin(cwd: &str, args: &[&str], stdin: &str) -> Result { + gitio::git(cwd, args, Some(stdin)).map_err(|e| TraceError::new("git-failed", e.0)) +} + +pub fn git_unchecked(cwd: &str, args: &[&str]) -> String { + gitio::git_unchecked(cwd, args).unwrap_or_default() +} + +pub fn repo_root(cwd: &str) -> Result { + git(cwd, &["rev-parse", "--show-toplevel"]) + .map(|out| out.trim().to_string()) + .map_err(|_| { + TraceError::new( + "not-a-repository", + format!("{} is not in a git repository", cwd), + ) + }) +} + +// -- notes -------------------------------------------------------------------- + +pub fn make_note(session_id: &str, call: &str, captured: &str) -> Value { + Value::Object(object! { + "loch" => NOTE_VERSION, + "agent" => AGENT, + "session" => session_id, + "call" => call, + "captured" => captured, + }) +} + +pub fn write_note(cwd: &str, commit: &str, note: &Value) -> Result<()> { + let body = json::dumps(note, json::COMPACT_SORTED); + git_stdin( + cwd, + &["notes", "--ref", NOTES_REF, "add", "-f", "-F", "-", commit], + &body, + )?; + Ok(()) +} + +/// `x == 1` as Python means it: 1, 1.0 and True all qualify. +fn is_one(value: Option<&Value>) -> bool { + match value { + Some(Value::Int(d)) => d == "1", + Some(Value::Float(f)) => *f == 1.0, + Some(Value::Bool(b)) => *b, + _ => false, + } +} + +pub fn read_note(cwd: &str, commit: &str) -> Option { + let text = git_unchecked(cwd, &["notes", "--ref", NOTES_REF, "show", commit]); + match json::loads(&text) { + Ok(Value::Object(note)) if is_one(note.get("loch")) => Some(note), + _ => None, + } +} + +pub fn noted_commits(cwd: &str) -> HashSet { + git_unchecked(cwd, &["notes", "--ref", NOTES_REF, "list"]) + .lines() + .filter_map(|line| { + let parts: Vec<&str> = py::split(line); + (parts.len() == 2).then(|| parts[1].to_string()) + }) + .collect() +} + +/// `str(value)` for a value read out of JSON. +pub fn py_str(value: Option<&Value>) -> String { + match value { + None | Some(Value::Null) => "None".into(), + Some(Value::Bool(true)) => "True".into(), + Some(Value::Bool(false)) => "False".into(), + Some(Value::Int(d)) => d.clone(), + Some(Value::Float(f)) => { + let repr = json::float_repr(*f); + match repr.as_str() { + "NaN" => "nan".into(), + "Infinity" => "inf".into(), + "-Infinity" => "-inf".into(), + _ => repr, + } + } + Some(Value::Str(s)) => s.clone(), + Some(other) => json::dumps(other, json::DEFAULT), + } +} + +// -- install ------------------------------------------------------------------ + +const HOOK_EVENTS: &[(&str, Option<&str>, &str)] = &[ + ("PreToolUse", Some("Bash"), "pre-tool"), + ("PostToolUse", Some("Bash"), "post-tool"), + ("Stop", None, "stop"), +]; + +#[derive(Debug)] +pub enum InstallError { + /// What Python's exception would have said; `internal` in the envelope. + Internal(String), +} + +/// Adds loch's hooks to a Claude Code settings file, keeping whatever else is +/// there. Returns the events it added; re-running adds nothing. +pub fn install_hooks( + settings_path: &str, + command: &str, +) -> std::result::Result, InstallError> { + let mut settings = match fs::read(settings_path) { + Ok(bytes) => { + let text = String::from_utf8(bytes) + .map_err(|_| InstallError::Internal(format!("{} is not UTF-8", settings_path)))?; + json::loads(&text).map_err(|_| { + InstallError::Internal(format!("{} is not valid JSON", settings_path)) + })? + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Value::Object(Map::new()), + Err(error) => return Err(InstallError::Internal(sys::os_error(&error, settings_path))), + }; + let not_a_dict = || InstallError::Internal("the settings are not a JSON object".into()); + let Value::Object(root) = &mut settings else { + return Err(not_a_dict()); + }; + let hooks = root + .entry("hooks".to_string()) + .or_insert_with(|| Value::Object(Map::new())); + let Value::Object(hooks) = hooks else { + return Err(not_a_dict()); + }; + let mut added = Vec::new(); + for (event, matcher, name) in HOOK_EVENTS { + // 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. + let line = format!("{} hook {} 2>/dev/null || true", command, name); + let groups = hooks + .entry(event.to_string()) + .or_insert_with(|| Value::Array(Vec::new())); + let Value::Array(groups) = groups else { + return Err(not_a_dict()); + }; + let present = groups.iter().any(|group| { + group + .get("hooks") + .and_then(Value::as_array) + .is_some_and(|entries| { + entries + .iter() + .any(|entry| entry.get("command").is_some_and(|c| c.is_str(&line))) + }) + }); + if present { + continue; + } + let mut group = object! {"hooks" => vec![Value::Object(object! {"type" => "command", "command" => line.as_str()})]}; + if let Some(matcher) = matcher { + group.insert("matcher".into(), (*matcher).into()); + } + groups.push(Value::Object(group)); + added.push(event.to_string()); + } + let parent = sys::dirname(settings_path); + fs::create_dir_all(&parent).map_err(|e| InstallError::Internal(sys::os_error(&e, &parent)))?; + let text = format!("{}\n", json::dumps(&settings, json::INDENTED)); + fs::write(settings_path, text) + .map_err(|e| InstallError::Internal(sys::os_error(&e, settings_path)))?; + Ok(added) +} + +// -- transcripts ---------------------------------------------------------------- + +/// trace.py's `_records_of`: a line is skipped when blank, but parsed +/// unstripped — unlike claude.py's reader, which strips first. +pub fn records_of(raw: &str) -> Vec { + raw.split('\n') + .filter(|line| !py::strip(line).is_empty()) + .filter_map(|line| match json::loads(line) { + Ok(Value::Object(record)) => Some(record), + _ => None, + }) + .collect() +} + +pub fn read_records(path: &str) -> Vec { + match fs::read(path) { + Ok(bytes) => records_of(&py::decode_surrogateescape(&bytes)), + Err(_) => Vec::new(), + } +} + +pub fn content(record: &Map) -> Vec<&Map> { + match record.get("message") { + Some(Value::Object(message)) => match message.get("content") { + Some(Value::Array(blocks)) => blocks.iter().filter_map(Value::as_object).collect(), + _ => Vec::new(), + }, + _ => Vec::new(), + } +} + +fn list_dir(path: &str) -> Vec { + fs::read_dir(path) + .map(|entries| { + entries + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect() + }) + .unwrap_or_default() +} + +/// Claude's own copy if it still exists, else the store's snapshot, fetched +/// into a cache laid out like Claude's project directory so the session's cwd +/// is chosen the same way. +pub fn find_transcript( + session_id: &str, + store: Option<&dyn Store>, +) -> std::result::Result, StoreError> { + let root = projects_dir(None); + if Path::new(&root).is_dir() { + for project in list_dir(&root) { + let path = sys::join( + &sys::join(&root, &project), + &format!("{}.jsonl", session_id), + ); + if Path::new(&path).exists() { + return Ok(Some(path)); + } + } + } + let Some(store) = store else { + return Ok(None); + }; + let prefix = transcripts_prefix(); + let Ok(keys) = store.list(&prefix) else { + return Ok(None); + }; + let suffix = format!("/{}.jsonl", session_id); + for key in keys { + if key.ends_with(&suffix) { + let project = key[prefix.len()..] + .split('/') + .next() + .unwrap_or("") + .to_string(); + let data = match store.get(&key) { + Ok(data) => data, + Err(StoreError::Missing(_)) => return Ok(None), + Err(error) => return Err(error), + }; + let cache = sys::join( + &sys::join(&sys::join(&home_dir(), ".loch"), "cache"), + &project, + ); + let cached = sys::join(&cache, &format!("{}.jsonl", session_id)); + let _ = fs::create_dir_all(&cache); + let _ = fs::write(&cached, data); + return Ok(Some(cached)); + } + } + Ok(None) +} + +// -- blame ------------------------------------------------------------------------ + +#[derive(Clone, Debug)] +pub struct Hunk { + pub start: usize, + pub end: usize, + pub commit: String, + pub summary: String, + pub lines: Vec, +} + +pub fn blame_hunks(cwd: &str, path: &str) -> Result> { + let porcelain = git(cwd, &["blame", "--porcelain", "--", path])?; + let mut summaries: HashMap = HashMap::new(); + let mut lines: Vec<(usize, String, String)> = Vec::new(); + let mut current = String::new(); + let mut number = 0usize; + for line in porcelain.split('\n') { + if let Some(text) = line.strip_prefix('\t') { + lines.push((number, current.clone(), text.to_string())); + continue; + } + let parts: Vec<&str> = line.split(' ').collect(); + if parts.len() >= 3 && parts[0].chars().count() == 40 && py::is_digits(parts[1]) { + current = parts[0].to_string(); + number = parts[2].parse().unwrap_or(0); + } else if let Some(summary) = line.strip_prefix("summary ") { + summaries.insert(current.clone(), summary.to_string()); + } + } + lines.sort(); + let mut hunks: Vec = Vec::new(); + for (number, commit, text) in lines { + match hunks.last_mut() { + Some(last) if last.commit == commit && last.end + 1 == number => { + last.end = number; + last.lines.push(text); + } + _ => hunks.push(Hunk { + start: number, + end: number, + summary: summaries.get(&commit).cloned().unwrap_or_default(), + commit, + lines: vec![text], + }), + } + } + Ok(hunks) +} + +pub struct Change { + pub commit: String, + pub time: i64, + pub summary: String, +} + +/// Every commit that touched `path` (or just `lines` of it), newest first, +/// by git's own tracking: `-L` for a range, `--follow` for a whole file. +pub fn history(cwd: &str, path: &str, lines: Option<(usize, usize)>) -> Result> { + let range = lines.map(|(a, b)| format!("{},{}:{}", a, b, path)); + let mut args = vec!["log", "-s", "--format=%x1e%H%x1f%ct%x1f%s"]; + match &range { + Some(range) => args.extend(["-L", range.as_str()]), + None => args.extend(["--follow", "--", path]), + } + let output = git(cwd, &args)?; + let mut changes = Vec::new(); + for record in output.split('\x1e').skip(1) { + let mut parts = record.trim_matches('\n').splitn(3, '\x1f'); + let commit = parts.next().unwrap_or("").to_string(); + let time = parts.next().unwrap_or("0").parse().unwrap_or(0); + let summary = parts + .next() + .unwrap_or("") + .split('\n') + .next() + .unwrap_or("") + .to_string(); + changes.push(Change { + commit, + time, + summary, + }); + } + Ok(changes) +} + +#[derive(Clone)] +pub struct Link { + pub session_id: String, + pub call: String, + pub captured: String, + pub transcript: Option, + pub turn: Option, + pub conversation: Option, + pub title: Option, + pub prompt: Option, +} + +impl Link { + pub fn payload(&self) -> Map { + object! { + "session" => self.session_id.as_str(), + "call" => self.call.as_str(), + "captured" => self.captured.as_str(), + "available" => self.transcript.is_some(), + "turn" => Value::opt_str(self.turn.as_deref()), + "conversation" => Value::opt_str(self.conversation.as_deref()), + "title" => Value::opt_str(self.title.as_deref()), + "prompt" => Value::opt_str(self.prompt.as_deref()), + } + } +} + +fn prompt_text(turn: &Turn) -> Option { + for block in turn.blocks.iter().flatten() { + if block.get("type").is_some_and(|t| t.is_str("text")) { + if let Some(Value::Str(text)) = block.get("text") { + if !py::strip(text).is_empty() && !text.starts_with('<') { + return Some(text.clone()); + } + } + } + } + None +} + +/// Resolves commits to turns, ingesting each session once however many +/// commits and lines point into it. +pub struct Resolver<'a> { + cwd: String, + store: Option<&'a dyn Store>, + sessions: HashMap, Vec, Map)>, +} + +impl<'a> Resolver<'a> { + pub fn new(cwd: &str, store: Option<&'a dyn Store>) -> Self { + Resolver { + cwd: cwd.into(), + store, + sessions: HashMap::new(), + } + } + + fn session( + &mut self, + session_id: &str, + ) -> std::result::Result<&(Option, Vec, Map), String> { + if !self.sessions.contains_key(session_id) { + let path = find_transcript(session_id, self.store).map_err(|e| e.to_string())?; + let mut turns = Vec::new(); + let mut header = Map::new(); + if let Some(path) = &path { + if let Some(meta) = read_session_meta(path) { + let origin = Origin { + cwd: meta.cwd, + home: home_dir(), + session_id: session_id.into(), + }; + let derived = + ingest::ingest(path, &origin, None).map_err(|e| format!("{:?}", e))?; + turns = derived.turns; + header = derived.header; + } + } + self.sessions + .insert(session_id.into(), (path, turns, header)); + } + Ok(&self.sessions[session_id]) + } + + pub fn resolve(&mut self, commit: &str) -> std::result::Result, String> { + let Some(note) = read_note(&self.cwd, commit) else { + return Ok(None); + }; + let session_id = py_str(note.get("session")); + let call = py_str(note.get("call")); + let (path, turns, header) = self.session(&session_id)?; + let by_id: HashMap<&str, &Turn> = turns.iter().map(|t| (t.id.as_str(), t)).collect(); + let turn = turns.iter().find(|candidate| { + candidate.blocks.iter().flatten().any(|block| { + block.get("type").is_some_and(|t| t.is_str("tool-call")) + && block.get("call").is_some_and(|c| c.is_str(&call)) + }) + }); + let mut prompt = None; + let mut conversation = None; + let mut walker = turn; + while let Some(current) = walker { + if prompt.is_none() + && current.kind() == "message" + && current.author_kind() == Some("human") + { + prompt = prompt_text(current); + } + let parents = current.parents(); + if parents.is_empty() { + conversation = Some(current.id.clone()); + } + walker = parents.first().and_then(|p| by_id.get(p.as_str()).copied()); + } + let empty = Map::new(); + let session = header + .get("session") + .and_then(Value::as_object) + .unwrap_or(&empty); + let title_of = |key: &str| match session.get(key) { + Some(v) if v.truthy() => v.as_str().map(str::to_string), + _ => None, + }; + Ok(Some(Link { + session_id: session_id.clone(), + call, + captured: py_str(note.get("captured")), + transcript: path.clone(), + turn: turn.map(|t| t.id.clone()), + conversation, + title: title_of("title").or_else(|| title_of("aiTitle")), + prompt: display_summary(prompt.as_deref()), + })) + } +} + +// -- backfill --------------------------------------------------------------------- + +#[derive(Clone)] +pub struct Call { + pub session_id: String, + pub call: String, + pub command: String, + pub started: f64, + pub finished: f64, +} + +fn seconds(stamp: Option<&Value>) -> Option { + sys::iso_seconds(stamp?.as_str()?) +} + +/// `(block.get("input") or {}).get("command", "")`, stringified. +pub fn input_command(block: &Map) -> Option { + match block.get("input") { + None => Some(String::new()), + Some(v) if !v.truthy() => Some(String::new()), + Some(Value::Object(input)) => Some(match input.get("command") { + None => String::new(), + other => py_str(other), + }), + Some(_) => None, + } +} + +/// 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. +pub fn commit_calls(path: &str) -> Vec { + let file = sys::basename(path); + let session_id = file[..file.len().saturating_sub(".jsonl".len())].to_string(); + let mut issued: HashMap = HashMap::new(); + let mut calls = Vec::new(); + for record in read_records(path) { + let stamp = seconds(record.get("timestamp")); + for block in content(&record) { + let kind = block.get("type").and_then(Value::as_str); + if kind == Some("tool_use") && block.get("name").is_some_and(|n| n.is_str("Bash")) { + let Some(command) = input_command(block) else { + continue; + }; + if let (true, Some(stamp)) = (command.contains("commit"), stamp) { + issued.insert(py_str(block.get("id")), (command, stamp)); + } + } else if kind == Some("tool_result") { + let call = py_str(block.get("tool_use_id")); + if let Some(stamp) = stamp { + if let Some((command, started)) = issued.remove(&call) { + calls.push(Call { + session_id: session_id.clone(), + call, + command, + started, + finished: stamp, + }); + } + } + } + } + } + calls +} + +/// `str.splitlines()`, which splits on more than newlines. +pub fn splitlines(text: &str) -> Vec<&str> { + let mut lines = Vec::new(); + let mut start = 0; + let mut chars = text.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + let breaks = matches!( + c, + '\n' | '\r' + | '\u{0b}' + | '\u{0c}' + | '\u{1c}' + | '\u{1d}' + | '\u{1e}' + | '\u{85}' + | '\u{2028}' + | '\u{2029}' + ); + if breaks { + lines.push(&text[start..i]); + let mut end = i + c.len_utf8(); + if c == '\r' { + if let Some(&(_, '\n')) = chars.peek() { + chars.next(); + end += 1; + } + } + start = end; + } + } + if start < text.len() { + lines.push(&text[start..]); + } + lines +} + +pub type Progress<'p> = &'p mut dyn FnMut(usize, usize, u64, u64); + +/// Links commits made before the hooks existed, accepting only an exact +/// match: one Bash call whose command contains the commit's subject and whose +/// run brackets the commit's author or committer time. +pub fn backfill( + cwd: &str, + revision: &str, + mut progress: Option, +) -> Result> { + let listing = git(cwd, &["log", "--format=%H%x00%at%x00%ct%x00%s", revision])?; + let already = noted_commits(cwd); + let mut pending: Vec<(String, [i64; 2], String)> = Vec::new(); + for line in splitlines(&listing) { + let parts: Vec<&str> = line.splitn(4, '\x00').collect(); + if parts.len() < 4 { + return Err(TraceError::new("git-failed", "unexpected git log output")); + } + let (sha, subject) = (parts[0], parts[3]); + if !already.contains(sha) && !subject.is_empty() { + let stamp = |s: &str| s.trim().parse::().unwrap_or(0); + pending.push(( + sha.into(), + [stamp(parts[1]), stamp(parts[2])], + subject.into(), + )); + } + } + if pending.is_empty() { + return Ok(Vec::new()); + } + let subjects: HashSet<&str> = pending.iter().map(|(_, _, s)| s.as_str()).collect(); + + let mut transcripts: Vec<(String, u64)> = Vec::new(); + let root = projects_dir(None); + let mut projects = list_dir(&root); + projects.sort_by(|a, b| py::cmp(a, b)); + for project in projects { + let directory = sys::join(&root, &project); + if !Path::new(&directory).is_dir() { + continue; + } + let mut names = list_dir(&directory); + names.sort_by(|a, b| py::cmp(a, b)); + for name in names { + if name.ends_with(".jsonl") { + let path = sys::join(&directory, &name); + if let Ok(meta) = fs::metadata(&path) { + transcripts.push((path, meta.len())); + } + } + } + } + let total: u64 = transcripts.iter().map(|(_, size)| size).sum(); + let mut calls: Vec = Vec::new(); + let mut read = 0u64; + let count = transcripts.len(); + for (done, (path, size)) in transcripts.iter().enumerate() { + read += size; + let raw = fs::read(path) + .map(|b| py::decode_replace(&b)) + .unwrap_or_default(); + if raw.contains("git commit") && subjects.iter().any(|s| raw.contains(s)) { + calls.extend(commit_calls(path)); + } + if let Some(progress) = progress.as_mut() { + progress(done + 1, count, read, total); + } + } + + let mut linked = Vec::new(); + for (sha, stamps, subject) in pending { + let matches: Vec<&Call> = calls + .iter() + .filter(|call| { + call.command.contains(&subject) + && stamps.iter().any(|&stamp| { + let stamp = stamp as f64; + call.started - CLOCK_SLACK <= stamp && stamp <= call.finished + CLOCK_SLACK + }) + }) + .collect(); + let distinct: HashSet<(&str, &str)> = matches + .iter() + .map(|c| (c.session_id.as_str(), c.call.as_str())) + .collect(); + if distinct.len() == 1 { + write_note( + cwd, + &sha, + &make_note(&matches[0].session_id, &matches[0].call, "backfill"), + )?; + linked.push((sha, matches[0].clone())); + } + } + Ok(linked) +} + +// -- ask ------------------------------------------------------------------------------ + +pub struct Fork { + pub session_id: String, + pub path: String, + pub cwd: String, + pub records: usize, + pub origin_session: String, +} + +fn parent(record: &Map) -> Option { + let parent = match record.get("parentUuid") { + None | Some(Value::Null) => record.get("logicalParentUuid"), + other => other, + }; + parent.and_then(Value::as_str).map(str::to_string) +} + +fn uuid(record: &Map) -> &str { + record.get("uuid").and_then(Value::as_str).unwrap_or("") +} + +/// A new Claude session holding the conversation, filed under `target_cwd`. +/// With no `call` it holds the conversation to its end; with one, it is cut +/// after the whole round of tool results that call belongs to. +pub fn fork_session( + transcript: &str, + target_cwd: &str, + call: Option<&str>, + title: Option<&str>, +) -> std::result::Result { + let bytes = + fs::read(transcript).map_err(|e| ForkError::Internal(sys::os_error(&e, transcript)))?; + let raw = py::decode_surrogateescape(&bytes); + let records: Vec = records_of(&raw) + .into_iter() + .filter(|r| matches!(r.get("uuid"), Some(Value::Str(_)))) + .collect(); + let mut children: HashMap> = HashMap::new(); + for (index, record) in records.iter().enumerate() { + if let Some(parent) = parent(record) { + children.entry(parent).or_default().push(index); + } + } + let Some(call) = call else { + if records.is_empty() { + return Err(ForkError::Trace(TraceError::new( + "call-not-found", + "the transcript holds no records", + ))); + } + let leaf = records.len() - 1; + return write_fork(transcript, &raw, &records, leaf, target_cwd, title); + }; + let is_result_for = |record: &Map| { + content(record).iter().any(|block| { + block.get("type").is_some_and(|t| t.is_str("tool_result")) + && block.get("tool_use_id").is_some_and(|id| id.is_str(call)) + }) + }; + let Some(mut leaf) = records.iter().position(is_result_for) else { + return Err(ForkError::Trace(TraceError::new( + "call-not-found", + format!("no result for tool call {}", call), + ))); + }; + loop { + let following: Vec = children + .get(uuid(&records[leaf])) + .into_iter() + .flatten() + .copied() + .filter(|&child| { + records[child].get("type").is_some_and(|t| t.is_str("user")) + && content(&records[child]) + .iter() + .any(|b| b.get("type").is_some_and(|t| t.is_str("tool_result"))) + }) + .collect(); + match following.first() { + Some(&next) => leaf = next, + None => break, + } + } + write_fork(transcript, &raw, &records, leaf, target_cwd, title) +} + +#[derive(Debug)] +pub enum ForkError { + Trace(TraceError), + Internal(String), +} + +fn write_fork( + transcript: &str, + raw: &str, + records: &[Map], + leaf: usize, + target_cwd: &str, + title: Option<&str>, +) -> std::result::Result { + let mut by_uuid: HashMap<&str, usize> = HashMap::new(); + for (index, record) in records.iter().enumerate() { + by_uuid.insert(uuid(record), index); + } + let mut keep: HashSet = HashSet::new(); + let mut walker = Some(leaf); + while let Some(index) = walker { + let id = uuid(&records[index]).to_string(); + if keep.contains(&id) { + break; + } + keep.insert(id); + walker = parent(&records[index]).and_then(|p| by_uuid.get(p.as_str()).copied()); + } + + let origin_cwd = match read_session_meta(transcript) { + Some(meta) => meta.cwd, + None => match claude::transcript_cwds(raw).into_iter().next() { + Some((cwd, _)) => cwd, + None => return Err(ForkError::Internal("the transcript names no cwd".into())), + }, + }; + let file = sys::basename(transcript); + let origin_session = file[..file.len().saturating_sub(".jsonl".len())].to_string(); + let new_id = sys::uuid4(); + + let mut kept: Vec = records + .iter() + .filter(|r| keep.contains(uuid(r))) + .map(|r| json::dumps(&Value::Object(r.clone()), json::UNICODE)) + .collect(); + let default_title = format!("loch ask: {}", py::truncate(&origin_session, 8)); + kept.push(json::dumps( + &Value::Object(object! { + "type" => "custom-title", + "customTitle" => title.filter(|t| !t.is_empty()).unwrap_or(&default_title), + "sessionId" => origin_session.as_str(), + }), + json::DEFAULT, + )); + let home = home_dir(); + let spec = RewriteSpec { + origin_cwd, + origin_home: home.clone(), + target_cwd: target_cwd.into(), + target_home: home, + origin_session_id: Some(origin_session.clone()), + target_session_id: Some(new_id.clone()), + }; + let text = rewrite_transcript(&format!("{}\n", kept.join("\n")), &spec); + let path = claude::transcript_path_for(target_cwd, &new_id, None); + let parent_dir = sys::dirname(&path); + fs::create_dir_all(&parent_dir) + .map_err(|e| ForkError::Internal(sys::os_error(&e, &parent_dir)))?; + let bytes = py::encode_surrogateescape(&text) + .map_err(|_| ForkError::Internal("the fork holds an unencodable surrogate".into()))?; + fs::write(&path, bytes).map_err(|e| ForkError::Internal(sys::os_error(&e, &path)))?; + Ok(Fork { + session_id: new_id, + path, + cwd: target_cwd.into(), + records: keep.len(), + origin_session, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn splitlines_matches_python() { + assert_eq!( + splitlines("a\nb\r\nc\rd\u{1c}e\n"), + vec!["a", "b", "c", "d", "e"] + ); + assert_eq!(splitlines(""), Vec::<&str>::new()); + } +} diff --git a/rust/src/usage.txt b/rust/src/usage.txt new file mode 100644 index 0000000..d787ab7 --- /dev/null +++ b/rust/src/usage.txt @@ -0,0 +1,44 @@ +loch — save and restore agent coding sessions across machines + +Usage: + 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 ingest [--cwd ] [--branch ] [--session ] + [--author | --author-key ] + [--out ] + loch install [--local] [--command ] + loch blame [--html [] [--lines ] [--no-open]] + [--store ] + loch log [:[-]] [--store ] + loch ask [] [--at-commit] [--no-launch] + [--store ] + loch backfill [--revision ] (default: every branch) + loch hook pre-tool | post-tool | stop (run by Claude Code) + loch --version + +Every command takes --json, which replaces the text below with one machine- +readable document on stdout. + +Stores: + local directory + s3://bucket/prefix any S3-compatible endpoint + +Environment: + LOCH_STORE default store URI + LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) + LOCH_S3_REGION region override + CLAUDE_CONFIG_DIR Claude Code's state directory (default ~/.claude) + +Derived conversation files go to ~/.loch/derived unless --out says otherwise. + +`install` adds Claude Code hooks to a repository that note, on every commit an +agent makes, the conversation and tool call that made it (git notes on +refs/notes/loch), and snapshot each session's transcript into the store. +`blame` shows which conversation wrote each line, `log` every conversation +that changed a file or line range over its history; `ask` forks that +conversation and resumes it in Claude Code — from its end, or with +--at-commit from just after the commit. From d5e937d25a2f937b5ee2295d6c997d80f529bc57 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 17:47:17 -0500 Subject: [PATCH 09/18] Hold every command to the reference, and make save reproducible The harness now compares every file a run leaves behind, not just the hook's, and renames generated v4 UUIDs so --new-id and ask's fork compare exactly. test_equivalence_commands.py covers every command in both renderings: usage errors and -h at several widths, list over moved and undecodable sessions and CLAUDE_CONFIG_DIR, save/list --remote/restore/ delete/reindex including unreadable bundles, ingest's graph cases and author keys, install, blame/--html/log/ask (also from the store) and backfill. Planted bugs in redact, rewrite, ingest, argparse, json, trace, index and cli each fail it. SOURCE_DATE_EPOCH now fixes save's createdAt in both builds, the reproducible-builds convention, which is what lets two builds' bundle refs be compared at all. base64 key errors follow binascii's strict mode. Co-Authored-By: Claude Opus 5.5 --- loch/cli.py | 13 +- rust/src/cli.rs | 2 +- rust/src/ingest.rs | 100 ++-- rust/src/sys.rs | 9 + rust/src/usage.txt | 1 + test/equivalence.py | 356 ++++++++++++++ test/test_cli.py | 26 + test/test_equivalence.py | 196 +------- test/test_equivalence_commands.py | 762 ++++++++++++++++++++++++++++++ 9 files changed, 1244 insertions(+), 221 deletions(-) create mode 100644 test/equivalence.py create mode 100644 test/test_equivalence_commands.py diff --git a/loch/cli.py b/loch/cli.py index c87804f..7d25e48 100644 --- a/loch/cli.py +++ b/loch/cli.py @@ -121,6 +121,7 @@ Environment: LOCH_STORE default store URI + SOURCE_DATE_EPOCH fixed createdAt for save, so a bundle is reproducible LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) LOCH_S3_REGION region override CLAUDE_CONFIG_DIR Claude Code's state directory (default ~/.claude) @@ -330,6 +331,16 @@ def _list_remote_text( return "".join(lines) +def _creation_time() -> float: + """`SOURCE_DATE_EPOCH` when it holds an integer, the reproducible-builds + convention: a bundle's ref hashes its createdAt, so fixing the clock is + what makes the same sessions pack to the same ref twice.""" + try: + return float(int(os.environ["SOURCE_DATE_EPOCH"])) + except (KeyError, ValueError): + return time.time() + + def command_save(argv: list[str]) -> Result: parser = _parser("save") parser.add_argument("--cwd") @@ -372,7 +383,7 @@ def command_save(argv: list[str]) -> Result: bundle = Bundle( version=BUNDLE_VERSION, agent=AGENT, - created_at=iso_timestamp(time.time()), + created_at=iso_timestamp(_creation_time()), origin=BundleOrigin( home=home_dir(), platform=_platform_name(), hostname=socket.gethostname() ), diff --git a/rust/src/cli.rs b/rust/src/cli.rs index e1179c5..10b0140 100644 --- a/rust/src/cli.rs +++ b/rust/src/cli.rs @@ -403,7 +403,7 @@ pub fn command_save(argv: &[String]) -> Run { let bundle = Bundle { version: BUNDLE_VERSION, agent: AGENT.into(), - created_at: sys::iso_timestamp(sys::now()), + created_at: sys::iso_timestamp(sys::creation_time()), origin: BundleOrigin { home: home_dir(), platform: sys::platform_name().into(), diff --git a/rust/src/ingest.rs b/rust/src/ingest.rs index 88388b5..6a3b098 100644 --- a/rust/src/ingest.rs +++ b/rust/src/ingest.rs @@ -584,39 +584,72 @@ fn b64encode(data: &[u8]) -> String { out } -/// `base64.b64decode(text, validate=True)`, with binascii's messages. +/// `base64.b64decode(text, validate=True)`: binascii's `a2b_base64` in +/// strict mode, which checks in this order and words each failure its way. fn b64decode_strict(text: &str) -> Result, String> { if !text.is_ascii() { return Err("string argument should contain only ASCII characters".into()); } - let body = text.trim_end_matches('='); - let pad = text.len() - body.len(); - if pad > 2 || !body.bytes().all(|b| B64.contains(&b)) { - return Err("Non-base64 digit found".into()); - } - let data_chars = body.len(); - if data_chars % 4 == 1 { - return Err(format!( - "Invalid base64-encoded string: number of data characters ({}) cannot be 1 more than a multiple of 4", - data_chars - )); - } - if !(data_chars + pad).is_multiple_of(4) { - return Err("Incorrect padding".into()); + let bytes = text.as_bytes(); + if bytes.first() == Some(&b'=') { + return Err("Leading padding not allowed".into()); } let mut out = Vec::new(); - let mut buffer = 0u32; - let mut bits = 0; - for b in body.bytes() { - let value = B64.iter().position(|&c| c == b).expect("checked alphabet") as u32; - buffer = buffer << 6 | value; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((buffer >> bits & 0xff) as u8); + let (mut quad, mut pads, mut left, mut padding) = (0usize, 0usize, 0u32, false); + for (i, &b) in bytes.iter().enumerate() { + if b == b'=' { + padding = true; + if quad == 0 { + return Err("Excess padding not allowed".into()); + } + if quad >= 2 { + pads += 1; + if quad + pads >= 4 { + if i + 1 < bytes.len() { + return Err("Excess data after padding".into()); + } + return Ok(out); + } + } + continue; + } + let Some(value) = B64.iter().position(|&c| c == b) else { + return Err("Only base64 data is allowed".into()); + }; + if padding { + return Err("Discontinuous padding not allowed".into()); + } + pads = 0; + let value = value as u32; + match quad { + 0 => { + left = value; + quad = 1; + } + 1 => { + out.push((left << 2 | value >> 4) as u8); + left = value & 0x0f; + quad = 2; + } + 2 => { + out.push((left << 4 | value >> 2) as u8); + left = value & 0x03; + quad = 3; + } + _ => { + out.push((left << 6 | value) as u8); + quad = 0; + } } } - Ok(out) + match quad { + 0 => Ok(out), + 1 => Err(format!( + "Invalid base64-encoded string: number of data characters ({}) cannot be 1 more than a multiple of 4", + out.len() / 3 * 4 + 1 + )), + _ => Err("Incorrect padding".into()), + } } /// `ssh:SHA256:`, the fingerprint `ssh-keygen -l` prints. @@ -644,9 +677,18 @@ mod tests { b64decode_strict("aGVsbG8").unwrap_err(), "Incorrect padding" ); - assert_eq!( - b64decode_strict("a!").unwrap_err(), - "Non-base64 digit found" - ); + for (input, error) in [ + ("not*base64", "Only base64 data is allowed"), + ("ab=c", "Discontinuous padding not allowed"), + ("aGVs====", "Excess padding not allowed"), + ("=aGVs", "Leading padding not allowed"), + ("aGVsbA==x", "Excess data after padding"), + ("aGVsbA===", "Excess data after padding"), + ("a===", "Invalid base64-encoded string: number of data characters (1) cannot be 1 more than a multiple of 4"), + ("aGVsb", "Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4"), + ] { + assert_eq!(b64decode_strict(input).unwrap_err(), error, "{input}"); + } + assert_eq!(b64decode_strict("abc=").unwrap(), b"i\xb7"); } } diff --git a/rust/src/sys.rs b/rust/src/sys.rs index 2f04c5a..59dfb62 100644 --- a/rust/src/sys.rs +++ b/rust/src/sys.rs @@ -187,6 +187,15 @@ pub fn now() -> f64 { .unwrap_or(0.0) } +/// `cli._creation_time`: `SOURCE_DATE_EPOCH` when it holds an integer. +pub fn creation_time() -> f64 { + std::env::var("SOURCE_DATE_EPOCH") + .ok() + .and_then(|v| crate::blame_html::py_int(&v)) + .map(|v| v as f64) + .unwrap_or_else(now) +} + /// `os.stat(path).st_mtime`, computed as CPython computes it: the seconds /// plus `nsec * 1e-9`, in double arithmetic. pub fn mtime(meta: &fs::Metadata) -> f64 { diff --git a/rust/src/usage.txt b/rust/src/usage.txt index d787ab7..cff8fff 100644 --- a/rust/src/usage.txt +++ b/rust/src/usage.txt @@ -29,6 +29,7 @@ Stores: Environment: LOCH_STORE default store URI + SOURCE_DATE_EPOCH fixed createdAt for save, so a bundle is reproducible LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) LOCH_S3_REGION region override CLAUDE_CONFIG_DIR Claude Code's state directory (default ~/.claude) diff --git a/test/equivalence.py b/test/equivalence.py new file mode 100644 index 0000000..a77cf3b --- /dev/null +++ b/test/equivalence.py @@ -0,0 +1,356 @@ +"""Shared machinery for holding the Rust build to the Python reference. + +Every scenario is built twice at the same path with pinned git dates and file +times, so commit hashes, note objects, the notes ref and session mtimes come +out byte-identical; one copy is driven by `python -m loch.cli`, the other by +the binary named in LOCH_RUST, and everything observable is compared: stdout, +stderr, exit status, and every file the run left behind. + +Two values are random by design — the id `restore --new-id` mints and the +fork `ask` creates — so v4 UUIDs are renamed in order of first appearance +before comparing. Fixture ids are deliberately not v4, so they never are. +""" + +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +RUST = os.environ.get("LOCH_RUST") + +SESSION = "11111111-2222-3333-4444-555555555555" +# In the future, so the hook's "committed after the call began" bound admits +# commits made during a call; fixed, so their hashes are too. +NOW = "2031-01-01T00:00:00Z" +PAST = "2020-01-01T00:00:00Z" +MTIME = 1_800_000_000.123456 +EPOCH = "1800000000" + +GENERATED = re.compile( + rb"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}" +) + + +def implementation(name: str) -> list[str]: + if name == "py": + return [sys.executable, "-m", "loch.cli"] + assert RUST is not None + return [os.path.abspath(RUST)] + + +@dataclass +class Run: + stdout: bytes + stderr: bytes + status: int + + +class World: + """One scratch machine: a HOME, a repository, a store, an environment.""" + + def __init__(self, root: Path) -> None: + self.root = root + self.home = root / "home" + self.repo = root / "repo" + self.store = root / "store" + self.home.mkdir(parents=True) + bin_dir = root / "bin" + bin_dir.mkdir() + # `install --local` records `shutil.which("loch")`; both builds must + # find the same one. + (bin_dir / "loch").write_text("#!/bin/sh\n") + (bin_dir / "loch").chmod(0o755) + self.env = { + "PATH": f"{bin_dir}:{os.environ['PATH']}", + "HOME": str(self.home), + "LOCH_STORE": str(self.store), + "TMPDIR": str(root), + "GIT_CONFIG_GLOBAL": str(root / "gitconfig"), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_NAME": "Test", + "GIT_AUTHOR_EMAIL": "test@example.com", + "GIT_COMMITTER_NAME": "Test", + "GIT_COMMITTER_EMAIL": "test@example.com", + "GIT_AUTHOR_DATE": NOW, + "GIT_COMMITTER_DATE": NOW, + "SOURCE_DATE_EPOCH": EPOCH, + "PYTHONPATH": str(Path(__file__).resolve().parent.parent), + } + + # -- git --------------------------------------------------------------- + + def git(self, *args: str, cwd: Path | None = None, date: str = NOW) -> str: + env = {**self.env, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} + return subprocess.run( + ["git", "-C", str(cwd or self.repo), *args], + capture_output=True, + text=True, + check=True, + env=env, + ).stdout.strip() + + def init(self, *extra: str) -> None: + self.repo.mkdir(exist_ok=True) + self.git("init", "-q", "-b", "main", *extra) + + def commit(self, message: str, cwd: Path | None = None, date: str = NOW) -> str: + self.git("commit", "-q", "--allow-empty", "-m", message, cwd=cwd, date=date) + return self.git("rev-parse", "HEAD", cwd=cwd) + + def commit_file(self, name: str, text: str, message: str, date: str = NOW) -> str: + path = self.repo / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + self.git("add", name) + self.git("commit", "-q", "-m", message, date=date) + return self.git("rev-parse", "HEAD") + + def note(self, commit: str, session: str, call: str) -> None: + body = json.dumps( + { + "loch": 1, + "agent": "claude-code", + "session": session, + "call": call, + "captured": "hook", + }, + sort_keys=True, + separators=(",", ":"), + ) + subprocess.run( + ["git", "-C", str(self.repo), "notes", "--ref", "refs/notes/loch"] + + ["add", "-f", "-m", body, commit], + check=True, + capture_output=True, + env=self.env, + ) + + # -- sessions ------------------------------------------------------------ + + def projects(self) -> Path: + return self.home / ".claude" / "projects" + + def session( + self, + cwd: str, + session_id: str, + records: list[Any], + directory: str | None = None, + raw: bytes = b"", + ) -> Path: + """A transcript filed as Claude files it, with a pinned mtime. Records + that are strings are written as-is, so a scenario can include lines + that aren't JSON.""" + encoded = directory or re.sub(r"[^a-zA-Z0-9]", "-", cwd) + folder = self.projects() / encoded + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"{session_id}.jsonl" + lines = [r if isinstance(r, str) else json.dumps(r) for r in records] + path.write_bytes("\n".join(lines).encode() + b"\n" + raw) + os.utime(path, (MTIME, MTIME)) + return path + + # -- running ------------------------------------------------------------- + + def loch( + self, + impl: str, + *args: str, + stdin: Any = None, + env: dict[str, str] | None = None, + cwd: Path | None = None, + ) -> Run: + data = ( + stdin + if isinstance(stdin, bytes) + else b"" + if stdin is None + else json.dumps(stdin).encode() + ) + merged = {**self.env, **(env or {})} + merged = {k: v for k, v in merged.items() if v is not None} + result = subprocess.run( + [*implementation(impl), *args], + input=data, + capture_output=True, + env=merged, + cwd=str(cwd or self.root), + ) + return Run(result.stdout, result.stderr, result.returncode) + + def event(self, call: str | None = "toolu_1", **fields: Any) -> dict[str, Any]: + body: dict[str, Any] = { + "session_id": SESSION, + "cwd": str(self.repo), + "tool_name": "Bash", + "tool_input": {"command": "git commit -m work"}, + } + if call is not None: + body["tool_use_id"] = call + body.update(fields) + return body + + # -- observing ------------------------------------------------------------- + + def observe(self) -> dict[str, Any]: + """Every file the run can have left behind, keyed by path, with git's + own churn (objects, index, logs) left out in favour of the refs that + matter. The pending state's timestamp is reduced to its type, being + the one value that is the clock and nothing else.""" + seen: dict[str, Any] = {} + for path in sorted(self.root.rglob("*")): + relative = path.relative_to(self.root).as_posix() + parts = relative.split("/") + if ".git" in parts: + at = parts.index(".git") + inside = parts[at + 1 :] + keep = inside[:1] == ["loch"] or ( + inside[:1] == ["worktrees"] and "loch" in inside + ) + if not keep: + continue + if path.is_dir(): + seen[relative] = "dir" + continue + if "/loch/pending/" in f"/{relative}": + try: + state = json.loads(path.read_text()) + except ValueError: + state = path.read_text() + seen[relative] = ( + {"head": state.get("head"), "at": type(state.get("at")).__name__} + if isinstance(state, dict) + else state + ) + continue + seen[relative] = path.read_bytes() + for repo in {self.repo, *self.root.glob("wt*")}: + if (repo / ".git").exists(): + for ref in ("refs/notes/loch", "HEAD"): + seen[f"{repo.name}:{ref}"] = self._git_quiet( + repo, "rev-parse", "-q", "--verify", ref + ) + seen[f"{repo.name}:rewriteRef"] = self._git_quiet( + repo, "config", "--get", "notes.rewriteRef" + ) + return seen + + def _git_quiet(self, repo: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(repo), *args], + capture_output=True, + text=True, + env=self.env, + ).stdout.strip() + + +Scenario = Callable[[World, Callable[..., Run]], list[Run]] + + +class Renamer: + """Generated v4 UUIDs → `UUID-n`, numbered by first appearance.""" + + def __init__(self) -> None: + self.names: dict[bytes, bytes] = {} + + def __call__(self, data: bytes) -> bytes: + def name(match: re.Match[bytes]) -> bytes: + found = match.group(0) + if found not in self.names: + self.names[found] = f"UUID-{len(self.names) + 1}".encode() + return self.names[found] + + return GENERATED.sub(name, data) + + +def normalized( + runs: list[Run], seen: dict[str, Any] +) -> tuple[list[Any], dict[str, Any]]: + rename = Renamer() + out_runs = [ + {"stdout": rename(r.stdout), "stderr": rename(r.stderr), "status": r.status} + for r in runs + ] + out_seen: dict[str, Any] = {} + for key in sorted(seen, key=lambda k: rename(k.encode())): + value = seen[key] + if isinstance(value, bytes): + value = rename(value) + out_seen[rename(key.encode()).decode()] = value + return out_runs, out_seen + + +def digest_of(value: Any) -> str: + """What a failure may show: a hash, never transcript content.""" + if isinstance(value, bytes): + return hashlib.sha256(value).hexdigest()[:16] + return hashlib.sha256(repr(value).encode()).hexdigest()[:16] + + +def first_difference(py: Any, rs: Any) -> str: + """Where two observations part, named by run index or file path. File + contents are reported by hash: a scenario's files are synthetic, but the + corpus checks share this and theirs are not.""" + py_runs, py_seen = py + rs_runs, rs_seen = rs + for index, (a, b) in enumerate(zip(py_runs, rs_runs)): + for stream in ("stdout", "stderr", "status"): + if a[stream] != b[stream]: + return f"run {index} {stream} differs:\n py: {a[stream]!r}\n rs: {b[stream]!r}" + if len(py_runs) != len(rs_runs): + return f"{len(py_runs)} runs against {len(rs_runs)}" + only_py = sorted(set(py_seen) - set(rs_seen)) + only_rs = sorted(set(rs_seen) - set(py_seen)) + if only_py or only_rs: + return f"files only in py: {only_py}; only in rs: {only_rs}" + for key in py_seen: + if py_seen[key] != rs_seen[key]: + a, b = py_seen[key], rs_seen[key] + if isinstance(a, bytes) and isinstance(b, bytes) and len(a) < 4000: + return f"{key} differs:\n py: {a!r}\n rs: {b!r}" + return f"{key} differs: py {digest_of(a)} rs {digest_of(b)}" + return "no difference" + + +def twin( + tmp_path: Path, + scenario: Scenario, + mix: tuple[str, str] | None = None, + quiet: bool = False, +) -> dict[str, Any]: + """Runs `scenario` once per implementation in identical worlds at the same + path, and asserts nothing observable differs. With `mix`, the second run + alternates implementations call by call — pre under one, post under the + other — which is what a machine switching over mid-session does. `quiet` + reports only hashes, for scenarios over real transcripts.""" + root = tmp_path / "world" + outcomes = [] + plans: list[tuple[str, ...]] = [("py",), ("rs",)] if mix is None else [("py",), mix] + raw_seen: list[dict[str, Any]] = [] + for plan in plans: + if root.exists(): + shutil.rmtree(root) + world = World(root) + calls = iter(range(10_000)) + + def loch( + *args: str, _w: World = world, _p: tuple[str, ...] = plan, **kw: Any + ) -> Run: + return _w.loch(_p[next(calls) % len(_p)], *args, **kw) + + runs = scenario(world, loch) + seen = world.observe() + raw_seen.append(seen) + outcomes.append(normalized(runs, seen)) + if outcomes[0] != outcomes[1]: + if quiet: + raise AssertionError("builds differ (details withheld: real transcripts)") + raise AssertionError(first_difference(outcomes[0], outcomes[1])) + return raw_seen[0] diff --git a/test/test_cli.py b/test/test_cli.py index 2daa0f0..df8bf78 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -1159,3 +1159,29 @@ def test_an_undecodable_transcript_is_listed_but_not_packed( assert code == 1 assert saved["code"] == "transcript-unreadable" assert not (tmp_path / "store").exists() + + +def test_source_date_epoch_makes_save_reproducible( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path +) -> None: + home = tmp_path / "home" + project = tmp_path / "proj" + project.mkdir() + write_session(home, str(project), "abc") + monkeypatch.setenv("SOURCE_DATE_EPOCH", "1700000000") + refs = [] + for store in ("a", "b"): + document, _, _ = invoke_json( + monkeypatch, + capsys, + home, + "save", + "--json", + "--cwd", + str(project), + "--store", + str(tmp_path / store), + ) + assert document["createdAt"] == "2023-11-14T22:13:20.000Z" + refs.append(document["ref"]) + assert refs[0] == refs[1] diff --git a/test/test_equivalence.py b/test/test_equivalence.py index fe87e55..1fefbe2 100644 --- a/test/test_equivalence.py +++ b/test/test_equivalence.py @@ -1,209 +1,25 @@ -"""The Rust build against the Python reference, on the same inputs. +"""`loch hook` in the Rust build against the Python reference. Opt-in: set LOCH_RUST to a built binary (`cargo build --release` in rust/, then -LOCH_RUST=rust/target/release/loch). Every scenario is built twice at the same -path with pinned git dates, so commit hashes, note objects and the notes ref -come out byte-identical; one copy is driven by `python -m loch.cli`, the other -by the binary, and everything observable is compared: stdout, stderr, exit -status, the notes ref, the pending-state directory and the store. - -With LOCH_CORPUS=1 as well, the transcript-reading path is run against this -machine's real transcripts. Their content only ever exists in a temporary -directory and in memory; failures report session ids and counts, never text. +LOCH_RUST=rust/target/release/loch). See equivalence.py for how a scenario is +run twice and compared. With LOCH_CORPUS=1 as well, the one hook path that +reads a transcript runs against this machine's real ones. """ -import hashlib import json import os import random import shutil -import subprocess -import sys from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from typing import Any import pytest - -RUST = os.environ.get("LOCH_RUST") +from equivalence import PAST, RUST, SESSION, Run, Scenario, World, twin pytestmark = pytest.mark.skipif(not RUST, reason="set LOCH_RUST to a Rust build") -SESSION = "11111111-2222-3333-4444-555555555555" -# In the future, so the hook's "committed after the call began" bound admits -# commits made during a call; fixed, so their hashes are too. -NOW = "2031-01-01T00:00:00Z" -PAST = "2020-01-01T00:00:00Z" - - -def implementation(name: str) -> list[str]: - if name == "py": - return [sys.executable, "-m", "loch.cli"] - assert RUST is not None - return [os.path.abspath(RUST)] - - -@dataclass -class Run: - stdout: bytes - stderr: bytes - status: int - - -class World: - """One scratch machine: a HOME, a repository, a store, an environment.""" - - def __init__(self, root: Path) -> None: - self.root = root - self.home = root / "home" - self.repo = root / "repo" - self.store = root / "store" - self.home.mkdir(parents=True) - self.env = { - "PATH": os.environ["PATH"], - "HOME": str(self.home), - "LOCH_STORE": str(self.store), - "GIT_CONFIG_GLOBAL": str(root / "gitconfig"), - "GIT_CONFIG_NOSYSTEM": "1", - "GIT_AUTHOR_NAME": "Test", - "GIT_AUTHOR_EMAIL": "test@example.com", - "GIT_COMMITTER_NAME": "Test", - "GIT_COMMITTER_EMAIL": "test@example.com", - "GIT_AUTHOR_DATE": NOW, - "GIT_COMMITTER_DATE": NOW, - "PYTHONPATH": str(Path(__file__).resolve().parent.parent), - } - - def git(self, *args: str, cwd: Path | None = None, date: str = NOW) -> str: - env = {**self.env, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} - return subprocess.run( - ["git", "-C", str(cwd or self.repo), *args], - capture_output=True, - text=True, - check=True, - env=env, - ).stdout.strip() - - def init(self, *extra: str) -> None: - self.repo.mkdir(exist_ok=True) - self.git("init", "-q", "-b", "main", *extra) - - def commit(self, message: str, cwd: Path | None = None, date: str = NOW) -> str: - self.git("commit", "-q", "--allow-empty", "-m", message, cwd=cwd, date=date) - return self.git("rev-parse", "HEAD", cwd=cwd) - - def loch( - self, - impl: str, - *args: str, - stdin: Any = None, - env: dict[str, str] | None = None, - cwd: Path | None = None, - ) -> Run: - data = ( - stdin - if isinstance(stdin, bytes) - else b"" - if stdin is None - else json.dumps(stdin).encode() - ) - result = subprocess.run( - [*implementation(impl), *args], - input=data, - capture_output=True, - env={**self.env, **(env or {})}, - cwd=str(cwd or self.root), - ) - return Run(result.stdout, result.stderr, result.returncode) - - def event(self, call: str | None = "toolu_1", **fields: Any) -> dict[str, Any]: - body: dict[str, Any] = { - "session_id": SESSION, - "cwd": str(self.repo), - "tool_name": "Bash", - "tool_input": {"command": "git commit -m work"}, - } - if call is not None: - body["tool_use_id"] = call - body.update(fields) - return body - - def observe(self) -> dict[str, Any]: - """Everything a hook can leave behind, in a form two runs can be - compared on. The one nondeterministic value — the pending state's - timestamp — is reduced to its type.""" - seen: dict[str, Any] = {} - for path in sorted(self.root.rglob("*")): - relative = path.relative_to(self.root).as_posix() - if "/.git/objects/" in f"/{relative}" or relative.startswith("home/.loch/"): - continue - if "/loch/pending/" in relative and path.is_file(): - try: - state = json.loads(path.read_text()) - except ValueError: - state = path.read_text() - seen[relative] = ( - {"head": state.get("head"), "at": type(state.get("at")).__name__} - if isinstance(state, dict) - else state - ) - elif path.is_file() and ( - relative.startswith("store/") or relative.endswith("/NOTES_EDITMSG") - ): - seen[relative] = hashlib.sha256(path.read_bytes()).hexdigest() - elif path.is_dir() and "/loch" in relative: - seen[relative] = "dir" - for repo in {self.repo, *self.root.glob("wt*")}: - if (repo / ".git").exists(): - seen[f"notes:{repo.name}"] = subprocess.run( - [ - "git", - "-C", - str(repo), - "rev-parse", - "-q", - "--verify", - "refs/notes/loch", - ], - capture_output=True, - text=True, - env=self.env, - ).stdout.strip() - return seen - - -Scenario = Callable[[World, Callable[..., Run]], list[Run]] - - -def twin( - tmp_path: Path, scenario: Scenario, mix: tuple[str, str] | None = None -) -> dict[str, Any]: - """Runs `scenario` once per implementation in identical worlds at the same - path, and asserts nothing observable differs. With `mix`, the second run - alternates implementations call by call — pre under one, post under the - other — which is what a machine switching over mid-session does.""" - root = tmp_path / "world" - outcomes = [] - plans: list[tuple[str, ...]] = [("py",), ("rs",)] if mix is None else [("py",), mix] - for plan in plans: - if root.exists(): - shutil.rmtree(root) - world = World(root) - calls = iter(range(10_000)) - - def loch( - *args: str, _w: World = world, _p: tuple[str, ...] = plan, **kw: Any - ) -> Run: - return _w.loch(_p[next(calls) % len(_p)], *args, **kw) - - runs = scenario(world, loch) - outcomes.append(([vars(run) for run in runs], world.observe())) - (py_runs, py_seen), (rs_runs, rs_seen) = outcomes - assert rs_runs == py_runs - assert rs_seen == py_seen - return py_seen - # -- scenarios ---------------------------------------------------------------- @@ -717,7 +533,7 @@ def scenario( mismatched.append(session) continue # Agreeing that nothing happened would pass vacuously. - unnoted += not seen["notes:repo"] + unnoted += not seen["repo:refs/notes/loch"] assert not unnoted, f"{unnoted}/{len(cases)} cases wrote no note" assert not mismatched, ( f"{len(mismatched)}/{len(cases)} sessions differ: {mismatched}" diff --git a/test/test_equivalence_commands.py b/test/test_equivalence_commands.py new file mode 100644 index 0000000..2f0eca3 --- /dev/null +++ b/test/test_equivalence_commands.py @@ -0,0 +1,762 @@ +"""Every command but `hook` in the Rust build against the Python reference. + +Opt-in with LOCH_RUST, like test_equivalence.py; the machinery is in +equivalence.py. Each scenario runs its commands in both renderings where the +two differ, since prose and payload are built separately and either can drift. +""" + +import gzip +import json +import os +import re +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pytest +from equivalence import MTIME, PAST, RUST, SESSION, Run, Scenario, World, twin + +pytestmark = pytest.mark.skipif(not RUST, reason="set LOCH_RUST to a Rust build") + +Loch = Callable[..., Run] + +OTHER = "22222222-3333-4444-5555-666666666666" +THIRD = "33333333-4444-5555-6666-777777777777" +SECRET = "ghp_" + "a1B2c3D4e5" * 4 + + +def both(loch: Loch, *args: str, **kw: Any) -> list[Run]: + """A command in text mode and in JSON mode.""" + return [loch(*args, **kw), loch(*args, "--json", **kw)] + + +def user(cwd: str, text: Any, branch: str | None = "main", **extra: Any) -> dict: + record: dict[str, Any] = { + "type": "user", + "uuid": extra.pop("uuid", "u1"), + "parentUuid": extra.pop("parent", None), + "sessionId": extra.pop("session", SESSION), + "cwd": cwd, + "version": "2.1.0", + "timestamp": "2026-01-01T00:00:00.000Z", + "message": {"role": "user", "content": text}, + } + if branch is not None: + record["gitBranch"] = branch + record.update(extra) + return record + + +def assistant( + cwd: str, blocks: list[Any], uuid: str, parent: str, **extra: Any +) -> dict: + record = { + "type": "assistant", + "uuid": uuid, + "parentUuid": parent, + "sessionId": extra.pop("session", SESSION), + "cwd": cwd, + "gitBranch": extra.pop("branch", "main"), + "version": "2.1.0", + "timestamp": extra.pop("timestamp", "2026-01-01T00:00:05.000Z"), + "message": { + "id": "msg_1", + "model": "claude-x", + "role": "assistant", + "content": blocks, + }, + } + record.update(extra) + return record + + +def project(w: World) -> str: + path = w.root / "proj" + path.mkdir(exist_ok=True) + return str(path) + + +def rich_sessions(w: World) -> str: + """Sessions with what list, save and ingest each have to get right: a + secret, odd whitespace, a non-ASCII summary, two branches, a session that + moved directories, a lone surrogate escape and a line that isn't JSON.""" + cwd = project(w) + w.session( + cwd, + SESSION, + [ + user(cwd, f"deploy with {SECRET}\tand
then é 😀", uuid="a1"), + assistant( + cwd, [{"type": "text", "text": f"ok {cwd}/src and ~"}], "a2", "a1" + ), + "not json {", + {"type": "ai-title", "aiTitle": "Deploying"}, + user( + cwd, + [{"type": "tool_result", "tool_use_id": "t1", "content": "done"}], + uuid="a3", + parent="a2", + ), + ], + ) + w.session( + cwd, + OTHER, + [ + user( + f"{cwd}-old", "before the move", branch="old", uuid="b1", session=OTHER + ), + user( + cwd, + [{"type": "text", "text": "after \\ud83d the move"}], + branch="feature/x", + uuid="b2", + parent="b1", + session=OTHER, + ), + '{"type": "user", "uuid": "b3", "parentUuid": "b2", "cwd": "' + + cwd + + '", "message": {"content": "lone \\ud83d"}}', + { + "type": "system", + "subtype": "turn_duration", + "uuid": "b4", + "parentUuid": "b3", + "cwd": cwd, + "durationMs": 5, + }, + {"type": "custom-title", "customTitle": "Moved"}, + ], + ) + w.session( + cwd, THIRD, [user(cwd, "no branch here", branch=None, uuid="c1", session=THIRD)] + ) + return cwd + + +# -- help, version, usage ------------------------------------------------------- + +COMMANDS = [ + "list", + "save", + "restore", + "delete", + "reindex", + "ingest", + "install", + "blame", + "log", + "ask", + "backfill", +] + +BAD_ARGUMENTS = [ + ["-h"], + ["--help"], + ["--bogus"], + ["--cwd"], + ["--store"], + ["--s", "x"], + ["--st=x"], + ["--json=1"], + ["--force=yes"], + ["-x"], + ["-hx"], + ["--", "-h"], + ["a", "b", "c"], + ["-5"], + ["--into", "-5"], +] + + +def usage(w: World, loch: Loch) -> list[Run]: + runs = [] + for command in COMMANDS: + for argv in BAD_ARGUMENTS: + runs += both(loch, command, *argv) + return runs + + +def usage_narrow(w: World, loch: Loch) -> list[Run]: + """Usage lines wrap at the terminal width, which COLUMNS sets.""" + runs = [] + for columns in ("40", "60", "12"): + for command in COMMANDS: + runs.append(loch(command, "-h", env={"COLUMNS": columns})) + runs.append(loch(command, "--bogus", env={"COLUMNS": columns})) + return runs + + +def top_level(w: World, loch: Loch) -> list[Run]: + return [ + *both(loch), + *both(loch, "help"), + *both(loch, "--help"), + *both(loch, "-h"), + *both(loch, "--version"), + *both(loch, "-V"), + *both(loch, "version"), + *both(loch, "nonsense"), + loch("--json"), + loch("--json", "--json"), + loch("list", "--json", "--json", "--cwd", project(w)), + ] + + +# -- list ----------------------------------------------------------------------- + + +def listing(w: World, loch: Loch) -> list[Run]: + cwd = rich_sessions(w) + (w.root / "empty").mkdir() + return [ + *both(loch, "list", "--cwd", cwd), + *both(loch, "list", "--cwd", cwd, "--branch", "main"), + *both(loch, "list", "--cwd", cwd, "--branch", "feature/x"), + *both(loch, "list", "--cwd", cwd, "--branch", "none-such"), + *both(loch, "list", "--cwd", str(w.root / "empty")), + *both(loch, "list", "--cwd", str(w.root / "missing")), + *both(loch, "list", cwd=Path(cwd)), + *both( + loch, + "list", + "--cwd", + cwd, + env={"CLAUDE_CONFIG_DIR": str(w.root / "other-config")}, + ), + ] + + +def listing_via_symlink(w: World, loch: Loch) -> list[Run]: + cwd = rich_sessions(w) + os.symlink(cwd, w.root / "link") + return both(loch, "list", "--cwd", str(w.root / "link")) + + +def listing_config_dir(w: World, loch: Loch) -> list[Run]: + cwd = project(w) + config = w.root / "work-account" + folder = config / "projects" / re.sub(r"[^a-zA-Z0-9]", "-", cwd) + folder.mkdir(parents=True) + (folder / f"{SESSION}.jsonl").write_text( + json.dumps(user(cwd, "in another account")) + "\n" + ) + os.utime(folder / f"{SESSION}.jsonl", (MTIME, MTIME)) + return both(loch, "list", "--cwd", cwd, env={"CLAUDE_CONFIG_DIR": str(config)}) + + +def listing_bad_bytes(w: World, loch: Loch) -> list[Run]: + cwd = project(w) + w.session(cwd, SESSION, [user(cwd, "fine")], raw=b'{"type": "user", "x": "\xff"}\n') + return [ + *both(loch, "list", "--cwd", cwd), + *both(loch, "save", "--cwd", cwd), + ] + + +# -- save, list --remote, restore, delete, reindex -------------------------------------- + + +def save_and_list_remote(w: World, loch: Loch) -> list[Run]: + cwd = rich_sessions(w) + runs = [ + *both(loch, "save", "--cwd", cwd), + loch("save", "--cwd", cwd, "--branch", "feature/x", "--json"), + loch("save", "--cwd", cwd, "--session", THIRD), + *both(loch, "save", "--cwd", cwd, "--branch", "none-such"), + *both(loch, "save", "--cwd", str(w.root / "missing")), + loch("save", "--cwd", cwd, "--store", "relative-store", "--json", cwd=w.root), + loch("save", "--cwd", cwd, "--store", f"file://{w.root}/uri%20store"), + ] + os.makedirs(w.repo, exist_ok=True) + w.init() + w.commit("first") + w.git("checkout", "-q", "-b", "feature/x") + for args in ( + ["--remote"], + ["--remote", "--cwd", str(w.repo)], + ["--remote", "--branch", "main"], + ["--remote", "--branch", "none-such"], + ["--all"], + ["--store", str(w.store), "--branch", "feature/x"], + ["--remote", "--store", str(w.root / "nowhere")], + ): + runs += both(loch, "list", *args, cwd=w.repo) + runs += both(loch, "list", "--remote", "--cwd", str(w.root)) + return runs + + +def bundle_ref(w: World) -> str: + bundles = sorted((w.store / "bundles").glob("*.loch")) + return bundles[0].stem + + +def restore(w: World, loch: Loch) -> list[Run]: + cwd = rich_sessions(w) + runs = [loch("save", "--cwd", cwd)] + ref = bundle_ref(w) + target = w.root / "elsewhere" + target.mkdir() + runs += [ + *both(loch, "restore", ref, "--into", str(target)), + # Everything is there now: skipped, so nothing restored. + *both(loch, "restore", ref, "--into", str(target)), + *both(loch, "restore", ref, "--into", str(target), "--force"), + *both(loch, "restore", ref, "--into", str(target), "--new-id"), + *both(loch, "restore"), + *both(loch, "restore", "0" * 64), + *both(loch, "restore", ref, "--store", str(w.root / "nowhere")), + ] + # Another machine: a different home, so the home pair rewrites too. + other_home = w.root / "other-home" + other_home.mkdir() + runs += both( + loch, + "restore", + ref, + "--into", + str(target), + "--force", + env={"HOME": str(other_home)}, + ) + return runs + + +def restore_unreadable(w: World, loch: Loch) -> list[Run]: + bundles = w.store / "bundles" + bundles.mkdir(parents=True) + (bundles / f"{'a' * 64}.loch").write_bytes(b"garbage") + (bundles / f"{'b' * 64}.loch").write_bytes(b"") + (bundles / f"{'c' * 64}.loch").write_bytes( + gzip.compress(json.dumps({"version": 2}).encode(), mtime=0) + ) + (bundles / f"{'d' * 64}.loch").write_bytes( + gzip.compress(json.dumps({"version": "1"}).encode(), mtime=0) + ) + runs = [] + for letter in "abcd": + runs += both(loch, "restore", letter * 64) + return runs + + +def delete_and_reindex(w: World, loch: Loch) -> list[Run]: + cwd = rich_sessions(w) + runs = [loch("save", "--cwd", cwd), loch("save", "--cwd", cwd, "--branch", "main")] + refs = sorted(p.stem for p in (w.store / "bundles").glob("*.loch")) + stale = w.store / "index" / "branch" / "gone" / ("f" * 64) + stale.parent.mkdir(parents=True) + stale.write_text("{}") + (w.store / "bundles" / "notes.txt").write_text("not a bundle") + runs += [ + *both(loch, "reindex"), + *both(loch, "reindex"), + *both(loch, "delete", refs[0]), + *both(loch, "delete", refs[0]), + *both(loch, "delete"), + *both(loch, "list", "--all"), + *both(loch, "reindex", "--store", str(w.root / "empty-store")), + ] + return runs + + +# -- ingest ---------------------------------------------------------------------- + + +def ingest(w: World, loch: Loch) -> list[Run]: + cwd = rich_sessions(w) + key = w.root / "id_ed25519.pub" + key.write_text( + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGq7k5Pi0VGa1sYhVPLvlXHjjhVQrDsWlvS4sUVJmPB0 me\n" + ) + bad = w.root / "bad.pub" + bad.write_text("ssh-ed25519 not*base64\n") + one = w.root / "one.pub" + one.write_text("just-one-field\n") + padding = w.root / "padding.pub" + padding.write_text("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5\n") + sidecar = w.projects() / re.sub(r"[^a-zA-Z0-9]", "-", cwd) / SESSION / "subagents" + sidecar.mkdir(parents=True) + (sidecar / "agent-1.jsonl").write_text('{"type": "user"}\n') + return [ + *both(loch, "ingest", "--cwd", cwd), + *both( + loch, + "ingest", + "--cwd", + cwd, + "--out", + str(w.root / "out"), + "--author", + "me@example.com", + ), + *both( + loch, + "ingest", + "--cwd", + cwd, + "--out", + str(w.root / "keyed"), + "--author-key", + str(key), + ), + *both(loch, "ingest", "--cwd", cwd, "--author-key", str(bad)), + *both(loch, "ingest", "--cwd", cwd, "--author-key", str(one)), + *both(loch, "ingest", "--cwd", cwd, "--author-key", str(padding)), + *both( + loch, "ingest", "--cwd", cwd, "--author-key", str(w.root / "missing.pub") + ), + *both(loch, "ingest", "--cwd", cwd, "--author", "x", "--author-key", str(key)), + *both( + loch, + "ingest", + "--cwd", + cwd, + "--session", + OTHER, + "--out", + str(w.root / "one"), + ), + *both(loch, "ingest", "--cwd", str(w.root / "missing")), + ] + + +def ingest_graph(w: World, loch: Loch) -> list[Run]: + """The converter's harder cases: a rewind that leaves a branch, a + resubmitted identical turn, a compaction boundary, a dangling parent, + records out of file order, a cycle, and every block type.""" + cwd = project(w) + blocks = [ + {"type": "thinking", "thinking": "hm", "signature": "sig"}, + {"type": "redacted_thinking", "data": "x"}, + { + "type": "tool_use", + "id": "t1", + "name": "Bash", + "input": {"command": f"ls {cwd}"}, + }, + {"type": "image", "source": {"type": "base64", "data": "AAAA"}}, + {"type": "server_tool_use", "id": "s1"}, + "a bare string", + {"type": "text", "text": "literal {{loch:root}} placeholder"}, + ] + records = [ + user(cwd, "start", uuid="r1"), + assistant(cwd, blocks, "r2", "r1"), + user( + cwd, + [ + { + "type": "tool_result", + "tool_use_id": "t1", + "content": [{"type": "text", "text": f"{cwd}/a"}], + "is_error": True, + } + ], + uuid="r3", + parent="r2", + ), + user(cwd, "branch A", uuid="r4", parent="r3"), + user(cwd, "branch B", uuid="r5", parent="r3"), + user(cwd, "branch A", uuid="r6", parent="r3"), + { + "type": "system", + "subtype": "compact_boundary", + "uuid": "r7", + "parentUuid": None, + "logicalParentUuid": "r5", + "cwd": cwd, + "content": "compacted", + }, + user(cwd, "summary", uuid="r8", parent="r7", isCompactSummary=True), + user(cwd, "orphan", uuid="r9", parent="never-seen"), + user(cwd, "child before parent", uuid="r10", parent="r11"), + user(cwd, "parent after child", uuid="r11", parent="r8"), + user(cwd, "cycle one", uuid="r12", parent="r13"), + user(cwd, "cycle two", uuid="r13", parent="r12"), + { + "type": "attachment", + "uuid": "r14", + "parentUuid": "r11", + "cwd": cwd, + "attachment": {"path": f"{cwd}/f", "keyed": {f"{cwd}/k": 1}}, + }, + { + "type": "system", + "subtype": "api_error", + "uuid": "r15", + "parentUuid": "r14", + "cwd": cwd, + "timestamp": "t", + }, + { + "type": "system", + "subtype": "stray", + "uuid": "r16", + "parentUuid": "nowhere", + "cwd": cwd, + }, + user(cwd, "meta", uuid="r17", parent="r15", isMeta=True), + {"type": "last-prompt", "leafUuid": "r4"}, + {"type": "user", "uuid": 5, "message": {"content": "non-string uuid"}}, + { + "type": "user", + "uuid": "r18", + "parentUuid": "r17", + "cwd": cwd, + "message": { + "content": [ + {"type": "text", "text": 1.5e300}, + {"type": "text", "text": 123456789012345678901234567890}, + ] + }, + }, + ] + w.session(cwd, SESSION, records) + return both(loch, "ingest", "--cwd", cwd, "--out", str(w.root / "derived")) + + +def ingest_from_home(w: World, loch: Loch) -> list[Run]: + """A session run from the home directory itself is a root, not a home.""" + cwd = str(w.home) + w.session(cwd, SESSION, [user(cwd, f"in {cwd}/x")]) + return both(loch, "ingest", "--cwd", cwd, "--out", str(w.root / "derived")) + + +# -- install ------------------------------------------------------------------------- + + +def install(w: World, loch: Loch) -> list[Run]: + w.init() + w.commit("first") + settings = w.repo / ".claude" + settings.mkdir() + (settings / "settings.json").write_text( + json.dumps( + {"model": "x", "n": 1.50, "é": "ü", "hooks": {"Stop": [{"hooks": []}]}} + ) + ) + return [ + *both(loch, "install", cwd=w.repo), + *both(loch, "install", cwd=w.repo), + *both(loch, "install", "--local", cwd=w.repo), + loch("install", "--command", "/opt/loch", "--cwd", str(w.repo)), + *both(loch, "install", cwd=w.root), + ] + + +# -- blame, log, ask, backfill ------------------------------------------------------ + + +def traced_repo(w: World) -> dict[str, str]: + """A repository whose commits link to a real-shaped transcript: two + requests in one session, one commit each, plus one unlinked commit and an + uncommitted edit.""" + w.init() + repo = str(w.repo) + base = w.commit_file("app.py", "one\ntwo\nthree\n", "unlinked start", date=PAST) + first = w.commit_file( + "app.py", "one\nTWO\nthree\nfour\n", "agent: two", date="2026-01-01T00:00:12Z" + ) + second = w.commit_file( + "app.py", + "one\nTWO\nthree\nfour\nfive\n", + "agent: five", + date="2026-01-01T00:01:12Z", + ) + w.commit_file("other.txt", "x\n", "agent: other", date="2026-01-01T00:02:12Z") + (w.repo / "app.py").write_text("one\nTWO\nthree\nfour\nfive\nsix\n") + records = [ + user(repo, "please change two “quote”", uuid="q1"), + assistant( + repo, + [ + { + "type": "tool_use", + "id": "toolu_a", + "name": "Bash", + "input": {"command": "git commit -m 'agent: two'"}, + } + ], + "q2", + "q1", + timestamp="2026-01-01T00:00:10.000Z", + ), + user( + repo, + [{"type": "tool_result", "tool_use_id": "toolu_a", "content": "ok"}], + uuid="q3", + parent="q2", + timestamp="2026-01-01T00:00:14.000Z", + ), + user(repo, "ignored", uuid="q4", parent="q3"), + user(repo, "now add five", uuid="q5", parent="q4"), + assistant( + repo, + [ + { + "type": "tool_use", + "id": "toolu_b", + "name": "Bash", + "input": {"command": "git commit -m 'agent: five'"}, + }, + { + "type": "tool_use", + "id": "toolu_c", + "name": "Bash", + "input": {"command": "git commit -m 'agent: other'"}, + }, + ], + "q6", + "q5", + timestamp="2026-01-01T00:01:10.000Z", + ), + user( + repo, + [{"type": "tool_result", "tool_use_id": "toolu_b", "content": "ok"}], + uuid="q7", + parent="q6", + timestamp="2026-01-01T00:01:14.000Z", + ), + user( + repo, + [{"type": "tool_result", "tool_use_id": "toolu_c", "content": "ok"}], + uuid="q8", + parent="q7", + timestamp="2026-01-01T00:02:14.000Z", + ), + {"type": "ai-title", "aiTitle": "Edit app"}, + { + "type": "user", + "uuid": "q9", + "parentUuid": "q8", + "cwd": repo, + "costs": [1e-05, 1e16, 0.5, 1e22, -0.0], + "message": {"content": "floats"}, + }, + ] + w.session(repo, SESSION, records) + return {"base": base, "first": first, "second": second} + + +def blame_and_log(w: World, loch: Loch) -> list[Run]: + commits = traced_repo(w) + w.note(commits["first"], SESSION, "toolu_a") + w.note(commits["second"], SESSION, "toolu_b") + w.note(commits["base"], "99999999-0000-0000-0000-000000000000", "toolu_gone") + runs = [] + for args in ( + ["blame", "app.py"], + ["blame", "other.txt"], + ["blame", "missing.py"], + ["blame", "app.py", "--html", str(w.root / "page.html"), "--no-open"], + ["blame", "app.py", "--html", "--no-open"], + [ + "blame", + "app.py", + "--html", + str(w.root / "lines.html"), + "--lines", + "1-2, 5", + "--no-open", + ], + [ + "blame", + "app.py", + "--html", + str(w.root / "bad.html"), + "--lines", + "x-1", + "--no-open", + ], + ["log", "app.py"], + ["log", "app.py:2"], + ["log", "app.py:2-4"], + ["log", "app.py:9"], + ["log", "app.py:0"], + ["log", "app.py:3-2"], + ["log", "app.py:x"], + ["log", "nope"], + ["log", "other.txt"], + ): + runs += both(loch, *args, cwd=w.repo) + runs += both(loch, "blame", str(w.root / "outside.txt"), cwd=w.root) + return runs + + +def ask(w: World, loch: Loch) -> list[Run]: + commits = traced_repo(w) + w.note(commits["first"], SESSION, "toolu_a") + w.note(commits["second"], SESSION, "toolu_b") + w.note(commits["base"], "99999999-0000-0000-0000-000000000000", "toolu_gone") + runs = [] + for args in ( + ["ask", commits["first"], "--no-launch"], + ["ask", "app.py:5", "why five?", "--no-launch", "--at-commit"], + ["ask", "app.py:2", "--at-commit", "--no-launch"], + ["ask", "app.py:6", "--no-launch"], + ["ask", "app.py:1", "--no-launch"], + ["ask", "app.py:99", "--no-launch"], + ["ask", "HEAD~3", "--no-launch"], + ["ask", "nonsense-rev", "--no-launch"], + ["ask", commits["first"], "--json"], + ): + runs += both(loch, *args, cwd=w.repo) + return runs + + +def ask_from_store(w: World, loch: Loch) -> list[Run]: + """A transcript Claude has deleted is found in the store's snapshot.""" + commits = traced_repo(w) + w.note(commits["second"], SESSION, "toolu_b") + transcript = next(w.projects().glob(f"*/{SESSION}.jsonl")) + runs = [ + loch( + "hook", + "stop", + stdin={"session_id": SESSION, "transcript_path": str(transcript)}, + ) + ] + transcript.unlink() + runs += both(loch, "ask", "app.py:5", "--no-launch", cwd=w.repo) + runs += both(loch, "blame", "app.py", cwd=w.repo) + return runs + + +def backfill(w: World, loch: Loch) -> list[Run]: + traced_repo(w) + w.git("checkout", "-q", "-b", "side") + # Two calls in different sessions bracket this one: ambiguous, so unlinked. + w.commit_file("x.txt", "x\n", "agent: two", date="2026-01-01T00:00:12Z") + runs = both(loch, "backfill", cwd=w.repo) + runs += both(loch, "backfill", "--revision", "main", cwd=w.repo) + runs += both(loch, "backfill", "--revision", "no-such-rev", cwd=w.repo) + runs += both(loch, "backfill", "--cwd", str(w.root)) + return runs + + +SCENARIOS: list[Scenario] = [ + usage, + usage_narrow, + top_level, + listing, + listing_via_symlink, + listing_config_dir, + listing_bad_bytes, + save_and_list_remote, + restore, + restore_unreadable, + delete_and_reindex, + ingest, + ingest_graph, + ingest_from_home, + install, + blame_and_log, + ask, + ask_from_store, + backfill, +] + + +@pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda s: s.__name__) +def test_command_matches_python(tmp_path: Path, scenario: Scenario) -> None: + twin(tmp_path, scenario) From 441f77853021bf76ab2bf22f0457007a1f9d3aee Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 19:11:25 -0500 Subject: [PATCH 10/18] Linear-time redaction in the Rust build, and a corpus check for every command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Redaction was most of save's cost in both builds — 150s in Python and 264s in Rust over 15 project directories — because a backtracking engine tries every rule at every position and env-assignment can start at any capital. The Rust build now searches the nine prefixed rules with the regex crate (boundary checks by hand) and tries env-assignment only at the start of each capital run holding a keyword, which is the only place it can match; 15s. The full Python alternation stays as a test oracle, fuzzed against the fast path over 40k generated strings that exercise every rule. test_equivalence_corpus.py lists, saves, restores onto a temporary home and ingests every project directory on the machine with both builds, read-only towards ~/.claude, reporting only offsets and hashes. Co-Authored-By: Claude Opus 5.5 --- rust/Cargo.lock | 13 + rust/Cargo.toml | 3 + rust/src/redact.rs | 421 +++++++++++++++++++++++++------- test/equivalence.py | 28 ++- test/test_equivalence_corpus.py | 104 ++++++++ 5 files changed, 477 insertions(+), 92 deletions(-) create mode 100644 test/test_equivalence_corpus.py diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 6cf0381..26abf2f 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -334,6 +334,7 @@ dependencies = [ "indexmap", "libc", "libz-sys", + "regex", "sha2", "ureq", ] @@ -395,6 +396,18 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + [[package]] name = "regex-automata" version = "0.4.18" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 3850cb9..bb47998 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -18,6 +18,9 @@ indexmap = "2" # Python's `re` has lookarounds, which the `regex` crate deliberately lacks; # fancy-regex adds them and hands everything else to `regex`. fancy-regex = "0.14" +# Linear-time search for the redaction rules once their lookarounds are +# checked by hand; see redact.rs. +regex = "1" # zlib itself, built from source and linked statically: the ref is a hash of # the gzip bytes, and only zlib's own deflate reproduces zlib's output. # miniz_oxide (flate2's default) compresses differently. diff --git a/rust/src/redact.rs b/rust/src/redact.rs index 3eef372..e4b3cfb 100644 --- a/rust/src/redact.rs +++ b/rust/src/redact.rs @@ -2,21 +2,81 @@ //! and nothing more. The patterns are the Python ones with one translation: //! Python's `\s` (`str.isspace`, which includes U+001C..U+001F) is spelled out, //! since the `regex` crate's `\s` is Unicode White_Space and differs from it. -//! fancy-regex supplies the lookarounds; it backtracks like Python's `re`, so -//! leftmost-first alternation picks the same rule at the same place. +//! +//! Python runs one alternation of every rule, and a backtracking engine tries +//! every rule at every position — `env-assignment` can start at any capital, +//! which is most of the cost of `save`. The answer is the same if the search +//! is restructured, so it is: +//! +//! - the nine prefixed rules have no lookaround once their one-character +//! boundary checks (START before, END after a fixed-length body) are made +//! by hand, so each is searched by the `regex` crate in linear time, whose +//! leftmost-first semantics are a backtracking engine's; +//! - `env-assignment` is tried, anchored, only at the start of a run of +//! `[A-Z0-9_]` holding a keyword. Every way it can match from a later +//! position in the run is also a way from the run's start, so failing there +//! means failing anywhere in the run, and the run's start is the only +//! candidate; +//! - the next match overall is the earliest position any rule matches at, +//! ties going to rule order, scanning resumed after each match — which is +//! what the one alternation means. +//! +//! The whole Python alternation is kept, under test, as the oracle the fast +//! path is fuzzed against. use crate::py::SPACE_CLASS; -use fancy_regex::{Regex, RegexBuilder}; use indexmap::IndexMap; +use regex::Regex; use std::sync::OnceLock; -const START: &str = r"(? Vec<(&'static str, String)> { - let env_assignment = format!( +const NAMES: [&str; 10] = [ + "aws-access-key", + "github-token", + "slack-token", + "stripe-key", + "anthropic-key", + "openai-key", + "google-api-key", + "private-key-block", + "jwt", + "env-assignment", +]; + +const ENV: usize = 9; + +/// (body, needs START before, needs END after) for the nine prefixed rules. +/// START is `(? [(&'static str, bool, bool); 9] { + [ + (r"(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}", true, true), + (r"gh[pousr]_[A-Za-z0-9]{36,}", true, false), + (r"xox[abprs]-[A-Za-z0-9-]{10,}", true, false), + (r"sk_live_[A-Za-z0-9]{24,}", true, false), + (r"sk-ant-[A-Za-z0-9_-]{20,}", true, false), + (r"sk-(?:proj-)?[A-Za-z0-9_-]{20,}", true, false), + (r"AIza[0-9A-Za-z_-]{35}", true, true), + // The body excludes the double quote so a BEGIN and an END in two + // different JSONL records can't be joined into one match. + ( + r#"-----BEGIN [A-Z ]*PRIVATE KEY-----[^"]*?-----END [A-Z ]*PRIVATE KEY-----"#, + false, + false, + ), + ( + r"eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", + true, + false, + ), + ] +} + +/// The value of a named assignment is the only way to find a credential with +/// no distinctive prefix. The lookaheads keep it off filesystem paths and off +/// a token this module already wrote. +fn env_assignment() -> String { + format!( concat!( r"(?P", r"[A-Z0-9_]*", @@ -27,73 +87,136 @@ fn rules() -> Vec<(&'static str, String)> { r#"(?!\[REDACTED:)(?![/~.])[^{s}"',;\\]{{8,}}"# ), s = SPACE_CLASS - ); - vec![ - ( - "aws-access-key", - format!(r"{START}(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{{16}}{END}"), - ), - ( - "github-token", - format!(r"{START}gh[pousr]_[A-Za-z0-9]{{36,}}"), - ), - ( - "slack-token", - format!(r"{START}xox[abprs]-[A-Za-z0-9-]{{10,}}"), - ), - ("stripe-key", format!(r"{START}sk_live_[A-Za-z0-9]{{24,}}")), - ( - "anthropic-key", - format!(r"{START}sk-ant-[A-Za-z0-9_-]{{20,}}"), - ), - ( - "openai-key", - format!(r"{START}sk-(?:proj-)?[A-Za-z0-9_-]{{20,}}"), - ), - ( - "google-api-key", - format!(r"{START}AIza[0-9A-Za-z_-]{{35}}{END}"), - ), - // The body excludes the double quote so a BEGIN and an END in two - // different JSONL records can't be joined into one match. - ( - "private-key-block", - r#"-----BEGIN [A-Z ]*PRIVATE KEY-----[^"]*?-----END [A-Z ]*PRIVATE KEY-----"#.into(), - ), - ( - "jwt", - format!(r"{START}eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"), - ), - ("env-assignment", env_assignment), - ] + ) } -struct Compiled { - regex: Regex, - names: Vec<&'static str>, +struct Engine { + rules: Vec<(Regex, bool, bool)>, + keyword: Regex, + env: fancy_regex::Regex, } -fn compiled() -> &'static Compiled { - static COMPILED: OnceLock = OnceLock::new(); - COMPILED.get_or_init(|| { - let rules = rules(); - let pattern = rules +fn engine() -> &'static Engine { + static ENGINE: OnceLock = OnceLock::new(); + ENGINE.get_or_init(|| Engine { + rules: prefixed() .iter() - .map(|(name, pattern)| format!("(?P<{}>{})", name.replace('-', "_"), pattern)) - .collect::>() - .join("|"); - Compiled { - // Python's `re` has no backtracking limit; a high one keeps a - // pathological transcript slow rather than failing it. - regex: RegexBuilder::new(&pattern) - .backtrack_limit(usize::MAX / 2) - .build() - .expect("the redaction rules compile"), - names: rules.iter().map(|(name, _)| *name).collect(), - } + .map(|(body, start, end)| (Regex::new(body).expect("rule compiles"), *start, *end)) + .collect(), + // Every keyword of the alternation contains one of these. + keyword: Regex::new("SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY").expect("compiles"), + env: fancy_regex::RegexBuilder::new(&format!("^(?:{})", env_assignment())) + .backtrack_limit(usize::MAX / 2) + .build() + .expect("env-assignment compiles"), }) } +fn word(c: char) -> bool { + c.is_ascii_alphanumeric() || c == '_' || c == '-' +} + +fn run_char(b: u8) -> bool { + b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_' +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Found { + start: usize, + end: usize, + /// End of `env_assignment_keep`, for the one rule that keeps a prefix. + keep: usize, +} + +impl Engine { + /// The first match of rule `index` starting at or after `from`. + fn next(&self, text: &str, index: usize, from: usize) -> Option { + if index == ENV { + return self.next_env(text, from); + } + let (regex, start_guard, end_guard) = &self.rules[index]; + let mut at = from; + while at <= text.len() { + let found = regex.find_at(text, at)?; + let before = text[..found.start()].chars().next_back(); + let after = text[found.end()..].chars().next(); + let start_ok = !*start_guard || !before.is_some_and(word); + let end_ok = !*end_guard || !after.is_some_and(word); + if start_ok && end_ok { + return Some(Found { + start: found.start(), + end: found.end(), + keep: found.start(), + }); + } + // Python's engine moves on one position, not past the match. + at = found.start() + + text[found.start()..] + .chars() + .next() + .map_or(1, char::len_utf8); + } + None + } + + fn next_env(&self, text: &str, from: usize) -> Option { + let bytes = text.as_bytes(); + let mut at = from; + loop { + let keyword = self.keyword.find_at(text, at)?; + let mut start = keyword.start(); + while start > from && run_char(bytes[start - 1]) { + start -= 1; + } + if let Ok(Some(captures)) = self.env.captures(&text[start..]) { + let whole = captures.get(0).expect("group 0"); + let keep = captures.name("env_assignment_keep").expect("keep group"); + return Some(Found { + start, + end: start + whole.end(), + keep: start + keep.end(), + }); + } + // Failing at a run's start is failing everywhere in it. + let mut end = keyword.end(); + while end < bytes.len() && run_char(bytes[end]) { + end += 1; + } + at = end; + } + } + + /// Every match, as the one alternation's `finditer` would report them. + fn matches(&self, text: &str) -> Vec<(usize, Found)> { + let mut cached: [Option>; 10] = [None; 10]; + let mut out = Vec::new(); + let mut cursor = 0; + loop { + let mut best: Option<(usize, Found)> = None; + for (index, slot) in cached.iter_mut().enumerate() { + let stale = match slot { + None => true, + Some(Some(found)) => found.start < cursor, + Some(None) => false, + }; + if stale { + *slot = Some(self.next(text, index, cursor)); + } + if let Some(Some(found)) = slot { + if best.is_none_or(|(_, b)| found.start < b.start) { + best = Some((index, *found)); + } + } + } + let Some((index, found)) = best else { + return out; + }; + out.push((index, found)); + cursor = found.end; + } + } +} + #[derive(Debug)] pub struct RedactionError(pub String); @@ -103,41 +226,25 @@ pub struct Redaction { pub counts: IndexMap, } -fn matched_rule(captures: &fancy_regex::Captures, names: &[&'static str]) -> &'static str { - names - .iter() - .find(|name| captures.name(&name.replace('-', "_")).is_some()) - .expect("a match belongs to a rule") -} - pub fn scan(text: &str) -> IndexMap { - let compiled = compiled(); let mut counts = IndexMap::new(); - for captures in compiled.regex.captures_iter(text).flatten() { - *counts - .entry(matched_rule(&captures, &compiled.names).to_string()) - .or_insert(0) += 1; + for (index, _) in engine().matches(text) { + *counts.entry(NAMES[index].to_string()).or_insert(0) += 1; } counts } pub fn redact(text: &str) -> Result { - let compiled = compiled(); let mut counts: IndexMap = IndexMap::new(); let mut out = String::with_capacity(text.len()); let mut last = 0; - for captures in compiled.regex.captures_iter(text).flatten() { - let whole = captures.get(0).expect("group 0 exists"); - let name = matched_rule(&captures, &compiled.names); + for (index, found) in engine().matches(text) { + let name = NAMES[index]; *counts.entry(name.to_string()).or_insert(0) += 1; - let kept = captures - .name(&format!("{}_keep", name.replace('-', "_"))) - .map(|m| m.as_str()) - .unwrap_or(""); - out.push_str(&text[last..whole.start()]); - out.push_str(kept); + out.push_str(&text[last..found.start]); + out.push_str(&text[found.start..found.keep]); out.push_str(&format!("[REDACTED:{}]", name)); - last = whole.end(); + last = found.end; } out.push_str(&text[last..]); @@ -178,6 +285,138 @@ pub fn summarize(counts: &IndexMap) -> String { mod tests { use super::*; + /// redact.py's one alternation, verbatim but for `\s`: the oracle. + fn oracle() -> fancy_regex::Regex { + let start = r"(? = prefixed() + .iter() + .map(|(body, s, e)| { + format!( + "{}{}{}", + if *s { start } else { "" }, + body, + if *e { end } else { "" } + ) + }) + .chain(std::iter::once(env_assignment())) + .collect(); + let pattern = NAMES + .iter() + .zip(&bodies) + .map(|(name, body)| format!("(?P<{}>{})", name.replace('-', "_"), body)) + .collect::>() + .join("|"); + fancy_regex::RegexBuilder::new(&pattern) + .backtrack_limit(usize::MAX / 2) + .build() + .unwrap() + } + + fn oracle_matches(regex: &fancy_regex::Regex, text: &str) -> Vec<(usize, usize, usize, usize)> { + regex + .captures_iter(text) + .map(|c| { + let c = c.unwrap(); + let index = NAMES + .iter() + .position(|n| c.name(&n.replace('-', "_")).is_some()) + .unwrap(); + let whole = c.get(0).unwrap(); + let keep = c + .name("env_assignment_keep") + .map_or(whole.start(), |k| k.end()); + (index, whole.start(), whole.end(), keep) + }) + .collect() + } + + /// Strings built from the pieces the rules care about, so that near + /// misses, overlaps and boundary cases are common rather than rare. + #[test] + fn the_fast_path_agrees_with_the_alternation() { + let pieces = [ + "AKIA", + "ASIA", + "ABCDEFGHIJKLMNOP", + "0123456789", + "gh", + "p_", + "ghp_", + "xoxb-", + "sk-", + "sk-ant-", + "sk_live_", + "proj-", + "AIza", + "eyJ", + ".", + "-", + "_", + "x", + "A", + "Z9", + " ", + "\t", + "\u{1c}", + "\n", + "=", + ":", + "\"", + "'", + ",", + ";", + "\\", + "/", + "~", + "TOKEN", + "SECRET", + "API_KEY", + "PASSWD", + "PASSWORD", + "PRIVATE_KEY", + "AWS_SECRET_ACCESS_KEY", + "MY_", + "[REDACTED:env-assignment]", + "abcdefghij", + "-----BEGIN RSA PRIVATE KEY-----", + "-----END RSA PRIVATE KEY-----", + "é", + "😀", + "a1B2c3D4e5a1B2c3D4e5a1B2c3D4e5a1B2c3D4e5", + "0123456789abcdefghijklmnopqrstuvwxy", + "eyJhbGci.eyJzdWIi.c2ln", + "eyJhbGci", + ".eyJzdWIi", + ]; + let regex = oracle(); + let mut state: u64 = 0x2545F4914F6CDD1D; + let mut next = || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let mut matched = [0usize; 10]; + for _ in 0..40_000 { + let length = 1 + (next() % 24) as usize; + let text: String = (0..length) + .map(|_| pieces[(next() % pieces.len() as u64) as usize]) + .collect(); + let fast: Vec<_> = engine() + .matches(&text) + .into_iter() + .map(|(i, f)| (i, f.start, f.end, f.keep)) + .collect(); + assert_eq!(fast, oracle_matches(®ex, &text), "{text:?}"); + for (index, ..) in fast { + matched[index] += 1; + } + } + // Agreement on texts that match nothing would prove nothing. + assert!(matched.iter().all(|&n| n > 10), "{matched:?}"); + } + #[test] fn redacts_and_keeps_the_assignment_name() { let secret = format!("ghp_{}", "a1B2c3D4e5".repeat(4)); diff --git a/test/equivalence.py b/test/equivalence.py index a77cf3b..1e9e1ea 100644 --- a/test/equivalence.py +++ b/test/equivalence.py @@ -294,6 +294,32 @@ def digest_of(value: Any) -> str: return hashlib.sha256(repr(value).encode()).hexdigest()[:16] +def quiet_difference(py: Any, rs: Any) -> str: + """Where two observations part, by position and hash only: safe to print + when they were made from real transcripts.""" + py_runs, py_seen = py + rs_runs, rs_seen = rs + for index, (a, b) in enumerate(zip(py_runs, rs_runs)): + for stream in ("stdout", "stderr", "status"): + x, y = a[stream], b[stream] + if x != y: + if isinstance(x, bytes) and isinstance(y, bytes): + at = next( + (i for i, (p, q) in enumerate(zip(x, y)) if p != q), + min(len(x), len(y)), + ) + return f"run {index} {stream}: lengths {len(x)}/{len(y)}, first difference at byte {at}" + return f"run {index} {stream}: {x!r} != {y!r}" + only_py = sorted(set(py_seen) - set(rs_seen)) + only_rs = sorted(set(rs_seen) - set(py_seen)) + if only_py or only_rs: + return f"{len(only_py)} files only in py, {len(only_rs)} only in rs" + for key in py_seen: + if py_seen[key] != rs_seen[key]: + return f"{key}: py {digest_of(py_seen[key])} rs {digest_of(rs_seen[key])}" + return "no difference" + + def first_difference(py: Any, rs: Any) -> str: """Where two observations part, named by run index or file path. File contents are reported by hash: a scenario's files are synthetic, but the @@ -351,6 +377,6 @@ def loch( outcomes.append(normalized(runs, seen)) if outcomes[0] != outcomes[1]: if quiet: - raise AssertionError("builds differ (details withheld: real transcripts)") + raise AssertionError(quiet_difference(outcomes[0], outcomes[1])) raise AssertionError(first_difference(outcomes[0], outcomes[1])) return raw_seen[0] diff --git a/test/test_equivalence_corpus.py b/test/test_equivalence_corpus.py new file mode 100644 index 0000000..fe7f585 --- /dev/null +++ b/test/test_equivalence_corpus.py @@ -0,0 +1,104 @@ +"""The Rust build against the Python reference on this machine's real +transcripts: every project directory is listed, saved, restored onto a +different home and ingested by both builds, and everything they write is +compared. + +Opt-in twice over — LOCH_RUST and LOCH_CORPUS=1 — and read-only towards +`~/.claude`: restores go to a temporary HOME, stores and derived files to a +temporary directory. Content never leaves memory; a failure names the project +directory, the command, and a byte offset or a hash. +""" + +import os +import re +from pathlib import Path + +import pytest +from equivalence import RUST, Run, World, twin + +from loch.claude import projects_dir, read_session_meta + +pytestmark = pytest.mark.skipif( + not RUST or os.environ.get("LOCH_CORPUS") != "1", + reason="set LOCH_RUST and LOCH_CORPUS=1", +) + +REAL_HOME = str(Path.home()) + + +def project_cwds() -> list[tuple[str, str]]: + """(directory name, the cwd its sessions are filed under), as list would + be asked for it. A directory whose name no session's cwd encodes to — a + hand-copied one — can't be reached by --cwd and is skipped.""" + root = Path(projects_dir()) + found = [] + for directory in sorted(root.iterdir()) if root.is_dir() else []: + for transcript in sorted(directory.glob("*.jsonl")): + meta = read_session_meta(str(transcript)) + if meta and re.sub(r"[^a-zA-Z0-9]", "-", meta.cwd) == directory.name: + found.append((directory.name, meta.cwd)) + break + limit = int(os.environ.get("LOCH_CORPUS_DIRS", "0")) + return found[:limit] if limit else found + + +def test_no_transcript_uses_the_surrogate_mapping_range() -> None: + """The Rust build carries lone surrogates in U+10F800..U+10FFFF (py.rs); + a transcript holding those code points literally would be misread.""" + reserved = re.compile("[\U0010f800-\U0010ffff]") + hits = [ + path.parent.name + for path in Path(projects_dir()).glob("*/*.jsonl") + if reserved.search(path.read_bytes().decode("utf-8", "surrogateescape")) + ] + assert not hits, f"{len(hits)} transcripts use the reserved range: {hits[:5]}" + + +def test_every_project_directory_matches(tmp_path: Path) -> None: + cases = project_cwds() + assert cases, "no Claude Code sessions on this machine" + mismatched: list[str] = [] + real = {"HOME": REAL_HOME, "CLAUDE_CONFIG_DIR": os.environ.get("CLAUDE_CONFIG_DIR")} + for index, (directory, cwd) in enumerate(cases): + + def scenario(w: World, loch, _cwd: str = cwd) -> list[Run]: + store = str(w.root / "store") + runs = [ + loch("list", "--cwd", _cwd, env=real), + loch("list", "--cwd", _cwd, "--json", env=real), + loch("save", "--cwd", _cwd, "--store", store, "--json", env=real), + loch( + "ingest", + "--cwd", + _cwd, + "--out", + str(w.root / "derived"), + "--json", + env=real, + ), + ] + bundles = sorted((w.root / "store" / "bundles").glob("*.loch")) + if bundles: + target = w.root / "target" + target.mkdir() + # The temporary home: a different machine, and nowhere real. + runs.append( + loch( + "restore", + bundles[0].stem, + "--store", + store, + "--into", + str(target), + "--json", + ) + ) + return runs + + try: + twin(tmp_path / str(index), scenario, quiet=True) + except AssertionError as error: + mismatched.append(f"{directory}: {error}") + assert not mismatched, ( + f"{len(mismatched)}/{len(cases)} directories differ:\n" + "\n".join(mismatched) + ) From a887781a0e56dea0542ae60cbf6b44ed1d5e6a2f Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 19:16:26 -0500 Subject: [PATCH 11/18] S3 commands held to the reference too; CLAUDE.md for the full port Listings now send encoding-type=url and decode the keys, as boto3 does, so a key with any character survives and a connection error names the same URL. The corpus check runs directories in parallel, since the reference's redaction makes a serial run take hours. CLAUDE.md's Rust section now covers the whole port: what equivalence required, the three reference bugs fixed on the way, the divergences kept, the harness and the numbers. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 4 +- CLAUDE.md | 271 ++++++++++++++++++++++-------- release.sh | 2 +- rust/src/s3.rs | 14 +- test/test_equivalence_commands.py | 79 +++++++++ test/test_equivalence_corpus.py | 103 +++++++----- 6 files changed, 353 insertions(+), 120 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f905c90..962d1a7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -41,7 +41,7 @@ jobs: - run: poetry run mypy . - run: poetry run pytest - # The Rust build, held to the Python reference by test/test_equivalence.py. + # The Rust build, held to the Python reference by test/test_equivalence*.py. # Linux and macOS because the hooks' native git fast path is Unix-only and # its filesystem details (realpath, ownership) differ between the two. rust: @@ -72,7 +72,7 @@ jobs: - run: pipx install poetry - run: poetry env use python && poetry install working-directory: . - - run: poetry run pytest -q test/test_equivalence.py + - run: poetry run pytest -q test/test_equivalence.py test/test_equivalence_commands.py working-directory: . env: LOCH_RUST: rust/target/release/loch diff --git a/CLAUDE.md b/CLAUDE.md index d486de7..dc8b8bd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -165,10 +165,11 @@ loch/ └── store.py # Store interface + local-fs and S3-compatible backends test/ ├── test_corpus.py # opt-in, against this machine's transcripts (LOCH_CORPUS=1) -├── test_equivalence.py # opt-in, Rust build vs Python (LOCH_RUST=) +├── equivalence.py # the harness: run both builds, compare everything +├── test_equivalence*.py # opt-in, Rust vs Python (LOCH_RUST=) └── test_*.py # one module per source module rust/ # the Rust build: one crate, binary `loch` (see "The Rust build") -├── src/ # main, output, hook, git, store, s3, claude +├── src/ # one module per Python module, plus argparse/json/py/sys ├── bench/hook.py # per-call wall clock of `loch hook`, any number of binaries └── rust-toolchain.toml npm/ # @ness-dev/loch and its per-platform packages @@ -506,7 +507,6 @@ never a code. The set today: | `git-failed` | a git command failed | | `unknown-command` | no such subcommand | | `usage` | argparse rejected the arguments (exit status 2) | -| `not-ported` | the Rust build was asked for a command only the Python one has yet | | `internal` | an unexpected exception | The four store-facing codes — `bundle-not-found`, `store-unreachable`, @@ -613,82 +613,201 @@ publishing. ## The Rust build The goal is one static binary that Ness, a VS Code extension and the Claude -Code hooks can ship and run, with no Python on the machine. **The Python -package stays the reference implementation** until the port is complete: a -command moves to Rust only once `test/test_equivalence.py` holds the two to -the same output and side effects, and the Python suite has to keep passing -on its own throughout. +Code hooks can ship and run, with no Python on the machine. **Every command +is ported**, and each is held to the Python by the equivalence harness. The +Python package is still the reference until it is deleted. Until then a +behaviour change lands in Python first, with the harness carrying it to Rust, +and the Python suite keeps passing on its own. **Layout: `rust/`, one crate, not a root workspace.** The repository root belongs to Poetry (pyproject, the `loch` package, `release.sh`), and a root `Cargo.toml` would mean two build systems claiming the same directory and a -`target/` beside the wheel's sources. One crate with modules mirroring the -Python ones (`hook.rs` ↔ the hook half of `trace.py`, `output.rs` ↔ -`output.py`, …) is enough until something needs splitting into a library a -second binary links; that is the point to make `rust/` a workspace, and -nothing outside it would have to move. +`target/` beside the wheel's sources. The modules mirror the Python ones +(`cli.rs` ↔ `cli.py`, `rewrite.rs` ↔ `rewrite.py`, `hook.rs` ↔ the hook half +of `trace.py`, …) plus four that Python gets from its standard library: +`argparse.rs`, `json.rs`, `py.rs` (string semantics) and `sys.rs` +(`os.path`, `datetime`, `OSError` strings). One crate is enough until a +second binary needs a library; that is the point to make `rust/` a +workspace, and nothing outside it moves. The toolchain is pinned in `rust/rust-toolchain.toml` (1.91.0), scoped to `rust/` so it never changes anyone's default. 1.83, which was installed, -can't build today's `url`/`idna`, and pinning half the dependency tree -backwards to stay on it would have been a standing cost for nothing. - -Unported commands answer `not-ported` rather than `unknown-command`: the -command exists, and the fix is the Python install, not a typo. - -**The equivalence harness** builds each scenario twice at the same path with -pinned git dates, so commit hashes, note blobs and even the notes-ref commit -come out byte-identical, then drives one copy with `python -m loch.cli` and -the other with the binary. It compares stdout, stderr and exit status -byte-for-byte — `output.rs` reproduces `json.dumps` exactly, `", "` -separators, `ensure_ascii` and float `repr` included, so that a comparison -can be on bytes rather than on parsed values — plus the notes ref, the -pending-state directory and the store. It also runs *mixed*: pre hook under -one build, post hook under the other, which is what happens the moment a -machine switches over mid-session; that is why the pending file's name and -JSON shape are part of the contract between the two. With `LOCH_CORPUS=1` -it adds the one hook path that reads a transcript (recovering a call id -when the payload lacks one) on 150 of this machine's real sessions by -default; their content exists only in a temp directory, failures name -session ids, and it asserts a note was written so that two builds agreeing -on nothing can't pass. Mutating the Rust (a wrong `captured` value, a -loosened time bound, a corrupted signing key) fails it; that was checked. - -**`loch hook` is ported, and costs 3ms a call instead of ~73ms.** Measured -with `rust/bench/hook.py` against the `uv tool` install: pre-tool 72.9 → -3.1ms, post-tool with no commit 72.4 → 3.1ms, post-tool writing a note -98.5 → 27.3ms (median of 60). The hooks run twice per agent shell command, -so that is ~145ms of every Bash call down to ~6ms. Python's cost was ~50ms -of imports — `importlib.metadata` alone is 19ms — and ~8ms per `git` -process, of which the hot path ran two. - -Getting under the git floor is the fast path in `git.rs`: the two -questions asked on every call — where is the git directory, what is HEAD — -are answered by reading `.git` (including a worktree's `gitdir:` file, -`commondir`, loose and packed refs) instead of spawning git. It answers -only on layouts it fully understands and returns "ask git" for anything -else: any discovery-changing `GIT_*` variable, reftable, a repository owned -by another user (git's `safe.directory` would refuse it), a cwd inside -`.git`, an unparseable ref, and Windows outright. **A gap there may only -ever cost speed, never a different answer**, which the harness checks by -having reftable, `GIT_DIR`, worktree, packed-refs, detached, unborn and -symlinked-subdirectory scenarios. The note-writing path still runs `git log` -and `git notes`, which is the remaining 24ms; it runs only when a call -actually committed. - -**S3 in Rust is SigV4 by hand over `ureq`/rustls**, not the AWS SDK — one -signed PUT doesn't justify an async runtime and several MB. Its credential -chain is `AWS_*` variables, then the shared credentials and config files for -`AWS_PROFILE`; **SSO, `credential_process`, assumed roles and instance -metadata are not read**, so a machine relying on them keeps the Python -hook for now. The signer is pinned to AWS's published worked example, and -the harness runs both builds against a moto server with IAM auth on, so a -bad signature is refused rather than waved through. moto's verifier itself -rejects boto3's correct signatures on keys holding a space or `+`, and on a -`ListObjectsV2` prefix holding `/`; the test works around both, and a -failure that looks like a signing bug in exactly those cases is moto's. -A stop hook against a store that doesn't answer gives up after 20s rather -than holding the turn. +can't build today's `url`/`idna`. + +### What "equivalent" had to mean, and what it cost + +Byte-for-byte, on stdout, stderr, exit status and every file written — the +standard the harness enforces — rules out leaning on Rust's libraries +wherever Python's behaviour is the specification. In the order they bit: + +- **JSON is Python's, not serde's.** `json.rs` parses as `json.loads` does + (duplicate keys keep their first position and last value, integers stay + exact at any size, `NaN`/`Infinity` accepted) and writes every flavour loch + uses (`ensure_ascii`, compact, sorted, `indent=2`, float `repr`) plus RFC + 8785. serde_json refuses lone surrogates, and **five transcripts on one + machine hold them** (`\ud83d` cut from its pair by truncation). +- **Lone surrogates are mapped into U+10F800..U+10FFFF** (`py.rs`), since a + Rust `String` can't hold one. That covers both the JSON escape and + `surrogateescape`'s undecodable bytes. They are mapped back wherever Python + would write them, and they sort, escape and canonicalize as the surrogate. + The cost: a transcript holding those private-use code points literally + would be misread. The corpus check asserts none on this machine does. +- **Python's whitespace is not Rust's.** `str.isspace` (and so `\s`, + `split()`, `strip()`) includes U+001C..U+001F, which Unicode White_Space + doesn't. `py::is_space` is the 29 code points Python says, and every + ported pattern spells `\s` out as that set. +- **argparse is ported, not approximated** (`argparse.rs`, from 3.12.10). Its + usage errors and `-h` text are output, so the A/O/- pattern matching, + abbreviation, `--opt=value`, `--`, the help formatter's wrapping at + `COLUMNS` and the 3.12.10 rule that stops a `nargs="?"` positional being + consumed empty before an option all had to match. The harness runs every + command through fifteen bad command lines at four widths. +- **zlib's own deflate**, through flate2's zlib backend (memLevel 8, raw + window 15, which is `zlib.compressobj(9, DEFLATED, -15, 8, 0)`), because + the ref is a hash of the gzip bytes and miniz_oxide compresses differently. + zlib is built from source and linked statically. +- **The rewrite and redaction regexes are run by hand** where a regex crate + couldn't express them: `rewrite.rs` executes the one-alternation `re.sub` + as an explicit scan with per-alternative guards (and, as in Python, a + source repeated with two targets maps to the last). `redact.rs` is + described below. +- **Error strings are Python's**: `str(OSError)` (`[Errno 2] No such file or + directory: '/x'`), binascii's strict-mode base64 messages, botocore's + `An error occurred (Code) when calling the Op operation: Message`, + `gzip`'s `Not a gzipped file (b'ga')`. They reach the `error` field. +- **boto3's request shapes**: a listing sends `encoding-type=url` and + decodes the keys, in boto3's parameter order, because the URL appears in a + connection error. + +**Three bugs in the reference turned up and were fixed in Python first**, +because the rule is that the reference stays the reference: + +- **Bundle refs depended on the Python version and the platform.** From 3.11 + `gzip.compress` lets zlib write the header's OS byte, 19 on macOS and 3 on + Linux, where 3.10 wrote 255. So the same sessions packed to a different + ref per machine. The header is now written by hand, byte-identical to + 3.10's everywhere. Bundles saved before keep their refs, but a re-save of + the same sessions from 3.11+ gets a new one. +- **One undecodable byte took down `list`** for the whole directory, since + `read_session_meta` caught `OSError` only. Metadata now decodes with + replacement, and `save` refuses such a session as `transcript-unreadable` + instead of with a traceback. +- **`save` wasn't reproducible**, since `createdAt` is part of the hashed + bytes. `SOURCE_DATE_EPOCH` now fixes it in both builds. That is the + reproducible-builds convention, and it is what lets the harness compare + two builds' refs at all. + +**Divergences that remain, deliberately:** + +- An unexpected exception is a traceback in Python and `loch: internal + error: …` in Rust. JSON mode matches, both being `code: "internal"`. +- A naive (offset-less) ISO timestamp is local time to Python and UTC to + Rust. Transcripts always carry `Z`. +- Unicode digits (`int("١٢")`) are accepted by a few of Python's parses and + by none of Rust's. +- The S3 credential chain stops at env and the shared files. SSO, + `credential_process`, assumed roles and instance metadata are not read. +- Windows compiles in principle and has never been built. + +While the port was partial, unported commands answered `not-ported`. With +nothing left unported that code is gone, and an unknown name is +`unknown-command` in both builds. + +### The harness + +`test/equivalence.py` is the machinery, and three modules use it: +`test_equivalence.py` (hooks), `test_equivalence_commands.py` (everything +else, including an S3 run against moto) and `test_equivalence_corpus.py` +(real transcripts). All are opt-in with `LOCH_RUST=`, and the corpus +also needs `LOCH_CORPUS=1`. + +How a scenario runs: +- **Twice, identically.** Each scenario is built twice at the same path with + pinned git dates, session mtimes and `SOURCE_DATE_EPOCH`. Python drives + one copy and the binary the other. +- **Everything is compared.** That means every file under the scratch root + (git's own churn aside) plus the notes ref, HEAD and `notes.rewriteRef`. +- **Generated values are renamed.** v4 UUIDs, which `--new-id` and `ask`'s + fork mint, become `UUID-n` in order of first appearance. Fixture ids are + deliberately not v4. +- **Mixed runs.** The hook scenarios also run pre-tool under one build and + post-tool under the other, which is what a machine switching over + mid-session does. That is why the pending file's shape is a contract + between the two. + +**Planted bugs fail it.** That was checked, not assumed: a changed redaction +token, a loosened path guard, the home-is-root rule, an argparse message, a +float exponent boundary, a prose string, the prompt walk in `trace`, the +percent-encoding of index segments, a converter fact name, a wrong +`captured` value, a loosened hook time bound and a corrupted signing key +each fail at least one scenario. Each of those first came back *green* +until a scenario exercised it. The float one needed floats added to the +fixtures, which is the reason to keep doing this whenever a scenario is +added. + +**The corpus check** lists, saves, restores (onto a temporary HOME) and +ingests every project directory on the machine with both builds, in +parallel (`LOCH_CORPUS_JOBS`). It is read-only towards `~/.claude`, and a +failure names a directory and a byte offset or hash, never content. + +### Performance + +**`loch hook`: 3ms a call instead of ~73ms.** Measured with +`rust/bench/hook.py` against the `uv tool` install, median of 60: + +| case | Python | Rust | +| --- | --- | --- | +| pre-tool | 72.9ms | 3.1ms | +| post-tool, no commit | 72.4ms | 3.1ms | +| post-tool, writing a note | 98.5ms | 27.3ms | + +The hooks run twice per agent shell command, so that is ~145ms of every +Bash call down to ~6ms. Python's cost was ~50ms of imports +(`importlib.metadata` alone is 19ms) and ~8ms per `git` process, of which +the hot path ran two. + +Getting under the git floor is the fast path in `git.rs`: where the git +directory is and what HEAD is are answered by reading `.git` (a worktree's +`gitdir:` file, `commondir`, loose and packed refs) instead of spawning git. +It answers only on layouts it fully understands and says "ask git" for +anything else: a discovery-changing `GIT_*` variable, reftable, a repository +owned by another user (`safe.directory`), a cwd inside `.git`, an +unparseable ref, and Windows outright. **A gap there may only ever cost +speed, never a different answer.** The harness checks that with reftable, +`GIT_DIR`, worktree, packed-refs, detached, unborn and symlinked scenarios. +Writing a note still runs `git log` and `git notes`, which is the remaining +24ms, and it happens only when a call committed. + +**Redaction was most of `save`'s cost in both builds**: 150s in Python and +264s in Rust (first cut, fancy-regex) over 15 project directories. A +backtracking engine tries all ten rules at every position, and +`env-assignment` can begin at any capital. `redact.rs` gives the same +answers with a restructured search: +- **The nine prefixed rules** become plain `regex` crate searches, linear and + with leftmost-first semantics equal to backtracking. Their one-character + START/END checks are made by hand. +- **`env-assignment`** is tried, anchored, only at the start of an + `[A-Z0-9_]` run that holds a keyword. Every way it could match from inside + the run is also a way from the run's start, so that is the only candidate. +- **The next match** is the earliest position any rule matches at, ties going + to rule order. + +That brought it to 15s. The full Python alternation stays in the tests as an +oracle, fuzzed against the fast path over 40k generated strings that +exercise every rule (the test asserts each rule matched, so the fuzz can't +pass vacuously). **Python's redaction is still the slow one**, which is why +the corpus check runs in parallel. It is the reference, so it was left +alone. + +**S3 is SigV4 by hand over `ureq`/rustls**, not the AWS SDK; four request +kinds don't justify an async runtime and several MB. The signer is pinned to +AWS's two published examples (a header-signed GET and a signed query +string). The stop hook is checked against a moto server with IAM auth on, so +a bad signature is refused. moto's verifier itself rejects boto3's correct +signatures on keys holding a space or `+` and on prefixed listings, so the +command-level S3 test runs with auth off; a failure that looks like a +signing bug in exactly those cases is moto's. A store that doesn't answer +fails after 20s rather than holding a turn. ### Packaging @@ -721,7 +840,7 @@ should write the binary's absolute path with `loch install --local rather than rely on PATH. **`uv tool install` users** have a working install of the reference, so -nothing changes for them until the port is complete. The intended switch is +nothing has to change for them while the Python exists. The intended switch is to ship the Rust binary as platform wheels too — maturin's `bindings = "bin"`, the way ruff and uv ship — attached to the GitHub release next to today's pure-Python wheel, so the switch is the same `uv tool install @@ -892,7 +1011,11 @@ agree is a one-line property test. `poetry run pytest`. Touching `rust/` adds `cargo fmt --check`, `cargo clippy --release --all-targets -- -D warnings`, `cargo test` there, and `LOCH_RUST=rust/target/release/loch poetry run pytest - test/test_equivalence.py` after a `cargo build --release`. + test/test_equivalence.py test/test_equivalence_commands.py` after a + `cargo build --release`. A change to how either build reads transcripts + adds the corpus check (`LOCH_CORPUS=1`). +- A behaviour change goes into both builds in one commit, with a scenario + that would have told them apart. - A command is ported when the harness covers it, not when it compiles. Port behaviour exactly, quirks included, and fix a quirk in Python first if it is a bug, so the reference stays the reference. diff --git a/release.sh b/release.sh index 2fa08cf..e387499 100755 --- a/release.sh +++ b/release.sh @@ -63,7 +63,7 @@ poetry run mypy . poetry run pytest -q (cd rust && cargo fmt --check && cargo clippy -q --release --all-targets -- -D warnings \ && cargo test -q --release && cargo build -q --release) -LOCH_RUST=rust/target/release/loch poetry run pytest -q test/test_equivalence.py +LOCH_RUST=rust/target/release/loch poetry run pytest -q test/test_equivalence.py test/test_equivalence_commands.py echo "==> tagging $tag" # pyproject may already hold this version — the first release, or a re-cut after diff --git a/rust/src/s3.rs b/rust/src/s3.rs index 8d3077d..328a884 100644 --- a/rust/src/s3.rs +++ b/rust/src/s3.rs @@ -91,10 +91,14 @@ impl S3Store { ®ion, now, ); - let url = if query_string.is_empty() { + let url = if query.is_empty() { target.url() } else { - format!("{}?{}", target.url(), query_string) + let in_order: Vec = query + .iter() + .map(|(k, v)| format!("{}={}", uri_encode(k, true), uri_encode(v, true))) + .collect(); + format!("{}?{}", target.url(), in_order.join("&")) }; let mut request = ureq::AgentBuilder::new() .timeout(TIMEOUT) @@ -184,16 +188,20 @@ impl Store for S3Store { let mut keys = Vec::new(); let mut token: Option = None; loop { + // boto3's order, which is the order the URL in an error shows; + // signing sorts its own copy. encoding-type=url is what boto3 + // asks for too, so a key with any character survives the XML. let mut query = vec![("list-type", "2"), ("prefix", full.as_str())]; if let Some(token) = &token { query.push(("continuation-token", token.as_str())); } + query.push(("encoding-type", "url")); let response = self.request("GET", None, &query, b"", "ListObjectsV2")?; let text = String::from_utf8_lossy(&response.body).into_owned(); let _ = response.status; for contents in xml_blocks(&text, "Contents") { for key in xml_values(contents, "Key") { - keys.push(self.relative_key(&key)); + keys.push(self.relative_key(&crate::index::unquote(&key))); } } let truncated = diff --git a/test/test_equivalence_commands.py b/test/test_equivalence_commands.py index 2f0eca3..100313a 100644 --- a/test/test_equivalence_commands.py +++ b/test/test_equivalence_commands.py @@ -760,3 +760,82 @@ def backfill(w: World, loch: Loch) -> list[Run]: @pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda s: s.__name__) def test_command_matches_python(tmp_path: Path, scenario: Scenario) -> None: twin(tmp_path, scenario) + + +def test_s3_store_matches_python(tmp_path: Path) -> None: + """The bundle commands against an S3 endpoint rather than a directory: + both builds' requests go to one moto server, reset between them. Auth is + off, because moto's verifier rejects boto3's own correct signatures on + the prefixed listings these commands make; signing is pinned to AWS's + published examples in s3.rs instead, and checked with auth on by the + stop-hook test.""" + import urllib.request + + import boto3 + from equivalence import first_difference, normalized + from moto.server import ThreadedMotoServer + + server = ThreadedMotoServer(ip_address="127.0.0.1", port=0) + server.start() + host, port = server.get_host_and_port() + endpoint = f"http://{host}:{port}" + credentials = { + "AWS_ACCESS_KEY_ID": "testing", + "AWS_SECRET_ACCESS_KEY": "testing", + "AWS_SHARED_CREDENTIALS_FILE": os.devnull, + "AWS_CONFIG_FILE": os.devnull, + "LOCH_S3_ENDPOINT": endpoint, + "LOCH_S3_REGION": "us-east-1", + "LOCH_STORE": "s3://loch-test/team/", + } + outcomes = [] + try: + for impl in ("py", "rs"): + urllib.request.urlopen( + urllib.request.Request(f"{endpoint}/moto-api/reset", b"") + ) + boto3.client( + "s3", + endpoint_url=endpoint, + region_name="us-east-1", + aws_access_key_id="testing", + aws_secret_access_key="testing", + ).create_bucket(Bucket="loch-test") + root = tmp_path / "world" + if root.exists(): + import shutil + + shutil.rmtree(root) + w = World(root) + cwd = rich_sessions(w) + + def loch(*args: str, _w: World = w, _impl: str = impl, **kw: Any) -> Run: + env = {**credentials, **kw.pop("env", {})} + return _w.loch(_impl, *args, env=env, **kw) + + runs = [*both(loch, "save", "--cwd", cwd)] + listed = json.loads(loch("list", "--all", "--json").stdout) + ref = listed["entries"][0]["ref"] + target = w.root / "target" + target.mkdir() + runs += [ + *both(loch, "list", "--all"), + *both(loch, "list", "--remote", "--branch", "feature/x"), + *both(loch, "restore", ref, "--into", str(target)), + *both(loch, "restore", "0" * 64), + *both(loch, "reindex"), + *both(loch, "delete", ref), + *both(loch, "delete", ref), + *both(loch, "list", "--all"), + *both(loch, "save", "--cwd", cwd, env={"AWS_ACCESS_KEY_ID": ""}), + *both( + loch, + "list", + "--all", + env={"LOCH_S3_ENDPOINT": "http://127.0.0.1:9"}, + ), + ] + outcomes.append(normalized(runs, w.observe())) + finally: + server.stop() + assert outcomes[0] == outcomes[1], first_difference(outcomes[0], outcomes[1]) diff --git a/test/test_equivalence_corpus.py b/test/test_equivalence_corpus.py index fe7f585..d76da7f 100644 --- a/test/test_equivalence_corpus.py +++ b/test/test_equivalence_corpus.py @@ -11,6 +11,7 @@ import os import re +from concurrent.futures import ThreadPoolExecutor from pathlib import Path import pytest @@ -54,51 +55,73 @@ def test_no_transcript_uses_the_surrogate_mapping_range() -> None: assert not hits, f"{len(hits)} transcripts use the reserved range: {hits[:5]}" -def test_every_project_directory_matches(tmp_path: Path) -> None: - cases = project_cwds() - assert cases, "no Claude Code sessions on this machine" - mismatched: list[str] = [] +def check_directory(root: Path, cwd: str) -> str | None: + """Both builds over one project directory; None if they agree.""" real = {"HOME": REAL_HOME, "CLAUDE_CONFIG_DIR": os.environ.get("CLAUDE_CONFIG_DIR")} - for index, (directory, cwd) in enumerate(cases): - - def scenario(w: World, loch, _cwd: str = cwd) -> list[Run]: - store = str(w.root / "store") - runs = [ - loch("list", "--cwd", _cwd, env=real), - loch("list", "--cwd", _cwd, "--json", env=real), - loch("save", "--cwd", _cwd, "--store", store, "--json", env=real), + + def scenario(w: World, loch) -> list[Run]: # type: ignore[no-untyped-def] + store = str(w.root / "store") + runs = [ + loch("list", "--cwd", cwd, env=real), + loch("list", "--cwd", cwd, "--json", env=real), + loch("save", "--cwd", cwd, "--store", store, "--json", env=real), + loch( + "ingest", + "--cwd", + cwd, + "--out", + str(w.root / "derived"), + "--json", + env=real, + ), + ] + bundles = sorted((w.root / "store" / "bundles").glob("*.loch")) + if bundles: + target = w.root / "target" + target.mkdir() + # The temporary home: a different machine, and nowhere real. + runs.append( loch( - "ingest", - "--cwd", - _cwd, - "--out", - str(w.root / "derived"), + "restore", + bundles[0].stem, + "--store", + store, + "--into", + str(target), "--json", - env=real, - ), - ] - bundles = sorted((w.root / "store" / "bundles").glob("*.loch")) - if bundles: - target = w.root / "target" - target.mkdir() - # The temporary home: a different machine, and nowhere real. - runs.append( - loch( - "restore", - bundles[0].stem, - "--store", - store, - "--into", - str(target), - "--json", - ) ) - return runs + ) + return runs + + try: + twin(root, scenario, quiet=True) + except AssertionError as error: + return str(error) + finally: + import shutil + + shutil.rmtree(root, ignore_errors=True) + return None - try: - twin(tmp_path / str(index), scenario, quiet=True) - except AssertionError as error: - mismatched.append(f"{directory}: {error}") + +def test_every_project_directory_matches(tmp_path: Path) -> None: + """In parallel — LOCH_CORPUS_JOBS, default every core — since the + reference's redaction makes a serial run over a busy machine take hours.""" + cases = project_cwds() + assert cases, "no Claude Code sessions on this machine" + jobs = int(os.environ.get("LOCH_CORPUS_JOBS", str(os.cpu_count() or 1))) + with ThreadPoolExecutor(max_workers=jobs) as pool: + results = list( + pool.map( + lambda item: check_directory(tmp_path / str(item[0]), item[1][1]), + enumerate(cases), + ) + ) + mismatched = [ + f"{directory}: {result}" + for (directory, _), result in zip(cases, results) + if result is not None + ] assert not mismatched, ( f"{len(mismatched)}/{len(cases)} directories differ:\n" + "\n".join(mismatched) ) From 3a0585515b65cb5963f95582c2830bc2a8a7f74e Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Tue, 17 Nov 2026 19:17:04 -0500 Subject: [PATCH 12/18] README: the native build and how to check it against the Python Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index de6c8ac..5b163b9 100644 --- a/README.md +++ b/README.md @@ -40,12 +40,23 @@ uv tool install "loch[s3] @ https://github.com/ness-dev/loch/releases/download/v Without it, an `s3://` store fails with `code: "s3-extra-missing"` rather than looking like a network problem. +**A native build** lives in `rust/`: one static binary with the same +commands, output and exit codes, S3 included, and a hook that costs 3ms a +call rather than ~73ms. It isn't released yet; to use it now: + +```sh +cd rust && cargo build --release # target/release/loch +``` + For development: ```sh poetry install # brings boto3, so the S3 backend is covered by the tests poetry run loch --help poetry run pytest +# the Rust build, held to the Python one output for output: +(cd rust && cargo build --release) +LOCH_RUST=rust/target/release/loch poetry run pytest test/test_equivalence*.py ``` ## Use From 53387b8c600f8116ab0e3e0a4dae47d16f7ae4a3 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 18 Nov 2026 10:28:28 -0500 Subject: [PATCH 13/18] Move the crate to the repository root and split it into lib and bin The Python is going, so Poetry no longer owns the root. A library target lets integration tests in tests/ reach the modules directly. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 11 ++---- rust/Cargo.lock => Cargo.lock | 0 rust/Cargo.toml => Cargo.toml | 0 {rust/bench => bench}/hook.py | 0 ...rust-toolchain.toml => rust-toolchain.toml | 0 rust/.gitignore | 1 - {rust/src => src}/argparse.rs | 0 {rust/src => src}/blame_html.rs | 0 {rust/src => src}/blame_template.html | 0 {rust/src => src}/bundle.rs | 0 {rust/src => src}/claude.rs | 0 {rust/src => src}/cli.rs | 0 {rust/src => src}/format.rs | 0 {rust/src => src}/git.rs | 0 {rust/src => src}/hook.rs | 0 {rust/src => src}/index.rs | 0 {rust/src => src}/ingest.rs | 0 {rust/src => src}/json.rs | 0 src/lib.rs | 25 +++++++++++++ {rust/src => src}/main.rs | 35 +++---------------- {rust/src => src}/output.rs | 0 {rust/src => src}/py.rs | 0 {rust/src => src}/redact.rs | 0 {rust/src => src}/rewrite.rs | 0 {rust/src => src}/s3.rs | 0 {rust/src => src}/store.rs | 0 {rust/src => src}/sys.rs | 0 {rust/src => src}/trace.rs | 0 {rust/src => src}/usage.txt | 0 29 files changed, 32 insertions(+), 40 deletions(-) rename rust/Cargo.lock => Cargo.lock (100%) rename rust/Cargo.toml => Cargo.toml (100%) rename {rust/bench => bench}/hook.py (100%) rename rust/rust-toolchain.toml => rust-toolchain.toml (100%) delete mode 100644 rust/.gitignore rename {rust/src => src}/argparse.rs (100%) rename {rust/src => src}/blame_html.rs (100%) rename {rust/src => src}/blame_template.html (100%) rename {rust/src => src}/bundle.rs (100%) rename {rust/src => src}/claude.rs (100%) rename {rust/src => src}/cli.rs (100%) rename {rust/src => src}/format.rs (100%) rename {rust/src => src}/git.rs (100%) rename {rust/src => src}/hook.rs (100%) rename {rust/src => src}/index.rs (100%) rename {rust/src => src}/ingest.rs (100%) rename {rust/src => src}/json.rs (100%) create mode 100644 src/lib.rs rename {rust/src => src}/main.rs (68%) rename {rust/src => src}/output.rs (100%) rename {rust/src => src}/py.rs (100%) rename {rust/src => src}/redact.rs (100%) rename {rust/src => src}/rewrite.rs (100%) rename {rust/src => src}/s3.rs (100%) rename {rust/src => src}/store.rs (100%) rename {rust/src => src}/sys.rs (100%) rename {rust/src => src}/trace.rs (100%) rename {rust/src => src}/usage.txt (100%) diff --git a/.gitignore b/.gitignore index 6f88f15..66fff4c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,4 @@ -.venv/ -__pycache__/ -*.pyc -.mypy_cache/ -.ruff_cache/ -.pytest_cache/ -dist/ -*.loch -!test/fixtures/*.loch +target/ .DS_Store .claude/settings.local.json +*.loch diff --git a/rust/Cargo.lock b/Cargo.lock similarity index 100% rename from rust/Cargo.lock rename to Cargo.lock diff --git a/rust/Cargo.toml b/Cargo.toml similarity index 100% rename from rust/Cargo.toml rename to Cargo.toml diff --git a/rust/bench/hook.py b/bench/hook.py similarity index 100% rename from rust/bench/hook.py rename to bench/hook.py diff --git a/rust/rust-toolchain.toml b/rust-toolchain.toml similarity index 100% rename from rust/rust-toolchain.toml rename to rust-toolchain.toml diff --git a/rust/.gitignore b/rust/.gitignore deleted file mode 100644 index 2f7896d..0000000 --- a/rust/.gitignore +++ /dev/null @@ -1 +0,0 @@ -target/ diff --git a/rust/src/argparse.rs b/src/argparse.rs similarity index 100% rename from rust/src/argparse.rs rename to src/argparse.rs diff --git a/rust/src/blame_html.rs b/src/blame_html.rs similarity index 100% rename from rust/src/blame_html.rs rename to src/blame_html.rs diff --git a/rust/src/blame_template.html b/src/blame_template.html similarity index 100% rename from rust/src/blame_template.html rename to src/blame_template.html diff --git a/rust/src/bundle.rs b/src/bundle.rs similarity index 100% rename from rust/src/bundle.rs rename to src/bundle.rs diff --git a/rust/src/claude.rs b/src/claude.rs similarity index 100% rename from rust/src/claude.rs rename to src/claude.rs diff --git a/rust/src/cli.rs b/src/cli.rs similarity index 100% rename from rust/src/cli.rs rename to src/cli.rs diff --git a/rust/src/format.rs b/src/format.rs similarity index 100% rename from rust/src/format.rs rename to src/format.rs diff --git a/rust/src/git.rs b/src/git.rs similarity index 100% rename from rust/src/git.rs rename to src/git.rs diff --git a/rust/src/hook.rs b/src/hook.rs similarity index 100% rename from rust/src/hook.rs rename to src/hook.rs diff --git a/rust/src/index.rs b/src/index.rs similarity index 100% rename from rust/src/index.rs rename to src/index.rs diff --git a/rust/src/ingest.rs b/src/ingest.rs similarity index 100% rename from rust/src/ingest.rs rename to src/ingest.rs diff --git a/rust/src/json.rs b/src/json.rs similarity index 100% rename from rust/src/json.rs rename to src/json.rs diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..7c04c50 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,25 @@ +//! loch as a library: every module the binary is built from, public so the +//! integration tests in `tests/` can reach them. + +// The error path is cold and runs once per process; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +pub mod argparse; +pub mod blame_html; +pub mod bundle; +pub mod claude; +pub mod cli; +pub mod format; +pub mod git; +pub mod hook; +pub mod index; +pub mod ingest; +pub mod json; +pub mod output; +pub mod py; +pub mod redact; +pub mod rewrite; +pub mod s3; +pub mod store; +pub mod sys; +pub mod trace; diff --git a/rust/src/main.rs b/src/main.rs similarity index 68% rename from rust/src/main.rs rename to src/main.rs index 8722715..c04ff5c 100644 --- a/rust/src/main.rs +++ b/src/main.rs @@ -1,33 +1,9 @@ -//! The Rust build of loch: one static binary for Ness, the VS Code extension -//! and the Claude Code hooks to ship. The Python package is the reference; -//! `test/test_equivalence.py` holds every command here to its output and side -//! effects. +//! `loch`: one static binary for Ness, the VS Code extension and the Claude +//! Code hooks to ship. -// The error path is cold and runs once per process; boxing it buys nothing. -#![allow(clippy::result_large_err)] -mod argparse; -mod blame_html; -mod bundle; -mod claude; -mod cli; -mod format; -mod git; -mod hook; -mod index; -mod ingest; -mod json; -mod output; -mod py; -mod redact; -mod rewrite; -mod s3; -mod store; -mod sys; -mod trace; - -use cli::Failure; -use output::{emit, emit_error, CommandError, Outcome, JSON_FLAG}; +use loch::cli::{self, Failure}; +use loch::output::{emit, emit_error, CommandError, Outcome, JSON_FLAG}; fn main() { let mut argv: Vec = std::env::args().skip(1).collect(); @@ -67,8 +43,7 @@ fn main() { emit(outcome, as_json); } Err(Failure::Error(error)) => emit_error(&command, error, as_json), - // Python prints a traceback here, which is the one thing a consumer - // can't parse; JSON mode gets the same `internal` document. + // A bug in this process rather than a failure a caller can act on. Err(Failure::Internal(message)) => { let mut error = CommandError::new("internal", message.clone()); if !as_json { diff --git a/rust/src/output.rs b/src/output.rs similarity index 100% rename from rust/src/output.rs rename to src/output.rs diff --git a/rust/src/py.rs b/src/py.rs similarity index 100% rename from rust/src/py.rs rename to src/py.rs diff --git a/rust/src/redact.rs b/src/redact.rs similarity index 100% rename from rust/src/redact.rs rename to src/redact.rs diff --git a/rust/src/rewrite.rs b/src/rewrite.rs similarity index 100% rename from rust/src/rewrite.rs rename to src/rewrite.rs diff --git a/rust/src/s3.rs b/src/s3.rs similarity index 100% rename from rust/src/s3.rs rename to src/s3.rs diff --git a/rust/src/store.rs b/src/store.rs similarity index 100% rename from rust/src/store.rs rename to src/store.rs diff --git a/rust/src/sys.rs b/src/sys.rs similarity index 100% rename from rust/src/sys.rs rename to src/sys.rs diff --git a/rust/src/trace.rs b/src/trace.rs similarity index 100% rename from rust/src/trace.rs rename to src/trace.rs diff --git a/rust/src/usage.txt b/src/usage.txt similarity index 100% rename from rust/src/usage.txt rename to src/usage.txt From e8640f545216e9372ae2f44e1ffdaf2928529e62 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 18 Nov 2026 10:34:51 -0500 Subject: [PATCH 14/18] CI and releases for the binary alone test.yml runs fmt, clippy and the tests on Linux and macOS. A tag now builds all six targets, packages them, assembles the npm packages and attaches everything to the GitHub release with SHA256SUMS; run by hand it rehearses all of that without publishing. release.sh bumps Cargo.toml instead of pyproject. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 101 ++++++++++++++++++++++------ .github/workflows/rust-binaries.yml | 73 -------------------- .github/workflows/test.yml | 58 ++-------------- Cargo.toml | 2 - release.sh | 57 +++++----------- 5 files changed, 103 insertions(+), 188 deletions(-) delete mode 100644 .github/workflows/rust-binaries.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4e01b16..6c8e3e3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,49 +1,108 @@ name: release +# A tag builds every platform's binary, attaches them to a GitHub release and +# assembles the npm packages beside them. Run by hand (workflow_dispatch) it +# does everything but publish, which is how to rehearse a release. on: push: tags: ["v*"] + workflow_dispatch: jobs: test: uses: ./.github/workflows/test.yml - release: + build: needs: test - runs-on: ubuntu-latest - permissions: - contents: write + strategy: + fail-fast: false + matrix: + include: + - { target: aarch64-apple-darwin, os: macos-latest } + - { target: x86_64-apple-darwin, os: macos-latest } + # musl, statically linked: one binary per architecture runs on any + # distribution, glibc or not, which is why npm has no -musl packages. + - { target: x86_64-unknown-linux-musl, os: ubuntu-latest, musl: true } + - { target: aarch64-unknown-linux-musl, os: ubuntu-24.04-arm, musl: true } + - { target: x86_64-pc-windows-msvc, os: windows-latest } + - { target: aarch64-pc-windows-msvc, os: windows-11-arm } + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash steps: - uses: actions/checkout@v7 - # setup-uv stopped publishing floating major tags after v7, so `@v10` - # 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 loch-0.1.0, and the + # A mismatch would publish v0.2.0 as assets named after 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 + - name: Check the tag against the crate version + if: startsWith(github.ref, 'refs/tags/') run: | - packaged=$(python3 -c 'import pathlib, tomllib; print(tomllib.loads(pathlib.Path("pyproject.toml").read_text())["project"]["version"])') + packaged=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1) if [ "${GITHUB_REF_NAME#v}" != "$packaged" ]; then - echo "tag ${GITHUB_REF_NAME} does not match pyproject version ${packaged}" >&2 + echo "tag ${GITHUB_REF_NAME} does not match Cargo.toml version ${packaged}" >&2 exit 1 fi - # py3-none-any, so one build serves every platform and there is no - # matrix here. The build is byte-reproducible; keep it that way. - - run: uv build + # ring compiles C, and a static musl build needs musl's own compiler. + - if: matrix.musl + run: sudo apt-get update && sudo apt-get install -y musl-tools + - run: rustup target add ${{ matrix.target }} + - run: cargo build --release --locked --target ${{ matrix.target }} + + - name: Check a Linux binary really is static + if: matrix.musl + run: file target/${{ matrix.target }}/release/loch | grep -q "statically linked" + + - name: Package + run: | + version=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1) + name=loch-$version-${{ matrix.target }} + mkdir -p "dist/$name" + bin=loch; [[ "${{ matrix.target }}" == *windows* ]] && bin=loch.exe + cp "target/${{ matrix.target }}/release/$bin" "dist/$name/" + cp LICENSE README.md "dist/$name/" + (cd dist && tar czf "$name.tar.gz" "$name") + echo "ASSET=dist/$name.tar.gz" >> "$GITHUB_ENV" + + - uses: actions/upload-artifact@v4 + with: + name: loch-${{ matrix.target }} + path: ${{ env.ASSET }} - - name: Check the wheel installs and runs + publish: + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v4 + with: + path: artifacts + merge-multiple: true + + - name: Assemble the npm packages run: | - python3 -m venv /tmp/smoke - /tmp/smoke/bin/pip install --quiet dist/*.whl - test "$(/tmp/smoke/bin/loch --version)" = "loch ${GITHUB_REF_NAME#v}" + version=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1) + args=() + for archive in artifacts/*.tar.gz; do + target=$(basename "$archive" .tar.gz); target=${target#loch-$version-} + mkdir -p "unpacked/$target" + tar xzf "$archive" -C "unpacked/$target" --strip-components 1 + args+=("$target=$(ls "unpacked/$target"/loch*)") + done + node npm/assemble.mjs "$version" npm-dist "${args[@]}" + for pkg in npm-dist/@ness-dev/*; do (cd "$pkg" && npm pack --pack-destination "$GITHUB_WORKSPACE/artifacts"); done + + - run: (cd artifacts && sha256sum * > SHA256SUMS) - # Both artifacts: the wheel is what `uv tool install` points at, the - # sdist is what anyone building from source needs. + # Rehearsals stop here, with everything built and checked. Publishing to + # npm needs the @ness-dev org and a token, and is not wired up yet. - name: Publish the release + if: startsWith(github.ref, 'refs/tags/') env: GH_TOKEN: ${{ github.token }} - run: gh release create "$GITHUB_REF_NAME" dist/* --generate-notes + run: gh release create "$GITHUB_REF_NAME" artifacts/* --generate-notes diff --git a/.github/workflows/rust-binaries.yml b/.github/workflows/rust-binaries.yml deleted file mode 100644 index 11d9c89..0000000 --- a/.github/workflows/rust-binaries.yml +++ /dev/null @@ -1,73 +0,0 @@ -name: rust-binaries - -# Builds the Rust binary for every npm platform and assembles the npm packages -# as an artifact. Manual and publish-free on purpose: it has never run, and the -# release path it will eventually join must not inherit an untested job. Fold -# it into release.yml once a run has produced binaries that pass the harness. -on: - workflow_dispatch: - inputs: - version: - description: "version to stamp into the npm packages" - required: true - -jobs: - build: - strategy: - fail-fast: false - matrix: - include: - - { target: aarch64-apple-darwin, os: macos-latest } - - { target: x86_64-apple-darwin, os: macos-latest } - # musl, statically linked: one binary per architecture runs on any - # distribution, glibc or not, which is why npm has no -musl packages. - - { target: x86_64-unknown-linux-musl, os: ubuntu-latest, musl: true } - - { target: aarch64-unknown-linux-musl, os: ubuntu-24.04-arm, musl: true } - - { target: x86_64-pc-windows-msvc, os: windows-latest } - - { target: aarch64-pc-windows-msvc, os: windows-11-arm } - runs-on: ${{ matrix.os }} - defaults: - run: - working-directory: rust - shell: bash - - steps: - - uses: actions/checkout@v7 - # ring compiles C, and a static musl build needs musl's own compiler. - - if: matrix.musl - run: sudo apt-get update && sudo apt-get install -y musl-tools - - run: rustup target add ${{ matrix.target }} - - run: cargo build --release --locked --target ${{ matrix.target }} - - - name: Check a Linux binary really is static - if: matrix.musl - run: | - file target/${{ matrix.target }}/release/loch - file target/${{ matrix.target }}/release/loch | grep -q "statically linked" - - - uses: actions/upload-artifact@v4 - with: - name: loch-${{ matrix.target }} - path: rust/target/${{ matrix.target }}/release/loch${{ contains(matrix.target, 'windows') && '.exe' || '' }} - - npm: - needs: build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/download-artifact@v4 - with: - path: binaries - - name: Assemble the npm packages - run: | - args=() - for dir in binaries/loch-*; do - target=${dir#binaries/loch-} - args+=("$target=$(ls "$dir"/loch*)") - done - node npm/assemble.mjs "${{ inputs.version }}" dist/npm "${args[@]}" - for pkg in dist/npm/@ness-dev/*; do (cd "$pkg" && npm pack --pack-destination ../../..); done - - uses: actions/upload-artifact@v4 - with: - name: npm-packages - path: dist/*.tgz diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 962d1a7..3b50594 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,7 +2,7 @@ name: test on: # Tags are excluded because the release workflow calls this one, and a tag - # push would otherwise run the whole matrix twice. + # push would otherwise run it twice. push: tags-ignore: ["**"] pull_request: @@ -14,65 +14,19 @@ concurrency: jobs: test: - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - # The floor and the ceiling of the supported range, where breakage - # appears; 3.12 is what development happens on. - python: ["3.10", "3.12", "3.13"] - - steps: - - uses: actions/checkout@v7 - - - uses: actions/setup-python@v7 - with: - python-version: ${{ matrix.python }} - - - run: pipx install poetry - - # Poetry otherwise builds the environment against its own interpreter - # rather than the one this matrix leg is for. - - run: poetry env use python - - run: poetry install - - - run: poetry run ruff check - - run: poetry run ruff format --check - - run: poetry run mypy . - - run: poetry run pytest - - # The Rust build, held to the Python reference by test/test_equivalence*.py. - # Linux and macOS because the hooks' native git fast path is Unix-only and - # its filesystem details (realpath, ownership) differ between the two. - rust: strategy: fail-fast: false matrix: + # Linux and macOS because the hooks' native git fast path is Unix-only + # and its filesystem details (realpath, ownership) differ between them. os: [ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} - defaults: - run: - working-directory: rust steps: - uses: actions/checkout@v7 - # rustup ships on both runner images and installs the version - # rust/rust-toolchain.toml pins on first use; this makes that explicit. + # rust-toolchain.toml pins on first use; this makes that explicit. - run: rustup show active-toolchain || rustup toolchain install - - run: cargo fmt --check - - run: cargo clippy --release --all-targets -- -D warnings - - run: cargo test --release - - run: cargo build --release - - - uses: actions/setup-python@v7 - with: - python-version: "3.12" - - run: pipx install poetry - - run: poetry env use python && poetry install - working-directory: . - - run: poetry run pytest -q test/test_equivalence.py test/test_equivalence_commands.py - working-directory: . - env: - LOCH_RUST: rust/target/release/loch + - run: cargo clippy --release --all-targets --locked -- -D warnings + - run: cargo test --release --locked diff --git a/Cargo.toml b/Cargo.toml index bb47998..42d3042 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,5 @@ [package] name = "loch" -# Kept equal to pyproject's version by release.sh: both implementations answer -# `loch --version`, and they must not disagree while both ship. version = "0.1.0" edition = "2021" rust-version = "1.91" diff --git a/release.sh b/release.sh index e387499..69b8b99 100755 --- a/release.sh +++ b/release.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# Cut a release. Bumps the version, verifies, tags, and pushes; CI builds the -# wheel and publishes the GitHub release from the tag. +# Cut a release. Bumps the version, verifies, tags, and pushes; CI builds every +# platform's binary and publishes the GitHub release from the tag. # # ./release.sh 0.2.0 # DRY_RUN=1 ./release.sh 0.2.0 rehearse without committing or pushing @@ -31,56 +31,33 @@ git ls-remote --exit-code --tags origin "$tag" >/dev/null 2>&1 && die "$tag alre # The tag has to point at a commit containing the workflow that builds it: a # tag-triggered run uses the workflow file as of the tagged commit. echo "==> setting version to $version" -python3 - "$version" <<'PY' -import pathlib, re, sys -path = pathlib.Path("pyproject.toml") -text = path.read_text() -new, count = re.subn(r'(?m)^version = "[^"]*"$', f'version = "{sys.argv[1]}"', text, count=1) -if count != 1: - raise SystemExit("release: could not find a single version line in pyproject.toml") -path.write_text(new) -PY -grep -q "^version = \"$version\"$" pyproject.toml || die "version bump did not apply" -# The Rust build answers `loch --version` too, and the two must agree. -python3 - "$version" <<'PY' -import pathlib, re, sys -path = pathlib.Path("rust/Cargo.toml") -text = path.read_text() -new, count = re.subn(r'(?m)^version = "[^"]*"$', f'version = "{sys.argv[1]}"', text, count=1) -if count != 1: - raise SystemExit("release: could not find a single version line in rust/Cargo.toml") -path.write_text(new) -PY -(cd rust && cargo update -q -w --offline 2>/dev/null || cargo update -q -w) +# The first `version = ` line is the package's; dependency tables come later. +sed -i.bak "1,/^version = \".*\"$/s/^version = \".*\"$/version = \"$version\"/" Cargo.toml +rm -f Cargo.toml.bak +grep -q "^version = \"$version\"$" Cargo.toml || die "version bump did not apply" -# 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" -poetry run ruff check -poetry run ruff format --check -poetry run mypy . -poetry run pytest -q -(cd rust && cargo fmt --check && cargo clippy -q --release --all-targets -- -D warnings \ - && cargo test -q --release && cargo build -q --release) -LOCH_RUST=rust/target/release/loch poetry run pytest -q test/test_equivalence.py test/test_equivalence_commands.py +cargo fmt --check +cargo clippy -q --release --all-targets -- -D warnings +cargo test -q --release +[ "$(cargo run -q --release -- --version)" = "loch $version" ] || die "--version disagrees" echo "==> tagging $tag" -# pyproject may already hold this version — the first release, or a re-cut after -# a deleted tag. An empty commit fails under `set -e`, so tag what's there. +# Cargo.toml may already hold this version — the first release, or a re-cut +# after a deleted tag. An empty commit fails under `set -e`, so tag what's there. if [ -n "$(git status --porcelain)" ]; then - run git add pyproject.toml rust/Cargo.toml rust/Cargo.lock + run git add Cargo.toml Cargo.lock run git commit -m "release: $tag" else - echo " pyproject is already at $version; tagging the current commit" + echo " Cargo.toml is already at $version; tagging the current commit" fi run git tag -a "$tag" -m "$tag" run git push origin "$BRANCH" run git push origin "$tag" if [ -n "$DRY_RUN" ]; then - git checkout -- pyproject.toml rust/Cargo.toml rust/Cargo.lock - echo "==> dry run: versions restored, nothing pushed" + git checkout -- Cargo.toml Cargo.lock + echo "==> dry run: version restored, nothing pushed" exit 0 fi @@ -89,5 +66,5 @@ cat < Date: Wed, 18 Nov 2026 10:54:25 -0500 Subject: [PATCH 15/18] Delete the Python; its tests survive as Rust integration tests The Rust build is the only implementation now. Every test in test/ was ported to tests/*.rs against the library or the binary (211 passing, 10 opt-in: live S3 endpoint and the real-transcript corpus); none needed ignoring for a behaviour difference. Three were dropped as Python-only machinery: an injectable broken redaction rule, a monkeypatched redact failure, and an uninstalled-checkout version. tests/git_fast_path.rs is new: the native HEAD answer must equal git's on every layout, and is shown to need no git process on the ones it handles. Gone with it: the equivalence harness, Poetry, the boto3 extra and s3-extra-missing, and bench/hook.py (now examples/bench_hook.rs). CLAUDE.md and the README describe a Rust-only repository; module comments no longer point at deleted files. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + CLAUDE.md | 597 ++++----- README.md | 54 +- bench/hook.py | 89 -- examples/bench_hook.rs | 140 +++ loch/__init__.py | 0 loch/blame_html.py | 273 ----- loch/bundle.py | 120 -- loch/claude.py | 250 ---- loch/cli.py | 1231 ------------------- loch/format.py | 257 ---- loch/git.py | 16 - loch/index.py | 187 --- loch/ingest.py | 450 ------- loch/output.py | 83 -- loch/redact.py | 123 -- loch/rewrite.py | 143 --- loch/store.py | 178 --- loch/trace.py | 750 ------------ poetry.lock | 1877 ----------------------------- poetry.toml | 2 - pyproject.toml | 61 - src/blame_html.rs | 6 +- src/bundle.rs | 10 +- src/claude.rs | 6 +- src/cli.rs | 8 +- src/format.rs | 2 +- src/hook.rs | 8 +- src/index.rs | 4 +- src/ingest.rs | 12 +- src/json.rs | 2 +- src/main.rs | 1 - src/output.rs | 2 +- src/redact.rs | 6 +- src/rewrite.rs | 2 +- src/store.rs | 2 +- src/trace.rs | 6 +- test/conftest.py | 8 - test/equivalence.py | 382 ------ test/test_bundle.py | 88 -- test/test_claude.py | 278 ----- test/test_cli.py | 1187 ------------------ test/test_corpus.py | 78 -- test/test_equivalence.py | 540 --------- test/test_equivalence_commands.py | 841 ------------- test/test_equivalence_corpus.py | 127 -- test/test_format.py | 165 --- test/test_git.py | 19 - test/test_index.py | 231 ---- test/test_ingest.py | 403 ------- test/test_output.py | 61 - test/test_redact.py | 149 --- test/test_rewrite.py | 238 ---- test/test_store.py | 209 ---- test/test_trace.py | 366 ------ tests/bundle.rs | 130 ++ tests/claude.rs | 351 ++++++ tests/cli.rs | 1544 ++++++++++++++++++++++++ tests/corpus.rs | 192 +++ tests/derived_reader/mod.rs | 143 +++ tests/format.rs | 287 +++++ tests/git.rs | 40 + tests/git_fast_path.rs | 354 ++++++ tests/index.rs | 342 ++++++ tests/ingest.rs | 596 +++++++++ tests/output.rs | 159 +++ tests/redact.rs | 222 ++++ tests/rewrite.rs | 274 +++++ tests/store.rs | 306 +++++ tests/trace.rs | 712 +++++++++++ 70 files changed, 6084 insertions(+), 11899 deletions(-) delete mode 100644 bench/hook.py create mode 100644 examples/bench_hook.rs delete mode 100644 loch/__init__.py delete mode 100644 loch/blame_html.py delete mode 100644 loch/bundle.py delete mode 100644 loch/claude.py delete mode 100644 loch/cli.py delete mode 100644 loch/format.py delete mode 100644 loch/git.py delete mode 100644 loch/index.py delete mode 100644 loch/ingest.py delete mode 100644 loch/output.py delete mode 100644 loch/redact.py delete mode 100644 loch/rewrite.py delete mode 100644 loch/store.py delete mode 100644 loch/trace.py delete mode 100644 poetry.lock delete mode 100644 poetry.toml delete mode 100644 pyproject.toml delete mode 100644 test/conftest.py delete mode 100644 test/equivalence.py delete mode 100644 test/test_bundle.py delete mode 100644 test/test_claude.py delete mode 100644 test/test_cli.py delete mode 100644 test/test_corpus.py delete mode 100644 test/test_equivalence.py delete mode 100644 test/test_equivalence_commands.py delete mode 100644 test/test_equivalence_corpus.py delete mode 100644 test/test_format.py delete mode 100644 test/test_git.py delete mode 100644 test/test_index.py delete mode 100644 test/test_ingest.py delete mode 100644 test/test_output.py delete mode 100644 test/test_redact.py delete mode 100644 test/test_rewrite.py delete mode 100644 test/test_store.py delete mode 100644 test/test_trace.py create mode 100644 tests/bundle.rs create mode 100644 tests/claude.rs create mode 100644 tests/cli.rs create mode 100644 tests/corpus.rs create mode 100644 tests/derived_reader/mod.rs create mode 100644 tests/format.rs create mode 100644 tests/git.rs create mode 100644 tests/git_fast_path.rs create mode 100644 tests/index.rs create mode 100644 tests/ingest.rs create mode 100644 tests/output.rs create mode 100644 tests/redact.rs create mode 100644 tests/rewrite.rs create mode 100644 tests/store.rs create mode 100644 tests/trace.rs diff --git a/.gitignore b/.gitignore index 66fff4c..de3e2fc 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,6 @@ target/ .DS_Store .claude/settings.local.json *.loch +# Python tooling a contributor might still run beside the repo. +__pycache__/ +.venv/ diff --git a/CLAUDE.md b/CLAUDE.md index dc8b8bd..2c90689 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,42 +146,47 @@ public API. Re-verify if something breaks. ## Layout -Python 3.10 through 3.13, Poetry, boto3 behind an extra. +One Rust crate at the root: a library holding every module, and the `loch` +binary on top of it. The toolchain is pinned in `rust-toolchain.toml`. ``` -loch/ -├── cli.py # entry point, arg parsing, list/save/restore/delete/reindex/ingest -├── claude.py # Claude Code adapter: path encoding, session discovery, metadata -├── bundle.py # bundle format, gzip, content-addressed ref -├── format.py # loch format: canonical JSON, turn and content ids, derived files -├── ingest.py # Claude Code JSONL -> loch turns (the converter) -├── index.py # store key layout, derived index entries, delete and reindex -├── trace.py # commit -> conversation notes, hooks, blame, log, backfill, ask's fork -├── blame_html.py # `blame --html`: self-contained page, no external assets -├── git.py # current branch of a checkout, for the list default -├── output.py # result envelope, the two renderers, structured failures -├── redact.py # secret scrubbing, applied on save before packing -├── rewrite.py # path rewriting (the load-bearing logic) -└── store.py # Store interface + local-fs and S3-compatible backends -test/ -├── test_corpus.py # opt-in, against this machine's transcripts (LOCH_CORPUS=1) -├── equivalence.py # the harness: run both builds, compare everything -├── test_equivalence*.py # opt-in, Rust vs Python (LOCH_RUST=) -└── test_*.py # one module per source module -rust/ # the Rust build: one crate, binary `loch` (see "The Rust build") -├── src/ # one module per Python module, plus argparse/json/py/sys -├── bench/hook.py # per-call wall clock of `loch hook`, any number of binaries -└── rust-toolchain.toml -npm/ # @ness-dev/loch and its per-platform packages +src/ +├── main.rs # argv handling, dispatch, the two renderers' entry point +├── cli.rs # every command: list/save/restore/delete/reindex/ingest/install/ +│ # blame/log/ask/backfill/hook/help/version +├── claude.rs # Claude Code adapter: path encoding, session discovery, metadata +├── bundle.rs # bundle format, gzip, content-addressed ref +├── format.rs # loch format: turn and content ids, derived files +├── ingest.rs # Claude Code JSONL -> loch turns (the converter) +├── index.rs # store key layout, derived index entries, delete and reindex +├── trace.rs # commit -> conversation notes, install, blame, log, backfill, ask's fork +├── hook.rs # `loch hook`: the Claude Code hooks +├── git.rs # git by subprocess, plus the hooks' native HEAD fast path +├── blame_html.rs # `blame --html`: self-contained page (blame_template.html) +├── output.rs # result envelope, the two renderers, structured failures +├── redact.rs # secret scrubbing, applied on save before packing +├── rewrite.rs # path rewriting (the load-bearing logic) +├── store.rs # Store interface + local-fs backend +├── s3.rs # the S3-compatible backend, SigV4 by hand +├── json.rs # JSON reading and writing, RFC 8785 canonical form +├── argparse.rs # command-line parsing, usage errors and -h +├── py.rs # string semantics: whitespace, lone surrogates, ordering +└── sys.rs # paths, timestamps, OS error strings, hostname, uuid4 +tests/ # integration tests, one file per module plus cli.rs +├── derived_reader/ # a verifying reader for derived files, shared by three tests +├── corpus.rs # opt-in, against this machine's transcripts (LOCH_CORPUS=1) +└── git_fast_path.rs # the native HEAD answer equals git's, layout by layout +examples/bench_hook.rs # per-call wall clock of `loch hook`, any number of binaries +npm/ # @ness-dev/loch and its per-platform packages ``` -`ingest.py` normalizes with `rewrite.py`'s machinery rather than its own: -`compile_replacements` is the same single pass with the same guards, fed +`ingest.rs` normalizes with `rewrite.rs`'s machinery rather than its own: +`rewrite::compile` 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 +`tests/corpus.rs` is the check that it still holds on real data: 3809 of 3810 sessions keep every turn id across a simulated move, and the one that doesn't is a transcript that already contains the destination paths (SPEC.md §14.1). @@ -222,8 +227,8 @@ before the bundle, since the entries are derived from it and losing the bundle first would strand them. `Store.delete` on an absent key succeeds, which is what lets either repair run. -`claude.py` decides **which** cwd a session gets, and everything in -`rewrite.py` is downstream of that answer: `SessionMeta.cwd` becomes the +`claude.rs` decides **which** cwd a session gets, and everything in +`rewrite.rs` is downstream of that answer: `SessionMeta.cwd` becomes the bundle manifest's cwd and then `RewriteSpec.origin_cwd`, so one wrong value poisons the whole rewrite. Because a session can hold several cwds (see above), it is chosen by comparing `encode_path` of each against the @@ -272,13 +277,16 @@ Optimise the per-file path if this ever matters. Reinstating a cap would buy back a fraction of a second on one anomalous directory in exchange for being silently wrong again. -`rewrite.py` is where correctness actually lives. It does a **single +`rewrite.rs` is where correctness actually lives. It does a **single left-to-right pass** with longest-match-first alternation, so a substitution's output can never be re-matched by a later pair. The hazard it guards against: a cwd nested under a home directory getting half-rewritten if the pairs were applied sequentially. Keep the -single-pass property if you touch it — one alternation regex, one -`re.sub`, never a loop of `str.replace` calls. +single-pass property if you touch it — one scan that tries every source at +each position, never a loop of `replace` calls. The scan is written by +hand (`Replacer::apply`) because the guards are lookaheads, which the +`regex` crate doesn't have; a source repeated with two targets maps to the +last one. The second property is a **boundary rule**: a path is only substituted where the match ends on a path-component boundary. Without it a sibling @@ -288,7 +296,7 @@ became the target path with its own tail duplicated. That failure was **silent**, and that is the part worth remembering: the corrupted string no longer contains the origin, so `residual_origin_paths` reported a clean rewrite across 239 bad values in one restored session. The guards are -per-alternative zero-width lookaheads, which is what keeps them compatible +per-alternative zero-width lookaheads (`Guard`), which is what keeps them compatible with the single pass — an alternative that fails its guard falls through to a shorter one, so `/Users/mike/projector` still gets its home rewritten after the cwd pair declines. @@ -350,7 +358,7 @@ a known non-chosen session cwd" is an exact match against a small known set, needs nothing from the far side, and fits the single pass — an identity pair sorts ahead of the shorter home pair by length, matches, and consumes the string, so the home pair never sees it. -`_apply_replacements` filters identity pairs out via `source != dest` and +`rewrite::compile` filters identity pairs out via `source != dest` and would have to admit them deliberately, which is a small change rather than a fight with the design. It is not built because reporting is sufficient and `--map` supersedes it: a mapping makes those records @@ -365,7 +373,7 @@ directories can have *every* one of them land somewhere real instead of one landing right and the rest being counted. It is the natural successor to `foreignCwds`: the report tells a caller which directories came out wrong, and the flag is how they say what those should become. -Nothing in `rewrite.py` needs to change to accept it — pairs already +Nothing in `rewrite.rs` needs to change to accept it — pairs already carry their own boundary guard and are already sorted longest-first, and **that sort must keep being by length rather than by caller order**: the single-pass guarantee depends on a nested path matching before the @@ -383,7 +391,7 @@ it is the one value nothing on either side can derive. Note the destination worktree must be `realpath`'d: git reports canonical paths, so `/tmp/...` comes back as `/private/tmp/...` and a lookup keyed on the uncanonical form silently misses. That is the same symlink resolution -`claude.py` does, for the same reason. +`claude.rs` does, for the same reason. The encoded slug takes a stricter rule for a reason that can't be fixed: `encode_path` maps every non-alphanumeric to `-`, so `/sub` and @@ -394,7 +402,7 @@ limitation, and the false negative is the deliberate half of it — don't "fix" it by loosening the guard, that reintroduces the corruption. The session-id pair is a UUID rather than a path and carries no guard. -`redact.py` scrubs secrets out of a transcript on `save`, before packing. +`redact.rs` scrubs secrets out of a transcript on `save`, before packing. It is **best-effort pattern matching and nothing more.** It finds credentials with distinctive structure (AWS/GitHub/Slack/Stripe/ Anthropic/OpenAI/Google keys, JWTs, PEM blocks) plus one context rule for @@ -409,12 +417,13 @@ they fire on every hash, UUID, and base64 blob in a transcript. Three properties it has to keep: -- **The local transcript is never modified.** `cli.py` reads, redacts the +- **The local transcript is never modified.** `cli.rs` reads, redacts the in-memory copy, packs that. Redaction changes the packed bytes and therefore the ref; that is correct, the redacted bundle is the artifact. -- **Single pass, same discipline as `rewrite.py`** — one alternation of - named groups, one `re.sub` — so no rule can match inside another rule's - replacement. The `env-assignment` value carries a `(?!\[REDACTED:)` +- **Single pass, same discipline as `rewrite.rs`** — one left-to-right + scan in which the next match is the earliest any rule makes, ties to rule + order — so no rule can match inside another rule's replacement. How that + scan is made fast without changing an answer is under Performance. The `env-assignment` value carries a `(?!\[REDACTED:)` lookahead for the same reason: without it, re-scanning `TOKEN=[REDACTED:env-assignment]` matches all over again. - **Redacted output is re-scanned, and a surviving match aborts the @@ -428,8 +437,8 @@ Three properties it has to keep: Counts are reported per session by rule name. **Never print the match**, not even truncated — `save`'s stdout lands in the next agent's transcript. -`save` is not the only path transcript content escapes on, so `claude.py` -scrubs the `list` summary too, in `_display_summary`. That summary is the +`save` is not the only path transcript content escapes on, so `claude.rs` +scrubs the `list` summary too, in `display_summary`. That summary is the first user message, it reaches a picker row and a pasted bug report without a `save` in between, and it is the only such field. Two ordering points: redact *before* truncating, since a cut can leave a secret's tail matching @@ -444,7 +453,7 @@ value needs a parser, so that failure mode stays — it mangles a line of code in the packed copy, it doesn't leak. The prefixed-key rules match nothing in that corpus, which is the point of the word boundaries. -Two smaller things `bundle.py` has to keep doing, because the ref is a +Two smaller things `bundle.rs` has to keep doing, because the ref is a hash of the packed bytes and any drift changes a bundle's identity: JSON is packed compactly (`separators=(",", ":")`, `ensure_ascii=False`), and absent session metadata is omitted rather than serialized as `null`. @@ -496,7 +505,6 @@ never a code. The set today: | `missing-ref` | `restore`/`delete` called without a ref | | `bundle-not-found` | the store answered and the ref isn't there | | `store-unreachable` | the store didn't answer | -| `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 | @@ -509,30 +517,28 @@ never a code. The set today: | `usage` | argparse rejected the arguments (exit status 2) | | `internal` | an unexpected exception | -The four store-facing codes — `bundle-not-found`, `store-unreachable`, -`s3-extra-missing`, `bundle-unreadable` — are one failure to a human and four -different affordances to a caller: don't retry, retry, reinstall, report -corruption. Telling them apart is why `store.py` raises typed -`MissingObject` and `MissingDependency` exceptions — a bare `except Exception` -around a store call can only produce the union, and `s3-extra-missing` was -`store-unreachable` until boto3 became optional, which told a caller to retry -a network problem that was really a missing package. The `store_errors` block -wraps the store call *alone*, since anything wider would relabel a bug in -this process as a failure of the store. - -**Exactly one document per invocation, including the paths argparse owns.** -argparse answers `-h` and a bad flag itself, writing prose and exiting -before a command ever runs, so `_Parser` routes both back through `main()`. -An unexpected exception becomes `code: "internal"` in JSON mode and stays a -traceback without the flag, since a traceback is the most useful thing a -human can get and the one thing a consumer can't parse. +The three store-facing codes — `bundle-not-found`, `store-unreachable`, +`bundle-unreadable` — are one failure to a human and three different +affordances to a caller: don't retry, retry, report corruption. Telling them +apart is why `StoreError` has `Missing` and `Unreachable` variants and an +unpack failure is its own error: a catch-all around a store call can only +produce the union. Map the store call *alone* to a store code, since +anything wider would relabel a bug in this process as a failure of the +store. (`s3-extra-missing` existed while S3 needed an optional Python +package; the binary carries its client, so it can't arise and is gone.) + +**Exactly one document per invocation, including parse failures.** +`argparse.rs` returns `-h` and a bad flag as `Exit` values rather than +printing and exiting, so `main()` renders both in the mode asked for. A bug +becomes `code: "internal"`, which in text mode is `loch: internal error: …` +on stderr. **Raw values, not renderings.** `format_bytes` and the fixed-width columns of `describe`/`describe_entry` belong to the text mode alone: the payload carries the integer and the ISO-8601 `...Z` timestamp. An empty result is `{"sessions": []}` with `ok: true`, never an error. -The `list --remote` payload is deliberately *not* `index.py`'s stored entry +The `list --remote` payload is deliberately *not* `index.rs`'s stored entry shape even though the fields line up. One is a storage format, the other is a versioned wire contract, and they change for different reasons. @@ -553,207 +559,127 @@ plus a `redacted` total, exactly as much as the prose summary carries and no more — `save`'s stdout lands in the next agent's transcript. The one field holding transcript content is `list`'s `summary` (the first 120 characters of the first user message, which the text output already prints), and it is -scrubbed in `claude.py` before it ever becomes a `SessionMeta`. It should +scrubbed in `claude.rs` before it ever becomes a `SessionMeta`. It should stay the only such field. ## Packaging and release -The distribution path is `uv tool install `: uv is a static -binary that brings its own CPython, so a machine being bootstrapped over SSH -needs no Python toolchain and there is no PyPI account in the loop. That -constrains three things. - -**Supported range is 3.10 through 3.13, with no upper bound.** The old -`>=3.12,<3.13` was pinning copied from an unrelated backend, and it is what -made `pipx install` fail on both ends — Ubuntu 22.04 ships 3.10, and a 3.13 -box failed the cap. Never reintroduce a ceiling: the next Python breaks the -install before it breaks the code. 3.10 is the floor because PEP 604 `X | None` -unions are pervasive and 3.9 would mean rewriting every annotation. One line -actually needed 3.12 — a backslash inside an f-string expression, PEP 701 -syntax — so keep interpolations backslash-free. `[tool.mypy] python_version` -is pinned to the floor rather than following the running interpreter, so a -3.11+ API fails on a 3.13 laptop and not only in CI. - -**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 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. - -**`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 -3.10. It is a `Result` like every other command, so `--version --json` is an -envelope. - -CI lives in `.github/workflows/`. `test.yml` runs ruff, mypy and pytest across -3.10/3.12/3.13 — the floor and the ceiling are where breakage appears — and -`release.yml` calls it via `workflow_call` rather than repeating it, so an -untested tag cannot publish. Releasing is `./release.sh `, which bumps -pyproject, runs the same four checks, commits, tags and pushes. It refuses a -dirty tree, a branch behind origin, or an existing tag, because a bad tag is -expensive to undo: a tag-triggered run uses the workflow file *as of the tagged -commit*, so a broken workflow can't be repaired by re-running the tag — the tag -has to be deleted from the remote and re-cut. Actions must be pinned to versions -that exist; `setup-uv` stopped publishing floating major tags after `v7`, and -`@v10` failed the first release attempt. The workflow independently refuses a -tag that disagrees with pyproject, since the install path is a pinned asset URL -and a wheel named after the wrong version is not something to discover -afterwards. `uv build` emits a -`py3-none-any` wheel — universal, hence no platform matrix — plus an sdist, and -both are attached to the GitHub release. The build is byte-reproducible; don't -introduce anything timestamp-dependent into it. There is deliberately no PyPI -publishing. - -## The Rust build - -The goal is one static binary that Ness, a VS Code extension and the Claude -Code hooks can ship and run, with no Python on the machine. **Every command -is ported**, and each is held to the Python by the equivalence harness. The -Python package is still the reference until it is deleted. Until then a -behaviour change lands in Python first, with the harness carrying it to Rust, -and the Python suite keeps passing on its own. - -**Layout: `rust/`, one crate, not a root workspace.** The repository root -belongs to Poetry (pyproject, the `loch` package, `release.sh`), and a root -`Cargo.toml` would mean two build systems claiming the same directory and a -`target/` beside the wheel's sources. The modules mirror the Python ones -(`cli.rs` ↔ `cli.py`, `rewrite.rs` ↔ `rewrite.py`, `hook.rs` ↔ the hook half -of `trace.py`, …) plus four that Python gets from its standard library: -`argparse.rs`, `json.rs`, `py.rs` (string semantics) and `sys.rs` -(`os.path`, `datetime`, `OSError` strings). One crate is enough until a -second binary needs a library; that is the point to make `rust/` a -workspace, and nothing outside it moves. - -The toolchain is pinned in `rust/rust-toolchain.toml` (1.91.0), scoped to -`rust/` so it never changes anyone's default. 1.83, which was installed, -can't build today's `url`/`idna`. - -### What "equivalent" had to mean, and what it cost - -Byte-for-byte, on stdout, stderr, exit status and every file written — the -standard the harness enforces — rules out leaning on Rust's libraries -wherever Python's behaviour is the specification. In the order they bit: - -- **JSON is Python's, not serde's.** `json.rs` parses as `json.loads` does - (duplicate keys keep their first position and last value, integers stay - exact at any size, `NaN`/`Infinity` accepted) and writes every flavour loch - uses (`ensure_ascii`, compact, sorted, `indent=2`, float `repr`) plus RFC - 8785. serde_json refuses lone surrogates, and **five transcripts on one - machine hold them** (`\ud83d` cut from its pair by truncation). +loch is one static binary, built for six targets: macOS arm64 and x64, Linux +arm64 and x64 (musl, statically linked, so one build runs on any +distribution, glibc or not) and Windows arm64 and x64. Its only runtime +dependency is `git` on PATH, for the commands that touch a repository. +zlib and rustls are compiled in. + +**Releasing** is `./release.sh `, which bumps `Cargo.toml`, runs +the checks, commits, tags and pushes. It refuses a dirty tree, a branch +behind origin, or an existing tag, because a bad tag is expensive to undo: a +tag-triggered run uses the workflow file *as of the tagged commit*, so a +broken workflow can't be repaired by re-running the tag. The tag has to be +deleted from the remote and re-cut. + +`release.yml` calls `test.yml` first, so an untested tag can't publish. It +then refuses a tag that disagrees with `Cargo.toml`, builds the matrix, +checks the Linux binaries really are static, and attaches a tarball per +target, the npm packages and `SHA256SUMS` to the GitHub release. Run by hand +(`workflow_dispatch`), it does all of that except publishing, which is how +to rehearse. Actions must be pinned to versions that exist: `setup-uv` +stopped publishing floating major tags after `v7`, and `@v10` failed the +first release attempt. + +**npm, the way Claude Code is shipped:** `@ness-dev/loch` with +`optionalDependencies` on `@ness-dev/loch-{darwin,linux,win32}-{arm64,x64}`, +each declaring `os`/`cpu` and holding one binary, so npm installs only the +host's. `npm/platforms.json` maps target triples to packages, and +`npm/assemble.mjs` lays out a release's packages from built binaries. The +release workflow builds the tarballs but **doesn't publish to npm yet**: +that needs the `@ness-dev` org and a token. Assembling, `npm pack` and a +global install were dry-run locally for darwin-arm64. + +Linux packages aren't split by libc, which differs from Claude Code's. +Ness's resolver adds `-musl` on musl hosts, so it must not do that for loch. + +**Embedders spawn the platform binary, never a Node shim.** Measured: going +through the wrapper's Node launcher costs ~24ms a call (27ms against 3ms), +which hands most of the hooks' speed back on every Bash call. +- **The path:** `index.js` exports `binaryPath()`, the same `createRequire` + plus `app.asar` → `app.asar.unpacked` resolution Ness already uses for + Claude Code. +- **Electron:** an app must `asarUnpack` `**/node_modules/@ness-dev/loch-*/**`. +- **Global installs:** for `npm install -g`, the postinstall replaces + `bin/loch` with a hardlink to the native binary, so the `loch` on PATH is + the binary itself. With `--ignore-scripts`, or on Windows, where npm runs + bins through a `.cmd` wrapper anyway, the shim remains and still works. +- **Hooks:** Ness should write the binary's absolute path with `loch install + --local --command ` (settings.local.json, since the path is + machine-specific) rather than rely on PATH. + +**Builds reproduce.** `SOURCE_DATE_EPOCH` fixes `save`'s `createdAt`, the +one clock in a bundle's bytes, so the same sessions pack to the same ref. + +**`uv tool install` is gone.** loch used to ship as a pure-Python wheel; a +machine that installed it that way has a `loch` on PATH that predates this +binary. It should `uv tool uninstall loch` and take a release tarball or the +npm package instead. Hook lines written by `install` name plain `loch`, so +PATH order decides which one the hooks run until the old one is removed. + +## Why some of the code looks the way it does + +loch was written in Python first and ported to Rust. Before the Python was +deleted, the port was held to it **byte for byte**: stdout, stderr, exit +status and every file written, over 51 synthetic scenarios and every project +directory on one machine (472, all identical). That standard is why several +modules reimplement things a crate would normally provide. Nothing requires +that compatibility any more, so change them freely, but know what each was +protecting: + +- **`json.rs` instead of serde_json.** serde refuses lone surrogates, and + **five transcripts on one machine hold them** (a `\ud83d` cut from its pair + by truncation). It also rounds integers wider than 64 bits and rejects + `NaN`. Every turn id is a hash over `json::canonical`, so how a transcript + parses decides every id. - **Lone surrogates are mapped into U+10F800..U+10FFFF** (`py.rs`), since a - Rust `String` can't hold one. That covers both the JSON escape and - `surrogateescape`'s undecodable bytes. They are mapped back wherever Python - would write them, and they sort, escape and canonicalize as the surrogate. - The cost: a transcript holding those private-use code points literally - would be misread. The corpus check asserts none on this machine does. -- **Python's whitespace is not Rust's.** `str.isspace` (and so `\s`, - `split()`, `strip()`) includes U+001C..U+001F, which Unicode White_Space - doesn't. `py::is_space` is the 29 code points Python says, and every - ported pattern spells `\s` out as that set. -- **argparse is ported, not approximated** (`argparse.rs`, from 3.12.10). Its - usage errors and `-h` text are output, so the A/O/- pattern matching, - abbreviation, `--opt=value`, `--`, the help formatter's wrapping at - `COLUMNS` and the 3.12.10 rule that stops a `nargs="?"` positional being - consumed empty before an option all had to match. The harness runs every - command through fifteen bad command lines at four widths. + Rust `String` can't hold one. That covers both JSON escapes and + `surrogateescape`d undecodable bytes. They are mapped back wherever they + are written, and they sort, escape and canonicalize as the surrogate. The + cost: a transcript holding those private-use code points literally would + be misread. The corpus check asserts none on this machine does. +- **Whitespace is `py::is_space`**, the 29 code points that include + U+001C..U+001F, not Unicode White_Space. Redaction's `\s` uses the same + set. +- **`argparse.rs`** reproduces Python's argparse: abbreviation, + `--opt=value`, `--`, the A/O/- matching that decides what a `nargs="?"` + positional takes, and the help formatter's wrapping at `COLUMNS`. Usage + errors exit 2. - **zlib's own deflate**, through flate2's zlib backend (memLevel 8, raw - window 15, which is `zlib.compressobj(9, DEFLATED, -15, 8, 0)`), because - the ref is a hash of the gzip bytes and miniz_oxide compresses differently. - zlib is built from source and linked statically. -- **The rewrite and redaction regexes are run by hand** where a regex crate - couldn't express them: `rewrite.rs` executes the one-alternation `re.sub` - as an explicit scan with per-alternative guards (and, as in Python, a - source repeated with two targets maps to the last). `redact.rs` is - described below. -- **Error strings are Python's**: `str(OSError)` (`[Errno 2] No such file or - directory: '/x'`), binascii's strict-mode base64 messages, botocore's - `An error occurred (Code) when calling the Op operation: Message`, - `gzip`'s `Not a gzipped file (b'ga')`. They reach the `error` field. -- **boto3's request shapes**: a listing sends `encoding-type=url` and - decodes the keys, in boto3's parameter order, because the URL appears in a - connection error. - -**Three bugs in the reference turned up and were fixed in Python first**, -because the rule is that the reference stays the reference: - -- **Bundle refs depended on the Python version and the platform.** From 3.11 - `gzip.compress` lets zlib write the header's OS byte, 19 on macOS and 3 on - Linux, where 3.10 wrote 255. So the same sessions packed to a different - ref per machine. The header is now written by hand, byte-identical to - 3.10's everywhere. Bundles saved before keep their refs, but a re-save of - the same sessions from 3.11+ gets a new one. -- **One undecodable byte took down `list`** for the whole directory, since - `read_session_meta` caught `OSError` only. Metadata now decodes with - replacement, and `save` refuses such a session as `transcript-unreadable` - instead of with a traceback. -- **`save` wasn't reproducible**, since `createdAt` is part of the hashed - bytes. `SOURCE_DATE_EPOCH` now fixes it in both builds. That is the - reproducible-builds convention, and it is what lets the harness compare - two builds' refs at all. - -**Divergences that remain, deliberately:** - -- An unexpected exception is a traceback in Python and `loch: internal - error: …` in Rust. JSON mode matches, both being `code: "internal"`. -- A naive (offset-less) ISO timestamp is local time to Python and UTC to - Rust. Transcripts always carry `Z`. -- Unicode digits (`int("١٢")`) are accepted by a few of Python's parses and - by none of Rust's. -- The S3 credential chain stops at env and the shared files. SSO, + window 15), behind a fixed gzip header (OS byte 255, XFL 2). The ref is a + hash of those bytes, and miniz_oxide compresses differently. Changing + either changes the ref of every bundle. +- **Error strings** follow Python's conventions: `[Errno 2] No such file or + directory: '/x'`, botocore's `An error occurred (Code) when calling the Op + operation: Message`. They reach the `error` field, which consumers + shouldn't parse anyway. + +Three defects in the Python turned up during the port and were fixed in both +builds before it was deleted: +- **Refs that varied by platform.** From 3.11, Python let zlib write the gzip + OS byte, so the same sessions got a different ref on macOS and Linux. That + is why the header is fixed now. +- **One bad byte took down a listing.** An undecodable byte took down `list` + for a whole directory, which is why metadata decodes with replacement and + `save` refuses such a session as `transcript-unreadable`. +- **`save` wasn't reproducible**, which is why `SOURCE_DATE_EPOCH` exists. + +Known gaps: +- **S3 credentials:** the chain reads env and the shared files only. SSO, `credential_process`, assumed roles and instance metadata are not read. -- Windows compiles in principle and has never been built. - -While the port was partial, unported commands answered `not-ported`. With -nothing left unported that code is gone, and an unknown name is -`unknown-command` in both builds. - -### The harness - -`test/equivalence.py` is the machinery, and three modules use it: -`test_equivalence.py` (hooks), `test_equivalence_commands.py` (everything -else, including an S3 run against moto) and `test_equivalence_corpus.py` -(real transcripts). All are opt-in with `LOCH_RUST=`, and the corpus -also needs `LOCH_CORPUS=1`. - -How a scenario runs: -- **Twice, identically.** Each scenario is built twice at the same path with - pinned git dates, session mtimes and `SOURCE_DATE_EPOCH`. Python drives - one copy and the binary the other. -- **Everything is compared.** That means every file under the scratch root - (git's own churn aside) plus the notes ref, HEAD and `notes.rewriteRef`. -- **Generated values are renamed.** v4 UUIDs, which `--new-id` and `ask`'s - fork mint, become `UUID-n` in order of first appearance. Fixture ids are - deliberately not v4. -- **Mixed runs.** The hook scenarios also run pre-tool under one build and - post-tool under the other, which is what a machine switching over - mid-session does. That is why the pending file's shape is a contract - between the two. - -**Planted bugs fail it.** That was checked, not assumed: a changed redaction -token, a loosened path guard, the home-is-root rule, an argparse message, a -float exponent boundary, a prose string, the prompt walk in `trace`, the -percent-encoding of index segments, a converter fact name, a wrong -`captured` value, a loosened hook time bound and a corrupted signing key -each fail at least one scenario. Each of those first came back *green* -until a scenario exercised it. The float one needed floats added to the -fixtures, which is the reason to keep doing this whenever a scenario is -added. - -**The corpus check** lists, saves, restores (onto a temporary HOME) and -ingests every project directory on the machine with both builds, in -parallel (`LOCH_CORPUS_JOBS`). It is read-only towards `~/.claude`, and a -failure names a directory and a byte offset or hash, never content. - -### Performance - -**`loch hook`: 3ms a call instead of ~73ms.** Measured with -`rust/bench/hook.py` against the `uv tool` install, median of 60: +- **Timestamps:** a naive (offset-less) ISO timestamp is read as UTC. + Transcripts always carry `Z`. +- **Windows** has never been built. + +## Performance + +**`loch hook`: 3ms a call.** The Python it replaced took ~73ms (measured +with `examples/bench_hook.rs`, median of 60): | case | Python | Rust | | --- | --- | --- | @@ -762,97 +688,49 @@ failure names a directory and a byte offset or hash, never content. | post-tool, writing a note | 98.5ms | 27.3ms | The hooks run twice per agent shell command, so that is ~145ms of every -Bash call down to ~6ms. Python's cost was ~50ms of imports -(`importlib.metadata` alone is 19ms) and ~8ms per `git` process, of which -the hot path ran two. - -Getting under the git floor is the fast path in `git.rs`: where the git -directory is and what HEAD is are answered by reading `.git` (a worktree's -`gitdir:` file, `commondir`, loose and packed refs) instead of spawning git. -It answers only on layouts it fully understands and says "ask git" for -anything else: a discovery-changing `GIT_*` variable, reftable, a repository -owned by another user (`safe.directory`), a cwd inside `.git`, an -unparseable ref, and Windows outright. **A gap there may only ever cost -speed, never a different answer.** The harness checks that with reftable, -`GIT_DIR`, worktree, packed-refs, detached, unborn and symlinked scenarios. -Writing a note still runs `git log` and `git notes`, which is the remaining -24ms, and it happens only when a call committed. - -**Redaction was most of `save`'s cost in both builds**: 150s in Python and -264s in Rust (first cut, fancy-regex) over 15 project directories. A -backtracking engine tries all ten rules at every position, and -`env-assignment` can begin at any capital. `redact.rs` gives the same -answers with a restructured search: -- **The nine prefixed rules** become plain `regex` crate searches, linear and +Bash call down to ~6ms. + +Getting under the cost of spawning git (~8ms a process) is the fast path in +`git.rs`: where the git directory is and what HEAD is are answered by +reading `.git` (a worktree's `gitdir:` file, `commondir`, loose and packed +refs) instead of spawning git. It answers only on layouts it fully +understands and says "ask git" for anything else: a discovery-changing +`GIT_*` variable, reftable, a repository owned by another user +(`safe.directory`), a cwd inside `.git`, an unparseable ref, and Windows +outright. **A gap there may only ever cost speed, never a different +answer.** `tests/git_fast_path.rs` checks the native answer against git's on +each layout. Writing a note still runs `git log` and `git notes`, which is +the remaining 24ms, and that happens only when a call committed. + +**Redaction is most of `save`'s cost.** A backtracking engine tries all ten +rules at every position, and `env-assignment` can begin at any capital: over +15 project directories that was 150s in Python and 264s in a first Rust cut +with fancy-regex. `redact.rs` gives the same answers with a restructured +search, 15s: +- **The nine prefixed rules** are plain `regex` crate searches, linear and with leftmost-first semantics equal to backtracking. Their one-character - START/END checks are made by hand. + boundary checks are made by hand. - **`env-assignment`** is tried, anchored, only at the start of an `[A-Z0-9_]` run that holds a keyword. Every way it could match from inside the run is also a way from the run's start, so that is the only candidate. - **The next match** is the earliest position any rule matches at, ties going to rule order. -That brought it to 15s. The full Python alternation stays in the tests as an -oracle, fuzzed against the fast path over 40k generated strings that -exercise every rule (the test asserts each rule matched, so the fuzz can't -pass vacuously). **Python's redaction is still the slow one**, which is why -the corpus check runs in parallel. It is the reference, so it was left -alone. +The full alternation stays in the unit tests as an oracle, fuzzed against +the fast path over 40k generated strings that exercise every rule. The test +asserts each rule matched, so it can't pass vacuously. -**S3 is SigV4 by hand over `ureq`/rustls**, not the AWS SDK; four request +**S3 is SigV4 by hand over `ureq`/rustls**, not the AWS SDK: four request kinds don't justify an async runtime and several MB. The signer is pinned to AWS's two published examples (a header-signed GET and a signed query -string). The stop hook is checked against a moto server with IAM auth on, so -a bad signature is refused. moto's verifier itself rejects boto3's correct -signatures on keys holding a space or `+` and on prefixed listings, so the -command-level S3 test runs with auth off; a failure that looks like a -signing bug in exactly those cases is moto's. A store that doesn't answer -fails after 20s rather than holding a turn. - -### Packaging - -**npm, the way Claude Code is shipped:** `@ness-dev/loch` with -`optionalDependencies` on `@ness-dev/loch-{darwin,linux,win32}-{arm64,x64}`, -each declaring `os`/`cpu` and holding one binary, so npm installs only the -host's. `npm/platforms.json` is the target-triple → package map, -`npm/assemble.mjs` lays out a release's packages from built binaries, and -`.github/workflows/rust-binaries.yml` (manual, publish-free, **never run**) -builds all six targets and assembles them. Assembling, `npm pack` and a -global install were dry-run locally for darwin-arm64. - -Linux binaries are static musl, so one package per architecture serves -glibc and musl alike. That is a deliberate difference from Claude Code's -packages, and Ness's resolver adds `-musl` on musl hosts, so it must not do -that for loch. - -**Embedders spawn the platform binary, never a Node shim.** Measured: going -through the wrapper's Node launcher costs ~24ms a call (27ms against 3ms), -which hands most of the port's win back on every hook. So `index.js` -exports `binaryPath()` — the same `createRequire` + `app.asar` → -`app.asar.unpacked` resolution Ness already uses for Claude Code — and an -Electron app must `asarUnpack` `**/node_modules/@ness-dev/loch-*/**`. For a -global `npm install -g`, the postinstall replaces `bin/loch` with a hardlink -to the native binary, so the `loch` on PATH is the binary itself; with -`--ignore-scripts`, or on Windows where npm runs bins through a `.cmd` -wrapper anyway, the shim remains and still works. For hooks, Ness -should write the binary's absolute path with `loch install --local ---command ` (settings.local.json, since the path is machine-specific) -rather than rely on PATH. - -**`uv tool install` users** have a working install of the reference, so -nothing has to change for them while the Python exists. The intended switch is -to ship the Rust binary as platform wheels too — maturin's `bindings = -"bin"`, the way ruff and uv ship — attached to the GitHub release next to -today's pure-Python wheel, so the switch is the same `uv tool install ---force ` people already run. Platform wheels make that URL -per-platform. `uv tool install loch --find-links -https://github.com/ness-dev/loch/releases/expanded_assets/` would let uv -pick the right one without PyPI, **but it hasn't been tried** against a real -release page. Until then, a `uv tool` install and an npm global install both -put a `loch` on PATH and whichever comes first wins; the settings files -written by `install` name `loch`, so it is PATH order that decides which -build the hooks run. That is fine while the two are equivalent, which is -what the harness is for. +string). Listings send `encoding-type=url` and decode the keys, so a key +with any character survives the XML. A store that doesn't answer fails +after 20s rather than holding a turn. The tests that need an endpoint are +`#[ignore]`d in `tests/store.rs` and `tests/index.rs`, and read it from +`LOCH_TEST_S3_ENDPOINT` (bucket `LOCH_TEST_S3_BUCKET`, default `sessions`): +`moto_server` or MinIO will do. moto's verifier rejects correct signatures on +keys holding a space or `+` and on prefixed listings when its IAM auth is on, +so a signing failure in exactly those cases against moto is moto's. ## State @@ -905,8 +783,8 @@ the transcript is the source of truth for what directories it names, and adding a field would change the ref of every bundle for a value the restore side can recompute. -**The S3 backend has still never run against a real bucket.** It has moto -coverage now, which is more than it had, but mocks agree with your +**The S3 backend has still never run against a real bucket.** It has run +against moto, 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 @@ -939,14 +817,11 @@ between `bundle-not-found` and `store-unreachable` came from, but nothing has been wired up against it yet, so the field names have never survived contact with a real integration. -The suite passes on 3.10.13 and 3.13 as well as 3.12, and a boto3-free -install saves and lists against a `file://` store unmodified. **Neither -workflow has ever run**, though — they were written against a repo with no -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. +**Neither workflow has ever run** — the first tag push is also the first +execution of the release path, including the six-target build matrix, and no +release exists yet. -**Blame and ask (`trace.py`) are a working demo on this repository.** All 12 +**Blame and ask (`trace.rs`) 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 @@ -997,28 +872,16 @@ 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. +`json::canonical` is RFC 8785: keys by UTF-16 code unit, numbers as +ECMAScript prints them, strings as JSON.stringify escapes them, integers +exact at any size. ## Conventions -- Verify before committing: `poetry run ruff check`, - `poetry run ruff format --check`, `poetry run mypy .`, and - `poetry run pytest`. Touching `rust/` adds `cargo fmt --check`, - `cargo clippy --release --all-targets -- -D warnings`, `cargo test` there, - and `LOCH_RUST=rust/target/release/loch poetry run pytest - test/test_equivalence.py test/test_equivalence_commands.py` after a - `cargo build --release`. A change to how either build reads transcripts - adds the corpus check (`LOCH_CORPUS=1`). -- A behaviour change goes into both builds in one commit, with a scenario - that would have told them apart. -- A command is ported when the harness covers it, not when it compiles. Port - behaviour exactly, quirks included, and fix a quirk in Python first if it - is a bug, so the reference stays the reference. +- Verify before committing: `cargo fmt --check`, + `cargo clippy --release --all-targets -- -D warnings` and + `cargo test --release`. A change to how transcripts are read adds the + corpus check (`LOCH_CORPUS=1 cargo test --release --test corpus -- --ignored`). - Commit coherent changes as you go rather than batching. - **Every command must be fully drivable by a program that never reads the human text.** A new command isn't finished until `--json` covers it — diff --git a/README.md b/README.md index 5b163b9..2adcc45 100644 --- a/README.md +++ b/README.md @@ -15,48 +15,36 @@ Currently supports Claude Code. ## Install +loch is a single static binary. Take the one for your platform from +[GitHub releases](https://github.com/ness-dev/loch/releases), for example: + ```sh -uv tool install https://github.com/ness-dev/loch/releases/download/v0.1.0/loch-0.1.0-py3-none-any.whl +curl -L https://github.com/ness-dev/loch/releases/download/v0.1.0/loch-0.1.0-aarch64-apple-darwin.tar.gz \ + | tar xz --strip-components 1 -C ~/.local/bin loch-0.1.0-aarch64-apple-darwin/loch 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/loch/releases) as a wheel -and an sdist. - -Python 3.10 or newer if you'd rather install it yourself — `pipx install`, -`pip install`, whatever puts a console script on `PATH`. +Builds exist for macOS (`aarch64-apple-darwin`, `x86_64-apple-darwin`), Linux +(`aarch64-unknown-linux-musl`, `x86_64-unknown-linux-musl`, static, so any +distribution) and Windows (`aarch64-pc-windows-msvc`, `x86_64-pc-windows-msvc`). +S3 support is built in. The only runtime requirement is `git`, for the +commands that work on a repository. -**An S3 store needs the `s3` extra**, which a default install does not pull -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: +From source, with a Rust toolchain: ```sh -uv tool install "loch[s3] @ https://github.com/ness-dev/loch/releases/download/v0.1.0/loch-0.1.0-py3-none-any.whl" +cargo install --git https://github.com/ness-dev/loch --locked ``` -Without it, an `s3://` store fails with `code: "s3-extra-missing"` rather than -looking like a network problem. - -**A native build** lives in `rust/`: one static binary with the same -commands, output and exit codes, S3 included, and a hook that costs 3ms a -call rather than ~73ms. It isn't released yet; to use it now: - -```sh -cd rust && cargo build --release # target/release/loch -``` +**If you installed the old Python version** with `uv tool install`, remove it +first (`uv tool uninstall loch`), or whichever `loch` comes first on PATH is +the one your hooks run. For development: ```sh -poetry install # brings boto3, so the S3 backend is covered by the tests -poetry run loch --help -poetry run pytest -# the Rust build, held to the Python one output for output: -(cd rust && cargo build --release) -LOCH_RUST=rust/target/release/loch poetry run pytest test/test_equivalence*.py +cargo build --release # target/release/loch +cargo test --release ``` ## Use @@ -151,12 +139,12 @@ loch restore --json deadbeef --store /tmp/outbound; echo "exit $?" Branch on `code`, not on `error` — the codes are stable (`no-sessions`, `redaction-failed`, `missing-ref`, `bundle-not-found`, -`store-unreachable`, `s3-extra-missing`, `bundle-unreadable`, +`store-unreachable`, `bundle-unreadable`, `transcript-unreadable`, `nothing-restored`, `unknown-command`, `usage`, `internal`), the messages are prose and will get reworded. A ref that isn't there is `bundle-not-found`, a -store that didn't answer is `store-unreachable`, and an install without the -`s3` extra is `s3-extra-missing` — so a caller knows which is worth retrying -and which needs a reinstall. +store that didn't answer is `store-unreachable`, and bytes that arrived but +won't unpack are `bundle-unreadable` — so a caller knows which is worth +retrying. `schema` versions the envelope. An empty result is `{"sessions": []}` with `ok: true`, not a failure, and `restore` reports each session as `restored` or `skipped` with its own diff --git a/bench/hook.py b/bench/hook.py deleted file mode 100644 index f2b61f1..0000000 --- a/bench/hook.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Wall-clock cost of `loch hook` per call, for any number of loch binaries. - - python rust/bench/hook.py [--runs N] [ ...] - -Each binary runs against its own scratch repository with the event Claude Code -sends around a Bash call. Three cases, since they cost different amounts: -`pre-tool`, `post-tool` when the call committed nothing (nearly every call), -and `post-tool` when it made a commit and a note gets written. Reports the -median and p90 in milliseconds. Nothing from a real transcript is used. -""" - -import argparse -import json -import os -import statistics -import subprocess -import sys -import tempfile -import time - -SESSION = "00000000-0000-4000-8000-000000000000" - - -def git(cwd: str, *args: str) -> None: - subprocess.run(["git", "-C", cwd, *args], check=True, capture_output=True) - - -def scratch_repo(root: str) -> str: - repo = os.path.join(root, "repo") - os.makedirs(repo) - git(repo, "init", "-q", "-b", "main") - git(repo, "commit", "-q", "--allow-empty", "-m", "initial") - return repo - - -def run(loch: str, name: str, event: dict, env: dict) -> float: - started = time.perf_counter() - subprocess.run( - [loch, "hook", name], - input=json.dumps(event).encode(), - env=env, - check=True, - capture_output=True, - ) - return (time.perf_counter() - started) * 1000 - - -def bench(loch: str, runs: int) -> dict[str, list[float]]: - times: dict[str, list[float]] = {"pre-tool": [], "post-tool": [], "post-commit": []} - with tempfile.TemporaryDirectory() as root: - repo = scratch_repo(root) - env = {**os.environ, "HOME": root, "GIT_CONFIG_GLOBAL": os.devnull} - env.pop("CLAUDE_CONFIG_DIR", None) - for i in range(runs): - event = { - "session_id": SESSION, - "cwd": repo, - "tool_name": "Bash", - "tool_input": {"command": f"echo {i}"}, - "tool_use_id": f"toolu_{i:08d}", - } - times["pre-tool"].append(run(loch, "pre-tool", event, env)) - if i % 2: - git(repo, "commit", "-q", "--allow-empty", "-m", f"change {i}") - times["post-commit"].append(run(loch, "post-tool", event, env)) - else: - times["post-tool"].append(run(loch, "post-tool", event, env)) - return times - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("--runs", type=int, default=40) - parser.add_argument("loch", nargs="+") - args = parser.parse_args() - print(f"{'binary':<48} {'case':<12} {'median':>8} {'p90':>8}") - for loch in args.loch: - for case, samples in bench(loch, args.runs).items(): - samples.sort() - p90 = samples[int(len(samples) * 0.9) - 1] - print( - f"{loch[-48:]:<48} {case:<12} " - f"{statistics.median(samples):>7.1f}ms {p90:>7.1f}ms" - ) - sys.stdout.flush() - - -if __name__ == "__main__": - main() diff --git a/examples/bench_hook.rs b/examples/bench_hook.rs new file mode 100644 index 0000000..6d75096 --- /dev/null +++ b/examples/bench_hook.rs @@ -0,0 +1,140 @@ +//! Wall-clock cost of `loch hook` per call, for any number of loch binaries. +//! +//! cargo run --release --example bench_hook -- [--runs N] [ ...] +//! +//! Each binary runs against its own scratch repository with the event Claude +//! Code sends around a Bash call. Three cases, since they cost different +//! amounts: `pre-tool`, `post-tool` when the call committed nothing (nearly +//! every call), and `post-tool` when it made a commit and a note gets written. +//! Reports the median and p90 in milliseconds. + +use std::io::Write; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::Instant; + +const SESSION: &str = "00000000-0000-4000-8000-000000000000"; + +fn git(repo: &Path, args: &[&str], home: &Path) { + let status = Command::new("git") + .arg("-C") + .arg(repo) + .args(args) + .env("HOME", home) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_AUTHOR_NAME", "Bench") + .env("GIT_AUTHOR_EMAIL", "bench@example.com") + .env("GIT_COMMITTER_NAME", "Bench") + .env("GIT_COMMITTER_EMAIL", "bench@example.com") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .expect("git runs"); + assert!(status.success(), "git {:?} failed", args); +} + +fn run(loch: &str, name: &str, event: &str, home: &Path) -> f64 { + let started = Instant::now(); + let mut child = Command::new(loch) + .args(["hook", name]) + .env("HOME", home) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("loch runs"); + child + .stdin + .take() + .expect("piped") + .write_all(event.as_bytes()) + .expect("stdin"); + child.wait().expect("loch exits"); + started.elapsed().as_secs_f64() * 1000.0 +} + +fn bench(loch: &str, runs: usize) -> Vec<(&'static str, Vec)> { + let root = std::env::temp_dir().join(format!("loch-bench-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let repo = root.join("repo"); + std::fs::create_dir_all(&repo).expect("scratch dir"); + git(&repo, &["init", "-q", "-b", "main"], &root); + git( + &repo, + &["commit", "-q", "--allow-empty", "-m", "initial"], + &root, + ); + + let mut pre = Vec::new(); + let mut post = Vec::new(); + let mut commit = Vec::new(); + for i in 0..runs { + let event = format!( + r#"{{"session_id": "{}", "cwd": "{}", "tool_name": "Bash", "tool_input": {{"command": "echo {}"}}, "tool_use_id": "toolu_{:08}"}}"#, + SESSION, + repo.display(), + i, + i + ); + pre.push(run(loch, "pre-tool", &event, &root)); + if i % 2 == 1 { + git( + &repo, + &[ + "commit", + "-q", + "--allow-empty", + "-m", + &format!("change {}", i), + ], + &root, + ); + commit.push(run(loch, "post-tool", &event, &root)); + } else { + post.push(run(loch, "post-tool", &event, &root)); + } + } + let _ = std::fs::remove_dir_all(&root); + vec![ + ("pre-tool", pre), + ("post-tool", post), + ("post-commit", commit), + ] +} + +fn main() { + let mut args: Vec = std::env::args().skip(1).collect(); + let mut runs = 40; + if args.first().map(String::as_str) == Some("--runs") { + runs = args.get(1).and_then(|n| n.parse().ok()).expect("--runs N"); + args.drain(..2); + } + assert!( + !args.is_empty(), + "usage: bench_hook [--runs N] [ ...]" + ); + println!( + "{:<48} {:<12} {:>9} {:>9}", + "binary", "case", "median", "p90" + ); + for loch in &args { + for (case, mut samples) in bench(loch, runs) { + samples.sort_by(|a, b| a.total_cmp(b)); + let median = samples[samples.len() / 2]; + let p90 = samples[(samples.len() * 9 / 10).saturating_sub(1)]; + let label: String = loch + .chars() + .rev() + .take(48) + .collect::>() + .into_iter() + .rev() + .collect(); + println!( + "{:<48} {:<12} {:>7.1}ms {:>7.1}ms", + label, case, median, p90 + ); + } + } +} diff --git a/loch/__init__.py b/loch/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/loch/blame_html.py b/loch/blame_html.py deleted file mode 100644 index d8cd47c..0000000 --- a/loch/blame_html.py +++ /dev/null @@ -1,273 +0,0 @@ -"""`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/bundle.py b/loch/bundle.py deleted file mode 100644 index 42eae78..0000000 --- a/loch/bundle.py +++ /dev/null @@ -1,120 +0,0 @@ -import gzip -import hashlib -import json -import struct -import zlib -from dataclasses import dataclass -from typing import Any - -BUNDLE_VERSION = 1 - - -@dataclass(frozen=True) -class BundleOrigin: - home: str - platform: str - hostname: str - - -@dataclass(frozen=True) -class BundleSession: - session_id: str - cwd: str - git_branch: str | None - claude_version: str | None - modified_at: str - transcript: str - - -@dataclass(frozen=True) -class Bundle: - version: int - agent: str - created_at: str - origin: BundleOrigin - sessions: list[BundleSession] - - -def _session_to_json(session: BundleSession) -> dict[str, Any]: - record: dict[str, Any] = {"sessionId": session.session_id, "cwd": session.cwd} - # Omitted rather than null: the ref is a hash of these bytes, so the - # encoding of "unknown" has to stay stable or identical sessions diverge. - if session.git_branch is not None: - record["gitBranch"] = session.git_branch - if session.claude_version is not None: - record["claudeVersion"] = session.claude_version - record["modifiedAt"] = session.modified_at - record["transcript"] = session.transcript - return record - - -def _bundle_to_json(bundle: Bundle) -> dict[str, Any]: - return { - "version": bundle.version, - "agent": bundle.agent, - "createdAt": bundle.created_at, - "origin": { - "home": bundle.origin.home, - "platform": bundle.origin.platform, - "hostname": bundle.origin.hostname, - }, - "sessions": [_session_to_json(session) for session in bundle.sessions], - } - - -# The gzip header, written out rather than left to gzip.compress: from 3.11 -# that delegates to zlib, which stamps its own OS byte (19 on macOS, 3 on -# Linux) where 3.10 wrote 255. The ref is a hash of these bytes, so the same -# sessions got a different ref per platform and per Python. Fixed at 255 -# ("unknown"), which is what 3.10 always produced; XFL 2 is level 9. -GZIP_HEADER = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff" - - -def gzip_deterministic(data: bytes) -> bytes: - compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, 8, 0) - body = compressor.compress(data) + compressor.flush() - trailer = struct.pack(" bytes: - encoded = json.dumps( - _bundle_to_json(bundle), separators=(",", ":"), ensure_ascii=False - ).encode("utf-8") - return gzip_deterministic(encoded) - - -def unpack_bundle(data: bytes) -> Bundle: - raw = json.loads(gzip.decompress(data).decode("utf-8")) - version = raw.get("version") - if version != BUNDLE_VERSION: - raise ValueError( - f"unsupported bundle version {version} (this build reads {BUNDLE_VERSION})" - ) - - origin = raw.get("origin", {}) - return Bundle( - version=version, - agent=raw.get("agent", ""), - created_at=raw.get("createdAt", ""), - origin=BundleOrigin( - home=origin.get("home", ""), - platform=origin.get("platform", ""), - hostname=origin.get("hostname", ""), - ), - sessions=[ - BundleSession( - session_id=session["sessionId"], - cwd=session["cwd"], - git_branch=session.get("gitBranch"), - claude_version=session.get("claudeVersion"), - modified_at=session.get("modifiedAt", ""), - transcript=session["transcript"], - ) - for session in raw.get("sessions", []) - ], - ) - - -def bundle_ref(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() diff --git a/loch/claude.py b/loch/claude.py deleted file mode 100644 index 68a111a..0000000 --- a/loch/claude.py +++ /dev/null @@ -1,250 +0,0 @@ -import json -import os -import re -from collections.abc import Iterator -from dataclasses import dataclass -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -from .redact import RedactionError, redact - -AGENT = "claude-code" - -SUMMARY_LIMIT = 120 - - -@dataclass(frozen=True) -class SessionMeta: - session_id: str - path: str - cwd: str - git_branch: str | None - claude_version: str | None - bytes: int - modified_at: str - summary: str | None - # Directories the session also worked in before it moved. A restore has one - # target cwd, so records naming these cannot be made correct on the far - # side; surfacing them here is the only honest option. - other_cwds: tuple[str, ...] = () - - -def home_dir() -> str: - return str(Path.home()) - - -def iso_timestamp(seconds: float) -> str: - """Millisecond-precision UTC with a Z suffix, as the bundle format - stores timestamps.""" - moment = datetime.fromtimestamp(seconds, tz=timezone.utc) - return f"{moment.strftime('%Y-%m-%dT%H:%M:%S')}.{moment.microsecond // 1000:03d}Z" - - -def config_dir(home: str | None = None) -> str: - """Where Claude Code keeps its state: `CLAUDE_CONFIG_DIR` when set, which - is how one machine runs several accounts, else `~/.claude`. Only the - variable is consulted, never both places, because that is the rule Claude - itself follows — a restore filed anywhere else is one `--resume` can't - find. An explicit `home` names another machine's layout and ignores it.""" - if home is None: - configured = os.environ.get("CLAUDE_CONFIG_DIR") - if configured: - return configured - home = home_dir() - return os.path.join(home, ".claude") - - -def projects_dir(home: str | None = None) -> str: - return os.path.join(config_dir(home), "projects") - - -def resolve_cwd(cwd: str) -> str: - """Claude resolves symlinks before deriving the directory name, so /tmp - becomes /private/tmp on macOS. Resolving here keeps lookups matching.""" - try: - return os.path.realpath(cwd, strict=True) - except OSError: - return cwd - - -def encode_path(path: str) -> str: - """Pure form of the encoding, for paths that don't exist locally (an - origin machine's cwd) and so can't be passed through realpath.""" - return re.sub(r"[^a-zA-Z0-9]", "-", path) - - -def encode_cwd(cwd: str) -> str: - return encode_path(resolve_cwd(cwd)) - - -def session_dir_for(cwd: str, home: str | None = None) -> str: - return os.path.join(projects_dir(home), encode_cwd(cwd)) - - -def transcript_path_for(cwd: str, session_id: str, home: str | None = None) -> str: - return os.path.join(session_dir_for(cwd, home), f"{session_id}.jsonl") - - -def _first_string(value: Any) -> str | None: - return value if isinstance(value, str) and value and value != "-" else None - - -def _records(raw: str) -> Iterator[dict[str, Any]]: - for line in raw.split("\n"): - line = line.strip() - if not line: - continue - try: - record = json.loads(line) - except ValueError: - continue - if isinstance(record, dict): - yield record - - -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 — loch's own --json output among them — - where it names some other process's directory.""" - counts: dict[str, int] = {} - for record in _records(raw): - cwd = _first_string(record.get("cwd")) - if cwd: - counts[cwd] = counts.get(cwd, 0) + 1 - return counts - - -def cwd_for_directory(cwds: list[str], directory: str) -> str: - """Which of a session's cwd values the transcript is actually filed under. - - A session holds more than one whenever the agent moves mid-session — into a - worktree, say — because the records from before the move stay in the file. - The first one can be hundreds of lines stale, and it is the one a restore - would otherwise rewrite from. Claude names the containing directory after - the *current* cwd, which makes the directory the disambiguator. - - The encoding is only ever compared here, never decoded. encode_path maps - every non-alphanumeric to `-`, so `/sub` and `-sub` produce the - same slug: a match is strong evidence, a mismatch is conclusive. That - asymmetry is what makes this safe. Nothing matching — a hand-copied - transcript, a renamed directory — falls back to the first cwd, which is the - behaviour this replaced. - """ - for cwd in cwds: - if encode_path(cwd) == directory: - return cwd - return cwds[0] - - -def _extract_summary(record: dict[str, Any]) -> str | None: - if record.get("type") != "user": - return None - message = record.get("message") - content = message.get("content") if isinstance(message, dict) else None - if isinstance(content, str): - return content - if not isinstance(content, list): - return None - for block in content: - text = block.get("text") if isinstance(block, dict) else None - if isinstance(text, str) and text: - return text - return None - - -def _display_summary(text: str | None) -> str | None: - """The one piece of transcript content that travels as metadata — onto a - picker row, into a pasted bug report — so it is scrubbed here rather than - at each renderer, and before truncation, since a cut can leave a secret's - tail matching no rule. A summary that won't come clean is dropped whole: - failing a listing over a label would be the wrong trade.""" - if text is None: - return None - try: - return redact(text).text[:SUMMARY_LIMIT] - except RedactionError: - return "[REDACTED]" - - -def read_session_meta(path: str) -> SessionMeta | None: - try: - stat = os.stat(path) - # Replacing rather than strict: one undecodable byte (a file truncated - # mid-character) used to raise out of `list` and lose every session in - # the directory. Only metadata is read here; `save` decides separately - # whether the transcript can be packed. - raw = Path(path).read_text(encoding="utf-8", errors="replace") - except OSError: - return None - - session_id = re.sub(r"\.jsonl$", "", path.split("/")[-1]) - counts: dict[str, int] = {} - branches: dict[str, str] = {} - versions: dict[str, str] = {} - summary: str | None = None - - # Whole file rather than a bounded window: the cwd the session is filed - # under can first appear hundreds of records in, so a window deep enough to - # be correct is no window at all. Only the branch and version are read per - # cwd, which costs one dict lookup on a line already being parsed. - for record in _records(raw): - cwd = _first_string(record.get("cwd")) - if cwd: - counts[cwd] = counts.get(cwd, 0) + 1 - branch = _first_string(record.get("gitBranch")) - if branch and cwd not in branches: - branches[cwd] = branch - version = _first_string(record.get("version")) - if version and cwd not in versions: - versions[cwd] = version - if summary is None: - summary = _extract_summary(record) - - if not counts: - return None - - ordered = list(counts) - cwd = cwd_for_directory(ordered, os.path.basename(os.path.dirname(path))) - - return SessionMeta( - session_id=session_id, - path=path, - cwd=cwd, - # Read alongside the chosen cwd. A branch from a record the session has - # since moved away from is the same defect as the stale cwd, and it - # decides which index entry the bundle gets filed under. - git_branch=branches.get(cwd), - claude_version=versions.get(cwd) or next(iter(versions.values()), None), - bytes=stat.st_size, - modified_at=iso_timestamp(stat.st_mtime), - summary=_display_summary(summary), - other_cwds=tuple(other for other in ordered if other != cwd), - ) - - -def list_sessions( - cwd: str, - branch: str | None = None, - session_id: str | None = None, - home: str | None = None, -) -> list[SessionMeta]: - directory = session_dir_for(cwd, home) - if not os.path.exists(directory): - return [] - - metas: list[SessionMeta] = [] - for file in os.listdir(directory): - if not file.endswith(".jsonl"): - continue - if session_id and file != f"{session_id}.jsonl": - continue - meta = read_session_meta(os.path.join(directory, file)) - if not meta: - continue - if branch and meta.git_branch != branch: - continue - metas.append(meta) - - return sorted(metas, key=lambda meta: meta.modified_at, reverse=True) diff --git a/loch/cli.py b/loch/cli.py deleted file mode 100644 index 7d25e48..0000000 --- a/loch/cli.py +++ /dev/null @@ -1,1231 +0,0 @@ -import argparse -import importlib.metadata -import json -import os -import platform -import re -import shutil -import socket -import sys -import tempfile -import time -import uuid -import webbrowser -from collections.abc import Iterator -from contextlib import contextmanager -from dataclasses import dataclass, field -from datetime import datetime, timezone -from pathlib import Path -from typing import Any, Callable, NoReturn - -from .blame_html import parse_ranges, render -from .bundle import ( - BUNDLE_VERSION, - Bundle, - BundleOrigin, - BundleSession, - bundle_ref, - pack_bundle, - unpack_bundle, -) -from .claude import ( - AGENT, - SessionMeta, - home_dir, - iso_timestamp, - list_sessions, - projects_dir, - resolve_cwd, - transcript_path_for, -) -from .format import pack_derived -from .git import current_branch -from .index import ( - BRANCH, - IndexEntry, - bundle_key, - delete_bundle, - dimension_prefix, - index_bundle, - index_key, - load_entries, - reindex, - value_prefix, -) -from .ingest import ( - CONVERTER, - AuthorKeyError, - Origin, - derived_name, - ingest, - ssh_author_id, -) -from .output import JSON_FLAG, CommandError, Result, emit, emit_error -from .redact import RedactionError, redact, summarize -from .rewrite import ( - ForeignCwd, - RewriteSpec, - foreign_cwds, - residual_origin_paths, - rewrite_transcript, -) -from .store import MissingDependency, MissingObject, create_store, resolve_store_uri -from .trace import ( - NOTES_REF, - UNCOMMITTED, - Link, - Resolver, - TraceError, - backfill, - blame_hunks, - fork_session, - git, - history, - hook_post_tool, - hook_pre_tool, - install_hooks, - repo_root, - snapshot_transcript, -) - -DEFAULT_DERIVED = os.path.join(str(Path.home()), ".loch", "derived") - -USAGE = """loch — save and restore agent coding sessions across machines - -Usage: - 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 ingest [--cwd ] [--branch ] [--session ] - [--author | --author-key ] - [--out ] - loch install [--local] [--command ] - loch blame [--html [] [--lines ] [--no-open]] - [--store ] - loch log [:[-]] [--store ] - loch ask [] [--at-commit] [--no-launch] - [--store ] - loch backfill [--revision ] (default: every branch) - loch hook pre-tool | post-tool | stop (run by Claude Code) - loch --version - -Every command takes --json, which replaces the text below with one machine- -readable document on stdout. - -Stores: - local directory - s3://bucket/prefix any S3-compatible endpoint - -Environment: - LOCH_STORE default store URI - SOURCE_DATE_EPOCH fixed createdAt for save, so a bundle is reproducible - LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) - LOCH_S3_REGION region override - CLAUDE_CONFIG_DIR Claude Code's state directory (default ~/.claude) - -Derived conversation files go to ~/.loch/derived unless --out says otherwise. - -`install` adds Claude Code hooks to a repository that note, on every commit an -agent makes, the conversation and tool call that made it (git notes on -refs/notes/loch), and snapshot each session's transcript into the store. -`blame` shows which conversation wrote each line, `log` every conversation -that changed a file or line range over its history; `ask` forks that -conversation and resumes it in Claude Code — from its end, or with ---at-commit from just after the commit. -""" - - -def fail(code: str, message: str) -> NoReturn: - raise CommandError(code, message) - - -@contextmanager -def store_errors(description: str) -> Iterator[None]: - """The three failures a caller can actually act on: an object that isn't - there is terminal, a store that didn't answer is worth retrying, and a - backend whose SDK is absent is fixed by an install and by nothing else. - Keep the block around the store call alone — anything wider mislabels a bug - in this process as a failure of the store.""" - try: - yield - except MissingObject as error: - fail("bundle-not-found", f"{description}: {error}") - except MissingDependency as error: - fail("s3-extra-missing", f"{description}: {error}") - except Exception as error: - fail("store-unreachable", f"{description}: {error}") - - -def format_bytes(count: int) -> str: - if count < 1024: - return f"{count}B" - if count < 1024 * 1024: - return f"{count / 1024:.0f}K" - return f"{count / (1024 * 1024):.1f}M" - - -def describe(meta: SessionMeta) -> str: - branch = f"[{meta.git_branch}]" if meta.git_branch else "[no branch]" - # Hoisted out of the f-string: a backslash inside an interpolation is - # PEP 701 syntax and won't parse below 3.12. - collapsed = re.sub(r"\s+", " ", meta.summary) if meta.summary else "" - summary = f" {collapsed}" if collapsed else "" - when = meta.modified_at[:16].replace("T", " ") - return ( - f"{meta.session_id} {when} {format_bytes(meta.bytes):>5} {branch}{summary}" - ) - - -def describe_entry(entry: IndexEntry) -> str: - branch = f"[{entry.value}]" if entry.value else "[no branch]" - when = entry.created_at[:16].replace("T", " ") - version = f" claude {entry.claude_version}" if entry.claude_version else "" - return ( - f"{when} {format_bytes(entry.bytes):>5} {entry.sessions} session(s) " - f"{branch}{version} {entry.cwd}" - ) - - -def collect( - cwd: str | None, branch: str | None, session: str | None = None -) -> tuple[str, list[SessionMeta]]: - resolved = resolve_cwd(cwd if cwd is not None else os.getcwd()) - return resolved, list_sessions(cwd=resolved, branch=branch, session_id=session) - - -class HelpRequested(Exception): - def __init__(self, text: str) -> None: - super().__init__(text) - self.text = text - - -class _Parser(argparse.ArgumentParser): - # argparse answers -h and a bad flag itself, writing prose and exiting - # before a command ever runs. Both are routed back to main() so that - # "one document per invocation" holds in JSON mode; the text each carries - # is argparse's own, so nothing changes without --json. - def error(self, message: str) -> NoReturn: - raise CommandError( - "usage", - message, - prose=f"{self.format_usage()}{self.prog}: error: {message}\n", - exit_status=2, - ) - - def print_help(self, file: Any = None) -> NoReturn: - raise HelpRequested(self.format_help()) - - -def _parser(command: str) -> argparse.ArgumentParser: - 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. - parser.add_argument(JSON_FLAG, action="store_true") - return parser - - -def _session_payload(meta: SessionMeta) -> dict[str, Any]: - return { - "sessionId": meta.session_id, - "path": meta.path, - "cwd": meta.cwd, - "otherCwds": list(meta.other_cwds), - "branch": meta.git_branch, - "claudeVersion": meta.claude_version, - "bytes": meta.bytes, - "modifiedAt": meta.modified_at, - "summary": meta.summary, - } - - -def _entry_payload(entry: IndexEntry) -> dict[str, Any]: - """Deliberately not index.py's stored shape: that one is a storage format, - this one is a versioned wire contract, and they change for different - reasons.""" - return { - "ref": entry.ref, - "dimension": entry.dimension, - "value": entry.value, - "agent": entry.agent, - "createdAt": entry.created_at, - "bytes": entry.bytes, - "sessions": entry.sessions, - "cwd": entry.cwd, - "claudeVersion": entry.claude_version, - } - - -def command_list(argv: list[str]) -> Result: - parser = _parser("list") - parser.add_argument("--cwd") - parser.add_argument("--branch") - parser.add_argument("--remote", action="store_true") - parser.add_argument("--all", action="store_true", dest="every") - parser.add_argument("--store") - args = parser.parse_args(argv) - - if args.remote or args.every or args.store is not None: - return list_remote(args) - - cwd, sessions = collect(args.cwd, args.branch) - return Result( - command="list", - payload={ - "remote": False, - "cwd": cwd, - "branch": args.branch, - "sessions": [_session_payload(meta) for meta in sessions], - }, - text=_list_text(cwd, sessions), - ) - - -def _list_text(cwd: str, sessions: list[SessionMeta]) -> str: - if not sessions: - return f"no {AGENT} sessions found for {cwd}\n" - lines = [f"{len(sessions)} session(s) for {cwd}\n"] - lines += [f" {describe(meta)}\n" for meta in sessions] - return "".join(lines) - - -def list_remote(args: argparse.Namespace) -> Result: - store = create_store(resolve_store_uri(args.store)) - cwd = resolve_cwd(args.cwd if args.cwd is not None else os.getcwd()) - branch = args.branch if args.branch is not None else current_branch(cwd) - - prefix = dimension_prefix(BRANCH) if args.every else value_prefix(BRANCH, branch) - with store_errors(f"could not list {store.describe()}"): - entries = load_entries(store, prefix) - refs = {entry.ref for entry in entries} - - return Result( - command="list", - payload={ - "remote": True, - "store": store.describe(), - "all": bool(args.every), - "branch": None if args.every else branch, - "bundles": len(refs), - "entries": [_entry_payload(entry) for entry in entries], - }, - text=_list_remote_text(store.describe(), args.every, branch, entries, refs), - ) - - -def _list_remote_text( - store: str, - every: bool, - branch: str | None, - entries: list[IndexEntry], - refs: set[str], -) -> str: - scope = "" if every else f" for [{branch or 'no branch'}]" - if not entries: - return f"no bundles{scope} in {store}\n" - lines = [f"{len(refs)} bundle(s){scope} in {store}\n"] - lines += [f" {entry.ref}\n {describe_entry(entry)}\n" for entry in entries] - return "".join(lines) - - -def _creation_time() -> float: - """`SOURCE_DATE_EPOCH` when it holds an integer, the reproducible-builds - convention: a bundle's ref hashes its createdAt, so fixing the clock is - what makes the same sessions pack to the same ref twice.""" - try: - return float(int(os.environ["SOURCE_DATE_EPOCH"])) - except (KeyError, ValueError): - return time.time() - - -def command_save(argv: list[str]) -> Result: - parser = _parser("save") - parser.add_argument("--cwd") - parser.add_argument("--branch") - parser.add_argument("--session") - parser.add_argument("--store") - 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}") - - packed_sessions: list[BundleSession] = [] - redactions: list[dict[str, int]] = [] - for meta in sessions: - # In memory only — the agent's own transcript on disk stays verbatim. - try: - raw = Path(meta.path).read_bytes().decode("utf-8") - except UnicodeDecodeError as error: - fail( - "transcript-unreadable", - f"refusing to pack {meta.session_id}: not UTF-8 at byte {error.start}", - ) - try: - scrubbed = redact(raw) - except RedactionError as error: - fail("redaction-failed", f"refusing to pack {meta.session_id}: {error}") - packed_sessions.append( - BundleSession( - session_id=meta.session_id, - cwd=meta.cwd, - git_branch=meta.git_branch, - claude_version=meta.claude_version, - modified_at=meta.modified_at, - transcript=scrubbed.text, - ) - ) - redactions.append(scrubbed.counts) - - bundle = Bundle( - version=BUNDLE_VERSION, - agent=AGENT, - created_at=iso_timestamp(_creation_time()), - origin=BundleOrigin( - home=home_dir(), platform=_platform_name(), hostname=socket.gethostname() - ), - sessions=packed_sessions, - ) - - packed = pack_bundle(bundle) - ref = bundle_ref(packed) - store = create_store(resolve_store_uri(args.store)) - with store_errors(f"could not write to {store.describe()}"): - # Bundle first: an index entry is derived from it, so a pointer to a - # bundle that isn't there yet is the worse half of a failed save. - store.put(bundle_key(ref), packed) - entries = index_bundle(store, bundle, ref, len(packed)) - - return Result( - command="save", - payload={ - "ref": ref, - "bytes": len(packed), - "store": store.describe(), - "cwd": cwd, - "createdAt": bundle.created_at, - # Counts by rule name only. The matched text never leaves this - # process: save's stdout lands in the next agent's transcript. - "redacted": sum(sum(counts.values()) for counts in redactions), - "sessions": [ - { - "sessionId": session.session_id, - "branch": session.git_branch, - "cwd": session.cwd, - "claudeVersion": session.claude_version, - "modifiedAt": session.modified_at, - "redactions": counts, - } - for session, counts in zip(bundle.sessions, redactions) - ], - "indexed": [ - { - "dimension": entry.dimension, - "value": entry.value, - "key": index_key(entry.dimension, entry.value, entry.ref), - } - for entry in entries - ], - }, - text=_save_text( - bundle, redactions, entries, store.describe(), len(packed), ref - ), - ) - - -def _save_text( - bundle: Bundle, - redactions: list[dict[str, int]], - entries: list[IndexEntry], - store: str, - size: int, - ref: str, -) -> str: - lines = [] - for session, counts in zip(bundle.sessions, redactions): - note = f" — {summarize(counts)}" if counts else "" - lines.append( - f" packed {session.session_id} [{session.git_branch or 'no branch'}]{note}\n" - ) - indexed = ", ".join(f"[{entry.value or 'no branch'}]" for entry in entries) - lines.append(f"\nstored {format_bytes(size)} in {store}\n") - lines.append(f"indexed under {indexed}\n") - lines.append(f"ref {ref}\n") - return "".join(lines) - - -@dataclass(frozen=True) -class RestoredSession: - session_id: str - origin_session_id: str - branch: str | None - status: str - path: str - residual_origin_paths: tuple[str, ...] - resume_command: str | None - foreign_cwds: dict[str, ForeignCwd] = field(default_factory=dict) - - -def command_restore(argv: list[str]) -> Result: - parser = _parser("restore") - parser.add_argument("ref", nargs="?") - parser.add_argument("--into") - parser.add_argument("--store") - parser.add_argument("--force", action="store_true") - parser.add_argument("--new-id", action="store_true", dest="new_id") - args = parser.parse_args(argv) - - if not args.ref: - fail("missing-ref", "restore requires a bundle ref") - - store = create_store(resolve_store_uri(args.store)) - described = f"could not read {args.ref} from {store.describe()}" - with store_errors(described): - packed = store.get(bundle_key(args.ref)) - try: - bundle = unpack_bundle(packed) - except Exception as error: - # Fetched fine and still unusable: neither absent nor unreachable. - fail("bundle-unreadable", f"{described}: {error}") - - target_cwd = resolve_cwd(args.into if args.into is not None else os.getcwd()) - target_home = home_dir() - restored: list[RestoredSession] = [] - - for session in bundle.sessions: - target_session_id = str(uuid.uuid4()) if args.new_id else session.session_id - spec = RewriteSpec( - origin_cwd=session.cwd, - origin_home=bundle.origin.home, - target_cwd=target_cwd, - target_home=target_home, - origin_session_id=session.session_id, - target_session_id=target_session_id, - ) - - transcript = rewrite_transcript(session.transcript, spec) - destination = Path(transcript_path_for(target_cwd, target_session_id)) - - if destination.exists() and not args.force: - restored.append( - RestoredSession( - session_id=target_session_id, - origin_session_id=session.session_id, - branch=session.git_branch, - status="skipped", - path=str(destination), - residual_origin_paths=(), - resume_command=None, - ) - ) - continue - - destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_text(transcript, encoding="utf-8") - - restored.append( - RestoredSession( - session_id=target_session_id, - origin_session_id=session.session_id, - branch=session.git_branch, - status="restored", - path=str(destination), - residual_origin_paths=tuple(residual_origin_paths(transcript, spec)), - resume_command=( - f"cd {target_cwd} && claude --resume {target_session_id}" - ), - # Pre-rewrite: the origin path only exists losslessly here. - foreign_cwds=foreign_cwds(session.transcript, spec), - ) - ) - - payload = { - "ref": args.ref, - "store": store.describe(), - "cwd": target_cwd, - "origin": { - "hostname": bundle.origin.hostname, - "home": bundle.origin.home, - "platform": bundle.origin.platform, - }, - "sessions": [_restored_payload(session) for session in restored], - } - warnings = tuple( - f" skipped {session.session_id} (already exists; --force to overwrite)\n" - for session in restored - if session.status == "skipped" - ) + tuple( - f" {session.session_id} worked in {origin} for {foreign.count} record(s), " - f"which no rewrite into {target_cwd} can satisfy\n" - for session in restored - for origin, foreign in session.foreign_cwds.items() - ) - - if not any(session.status == "restored" for session in restored): - raise CommandError("nothing-restored", "nothing restored", payload, warnings) - - return Result( - command="restore", - payload=payload, - text=_restore_text(bundle, restored), - warnings=warnings, - ) - - -def _restored_payload(session: RestoredSession) -> dict[str, Any]: - return { - "sessionId": session.session_id, - "originSessionId": session.origin_session_id, - "branch": session.branch, - "status": session.status, - "path": session.path, - "residualOriginPaths": list(session.residual_origin_paths), - # Keyed by the origin path, which is the left-hand side a caller states - # a mapping with; `restored` is what the file on disk actually says. - "foreignCwds": { - origin: {"count": foreign.count, "restored": foreign.restored} - for origin, foreign in session.foreign_cwds.items() - }, - "resumeCommand": session.resume_command, - } - - -def _restore_text(bundle: Bundle, restored: list[RestoredSession]) -> str: - lines = [] - for session in restored: - if session.status != "restored": - continue - residual = session.residual_origin_paths - note = f" (residual origin paths: {', '.join(residual)})" if residual else "" - lines.append( - f" restored {session.session_id} [{session.branch or 'no branch'}]{note}\n" - ) - for origin, foreign in session.foreign_cwds.items(): - lines.append( - f" {foreign.count} record(s) worked in {origin}, " - f"now {foreign.restored}\n" - ) - lines.append( - f"\nfrom {bundle.origin.hostname} ({bundle.origin.home})\nresume with:\n" - ) - lines += [ - f" {session.resume_command}\n" - for session in restored - if session.resume_command - ] - return "".join(lines) - - -def command_delete(argv: list[str]) -> Result: - parser = _parser("delete") - parser.add_argument("ref", nargs="?") - parser.add_argument("--store") - args = parser.parse_args(argv) - - if not args.ref: - fail("missing-ref", "delete requires a bundle ref") - - store = create_store(resolve_store_uri(args.store)) - with store_errors(f"could not delete {args.ref} from {store.describe()}"): - removed = delete_bundle(store, args.ref) - - text = "".join(f" removed {key}\n" for key in removed) - text += f"\ndeleted {args.ref} from {store.describe()}\n" - return Result( - command="delete", - payload={"ref": args.ref, "store": store.describe(), "removed": removed}, - text=text, - ) - - -def command_reindex(argv: list[str]) -> Result: - parser = _parser("reindex") - parser.add_argument("--store") - args = parser.parse_args(argv) - - store = create_store(resolve_store_uri(args.store)) - with store_errors(f"could not reindex {store.describe()}"): - result = reindex(store) - - return Result( - command="reindex", - payload={ - "store": store.describe(), - "bundles": result.bundles, - "entries": result.entries, - "removed": result.removed, - }, - text=( - f"scanned {result.bundles} bundle(s) in {store.describe()}\n" - f"wrote {result.entries} index entries, removed {result.removed} stale\n" - ), - ) - - -def command_ingest(argv: list[str]) -> Result: - parser = _parser("ingest") - parser.add_argument("--cwd") - parser.add_argument("--branch") - parser.add_argument("--session") - parser.add_argument("--author") - parser.add_argument("--author-key") - parser.add_argument("--out") - args = parser.parse_args(argv) - - author = args.author - if args.author_key is not None: - if author is not None: - fail("usage", "pass --author or --author-key, not both") - try: - author = ssh_author_id(Path(args.author_key).read_text(encoding="utf-8")) - except (OSError, AuthorKeyError) as error: - fail("author-key-unreadable", f"{args.author_key}: {error}") - - cwd, sessions = collect(args.cwd, args.branch, args.session) - if not sessions: - fail("no-sessions", f"no {AGENT} sessions found for {cwd}") - - out = args.out if args.out is not None else DEFAULT_DERIVED - os.makedirs(out, exist_ok=True) - home = home_dir() - - results: list[dict[str, Any]] = [] - lines: list[str] = [] - for meta in sessions: - derived = ingest(meta.path, Origin(meta.cwd, home, meta.session_id), author) - path = os.path.join(out, derived_name(derived)) - Path(path).write_bytes(pack_derived(derived)) - results.append( - { - "sessionId": meta.session_id, - "source": derived.header["source"]["id"], - "path": path, - "turns": len(derived.turns), - "heads": derived.heads, - } - ) - leaves = len(derived.heads["leaves"]) - lines.append( - f" {meta.session_id} {len(derived.turns)} turns {leaves} head(s)\n" - ) - - text = "".join(lines) + f"\ningested {len(sessions)} session(s) into {out}\n" - return Result( - command="ingest", - payload={ - "cwd": cwd, - "out": out, - "converter": CONVERTER, - "sessions": results, - }, - text=text, - ) - - -@contextmanager -def trace_errors() -> Iterator[None]: - try: - yield - except TraceError as error: - fail(error.code, str(error)) - - -def command_hook(argv: list[str]) -> Result: - """Run by Claude Code with the event as JSON on stdin. It must never fail - the tool call it wraps, so every error is swallowed and nothing is - written: a hook that breaks commits gets uninstalled.""" - name = argv[0] if argv else "" - try: - event = json.loads(sys.stdin.read() or "{}") - if not isinstance(event, dict): - event = {} - if name == "pre-tool": - hook_pre_tool(event) - elif name == "post-tool": - hook_post_tool(event) - elif name == "stop": - snapshot_transcript(event, create_store(resolve_store_uri())) - except Exception: - pass - return Result(command="hook") - - -def command_install(argv: list[str]) -> Result: - parser = _parser("install") - parser.add_argument("--cwd") - parser.add_argument("--local", action="store_true") - parser.add_argument("--command") - args = parser.parse_args(argv) - - with trace_errors(): - root = repo_root(args.cwd or os.getcwd()) - if args.command is not None: - command = args.command - elif args.local: - # A machine-specific path, which is why it only goes in the - # uncommitted settings file. - command = shutil.which("loch") or os.path.abspath(sys.argv[0]) - else: - command = "loch" - name = "settings.local.json" if args.local else "settings.json" - settings = os.path.join(root, ".claude", name) - added = install_hooks(settings, command) - # Amend and rebase copy a commit's note to its replacement only when told - # to, and an amended commit is still the one the conversation made. - git(root, "config", "notes.rewriteRef", NOTES_REF) - - text = ( - f"installed loch hooks ({', '.join(added)}) in {settings}\n" - if added - else f"loch hooks already installed in {settings}\n" - ) - text += ( - "restart Claude Code sessions in this repository to pick them up\n" - f"share links with: git push {NOTES_REF}\n" - ) - return Result( - command="install", - payload={"settings": settings, "command": command, "added": added}, - text=text, - ) - - -def _store_or_none(uri: str | None) -> Any: - try: - return create_store(resolve_store_uri(uri)) - except Exception: - return None - - -def _flat(text: str, limit: int) -> str: - flat = " ".join(text.split()) - return flat if len(flat) <= limit else flat[: limit - 1] + "…" - - -def _link_text(link: Link | None) -> str: - if link is None: - return "no conversation recorded" - if link.transcript is None: - return f"session {link.session_id[:8]} (transcript not available)" - title = f' "{link.title}"' if link.title else "" - prompt = f' — asked: "{_flat(link.prompt, 72)}"' if link.prompt else "" - return f"session {link.session_id[:8]}{title}{prompt}" - - -UNLINKED_MARK = "·" -UNCOMMITTED_MARK = "+" - - -def _mark(index: int) -> str: - letters = "" - index += 1 - while index: - index, remainder = divmod(index - 1, 26) - letters = chr(ord("A") + remainder) + letters - return letters - - -def command_blame(argv: list[str]) -> Result: - parser = _parser("blame") - parser.add_argument("file") - parser.add_argument("--html", nargs="?", const="", metavar="PATH") - parser.add_argument("--lines", metavar="RANGES") - parser.add_argument("--no-open", action="store_true") - parser.add_argument("--store") - args = parser.parse_args(argv) - - cwd = os.path.dirname(os.path.abspath(args.file)) or os.getcwd() - with trace_errors(): - root = repo_root(cwd) - hunks = blame_hunks(root, os.path.relpath(os.path.abspath(args.file), root)) - resolver = Resolver(root, _store_or_none(args.store)) - links: dict[str, Link | None] = {} - for hunk in hunks: - if hunk.commit not in links and hunk.commit != UNCOMMITTED: - links[hunk.commit] = resolver.resolve(hunk.commit) - - # One mark per request rather than per session: a long session makes many - # commits for many asks, and marking by session would paint the whole file - # one letter. Marks are handed out in order of first appearance in the - # file, so A is always the first conversation you read. - marks: dict[tuple[str, str], str] = {} - legend: list[dict[str, Any]] = [] - mark_of: dict[str, str] = {} - for hunk in hunks: - link = links.get(hunk.commit) - if hunk.commit == UNCOMMITTED: - mark_of[hunk.commit] = UNCOMMITTED_MARK - continue - if link is None: - mark_of[hunk.commit] = UNLINKED_MARK - continue - key = (link.session_id, link.prompt or link.call) - if key not in marks: - marks[key] = _mark(len(marks)) - legend.append({"mark": marks[key], **link.payload(), "commits": []}) - entry = next(item for item in legend if item["mark"] == marks[key]) - if hunk.commit not in entry["commits"]: - entry["commits"].append(hunk.commit) - mark_of[hunk.commit] = marks[key] - - rows: list[dict[str, Any]] = [] - for hunk in hunks: - link = links.get(hunk.commit) - rows.append( - { - "start": hunk.start, - "end": hunk.end, - "commit": None if hunk.commit == UNCOMMITTED else hunk.commit, - "summary": hunk.summary, - "mark": mark_of[hunk.commit], - "conversation": link.payload() if link is not None else None, - } - ) - text = _hunks_text(args.file, hunks, links) - payload: dict[str, Any] = { - "file": args.file, - "conversations": legend, - "hunks": rows, - } - if args.html is not None: - try: - visible = parse_ranges(args.lines) if args.lines else None - except ValueError: - fail("usage", f"--lines takes ranges like 1-12,99-110, not {args.lines}") - page = render( - args.file, - legend, - rows, - { - hunk.start + offset: line - for hunk in hunks - for offset, line in enumerate(hunk.lines) - }, - visible, - ) - target = args.html or os.path.join( - tempfile.gettempdir(), f"loch-blame-{os.path.basename(args.file)}.html" - ) - Path(target).write_text(page, encoding="utf-8") - payload["html"] = os.path.abspath(target) - text = f"wrote {payload['html']}\n" - if not args.no_open and JSON_FLAG not in sys.argv: - webbrowser.open(Path(target).resolve().as_uri()) - return Result(command="blame", payload=payload, text=text) - - -def _hunks_text(file: str, hunks: list[Any], links: dict[str, Link | None]) -> str: - lines = [f"{file}\n"] - for hunk in hunks: - link = links.get(hunk.commit) - span = f"{hunk.start}-{hunk.end}" if hunk.end > hunk.start else str(hunk.start) - if hunk.commit == UNCOMMITTED: - lines.append(f" {span:>9} uncommitted\n") - continue - lines.append(f" {span:>9} {hunk.commit[:7]} {hunk.summary[:60]}\n") - lines.append(f" {'':>9} {'':7} {_link_text(link)}\n") - linked = sum(1 for link in links.values() if link is not None) - lines.append( - f"\n{linked} of {len(links)} commit(s) linked to a conversation; " - f"follow one up with: loch ask {file}:\n" - ) - return "".join(lines) - - -def _history_target(target: str) -> tuple[str, tuple[int, int] | None]: - """`file`, `file:105` or `file:100-120`; a path that exists wins outright.""" - if os.path.exists(target): - return target, None - file, _, span = target.rpartition(":") - start, _, end = span.partition("-") - if not file or not start.isdigit() or (end and not end.isdigit()): - fail("usage", f"{target} is neither a file nor :[-]") - first, last = int(start), int(end) if end else int(start) - if first < 1 or last < first: - fail("usage", f"{span} is not a line range") - return file, (first, last) - - -def command_log(argv: list[str]) -> Result: - parser = _parser("log") - parser.add_argument("target") - parser.add_argument("--store") - args = parser.parse_args(argv) - - file, lines = _history_target(args.target) - cwd = os.path.dirname(os.path.abspath(file)) or os.getcwd() - with trace_errors(): - root = repo_root(cwd) - relative = os.path.relpath(os.path.abspath(file), root) - if lines is not None: - # -L past the end is a fatal git error with a worse message. - length = max((hunk.end for hunk in blame_hunks(root, relative)), default=0) - if lines[1] > length: - fail("usage", f"{file} has {length} lines, not {lines[1]}") - changes = history(root, relative, lines) - resolver = Resolver(root, _store_or_none(args.store)) - - # Grouped the way blame marks them — per request, not per session — and - # in order of most recent change, since "who touched this last" is the - # question a history is usually opened to answer. - conversations: list[dict[str, Any]] = [] - keyed: dict[tuple[str, str], dict[str, Any]] = {} - entries: list[dict[str, Any]] = [] - text = [] - for change in changes: - link = resolver.resolve(change.commit) - when = datetime.fromtimestamp(change.time, timezone.utc) - entries.append( - { - "commit": change.commit, - "time": when.strftime("%Y-%m-%dT%H:%M:%SZ"), - "summary": change.summary, - "conversation": link.payload() if link is not None else None, - } - ) - text.append( - f" {change.commit[:7]} {when:%Y-%m-%d} {change.summary[:60]}\n" - f" {'':7} {'':10} {_link_text(link)}\n" - ) - if link is None: - continue - key = (link.session_id, link.prompt or link.call) - if key not in keyed: - keyed[key] = {**link.payload(), "commits": []} - conversations.append(keyed[key]) - keyed[key]["commits"].append(change.commit) - - span = ( - "" - if lines is None - else (f":{lines[0]}" if lines[0] == lines[1] else f":{lines[0]}-{lines[1]}") - ) - header = ( - f"{file}{span}: {len(changes)} commit(s) from " - f"{len(conversations)} conversation(s), newest first\n" - ) - footer = "\nfollow one up with: loch ask \n" if conversations else "" - return Result( - command="log", - payload={ - "file": file, - "lines": None if lines is None else {"start": lines[0], "end": lines[1]}, - "conversations": conversations, - "commits": entries, - }, - text=header + "".join(text) + footer, - ) - - -def _resolve_commit(root: str, target: str) -> str: - file, _, line = target.rpartition(":") - if file and line.isdigit() and os.path.exists(file): - relative = os.path.relpath(os.path.abspath(file), root) - for hunk in blame_hunks(root, relative): - if hunk.start <= int(line) <= hunk.end: - if hunk.commit == UNCOMMITTED: - fail("not-linked", f"{target} is not committed yet") - return hunk.commit - fail("usage", f"{file} has no line {line}") - output = git( - root, "rev-parse", "--verify", "-q", f"{target}^{{commit}}", check=False - ) - if not output.strip(): - fail("usage", f"{target} is neither a commit nor :") - return output.strip() - - -def command_ask(argv: list[str]) -> Result: - parser = _parser("ask") - parser.add_argument("target") - parser.add_argument("question", nargs="?") - parser.add_argument("--at-commit", action="store_true") - parser.add_argument("--no-launch", action="store_true") - parser.add_argument("--store") - args = parser.parse_args(argv) - as_json = JSON_FLAG in sys.argv - - with trace_errors(): - root = repo_root(os.getcwd()) - commit = _resolve_commit(root, args.target) - link = Resolver(root, _store_or_none(args.store)).resolve(commit) - if link is None: - fail("not-linked", f"no conversation is recorded for {commit[:7]}") - if link.transcript is None: - fail( - "transcript-missing", - f"session {link.session_id} is linked but its transcript is " - f"neither in {projects_dir()} nor in the store", - ) - fork = fork_session( - link.transcript, - root, - call=link.call if args.at_commit else None, - title=f"loch ask {commit[:7]}", - ) - - command = ["claude", "--resume", fork.session_id] - if args.question: - command.append(args.question) - payload = { - "commit": commit, - "conversation": link.payload(), - "fork": { - "sessionId": fork.session_id, - "path": fork.path, - "cwd": fork.cwd, - "records": fork.records, - }, - "at": "commit" if args.at_commit else "end", - "launch": command, - } - where = "just after it" if args.at_commit else "to its end" - text = ( - f"forked session {fork.origin_session[:8]}, which made {commit[:7]}, " - f"{where}: {fork.records} records, as {fork.session_id}\n" - ) - if args.no_launch or as_json: - return Result( - command="ask", - payload=payload, - text=text + f"resume with: cd {root} && {' '.join(command)}\n", - ) - sys.stderr.write(text) - os.chdir(root) - os.execvp("claude", command) - - -def _progress_meter() -> Callable[[int, int, int, int], None] | None: - """A one-line counter on stderr, for a person watching a terminal only. - - JSON mode keeps stderr empty, and a pipe or log file would get every - redraw as garbage, so both get nothing. - """ - if JSON_FLAG in sys.argv or not sys.stderr.isatty(): - return None - last = [0.0] - - def meter(done: int, total: int, read: int, size: int) -> None: - now = time.monotonic() - if done < total and now - last[0] < 0.1: - return - last[0] = now - percent = 100 * read // size if size else 100 - sys.stderr.write( - f"\rscanning transcripts {done}/{total} " - f"({format_bytes(read)} of {format_bytes(size)}, {percent}%)\033[K" - ) - if done == total: - sys.stderr.write("\n") - sys.stderr.flush() - - return meter - - -def command_backfill(argv: list[str]) -> Result: - parser = _parser("backfill") - parser.add_argument("--cwd") - # Branches rather than --all, which would walk refs/notes/loch too. - parser.add_argument("--revision", default="--branches") - args = parser.parse_args(argv) - - with trace_errors(): - root = repo_root(args.cwd or os.getcwd()) - linked = backfill(root, args.revision, _progress_meter()) - rows = [ - {"commit": sha, "session": call.session_id, "call": call.call} - for sha, call in linked - ] - text = "".join( - f" {sha[:7]} session {call.session_id[:8]}\n" for sha, call in linked - ) - text += f"linked {len(linked)} commit(s)\n" - return Result(command="backfill", payload={"linked": rows}, text=text) - - -def command_help(argv: list[str]) -> Result: - return Result(command="help", payload={"usage": USAGE}, text=USAGE) - - -def installed_version() -> str: - """Read from package metadata rather than held here, so there is one copy - of the number and pyproject stays the one that sets it. A source checkout - 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("loch") - except importlib.metadata.PackageNotFoundError: - return "unknown" - - -def command_version(argv: list[str]) -> Result: - version = installed_version() - return Result( - command="version", payload={"version": version}, text=f"loch {version}\n" - ) - - -def _platform_name() -> str: - system = platform.system().lower() - return {"darwin": "darwin", "linux": "linux", "windows": "win32"}.get( - system, system - ) - - -COMMANDS: dict[str, Callable[[list[str]], Result]] = { - "list": command_list, - "save": command_save, - "restore": command_restore, - "delete": command_delete, - "reindex": command_reindex, - "ingest": command_ingest, - "install": command_install, - "blame": command_blame, - "ask": command_ask, - "log": command_log, - "backfill": command_backfill, - "hook": command_hook, - "help": command_help, - "version": command_version, -} - - -def main() -> None: - argv = sys.argv[1:] - # Read off argv rather than from a parsed namespace: an unknown command, or - # a subparser rejecting a flag, has to render in the mode the caller asked - # for, and neither of those has a namespace by the time it fails. - as_json = JSON_FLAG in argv - if argv and argv[0] == JSON_FLAG: - argv = argv[1:] - - command = argv[0] if argv else "help" - if command in ("--help", "-h"): - command = "help" - if command in ("--version", "-V"): - command = "version" - - try: - handler = COMMANDS.get(command) - if handler is None: - 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) - except CommandError as error: - emit_error(command, error, as_json) - except Exception as error: - # A traceback is the most useful thing a human can get, and the one - # thing a JSON consumer can't parse. - if not as_json: - raise - emit_error(command, CommandError("internal", str(error)), True) - - emit(result, as_json) - - -if __name__ == "__main__": - main() diff --git a/loch/format.py b/loch/format.py deleted file mode 100644 index 0d8677b..0000000 --- a/loch/format.py +++ /dev/null @@ -1,257 +0,0 @@ -import hashlib -import json -import re -from collections.abc import Iterable, Iterator -from dataclasses import dataclass, field -from decimal import Decimal -from typing import Any - -FORMAT_VERSION = 1 - -HASH_PREFIX = "sha256:" - - -class FormatError(ValueError): - """A derived file that doesn't parse, names a format this build can't - read, or carries an id its own contents don't hash to.""" - - -_LONE_SURROGATE = re.compile("[\ud800-\udfff]") - - -def _string(text: str) -> str: - """JSON.stringify's escaping, which Python's matches except for a lone - surrogate: Python writes it raw, which isn't valid UTF-8, where - ECMAScript escapes it. Transcripts do hold them — a `\\ud83d` cut from its - pair by truncation — so they are escaped rather than refused.""" - encoded = json.dumps(text, ensure_ascii=False) - if _LONE_SURROGATE.search(encoded): - encoded = _LONE_SURROGATE.sub( - lambda match: f"\\u{ord(match.group(0)):04x}", encoded - ) - return encoded - - -def _number(value: float) -> str: - """ECMAScript Number-to-String, as RFC 8785 requires. Python's repr finds - the same shortest round-trip digits but places the exponent differently - (`1e+16` and `1e-05` where ECMAScript writes `10000000000000000` and - `0.00001`), so only the digits are taken from it.""" - if value != value or value in (float("inf"), float("-inf")): - raise ValueError(f"{value} has no JSON representation") - if value == 0: - return "0" - sign = "-" if value < 0 else "" - parts = Decimal(repr(abs(value))).normalize().as_tuple() - digits = "".join(str(digit) for digit in parts.digits) - exponent = parts.exponent - assert isinstance(exponent, int) - k = len(digits) - n = k + exponent - if k <= n <= 21: - return sign + digits + "0" * (n - k) - if 0 < n <= 21: - return sign + digits[:n] + "." + digits[n:] - if -6 < n <= 0: - return sign + "0." + "0" * -n + digits - mantissa = digits[0] + ("." + digits[1:] if k > 1 else "") - power = n - 1 - return f"{sign}{mantissa}e{'+' if power >= 0 else '-'}{abs(power)}" - - -def _utf16_order(key: str) -> bytes: - return key.encode("utf-16-be", "surrogatepass") - - -def _encode(value: Any, out: list[str]) -> None: - if isinstance(value, str): - out.append(_string(value)) - elif value is None: - out.append("null") - elif value is True: - out.append("true") - elif value is False: - out.append("false") - elif isinstance(value, int): - out.append(str(value)) - elif isinstance(value, float): - out.append(_number(value)) - elif isinstance(value, dict): - out.append("{") - for index, key in enumerate(sorted(value, key=_utf16_order)): - if not isinstance(key, str): - raise TypeError(f"object key {key!r} is not a string") - if index: - out.append(",") - out.append(_string(key)) - out.append(":") - _encode(value[key], out) - out.append("}") - elif isinstance(value, (list, tuple)): - out.append("[") - for index, item in enumerate(value): - if index: - out.append(",") - _encode(item, out) - out.append("]") - else: - raise TypeError(f"{type(value).__name__} is not JSON") - - -def canonical(value: Any) -> bytes: - """RFC 8785 (JSON Canonicalization Scheme): the one encoding every id is - computed over, so a second implementation in any language can reproduce - an id byte for byte. Keys sort by UTF-16 code units, numbers print as - ECMAScript does, and strings escape as JSON.stringify does. - - One deliberate departure: an integer prints exactly, at any size. RFC - 8785 treats every number as a double, which would silently round a - 63-bit id inside a tool result; exact is what the transcript said.""" - out: list[str] = [] - _encode(value, out) - return "".join(out).encode("utf-8") - - -def digest(value: Any) -> str: - return HASH_PREFIX + hashlib.sha256(canonical(value)).hexdigest() - - -def digest_bytes(data: bytes) -> str: - return HASH_PREFIX + hashlib.sha256(data).hexdigest() - - -def hex_of(object_id: str) -> str: - if not object_id.startswith(HASH_PREFIX): - raise FormatError(f"not a {HASH_PREFIX} id: {object_id}") - return object_id[len(HASH_PREFIX) :] - - -@dataclass(frozen=True) -class Turn: - """One node of the conversation graph, in two halves. - - `core` is the hashed envelope — format version, kind, author, parents, and - the *hash* of the content, never the content itself. That indirection is - what lets content be deleted while every id that depends on it stays - verifiable: a tombstoned turn still hashes to its id. - - `facts` are what the converter knew about the turn that is not part of its - identity — timestamps, the source record's uuid and line, model, branch. - They are regenerable and may differ between two derivations of the same - turn without the turn being a different one.""" - - id: str - core: dict[str, Any] - blocks: list[dict[str, Any]] | None - facts: dict[str, Any] = field(default_factory=dict) - - -def content_id(blocks: list[dict[str, Any]]) -> str: - return digest({"blocks": blocks}) - - -def make_core( - kind: str, - author: dict[str, Any], - parents: list[str], - blocks: list[dict[str, Any]], -) -> dict[str, Any]: - return { - "loch": FORMAT_VERSION, - "kind": kind, - "author": author, - "parents": parents, - "content": content_id(blocks), - } - - -def make_turn( - kind: str, - author: dict[str, Any], - parents: list[str], - blocks: list[dict[str, Any]], - facts: dict[str, Any] | None = None, -) -> Turn: - core = make_core(kind, author, parents, blocks) - return Turn(id=digest(core), core=core, blocks=blocks, facts=facts or {}) - - -@dataclass(frozen=True) -class Derived: - """A converter's understanding of one source, at the time it ran. Throw it - away and re-derive whenever the converter improves; the source is what - has to survive.""" - - header: dict[str, Any] - turns: list[Turn] - heads: dict[str, Any] - - -def derived_lines(derived: Derived) -> Iterator[bytes]: - yield canonical({"type": "header", **derived.header}) - for turn in derived.turns: - record: dict[str, Any] = {"type": "turn", "id": turn.id, "turn": turn.core} - if turn.blocks is not None: - record["content"] = {"blocks": turn.blocks} - if turn.facts: - record["facts"] = turn.facts - yield canonical(record) - yield canonical({"type": "heads", **derived.heads}) - - -def pack_derived(derived: Derived) -> bytes: - return b"".join(line + b"\n" for line in derived_lines(derived)) - - -def verify_turn(turn: Turn) -> None: - if digest(turn.core) != turn.id: - raise FormatError(f"turn {turn.id} does not hash to its id") - if turn.blocks is not None and content_id(turn.blocks) != turn.core["content"]: - raise FormatError(f"turn {turn.id} content does not match its hash") - - -def read_derived(lines: Iterable[str]) -> Derived: - """Parses and verifies. Every id is recomputed, so a file that reads back - without raising is internally consistent, not merely well-formed.""" - header: dict[str, Any] | None = None - heads: dict[str, Any] = {} - turns: list[Turn] = [] - seen: set[str] = set() - - for number, line in enumerate(lines, start=1): - if not line.strip(): - continue - try: - record = json.loads(line) - except ValueError as error: - raise FormatError(f"line {number}: {error}") from error - kind = record.pop("type", None) - if kind == "header": - if record.get("loch") != FORMAT_VERSION: - raise FormatError( - f"unsupported loch format {record.get('loch')} " - f"(this build reads {FORMAT_VERSION})" - ) - header = record - elif kind == "turn": - content = record.get("content") - turn = Turn( - id=record["id"], - core=record["turn"], - blocks=content["blocks"] if content is not None else None, - facts=record.get("facts", {}), - ) - verify_turn(turn) - for parent in turn.core["parents"]: - if parent not in seen: - raise FormatError(f"turn {turn.id} precedes its parent {parent}") - seen.add(turn.id) - turns.append(turn) - elif kind == "heads": - heads = record - else: - raise FormatError(f"line {number}: unknown record type {kind!r}") - - if header is None: - raise FormatError("no header") - return Derived(header=header, turns=turns, heads=heads) diff --git a/loch/git.py b/loch/git.py deleted file mode 100644 index 3e2b280..0000000 --- a/loch/git.py +++ /dev/null @@ -1,16 +0,0 @@ -import subprocess - - -def current_branch(cwd: str) -> str | None: - """None covers both a detached HEAD and a directory outside any repo — - the same two cases that leave gitBranch unset on a session.""" - try: - result = subprocess.run( - ["git", "-C", cwd, "symbolic-ref", "--short", "HEAD"], - capture_output=True, - text=True, - check=False, - ) - except OSError: - return None - return result.stdout.strip() or None diff --git a/loch/index.py b/loch/index.py deleted file mode 100644 index 6a88ff8..0000000 --- a/loch/index.py +++ /dev/null @@ -1,187 +0,0 @@ -import json -from dataclasses import dataclass -from typing import Any -from urllib.parse import quote, unquote - -from .bundle import Bundle, BundleSession, unpack_bundle -from .store import Store - -BUNDLES_PREFIX = "bundles/" -INDEX_PREFIX = "index/" - -BRANCH = "branch" - -# Percent-encoding rather than Claude's [^a-zA-Z0-9] -> - scheme: that one is -# lossy and would file feature/foo and feature-foo under the same segment. -# A value can't contain a control character, so this can't collide with one. -UNSET_SEGMENT = "%00" - - -@dataclass(frozen=True) -class IndexEntry: - ref: str - dimension: str - value: str | None - agent: str - created_at: str - bytes: int - sessions: int - cwd: str - claude_version: str | None - - -@dataclass(frozen=True) -class ReindexResult: - bundles: int - entries: int - removed: int - - -def bundle_key(ref: str) -> str: - return f"{BUNDLES_PREFIX}{ref}.loch" - - -def ref_from_key(key: str) -> str: - return key[len(BUNDLES_PREFIX) : -len(".loch")] - - -def encode_segment(value: str | None) -> str: - return UNSET_SEGMENT if value is None else quote(value, safe="") - - -def decode_segment(segment: str) -> str | None: - return None if segment == UNSET_SEGMENT else unquote(segment) - - -def dimension_prefix(dimension: str) -> str: - return f"{INDEX_PREFIX}{dimension}/" - - -def value_prefix(dimension: str, value: str | None) -> str: - return f"{dimension_prefix(dimension)}{encode_segment(value)}/" - - -def index_key(dimension: str, value: str | None, ref: str) -> str: - return f"{value_prefix(dimension, value)}{ref}" - - -def _entry_to_json(entry: IndexEntry) -> dict[str, Any]: - return { - "ref": entry.ref, - "dimension": entry.dimension, - "value": entry.value, - "agent": entry.agent, - "createdAt": entry.created_at, - "bytes": entry.bytes, - "sessions": entry.sessions, - "cwd": entry.cwd, - "claudeVersion": entry.claude_version, - } - - -def _entry_from_json(raw: dict[str, Any]) -> IndexEntry: - return IndexEntry( - ref=raw["ref"], - dimension=raw["dimension"], - value=raw.get("value"), - agent=raw.get("agent", ""), - created_at=raw.get("createdAt", ""), - bytes=raw.get("bytes", 0), - sessions=raw.get("sessions", 0), - cwd=raw.get("cwd", ""), - claude_version=raw.get("claudeVersion"), - ) - - -def _first_version(sessions: list[BundleSession]) -> str | None: - for session in sessions: - if session.claude_version: - return session.claude_version - return None - - -def entries_for(bundle: Bundle, ref: str, size: int) -> list[IndexEntry]: - """One entry per (branch, ref): a save without --branch can pack sessions - from several branches, so a bundle may be indexed under each of them.""" - grouped: dict[str | None, list[BundleSession]] = {} - for session in bundle.sessions: - grouped.setdefault(session.git_branch, []).append(session) - - return [ - IndexEntry( - ref=ref, - dimension=BRANCH, - value=branch, - agent=bundle.agent, - created_at=bundle.created_at, - bytes=size, - sessions=len(sessions), - cwd=sessions[0].cwd, - claude_version=_first_version(sessions), - ) - for branch, sessions in sorted( - grouped.items(), key=lambda item: encode_segment(item[0]) - ) - ] - - -def write_entries(store: Store, entries: list[IndexEntry]) -> list[str]: - keys = [] - for entry in entries: - key = index_key(entry.dimension, entry.value, entry.ref) - store.put(key, json.dumps(_entry_to_json(entry)).encode("utf-8")) - keys.append(key) - return keys - - -def index_bundle(store: Store, bundle: Bundle, ref: str, size: int) -> list[IndexEntry]: - entries = entries_for(bundle, ref, size) - write_entries(store, entries) - return entries - - -def load_entries(store: Store, prefix: str) -> list[IndexEntry]: - entries = [ - _entry_from_json(json.loads(store.get(key).decode("utf-8"))) - for key in store.list(prefix) - ] - return sorted(entries, key=lambda entry: entry.created_at, reverse=True) - - -def delete_bundle(store: Store, ref: str) -> list[str]: - """Entries first: they are derived from the bundle, so removing it before - them would strand any that a failure here left behind.""" - packed = store.get(bundle_key(ref)) - bundle = unpack_bundle(packed) - - removed = [] - for entry in entries_for(bundle, ref, len(packed)): - key = index_key(entry.dimension, entry.value, entry.ref) - store.delete(key) - removed.append(key) - - store.delete(bundle_key(ref)) - removed.append(bundle_key(ref)) - return removed - - -def reindex(store: Store) -> ReindexResult: - stale = set(store.list(INDEX_PREFIX)) - bundles = 0 - written: set[str] = set() - - for key in store.list(BUNDLES_PREFIX): - if not key.endswith(".loch"): - continue - packed = store.get(key) - bundle = unpack_bundle(packed) - entries = entries_for(bundle, ref_from_key(key), len(packed)) - written.update(write_entries(store, entries)) - bundles += 1 - - for key in sorted(stale - written): - store.delete(key) - - return ReindexResult( - bundles=bundles, entries=len(written), removed=len(stale - written) - ) diff --git a/loch/ingest.py b/loch/ingest.py deleted file mode 100644 index 4c77a9a..0000000 --- a/loch/ingest.py +++ /dev/null @@ -1,450 +0,0 @@ -import base64 -import hashlib -import heapq -import json -import os -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path -from typing import Any - -from .claude import AGENT, encode_path -from .format import FORMAT_VERSION, Derived, Turn, digest, digest_bytes -from .format import make_turn as build_turn -from .rewrite import ( - ENCODED_COMPONENT_BOUNDARY, - PATH_BOUNDARY, - UNGUARDED, - compile_replacements, -) - -CONVERTER = {"id": AGENT, "version": 1} - -PLACEHOLDER_PREFIX = "{{loch:" -ESCAPE = "{{loch:esc}}" -ROOT = "{{loch:root}}" -HOME = "{{loch:home}}" -ROOT_SLUG = "{{loch:root-slug}}" -SESSION = "{{loch:session}}" - -AGENT_AUTHOR = {"kind": "agent", "agent": AGENT} -TOOL_AUTHOR = {"kind": "tool", "agent": AGENT} -SYSTEM_AUTHOR = {"kind": "system", "agent": AGENT} - -# Record fields that place a record (in time, on a machine, in Claude's own -# bookkeeping) rather than say anything. Excluded from the hashed payload of -# system and attachment turns; the identity of a user or assistant turn comes -# from message content alone, so this list doesn't reach those. -ENVELOPE_FIELDS = frozenset( - { - "type", - "uuid", - "parentUuid", - "logicalParentUuid", - "sessionId", - "session_id", - "timestamp", - "cwd", - "gitBranch", - "version", - "entrypoint", - "userType", - "slug", - "isSidechain", - "agentId", - "requestId", - "promptId", - } -) - - -@dataclass(frozen=True) -class Origin: - """Where the source lived when it was ingested. These are the only - machine-specific strings a derived file carries, and they live in its - header alone: every turn refers to them through placeholders.""" - - cwd: str - home: str - session_id: str - - -def normalizer(origin: Origin) -> Callable[[str], str]: - """Maps a string to its machine-neutral form, with the same single-pass, - boundary-guarded machinery restore rewrites with — so a session copied - elsewhere by `restore` normalizes back to the same bytes. - - The escape pair comes first in meaning though not in order: a literal - `{{loch:` already in a transcript becomes `{{loch:esc}}`, which keeps - every placeholder in the output unambiguous and the mapping reversible.""" - pairs = [ - (PLACEHOLDER_PREFIX, ESCAPE, UNGUARDED), - (origin.cwd, ROOT, PATH_BOUNDARY), - (encode_path(origin.cwd), ROOT_SLUG, ENCODED_COMPONENT_BOUNDARY), - (origin.session_id, SESSION, UNGUARDED), - ] - # A session run from the home directory itself is a root, not a home. - if origin.home != origin.cwd: - pairs.append((origin.home, HOME, PATH_BOUNDARY)) - return compile_replacements(pairs) - - -def normalize_value(value: Any, text: Callable[[str], str]) -> Any: - """Keys as well as values: a tool result can key a map by file path, and - `restore` rewrites the text of the whole record, keys included.""" - if isinstance(value, str): - return text(value) - if isinstance(value, list): - return [normalize_value(item, text) for item in value] - if isinstance(value, dict): - return {text(key): normalize_value(item, text) for key, item in value.items()} - return value - - -def _blocks_from_content(content: Any) -> list[dict[str, Any]]: - if isinstance(content, str): - return [{"type": "text", "text": content}] - if not isinstance(content, list): - return [] - return [_block(block) for block in content] - - -def _block(block: Any) -> dict[str, Any]: - if not isinstance(block, dict): - return {"type": "x-claude-code:block", "block": block} - kind = block.get("type") - if kind == "text": - return {"type": "text", "text": block.get("text", "")} - if kind == "thinking": - # The signature is Anthropic's attestation for resuming, not content, - # and it lives on in the source. - return {"type": "thinking", "text": block.get("thinking", "")} - if kind == "redacted_thinking": - return {"type": "redacted-thinking"} - if kind == "tool_use": - return { - "type": "tool-call", - "call": block.get("id"), - "name": block.get("name"), - "input": block.get("input"), - } - if kind == "tool_result": - normalized: dict[str, Any] = { - "type": "tool-result", - "call": block.get("tool_use_id"), - "content": _blocks_from_content(block.get("content")), - } - if block.get("is_error"): - normalized["error"] = True - return normalized - if kind == "image": - return {"type": "image", "source": block.get("source")} - # Unknown block types pass through whole rather than being dropped, so a - # later converter version can learn them without the source being re-read - # by anyone who only has the derived file. - return {"type": "x-claude-code:block", "block": block} - - -def _payload(record: dict[str, Any]) -> dict[str, Any]: - return {key: value for key, value in record.items() if key not in ENVELOPE_FIELDS} - - -def classify(record: dict[str, Any]) -> tuple[str, dict[str, Any], list[Any]] | None: - """(kind, author, blocks) for a chain record, or None for one that isn't - part of the conversation graph. The human author is filled in by the - caller, since only the ingest knows who it is.""" - kind = record.get("type") - message = record.get("message") - content = message.get("content") if isinstance(message, dict) else None - - if kind == "assistant": - return "message", AGENT_AUTHOR, _blocks_from_content(content) - if kind == "user": - blocks = _blocks_from_content(content) - if record.get("isCompactSummary") or record.get("isMeta"): - return "context", SYSTEM_AUTHOR, blocks - if any(block["type"] == "tool-result" for block in blocks): - return "tool-result", TOOL_AUTHOR, blocks - return "message", {"kind": "human"}, blocks - if kind == "attachment": - block = {"type": "x-claude-code:attachment", "attachment": _payload(record)} - return "context", SYSTEM_AUTHOR, [block] - if kind == "system": - block = {"type": "x-claude-code:system", "system": _payload(record)} - if record.get("subtype") == "compact_boundary": - return "compaction", SYSTEM_AUTHOR, [block] - return "event", SYSTEM_AUTHOR, [block] - return None - - -def _parent_uuid(record: dict[str, Any]) -> str | None: - """A compaction boundary has no parent by design and names the record it - logically follows instead. Following that link is what keeps a compacted - session one connected graph rather than a stack of disjoint roots.""" - parent = record.get("parentUuid") - if parent is None: - parent = record.get("logicalParentUuid") - return parent if isinstance(parent, str) else None - - -def _parse(raw: str) -> list[tuple[int, dict[str, Any]]]: - records: list[tuple[int, dict[str, Any]]] = [] - for number, line in enumerate(raw.split("\n"), start=1): - if not line.strip(): - continue - try: - record = json.loads(line) - except ValueError: - continue - if isinstance(record, dict): - records.append((number, record)) - return records - - -def _topological( - chain: list[tuple[int, dict[str, Any]]], -) -> tuple[list[tuple[int, dict[str, Any]]], set[str]]: - """File order wherever it already respects parentage, which for Claude's - append-only files is everywhere. Parents that never appear are dangling - (the record becomes a root); a cycle, which a well-formed file can't hold, - is broken the same way rather than looping.""" - present = {record["uuid"] for _, record in chain} - children: dict[str, list[int]] = {} - waiting = [0] * len(chain) - for index, (_, record) in enumerate(chain): - parent = _parent_uuid(record) - if parent is not None and parent in present and parent != record["uuid"]: - children.setdefault(parent, []).append(index) - waiting[index] = 1 - - ready = [index for index, count in enumerate(waiting) if count == 0] - heapq.heapify(ready) - ordered: list[tuple[int, dict[str, Any]]] = [] - done = [False] * len(chain) - while len(ordered) < len(chain): - if not ready: - stuck = next(index for index, finished in enumerate(done) if not finished) - waiting[stuck] = 0 - heapq.heappush(ready, stuck) - index = heapq.heappop(ready) - if done[index]: - continue - done[index] = True - ordered.append(chain[index]) - for child in children.get(chain[index][1]["uuid"], []): - if not done[child]: - waiting[child] -= 1 - if waiting[child] <= 0: - heapq.heappush(ready, child) - return ordered, present - - -def _facts( - number: int, record: dict[str, Any], text: Callable[[str], str] -) -> dict[str, Any]: - facts: dict[str, Any] = {"line": number, "uuid": record["uuid"]} - message = record.get("message") - if isinstance(message, dict): - for source, name in (("id", "messageId"), ("model", "model")): - if isinstance(message.get(source), str): - facts[name] = message[source] - for name in ("timestamp", "gitBranch", "version", "subtype"): - if isinstance(record.get(name), str): - facts[name] = record[name] - if isinstance(record.get("cwd"), str): - facts["cwd"] = text(record["cwd"]) - facts["record"] = record.get("type") - return facts - - -def _fold_event( - number: int, - record: dict[str, Any], - blocks: list[Any], - turn_of: dict[str, str], - turns: dict[str, Turn], - session: dict[str, Any], - text: Callable[[str], str], -) -> None: - """Hook summaries, turn durations, API retries: Claude Code's own - bookkeeping, written into the parent chain but not part of what anyone - said. As turns they made a quarter of the graph's identity depend on - Claude Code's internal record shapes. Folded into the facts of the turn - they follow instead, and the event's uuid resolves to that turn, so a - record whose parent was the event links straight past it.""" - event: dict[str, Any] = {"line": number, **normalize_value(blocks[0], text)} - if isinstance(record.get("timestamp"), str): - event["timestamp"] = record["timestamp"] - parent_uuid = _parent_uuid(record) - parent = turn_of.get(parent_uuid) if parent_uuid is not None else None - if parent is None: - session.setdefault("events", []).append(event) - return - turn_of[record["uuid"]] = parent - turns[parent].facts.setdefault("events", []).append(event) - - -def convert( - raw: str, origin: Origin, human: dict[str, Any] -) -> tuple[list[Turn], dict[str, Any], dict[str, Any]]: - """Claude Code JSONL to loch turns, plus heads and session-level facts. - - One chain record is one turn, and its parents are its `parentUuid`'s turn. - Assistant messages are therefore several turns when Claude split one API - message across records (one per content block) — `facts.messageId` is what - groups them back. Keeping records whole is what keeps Claude's own tree, - including the branches a rewind leaves in the file, intact as the graph. - - Two records whose cores are identical are one turn. That happens when a - rewind resubmits exactly what was said before from the same point, which - is the same turn by any reasonable reading; the later uuids are kept in - the first one's facts. - """ - text = normalizer(origin) - records = _parse(raw) - chain = [ - (number, record) - for number, record in records - if isinstance(record.get("uuid"), str) - ] - ordered, present = _topological(chain) - - turn_of: dict[str, str] = {} - turns: dict[str, Turn] = {} - has_children: set[str] = set() - last_turn: str | None = None - session: dict[str, Any] = {} - - for number, record in ordered: - classified = classify(record) - if classified is None: - continue - kind, author, blocks = classified - if kind == "event": - _fold_event(number, record, blocks, turn_of, turns, session, text) - continue - if author.get("kind") == "human": - author = human - parent_uuid = _parent_uuid(record) - facts = _facts(number, record, text) - parents: list[str] = [] - if parent_uuid is not None: - if parent_uuid in turn_of: - parents = [turn_of[parent_uuid]] - elif parent_uuid not in present: - facts["danglingParent"] = parent_uuid - - turn = build_turn(kind, author, parents, normalize_value(blocks, text), facts) - turn_of[record["uuid"]] = turn.id - last_turn = turn.id - if turn.id in turns: - turns[turn.id].facts.setdefault("alsoUuids", []).append(record["uuid"]) - else: - turns[turn.id] = turn - has_children.update(parents) - - current = last_turn - for _, record in records: - record_type = record.get("type") - if record_type == "last-prompt" and record.get("leafUuid") in turn_of: - current = turn_of[record["leafUuid"]] - elif record_type == "ai-title" and isinstance(record.get("aiTitle"), str): - session["aiTitle"] = record["aiTitle"] - elif record_type == "custom-title" and isinstance( - record.get("customTitle"), str - ): - session["title"] = record["customTitle"] - - heads: dict[str, Any] = { - "leaves": [turn_id for turn_id in turns if turn_id not in has_children] - } - if current is not None: - heads["current"] = current - return list(turns.values()), heads, normalize_value(session, text) - - -def source_files(transcript_path: str) -> list[tuple[str, str]]: - """The transcript and everything Claude files beside it for the session: - subagent transcripts and spilled tool output under `/`. All of - it is the source, and a source that dropped the sidecar would silently - lose every subagent conversation.""" - files = [("transcript.jsonl", transcript_path)] - sidecar = transcript_path[: -len(".jsonl")] - if os.path.isdir(sidecar): - for directory, _, names in os.walk(sidecar): - for name in names: - path = os.path.join(directory, name) - relative = os.path.relpath(path, sidecar).replace(os.sep, "/") - files.append((f"sidecar/{relative}", path)) - return sorted(files) - - -def source_manifest(transcript_path: str) -> tuple[dict[str, Any], str]: - """The content-addressed identity of the raw source: every file's hash, - in path order. Returns the manifest and the transcript text.""" - entries = [] - transcript = "" - for relative, path in source_files(transcript_path): - data = Path(path).read_bytes() - entries.append( - {"path": relative, "sha256": digest_bytes(data), "bytes": len(data)} - ) - if relative == "transcript.jsonl": - transcript = data.decode("utf-8", "surrogateescape") - manifest = {"agent": AGENT, "files": entries} - return {"id": digest(manifest), **manifest}, transcript - - -def ingest( - transcript_path: str, - origin: Origin, - author_id: str | None = None, -) -> Derived: - human: dict[str, Any] = {"kind": "human"} - # Omitted rather than null, for the same reason the bundle format omits - # absent metadata: the encoding of "unknown" is part of every id. - if author_id is not None: - human["id"] = author_id - - source, transcript = source_manifest(transcript_path) - turns, heads, session = convert(transcript, origin, human) - header: dict[str, Any] = { - "loch": FORMAT_VERSION, - "converter": CONVERTER, - "source": source, - "origin": { - "cwd": origin.cwd, - "home": origin.home, - "sessionId": origin.session_id, - }, - "author": human, - } - if session: - header["session"] = session - return Derived(header=header, turns=turns, heads=heads) - - -def derived_name(derived: Derived) -> str: - source = derived.header["source"]["id"].split(":", 1)[1] - converter = derived.header["converter"] - return f"{source}.{converter['id']}-v{converter['version']}.jsonl" - - -class AuthorKeyError(ValueError): - pass - - -def ssh_author_id(public_key: str) -> str: - """`ssh:SHA256:` — the fingerprint `ssh-keygen -l` prints, so an - author id can be checked by eye against a key someone already publishes - (GitHub serves them at /.keys), and the same key can later sign the - turns it authored.""" - fields = public_key.split() - if len(fields) < 2: - raise AuthorKeyError("not an OpenSSH public key line") - try: - blob = base64.b64decode(fields[1], validate=True) - except ValueError as error: - raise AuthorKeyError(f"key body is not base64: {error}") from error - fingerprint = base64.b64encode(hashlib.sha256(blob).digest()).decode() - return f"ssh:SHA256:{fingerprint.rstrip('=')}" diff --git a/loch/output.py b/loch/output.py deleted file mode 100644 index f186baf..0000000 --- a/loch/output.py +++ /dev/null @@ -1,83 +0,0 @@ -import json -import sys -from dataclasses import dataclass, field -from typing import Any, NoReturn - -SCHEMA = 1 - -JSON_FLAG = "--json" - - -@dataclass(frozen=True) -class Result: - """What a command produced, in both renderings. Building the payload and - the prose in one place is what keeps them from drifting apart.""" - - command: str - payload: dict[str, Any] = field(default_factory=dict) - text: str = "" - warnings: tuple[str, ...] = () - - -class CommandError(Exception): - """A failure the caller is meant to act on. `code` is a stable token — - consumers branch on it, so reword `message` freely but not `code`.""" - - def __init__( - self, - code: str, - message: str, - payload: dict[str, Any] | None = None, - warnings: tuple[str, ...] = (), - exit_status: int = 1, - prose: str | None = None, - ) -> None: - super().__init__(message) - self.code = code - self.message = message - self.payload = payload if payload is not None else {} - self.warnings = warnings - self.exit_status = exit_status - self.prose = prose - - -def document( - command: str, - ok: bool, - payload: dict[str, Any], - code: str | None = None, - error: str | None = None, -) -> dict[str, Any]: - body: dict[str, Any] = {"schema": SCHEMA, "ok": ok, "command": command} - if not ok: - body["code"] = code - body["error"] = error - body.update(payload) - return body - - -def emit(result: Result, as_json: bool) -> None: - if as_json: - _write(document(result.command, True, result.payload)) - return - # Warnings are stderr-only prose; JSON carries the same facts as per-item - # status, so nothing but the document is written in that mode. - for warning in result.warnings: - sys.stderr.write(warning) - sys.stdout.write(result.text) - - -def emit_error(command: str, error: CommandError, as_json: bool) -> NoReturn: - if as_json: - _write( - document(command, False, error.payload, error.code, error.message), - ) - else: - for warning in error.warnings: - sys.stderr.write(warning) - sys.stderr.write(error.prose if error.prose else f"loch: {error.message}\n") - raise SystemExit(error.exit_status) - - -def _write(body: dict[str, Any]) -> None: - sys.stdout.write(json.dumps(body) + "\n") diff --git a/loch/redact.py b/loch/redact.py deleted file mode 100644 index ebbe2e1..0000000 --- a/loch/redact.py +++ /dev/null @@ -1,123 +0,0 @@ -import re -from dataclasses import dataclass -from functools import lru_cache - - -@dataclass(frozen=True) -class Rule: - name: str - pattern: str - - @property - def key(self) -> str: - return self.name.replace("-", "_") - - -# The value of a named assignment is the only way to find a credential that -# carries no distinctive prefix (an AWS secret access key is 40 chars of -# base64). Uppercase-only keeps it off ordinary prose. The lookaheads keep it -# off filesystem paths and off a token this module already wrote, which is what -# makes a second pass over redacted text find nothing. -ENV_ASSIGNMENT = ( - r"(?P" - r"[A-Z0-9_]*" - r"(?:AWS_SECRET_ACCESS_KEY|SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)" - r"[A-Z0-9_]*" - r"[\"']?\s*[=:]\s*[\"']?" - r")" - r"(?!\[REDACTED:)(?![/~.])[^\s\"',;\\]{8,}" -) - -# A PEM block is the one rule whose match spans newlines. Its body excludes the -# double quote so a BEGIN and an END in two different JSONL records can't be -# joined into one match — that would swallow the records between them. -PRIVATE_KEY_BLOCK = ( - r"-----BEGIN [A-Z ]*PRIVATE KEY-----" - r"[^\"]*?" - r"-----END [A-Z ]*PRIVATE KEY-----" -) - -# A prefixed key is only a key when the prefix starts a word. Without this, -# scanning 350MB of real transcripts turned up 631 "AWS keys" (ACCA landing -# mid-base64-blob) and 56 "OpenAI keys" (the "sk-" inside a CSS `.task-*` -# class), and zero real ones. The fixed-length keys get a closing guard too, -# since a longer run of the same characters means it isn't a key. -START = r"(? re.Pattern[str]: - """One alternation, applied in a single left-to-right pass, so a rule can - never match inside the replacement an earlier rule produced.""" - return re.compile("|".join(f"(?P<{rule.key}>{rule.pattern})" for rule in rules)) - - -def _matched_rule(match: re.Match[str], rules: tuple[Rule, ...]) -> Rule: - for rule in rules: - if match.group(rule.key) is not None: - return rule - raise RedactionError("a match belonged to no rule") - - -def scan(text: str, rules: tuple[Rule, ...] = RULES) -> dict[str, int]: - counts: dict[str, int] = {} - for match in _compiled(rules).finditer(text): - name = _matched_rule(match, rules).name - counts[name] = counts.get(name, 0) + 1 - return counts - - -def redact(text: str, rules: tuple[Rule, ...] = RULES) -> Redaction: - counts: dict[str, int] = {} - - def substitute(match: re.Match[str]) -> str: - rule = _matched_rule(match, rules) - counts[rule.name] = counts.get(rule.name, 0) + 1 - kept = match.groupdict().get(f"{rule.key}_keep") or "" - return f"{kept}[REDACTED:{rule.name}]" - - redacted = _compiled(rules).sub(substitute, text) - - leftover = scan(redacted, rules) - if leftover: - raise RedactionError( - f"secrets still match after redaction: {_detail(leftover)}" - ) - - return Redaction(text=redacted, counts=counts) - - -def _detail(counts: dict[str, int]) -> str: - return ", ".join(f"{name} ×{count}" for name, count in sorted(counts.items())) - - -def summarize(counts: dict[str, int]) -> str: - if not counts: - return "" - total = sum(counts.values()) - return f"redacted {total} secret{'' if total == 1 else 's'} ({_detail(counts)})" diff --git a/loch/rewrite.py b/loch/rewrite.py deleted file mode 100644 index 8cf5a48..0000000 --- a/loch/rewrite.py +++ /dev/null @@ -1,143 +0,0 @@ -import re -from collections.abc import Callable -from dataclasses import dataclass - -from .claude import encode_path, transcript_cwds - - -@dataclass(frozen=True) -class RewriteSpec: - origin_cwd: str - origin_home: str - target_cwd: str - target_home: str - origin_session_id: str | None = None - target_session_id: str | None = None - - -# A path only matches when it ends on a component boundary, so a sibling -# directory that merely extends the origin's last component is left alone. -# The guard rejects any character that could continue a filename and allows -# everything else, because a transcript surrounds paths with `"`, `\`, `:`, -# `,`, 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._-])" - -# 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-])" - -# The session id is a UUID, not a path: it appears bare in filenames and in -# `"sessionId":"..."` values, where no boundary rule holds. -UNGUARDED = "" - - -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. - - 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 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 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), - ( - encode_path(spec.origin_cwd), - encode_path(spec.target_cwd), - ENCODED_COMPONENT_BOUNDARY, - ), - ] - - if spec.origin_session_id and spec.target_session_id: - pairs.append((spec.origin_session_id, spec.target_session_id, UNGUARDED)) - - return _apply_replacements(raw, pairs) - - -def residual_origin_paths(text: str, spec: RewriteSpec) -> list[str]: - """Occurrences of the origin's paths that survived a rewrite. A non-empty - result means the restored session will reference files that don't exist on - this machine. - - Necessary and nowhere near sufficient — see foreign_cwds. This only catches - a path that still carries an origin marker, and the more dangerous failure - consumes the marker on its way to being wrong. - """ - found: dict[str, None] = {} - for needle in (spec.origin_cwd, spec.origin_home): - if ( - needle - and needle != spec.target_cwd - and needle != spec.target_home - and needle in text - ): - found[needle] = None - return list(found) - - -@dataclass(frozen=True) -class ForeignCwd: - count: int - restored: str - - -def foreign_cwds(raw: str, spec: RewriteSpec) -> dict[str, ForeignCwd]: - """Directories a transcript works in that no rewrite into `target_cwd` can - satisfy, keyed by their path on the *origin* machine, with the number of - records naming each and the string they end up as here. - - This is the check residual_origin_paths structurally cannot make. A cwd the - spec was not keyed on declines the cwd pair and falls through to the home - pair, which turns it into a well-formed path on this machine that simply - isn't there. The origin marker is consumed on the way, so a substring - search for it comes back clean — the restore reports success while every - one of those records points at nothing. - - Takes the transcript *before* rewriting, which is the only place the origin - path still exists losslessly. Recovering it from the restored value would - mean reversing the home substitution, and that reversal is a guess: a - leading target home may have been rewritten from the origin's or may have - been there all along, with no way to tell after the fact. Guessing is the - failure this module exists to stop, so the caller is handed the real string - instead. `restored` is derived by putting each cwd through the same spec, - so it is what the file on disk actually says. - - Non-empty does not always mean a bug: a session that genuinely moved - between directories has records only one of which any single target cwd can - satisfy. It always means the restored transcript is partly wrong about the - filesystem, which is what a caller needs to know. - """ - found: dict[str, ForeignCwd] = {} - for cwd, count in transcript_cwds(raw).items(): - restored = rewrite_transcript(cwd, spec) - if restored != spec.target_cwd: - found[cwd] = ForeignCwd(count=count, restored=restored) - return found diff --git a/loch/store.py b/loch/store.py deleted file mode 100644 index a1106ad..0000000 --- a/loch/store.py +++ /dev/null @@ -1,178 +0,0 @@ -import os -import re -from abc import ABC, abstractmethod -from pathlib import Path -from typing import TYPE_CHECKING -from urllib.parse import unquote, urlparse - -if TYPE_CHECKING: - from mypy_boto3_s3.client import S3Client - -DEFAULT_STORE = os.path.join(str(Path.home()), ".loch", "store") - - -class MissingObject(Exception): - """The store answered and the object isn't there. Distinct from a store - that didn't answer at all: one is terminal, the other worth retrying, and - a caller has to be able to tell them apart.""" - - -class MissingDependency(Exception): - """A backend whose SDK isn't installed. Neither terminal nor worth - retrying: the fix is an install, so a caller has to be able to tell this - from a store that didn't answer.""" - - -class Store(ABC): - @abstractmethod - def describe(self) -> str: ... - - @abstractmethod - def put(self, key: str, data: bytes) -> None: ... - - @abstractmethod - def get(self, key: str) -> bytes: ... - - @abstractmethod - def list(self, prefix: str) -> list[str]: ... - - # Deleting an absent key succeeds: index entries are derived, so a repair - # pass has to be able to remove ones a half-finished save never wrote. - @abstractmethod - def delete(self, key: str) -> None: ... - - -class FileStore(Store): - def __init__(self, root: str) -> None: - self._root = root - - def describe(self) -> str: - return self._root - - def put(self, key: str, data: bytes) -> None: - path = Path(self._root) / key - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(data) - - def get(self, key: str) -> bytes: - try: - return (Path(self._root) / key).read_bytes() - except FileNotFoundError as error: - raise MissingObject(f"no object at {key}") from error - - def list(self, prefix: str) -> list[str]: - root = Path(self._root) - if not root.is_dir(): - return [] - # String prefix rather than directory descent, so both backends answer - # the same question for a prefix that stops mid-segment. - return sorted( - key - for path in root.rglob("*") - if path.is_file() - and (key := path.relative_to(root).as_posix()).startswith(prefix) - ) - - def delete(self, key: str) -> None: - (Path(self._root) / key).unlink(missing_ok=True) - - -class S3Store(Store): - def __init__(self, bucket: str, prefix: str) -> None: - self._bucket = bucket - self._prefix = prefix - - def describe(self) -> str: - return f"s3://{self._bucket}/{self._prefix}" - - def _key_for(self, key: str) -> str: - return f"{self._prefix}/{key}" if self._prefix else key - - def _relative_key(self, key: str) -> str: - return key[len(self._prefix) + 1 :] if self._prefix else key - - # Imported lazily so the file backend never pays for loading the SDK — - # which is also what lets boto3 be an optional extra rather than a - # dependency every install carries. - def _client(self) -> "S3Client": - try: - import boto3 - from botocore.config import Config - except ImportError as error: - raise MissingDependency( - "the S3 backend needs boto3, which this install doesn't have " - "(reinstall as loch[s3])" - ) from error - - endpoint = os.environ.get("LOCH_S3_ENDPOINT") - region = os.environ.get("LOCH_S3_REGION") - return boto3.client( - "s3", - endpoint_url=endpoint, - region_name=region, - # A custom endpoint means MinIO/R2/Garage, which need path style. - config=Config(s3={"addressing_style": "path"}) if endpoint else None, - ) - - def put(self, key: str, data: bytes) -> None: - self._client().put_object( - Bucket=self._bucket, - Key=self._key_for(key), - Body=data, - ContentType="application/gzip", - ) - - def get(self, key: str) -> bytes: - # Before the botocore import, so an install without the extra reports - # the missing dependency rather than a bare ImportError. - client = self._client() - from botocore.exceptions import ClientError - - try: - response = client.get_object(Bucket=self._bucket, Key=self._key_for(key)) - except ClientError as error: - # A missing bucket stays a plain ClientError: it means the store - # is misconfigured, not that this one object was deleted. - if error.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"): - raise MissingObject(f"no object at {key}") from error - raise - body = response.get("Body") - if body is None: - raise ValueError(f"empty object at {self._key_for(key)}") - data: bytes = body.read() - return data - - def list(self, prefix: str) -> list[str]: - # Paginated: list_objects_v2 truncates at 1000 keys. - pages = self._client().get_paginator("list_objects_v2") - return sorted( - self._relative_key(item["Key"]) - for page in pages.paginate( - Bucket=self._bucket, Prefix=self._key_for(prefix) - ) - for item in page.get("Contents", []) - ) - - def delete(self, key: str) -> None: - self._client().delete_object(Bucket=self._bucket, Key=self._key_for(key)) - - -def create_store(uri: str) -> Store: - if uri.startswith("s3://"): - without_scheme = uri[len("s3://") :] - slash = without_scheme.find("/") - bucket = without_scheme if slash == -1 else without_scheme[:slash] - prefix = "" if slash == -1 else re.sub(r"/$", "", without_scheme[slash + 1 :]) - if not bucket: - raise ValueError(f"invalid S3 store URI: {uri}") - return S3Store(bucket, prefix) - - if uri.startswith("file://"): - return FileStore(unquote(urlparse(uri).path)) - return FileStore(uri if os.path.isabs(uri) else os.path.abspath(uri)) - - -def resolve_store_uri(explicit: str | None = None) -> str: - if explicit is not None: - return explicit - return os.environ.get("LOCH_STORE", DEFAULT_STORE) diff --git a/loch/trace.py b/loch/trace.py deleted file mode 100644 index cd5fd02..0000000 --- a/loch/trace.py +++ /dev/null @@ -1,750 +0,0 @@ -"""Which conversation made which commit, and getting back into it. - -A commit is linked to the turn that made it by a git note on `refs/notes/loch`: -a small JSON document naming the agent session and the tool call that ran -`git commit`. It holds no transcript text, so it travels with the repository -like any other envelope (SPEC.md §9, §10). The transcript it points at lives in -Claude's project directory or, once a hook has snapshotted it, in the store. - -Links are captured live, by Claude Code hooks around every Bash call, because -recovering them afterwards is unreliable: `git commit -q` prints no hash, and -commits made from a script never appear in any tool output. `backfill` exists -for history made before the hooks, and accepts only an exact match. -""" - -import hashlib -import json -import os -import subprocess -import time -import uuid -from collections.abc import Callable, Iterator -from dataclasses import dataclass -from datetime import datetime -from pathlib import Path -from typing import Any - -from .claude import ( - AGENT, - _display_summary, - home_dir, - projects_dir, - read_session_meta, - transcript_cwds, - transcript_path_for, -) -from .format import Turn -from .ingest import Origin, ingest -from .rewrite import RewriteSpec, rewrite_transcript -from .store import MissingObject, Store - -NOTES_REF = "refs/notes/loch" - -NOTE_VERSION = 1 - -TRANSCRIPTS_PREFIX = f"transcripts/{AGENT}/" - -UNCOMMITTED = "0" * 40 - -# How far a commit's committer time may sit outside the tool call that made it. -# Git records whole seconds and the transcript milliseconds, so one second of -# slack covers truncation; the rest covers a slow hook process. -CLOCK_SLACK = 2.0 - - -class TraceError(Exception): - def __init__(self, code: str, message: str) -> None: - super().__init__(message) - self.code = code - - -def git(cwd: str, *args: str, check: bool = True, stdin: str | None = None) -> str: - result = subprocess.run( - ["git", "-C", cwd, *args], - capture_output=True, - text=True, - check=False, - input=stdin, - ) - if check and result.returncode != 0: - raise TraceError("git-failed", result.stderr.strip() or "git failed") - return result.stdout - - -def repo_root(cwd: str) -> str: - try: - return git(cwd, "rev-parse", "--show-toplevel").strip() - except (TraceError, OSError) as error: - raise TraceError("not-a-repository", f"{cwd} is not in a git repository") from ( - error - ) - - -def head(cwd: str) -> str | None: - return git(cwd, "rev-parse", "--verify", "-q", "HEAD", check=False).strip() or None - - -# -- notes ------------------------------------------------------------------ - - -def make_note(session_id: str, call: str, captured: str) -> dict[str, Any]: - return { - "loch": NOTE_VERSION, - "agent": AGENT, - "session": session_id, - "call": call, - "captured": captured, - } - - -def write_note(cwd: str, commit: str, note: dict[str, Any]) -> None: - body = json.dumps(note, sort_keys=True, separators=(",", ":")) - git(cwd, "notes", "--ref", NOTES_REF, "add", "-f", "-F", "-", commit, stdin=body) - - -def read_note(cwd: str, commit: str) -> dict[str, Any] | None: - text = git(cwd, "notes", "--ref", NOTES_REF, "show", commit, check=False) - try: - note = json.loads(text) - except ValueError: - return None - return note if isinstance(note, dict) and note.get("loch") == NOTE_VERSION else None - - -def noted_commits(cwd: str) -> set[str]: - listing = git(cwd, "notes", "--ref", NOTES_REF, "list", check=False) - return {line.split()[1] for line in listing.splitlines() if len(line.split()) == 2} - - -# -- hooks ------------------------------------------------------------------ - - -def _pending_dir(cwd: str) -> str: - git_dir = git(cwd, "rev-parse", "--absolute-git-dir").strip() - return os.path.join(git_dir, "loch", "pending") - - -def _call_key(event: dict[str, Any]) -> str: - call = event.get("tool_use_id") - if isinstance(call, str) and call: - return call - command = str((event.get("tool_input") or {}).get("command", "")) - return "cmd-" + hashlib.sha256(command.encode()).hexdigest()[:32] - - -def hook_pre_tool(event: dict[str, Any]) -> None: - """Remembers HEAD before a Bash call, so the matching post hook can tell - exactly which commits the call made rather than guessing from history.""" - cwd = str(event.get("cwd") or os.getcwd()) - try: - before = head(cwd) or "" - directory = _pending_dir(cwd) - except (TraceError, OSError): - return - os.makedirs(directory, exist_ok=True) - state = {"head": before, "at": time.time()} - Path(directory, _call_key(event)).write_text(json.dumps(state)) - - -def commits_made(cwd: str, before: str, after: str, since: float) -> list[str]: - """Commits reachable from `after` and not from `before`, and committed - after the call began. The time bound is what keeps a `git checkout` or a - fast-forward pull — which move HEAD onto commits someone else made — from - being attributed to this call.""" - span = f"{before}..{after}" if before else after - listing = git(cwd, "log", "--format=%H %ct", span) - made = [] - for line in listing.splitlines(): - sha, _, stamp = line.partition(" ") - if stamp and int(stamp) >= int(since) - 1: - made.append(sha) - return made - - -def _call_from_transcript(path: str, command: str) -> str | None: - """The tool call id, for a hook payload that didn't carry one: the last - Bash call in the transcript that ran exactly this command.""" - found = None - for record in _read_records(path): - for block in _content(record): - if ( - block.get("type") == "tool_use" - and block.get("name") == "Bash" - and (block.get("input") or {}).get("command") == command - ): - found = block.get("id") - return found if isinstance(found, str) else None - - -def hook_post_tool(event: dict[str, Any]) -> list[str]: - cwd = str(event.get("cwd") or os.getcwd()) - session_id = event.get("session_id") - if not isinstance(session_id, str): - return [] - try: - state_path = Path(_pending_dir(cwd), _call_key(event)) - state = json.loads(state_path.read_text()) - state_path.unlink() - except (TraceError, OSError, ValueError): - return [] - after = head(cwd) - if after is None or after == state["head"]: - return [] - - call = event.get("tool_use_id") - if not isinstance(call, str) or not call: - transcript = event.get("transcript_path") - command = str((event.get("tool_input") or {}).get("command", "")) - call = ( - _call_from_transcript(transcript, command) - if isinstance(transcript, str) - else None - ) - if call is None: - return [] - - made = commits_made(cwd, state["head"], after, state["at"]) - for commit in made: - write_note(cwd, commit, make_note(session_id, call, "hook")) - return made - - -def snapshot_transcript(event: dict[str, Any], store: Store) -> str | None: - """Copies the live transcript into the store. Claude Code deletes - transcripts after `cleanupPeriodDays` (30 by default), which would leave - every note pointing at nothing; this is the copy that outlives it. The - file is append-only, so the latest snapshot covers every earlier one and - one key per session suffices.""" - path = event.get("transcript_path") - session_id = event.get("session_id") - if not isinstance(path, str) or not isinstance(session_id, str): - return None - try: - data = Path(path).read_bytes() - except OSError: - return None - key = transcript_key(os.path.basename(os.path.dirname(path)), session_id) - store.put(key, data) - return key - - -def transcript_key(project: str, session_id: str) -> str: - return f"{TRANSCRIPTS_PREFIX}{project}/{session_id}.jsonl" - - -HOOK_EVENTS = { - "PreToolUse": ("Bash", "pre-tool"), - "PostToolUse": ("Bash", "post-tool"), - "Stop": (None, "stop"), -} - - -def install_hooks(settings_path: str, command: str) -> list[str]: - """Adds loch's hooks to a Claude Code settings file, keeping whatever else - is there. Returns the events it added; re-running adds nothing.""" - try: - settings = json.loads(Path(settings_path).read_text()) - except FileNotFoundError: - settings = {} - hooks = settings.setdefault("hooks", {}) - added = [] - for event, (matcher, name) in HOOK_EVENTS.items(): - # A checkout whose machine lacks loch gets a silent no-op rather than - # an error on every Bash call, since the settings file is committed. - line = f"{command} hook {name} 2>/dev/null || true" - groups = hooks.setdefault(event, []) - present = any( - entry.get("command") == line - for group in groups - for entry in group.get("hooks", []) - ) - if present: - continue - group: dict[str, Any] = {"hooks": [{"type": "command", "command": line}]} - if matcher is not None: - group["matcher"] = matcher - groups.append(group) - added.append(event) - os.makedirs(os.path.dirname(settings_path), exist_ok=True) - Path(settings_path).write_text(json.dumps(settings, indent=2) + "\n") - return added - - -# -- transcripts -------------------------------------------------------------- - - -def _records_of(raw: str) -> Iterator[dict[str, Any]]: - for line in raw.split("\n"): - if not line.strip(): - continue - try: - record = json.loads(line) - except ValueError: - continue - if isinstance(record, dict): - yield record - - -def _read_records(path: str) -> Iterator[dict[str, Any]]: - try: - raw = Path(path).read_text(encoding="utf-8", errors="surrogateescape") - except OSError: - return - yield from _records_of(raw) - - -def _content(record: dict[str, Any]) -> list[dict[str, Any]]: - message = record.get("message") - content = message.get("content") if isinstance(message, dict) else None - if not isinstance(content, list): - return [] - return [block for block in content if isinstance(block, dict)] - - -def find_transcript(session_id: str, store: Store | None) -> str | None: - """Claude's own copy if it still exists, else the store's snapshot, - fetched into a cache laid out like Claude's project directory so the - session's cwd is chosen the same way (claude.cwd_for_directory).""" - root = projects_dir() - if os.path.isdir(root): - for project in os.listdir(root): - path = os.path.join(root, project, f"{session_id}.jsonl") - if os.path.exists(path): - return path - if store is None: - return None - try: - keys = store.list(TRANSCRIPTS_PREFIX) - except Exception: - return None - for key in keys: - if key.endswith(f"/{session_id}.jsonl"): - project = key[len(TRANSCRIPTS_PREFIX) :].split("/")[0] - try: - data = store.get(key) - except MissingObject: - return None - cached = os.path.join( - home_dir(), ".loch", "cache", project, f"{session_id}.jsonl" - ) - os.makedirs(os.path.dirname(cached), exist_ok=True) - Path(cached).write_bytes(data) - return cached - return None - - -# -- blame -------------------------------------------------------------------- - - -@dataclass(frozen=True) -class Hunk: - start: int - end: int - commit: str - summary: str - lines: tuple[str, ...] = () - - -def blame_hunks(cwd: str, path: str) -> list[Hunk]: - porcelain = git(cwd, "blame", "--porcelain", "--", path) - summaries: dict[str, str] = {} - lines: list[tuple[int, str, str]] = [] - current = "" - number = 0 - for line in porcelain.split("\n"): - if line.startswith("\t"): - # Each header is followed by the line's text, tab-prefixed. - lines.append((number, current, line[1:])) - continue - parts = line.split(" ") - if len(parts) >= 3 and len(parts[0]) == 40 and parts[1].isdigit(): - current, number = parts[0], int(parts[2]) - elif line.startswith("summary "): - summaries[current] = line[len("summary ") :] - - hunks: list[Hunk] = [] - for number, commit, text in sorted(lines): - last = hunks[-1] if hunks else None - if last is not None and last.commit == commit and last.end == number - 1: - hunks[-1] = Hunk( - last.start, number, commit, last.summary, (*last.lines, text) - ) - else: - hunks.append( - Hunk(number, number, commit, summaries.get(commit, ""), (text,)) - ) - return hunks - - -@dataclass(frozen=True) -class Change: - commit: str - time: int - summary: str - - -def history(cwd: str, path: str, lines: tuple[int, int] | None = None) -> list[Change]: - """Every commit that touched `path` (or just `lines` of it), newest first. - - `-L` follows the range through edits above it and through moves; a whole - file follows renames. Both are git's own tracking, so this answers "which - commits shaped these lines" exactly as `git log` would. - """ - scope = ( - ["-L", f"{lines[0]},{lines[1]}:{path}"] - if lines is not None - else ["--follow", "--", path] - ) - output = git(cwd, "log", "-s", "--format=%x1e%H%x1f%ct%x1f%s", *scope) - changes = [] - for record in output.split("\x1e")[1:]: - commit, time, summary = record.strip("\n").split("\x1f", 2) - changes.append(Change(commit, int(time), summary.split("\n", 1)[0])) - return changes - - -@dataclass(frozen=True) -class Link: - """A commit resolved to the conversation turn that made it.""" - - commit: str - session_id: str - call: str - captured: str - transcript: str | None - turn: str | None - conversation: str | None - title: str | None - prompt: str | None - - def payload(self) -> dict[str, Any]: - return { - "session": self.session_id, - "call": self.call, - "captured": self.captured, - "available": self.transcript is not None, - "turn": self.turn, - "conversation": self.conversation, - "title": self.title, - "prompt": self.prompt, - } - - -def _prompt_text(turn: Turn) -> str | None: - for block in turn.blocks or []: - text = block.get("text") if block.get("type") == "text" else None - if isinstance(text, str) and text.strip() and not text.startswith("<"): - return text - return None - - -class Resolver: - """Resolves commits to turns, ingesting each session once however many - commits and lines point into it.""" - - def __init__(self, cwd: str, store: Store | None) -> None: - self.cwd = cwd - self.store = store - self._sessions: dict[str, tuple[str | None, list[Turn], dict[str, Any]]] = {} - - def _session( - self, session_id: str - ) -> tuple[str | None, list[Turn], dict[str, Any]]: - if session_id not in self._sessions: - path = find_transcript(session_id, self.store) - turns: list[Turn] = [] - header: dict[str, Any] = {} - if path is not None: - meta = read_session_meta(path) - if meta is not None: - derived = ingest(path, Origin(meta.cwd, home_dir(), session_id)) - turns, header = derived.turns, derived.header - self._sessions[session_id] = (path, turns, header) - return self._sessions[session_id] - - def resolve(self, commit: str) -> Link | None: - note = read_note(self.cwd, commit) - if note is None: - return None - session_id, call = str(note.get("session")), str(note.get("call")) - path, turns, header = self._session(session_id) - by_id = {turn.id: turn for turn in turns} - - turn = next( - ( - candidate - for candidate in turns - if any( - block.get("type") == "tool-call" and block.get("call") == call - for block in candidate.blocks or [] - ) - ), - None, - ) - prompt = None - conversation = None - walker = turn - while walker is not None: - if ( - prompt is None - and walker.core["kind"] == "message" - and walker.core["author"].get("kind") == "human" - ): - prompt = _prompt_text(walker) - parents = walker.core["parents"] - if not parents: - conversation = walker.id - walker = by_id.get(parents[0]) if parents else None - - session = header.get("session") or {} - return Link( - commit=commit, - session_id=session_id, - call=call, - captured=str(note.get("captured")), - transcript=path, - turn=turn.id if turn is not None else None, - conversation=conversation, - title=session.get("title") or session.get("aiTitle"), - prompt=_display_summary(prompt), - ) - - -# -- backfill ----------------------------------------------------------------- - - -@dataclass(frozen=True) -class Call: - session_id: str - call: str - command: str - started: float - finished: float - - -def _seconds(stamp: Any) -> float | None: - if not isinstance(stamp, str): - return None - try: - return datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp() - except ValueError: - return None - - -def commit_calls(path: str) -> list[Call]: - """Every Bash call in a transcript that could have made a commit, with the - window between the call being issued and its result coming back.""" - session_id = os.path.basename(path)[: -len(".jsonl")] - issued: dict[str, tuple[str, float]] = {} - calls: list[Call] = [] - for record in _read_records(path): - stamp = _seconds(record.get("timestamp")) - for block in _content(record): - if block.get("type") == "tool_use" and block.get("name") == "Bash": - command = str((block.get("input") or {}).get("command", "")) - if "commit" in command and stamp is not None: - issued[str(block.get("id"))] = (command, stamp) - elif block.get("type") == "tool_result": - call = str(block.get("tool_use_id")) - if call in issued and stamp is not None: - command, started = issued.pop(call) - calls.append(Call(session_id, call, command, started, stamp)) - return calls - - -def backfill( - cwd: str, - revision: str = "HEAD", - progress: Callable[[int, int, int, int], None] | None = None, -) -> list[tuple[str, Call]]: - """Links commits made before the hooks existed, accepting only an exact - match: one Bash call whose command contains the commit's subject line and - whose run brackets the commit's timestamp. A commit with no such call, or - with two, stays unlinked — a wrong link would send `ask` into the wrong - conversation and look exactly like a right one. - - Either timestamp may fall in the window: a rebase or cherry-pick rewrites - the committer time and keeps the author time, and the conversation that - wrote the change is still the one that made the original commit.""" - listing = git(cwd, "log", "--format=%H%x00%at%x00%ct%x00%s", revision) - already = noted_commits(cwd) - pending: list[tuple[str, tuple[int, int], str]] = [] - for line in listing.splitlines(): - sha, authored, committed, subject = line.split("\x00", 3) - if sha not in already and subject: - pending.append((sha, (int(authored), int(committed)), subject)) - if not pending: - return [] - - subjects = {subject for _, _, subject in pending} - # Listed and sized up front so progress has a real total: reading every - # transcript on the machine is the whole cost (~25s on 750MB). - transcripts: list[tuple[str, int]] = [] - root = projects_dir() - for project in sorted(os.listdir(root)) if os.path.isdir(root) else []: - directory = os.path.join(root, project) - if not os.path.isdir(directory): - continue - for name in sorted(os.listdir(directory)): - if name.endswith(".jsonl"): - path = os.path.join(directory, name) - try: - transcripts.append((path, os.path.getsize(path))) - except OSError: - continue - total_bytes = sum(size for _, size in transcripts) - - calls: list[Call] = [] - read = 0 - for done, (path, size) in enumerate(transcripts, 1): - read += size - try: - raw = Path(path).read_text(encoding="utf-8", errors="replace") - except OSError: - raw = "" - if "git commit" in raw and any(subject in raw for subject in subjects): - calls.extend(commit_calls(path)) - if progress is not None: - progress(done, len(transcripts), read, total_bytes) - - linked: list[tuple[str, Call]] = [] - for sha, stamps, subject in pending: - matches = [ - call - for call in calls - if subject in call.command - and any( - call.started - CLOCK_SLACK <= stamp <= call.finished + CLOCK_SLACK - for stamp in stamps - ) - ] - if len({(call.session_id, call.call) for call in matches}) == 1: - write_note( - cwd, sha, make_note(matches[0].session_id, matches[0].call, "backfill") - ) - linked.append((sha, matches[0])) - return linked - - -# -- ask ---------------------------------------------------------------------- - - -@dataclass(frozen=True) -class Fork: - session_id: str - path: str - cwd: str - records: int - origin_session: str - - -def _parent(record: dict[str, Any]) -> str | None: - parent = record.get("parentUuid") - if parent is None: - parent = record.get("logicalParentUuid") - return parent if isinstance(parent, str) else None - - -def fork_session( - transcript: str, - target_cwd: str, - call: str | None = None, - title: str | None = None, -) -> Fork: - """A new Claude session holding the conversation, filed under - `target_cwd` so `claude --resume` finds it. The original session is never - modified: a follow-up is a branch of the conversation, not more of it. - - With no `call` it holds the conversation to its end — the last record - written, which after a rewind is the branch the session was left on. - With one, it is cut after the whole round of tool results that call - belongs to, not after the call alone: an assistant message that issued - parallel calls is one API message, and resuming with any of its results - missing is a malformed conversation.""" - raw = Path(transcript).read_text(encoding="utf-8", errors="surrogateescape") - records = [ - record for record in _records_of(raw) if isinstance(record.get("uuid"), str) - ] - children: dict[str, list[dict[str, Any]]] = {} - for record in records: - parent = _parent(record) - if parent is not None: - children.setdefault(parent, []).append(record) - - if call is None: - if not records: - raise TraceError("call-not-found", "the transcript holds no records") - return _write_fork(transcript, raw, records, records[-1], target_cwd, title) - - result = next( - ( - record - for record in records - if any( - block.get("type") == "tool_result" and block.get("tool_use_id") == call - for block in _content(record) - ) - ), - None, - ) - if result is None: - raise TraceError("call-not-found", f"no result for tool call {call}") - - leaf = result - while True: - following = [ - child - for child in children.get(leaf["uuid"], []) - if child.get("type") == "user" - and any(block.get("type") == "tool_result" for block in _content(child)) - ] - if not following: - break - leaf = following[0] - return _write_fork(transcript, raw, records, leaf, target_cwd, title) - - -def _write_fork( - transcript: str, - raw: str, - records: list[dict[str, Any]], - leaf: dict[str, Any], - target_cwd: str, - title: str | None, -) -> Fork: - by_uuid = {record["uuid"]: record for record in records} - keep: set[str] = set() - walker: dict[str, Any] | None = leaf - while walker is not None and walker["uuid"] not in keep: - keep.add(walker["uuid"]) - parent = _parent(walker) - walker = by_uuid.get(parent) if parent is not None else None - - meta = read_session_meta(transcript) - origin_cwd = meta.cwd if meta is not None else next(iter(transcript_cwds(raw))) - origin_session = os.path.basename(transcript)[: -len(".jsonl")] - new_id = str(uuid.uuid4()) - - kept = [ - json.dumps(record, ensure_ascii=False) - for record in records - if record["uuid"] in keep - ] - kept.append( - json.dumps( - { - "type": "custom-title", - "customTitle": title or f"loch ask: {origin_session[:8]}", - "sessionId": origin_session, - } - ) - ) - spec = RewriteSpec( - origin_cwd, home_dir(), target_cwd, home_dir(), origin_session, new_id - ) - text = rewrite_transcript("\n".join(kept) + "\n", spec) - - path = transcript_path_for(target_cwd, new_id) - os.makedirs(os.path.dirname(path), exist_ok=True) - Path(path).write_text(text, encoding="utf-8", errors="surrogateescape") - return Fork(new_id, path, target_cwd, len(keep), origin_session) diff --git a/poetry.lock b/poetry.lock deleted file mode 100644 index 1de2d72..0000000 --- a/poetry.lock +++ /dev/null @@ -1,1877 +0,0 @@ -# This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand. - -[[package]] -name = "blinker" -version = "1.9.0" -description = "Fast, simple object-to-object and broadcast signaling" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -markers = "python_version < \"4.0\"" -files = [ - {file = "blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc"}, - {file = "blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf"}, -] - -[[package]] -name = "boto3" -version = "1.43.71" -description = "The AWS SDK for Python" -optional = false -python-versions = ">=3.10" -groups = ["main", "dev"] -files = [ - {file = "boto3-1.43.71-py3-none-any.whl", hash = "sha256:3bb46661dc33121e56e3706753069d18f8dbcb644599cf098206546338602e16"}, - {file = "boto3-1.43.71.tar.gz", hash = "sha256:e3eddb6346ee23c895dd98e5c2cfc72cb5e5ed111aa6d4331f9e903a3e3bf4ee"}, -] - -[package.dependencies] -botocore = ">=1.43.71,<1.44.0" -jmespath = ">=0.7.1,<2.0.0" -s3transfer = ">=0.19.0,<0.20.0" - -[package.extras] -crt = ["botocore[crt] (>=1.21.0,<2.0a0)"] - -[[package]] -name = "boto3-stubs" -version = "1.43.71" -description = "Type annotations for boto3 1.43.71 generated with mypy-boto3-builder 8.12.0" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "boto3_stubs-1.43.71-py3-none-any.whl", hash = "sha256:bae78a1f5dbc904729725e5cc6f5c2755d61e2b574c94a97d27c068d1335a028"}, - {file = "boto3_stubs-1.43.71.tar.gz", hash = "sha256:a9ddda41ececeb4d478b2dc7789b85f8d32c05ef6bfc3a45af949b5b488ffb60"}, -] - -[package.dependencies] -botocore-stubs = "*" -types-s3transfer = "*" -typing-extensions = {version = ">=4.1.0", markers = "python_version < \"3.12\""} - -[package.extras] -accessanalyzer = ["mypy-boto3-accessanalyzer (>=1.43.0,<1.44.0)"] -account = ["mypy-boto3-account (>=1.43.0,<1.44.0)"] -account-access = ["mypy-boto3-account-access (>=1.43.0,<1.44.0)"] -acm = ["mypy-boto3-acm (>=1.43.0,<1.44.0)"] -acm-pca = ["mypy-boto3-acm-pca (>=1.43.0,<1.44.0)"] -agent-registry = ["mypy-boto3-agent-registry (>=1.43.0,<1.44.0)"] -agent-registry-control = ["mypy-boto3-agent-registry-control (>=1.43.0,<1.44.0)"] -aiops = ["mypy-boto3-aiops (>=1.43.0,<1.44.0)"] -all = ["mypy-boto3-accessanalyzer (>=1.43.0,<1.44.0)", "mypy-boto3-account (>=1.43.0,<1.44.0)", "mypy-boto3-account-access (>=1.43.0,<1.44.0)", "mypy-boto3-acm (>=1.43.0,<1.44.0)", "mypy-boto3-acm-pca (>=1.43.0,<1.44.0)", "mypy-boto3-agent-registry (>=1.43.0,<1.44.0)", "mypy-boto3-agent-registry-control (>=1.43.0,<1.44.0)", "mypy-boto3-aiops (>=1.43.0,<1.44.0)", "mypy-boto3-amp (>=1.43.0,<1.44.0)", "mypy-boto3-amplify (>=1.43.0,<1.44.0)", "mypy-boto3-amplifybackend (>=1.43.0,<1.44.0)", "mypy-boto3-amplifyuibuilder (>=1.43.0,<1.44.0)", "mypy-boto3-apigateway (>=1.43.0,<1.44.0)", "mypy-boto3-apigatewaymanagementapi (>=1.43.0,<1.44.0)", "mypy-boto3-apigatewayv2 (>=1.43.0,<1.44.0)", "mypy-boto3-appconfig (>=1.43.0,<1.44.0)", "mypy-boto3-appconfigdata (>=1.43.0,<1.44.0)", "mypy-boto3-appfabric (>=1.43.0,<1.44.0)", "mypy-boto3-appflow (>=1.43.0,<1.44.0)", "mypy-boto3-appintegrations (>=1.43.0,<1.44.0)", "mypy-boto3-application-autoscaling (>=1.43.0,<1.44.0)", "mypy-boto3-application-insights (>=1.43.0,<1.44.0)", "mypy-boto3-application-signals (>=1.43.0,<1.44.0)", "mypy-boto3-applicationcostprofiler (>=1.43.0,<1.44.0)", "mypy-boto3-appmesh (>=1.43.0,<1.44.0)", "mypy-boto3-apprunner (>=1.43.0,<1.44.0)", "mypy-boto3-appstream (>=1.43.0,<1.44.0)", "mypy-boto3-appsync (>=1.43.0,<1.44.0)", "mypy-boto3-arc-region-switch (>=1.43.0,<1.44.0)", "mypy-boto3-arc-zonal-shift (>=1.43.0,<1.44.0)", "mypy-boto3-artifact (>=1.43.0,<1.44.0)", "mypy-boto3-athena (>=1.43.0,<1.44.0)", "mypy-boto3-auditmanager (>=1.43.0,<1.44.0)", "mypy-boto3-autoscaling (>=1.43.0,<1.44.0)", "mypy-boto3-autoscaling-plans (>=1.43.0,<1.44.0)", "mypy-boto3-b2bi (>=1.43.0,<1.44.0)", "mypy-boto3-backup (>=1.43.0,<1.44.0)", "mypy-boto3-backup-gateway (>=1.43.0,<1.44.0)", "mypy-boto3-backupsearch (>=1.43.0,<1.44.0)", "mypy-boto3-batch (>=1.43.0,<1.44.0)", "mypy-boto3-bcm-dashboards (>=1.43.0,<1.44.0)", "mypy-boto3-bcm-data-exports (>=1.43.0,<1.44.0)", "mypy-boto3-bcm-pricing-calculator (>=1.43.0,<1.44.0)", "mypy-boto3-bcm-recommended-actions (>=1.43.0,<1.44.0)", "mypy-boto3-bedrock (>=1.43.0,<1.44.0)", "mypy-boto3-bedrock-agent (>=1.43.0,<1.44.0)", "mypy-boto3-bedrock-agent-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-bedrock-agentcore (>=1.43.0,<1.44.0)", "mypy-boto3-bedrock-agentcore-control (>=1.43.0,<1.44.0)", "mypy-boto3-bedrock-data-automation (>=1.43.0,<1.44.0)", "mypy-boto3-bedrock-data-automation-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-bedrock-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-billing (>=1.43.0,<1.44.0)", "mypy-boto3-billingconductor (>=1.43.0,<1.44.0)", "mypy-boto3-braket (>=1.43.0,<1.44.0)", "mypy-boto3-budgets (>=1.43.0,<1.44.0)", "mypy-boto3-ce (>=1.43.0,<1.44.0)", "mypy-boto3-chatbot (>=1.43.0,<1.44.0)", "mypy-boto3-chime (>=1.43.0,<1.44.0)", "mypy-boto3-chime-sdk-identity (>=1.43.0,<1.44.0)", "mypy-boto3-chime-sdk-media-pipelines (>=1.43.0,<1.44.0)", "mypy-boto3-chime-sdk-meetings (>=1.43.0,<1.44.0)", "mypy-boto3-chime-sdk-messaging (>=1.43.0,<1.44.0)", "mypy-boto3-chime-sdk-voice (>=1.43.0,<1.44.0)", "mypy-boto3-cleanrooms (>=1.43.0,<1.44.0)", "mypy-boto3-cleanroomsml (>=1.43.0,<1.44.0)", "mypy-boto3-cloud9 (>=1.43.0,<1.44.0)", "mypy-boto3-cloudcontrol (>=1.43.0,<1.44.0)", "mypy-boto3-clouddirectory (>=1.43.0,<1.44.0)", "mypy-boto3-cloudformation (>=1.43.0,<1.44.0)", "mypy-boto3-cloudfront (>=1.43.0,<1.44.0)", "mypy-boto3-cloudfront-keyvaluestore (>=1.43.0,<1.44.0)", "mypy-boto3-cloudhsm (>=1.43.0,<1.44.0)", "mypy-boto3-cloudhsmv2 (>=1.43.0,<1.44.0)", "mypy-boto3-cloudsearch (>=1.43.0,<1.44.0)", "mypy-boto3-cloudsearchdomain (>=1.43.0,<1.44.0)", "mypy-boto3-cloudtrail (>=1.43.0,<1.44.0)", "mypy-boto3-cloudtrail-data (>=1.43.0,<1.44.0)", "mypy-boto3-cloudwatch (>=1.43.0,<1.44.0)", "mypy-boto3-codeartifact (>=1.43.0,<1.44.0)", "mypy-boto3-codebuild (>=1.43.0,<1.44.0)", "mypy-boto3-codecatalyst (>=1.43.0,<1.44.0)", "mypy-boto3-codecommit (>=1.43.0,<1.44.0)", "mypy-boto3-codeconnections (>=1.43.0,<1.44.0)", "mypy-boto3-codedeploy (>=1.43.0,<1.44.0)", "mypy-boto3-codeguru-reviewer (>=1.43.0,<1.44.0)", "mypy-boto3-codeguru-security (>=1.43.0,<1.44.0)", "mypy-boto3-codeguruprofiler (>=1.43.0,<1.44.0)", "mypy-boto3-codepipeline (>=1.43.0,<1.44.0)", "mypy-boto3-codestar-connections (>=1.43.0,<1.44.0)", "mypy-boto3-codestar-notifications (>=1.43.0,<1.44.0)", "mypy-boto3-cognito-identity (>=1.43.0,<1.44.0)", "mypy-boto3-cognito-idp (>=1.43.0,<1.44.0)", "mypy-boto3-cognito-sync (>=1.43.0,<1.44.0)", "mypy-boto3-comprehend (>=1.43.0,<1.44.0)", "mypy-boto3-comprehendmedical (>=1.43.0,<1.44.0)", "mypy-boto3-compute-optimizer (>=1.43.0,<1.44.0)", "mypy-boto3-compute-optimizer-automation (>=1.43.0,<1.44.0)", "mypy-boto3-config (>=1.43.0,<1.44.0)", "mypy-boto3-connect (>=1.43.0,<1.44.0)", "mypy-boto3-connect-contact-lens (>=1.43.0,<1.44.0)", "mypy-boto3-connectcampaigns (>=1.43.0,<1.44.0)", "mypy-boto3-connectcampaignsv2 (>=1.43.0,<1.44.0)", "mypy-boto3-connectcases (>=1.43.0,<1.44.0)", "mypy-boto3-connecthealth (>=1.43.0,<1.44.0)", "mypy-boto3-connectparticipant (>=1.43.0,<1.44.0)", "mypy-boto3-controlcatalog (>=1.43.0,<1.44.0)", "mypy-boto3-controltower (>=1.43.0,<1.44.0)", "mypy-boto3-cost-optimization-hub (>=1.43.0,<1.44.0)", "mypy-boto3-cur (>=1.43.0,<1.44.0)", "mypy-boto3-customer-profiles (>=1.43.0,<1.44.0)", "mypy-boto3-databrew (>=1.43.0,<1.44.0)", "mypy-boto3-dataexchange (>=1.43.0,<1.44.0)", "mypy-boto3-datapipeline (>=1.43.0,<1.44.0)", "mypy-boto3-datasync (>=1.43.0,<1.44.0)", "mypy-boto3-datazone (>=1.43.0,<1.44.0)", "mypy-boto3-dax (>=1.43.0,<1.44.0)", "mypy-boto3-deadline (>=1.43.0,<1.44.0)", "mypy-boto3-detective (>=1.43.0,<1.44.0)", "mypy-boto3-devicefarm (>=1.43.0,<1.44.0)", "mypy-boto3-devops-agent (>=1.43.0,<1.44.0)", "mypy-boto3-devops-guru (>=1.43.0,<1.44.0)", "mypy-boto3-directconnect (>=1.43.0,<1.44.0)", "mypy-boto3-discovery (>=1.43.0,<1.44.0)", "mypy-boto3-dlm (>=1.43.0,<1.44.0)", "mypy-boto3-dms (>=1.43.0,<1.44.0)", "mypy-boto3-docdb (>=1.43.0,<1.44.0)", "mypy-boto3-docdb-elastic (>=1.43.0,<1.44.0)", "mypy-boto3-drs (>=1.43.0,<1.44.0)", "mypy-boto3-ds (>=1.43.0,<1.44.0)", "mypy-boto3-ds-data (>=1.43.0,<1.44.0)", "mypy-boto3-dsql (>=1.43.0,<1.44.0)", "mypy-boto3-dynamodb (>=1.43.0,<1.44.0)", "mypy-boto3-dynamodbstreams (>=1.43.0,<1.44.0)", "mypy-boto3-ebs (>=1.43.0,<1.44.0)", "mypy-boto3-ec2 (>=1.43.0,<1.44.0)", "mypy-boto3-ec2-instance-connect (>=1.43.0,<1.44.0)", "mypy-boto3-ecr (>=1.43.0,<1.44.0)", "mypy-boto3-ecr-public (>=1.43.0,<1.44.0)", "mypy-boto3-ecs (>=1.43.0,<1.44.0)", "mypy-boto3-efs (>=1.43.0,<1.44.0)", "mypy-boto3-eks (>=1.43.0,<1.44.0)", "mypy-boto3-eks-auth (>=1.43.0,<1.44.0)", "mypy-boto3-elasticache (>=1.43.0,<1.44.0)", "mypy-boto3-elasticbeanstalk (>=1.43.0,<1.44.0)", "mypy-boto3-elb (>=1.43.0,<1.44.0)", "mypy-boto3-elbv2 (>=1.43.0,<1.44.0)", "mypy-boto3-elementalinference (>=1.43.0,<1.44.0)", "mypy-boto3-emr (>=1.43.0,<1.44.0)", "mypy-boto3-emr-containers (>=1.43.0,<1.44.0)", "mypy-boto3-emr-serverless (>=1.43.0,<1.44.0)", "mypy-boto3-entityresolution (>=1.43.0,<1.44.0)", "mypy-boto3-es (>=1.43.0,<1.44.0)", "mypy-boto3-events (>=1.43.0,<1.44.0)", "mypy-boto3-evs (>=1.43.0,<1.44.0)", "mypy-boto3-finspace (>=1.43.0,<1.44.0)", "mypy-boto3-finspace-data (>=1.43.0,<1.44.0)", "mypy-boto3-firehose (>=1.43.0,<1.44.0)", "mypy-boto3-fis (>=1.43.0,<1.44.0)", "mypy-boto3-fms (>=1.43.0,<1.44.0)", "mypy-boto3-forecast (>=1.43.0,<1.44.0)", "mypy-boto3-forecastquery (>=1.43.0,<1.44.0)", "mypy-boto3-frauddetector (>=1.43.0,<1.44.0)", "mypy-boto3-freetier (>=1.43.0,<1.44.0)", "mypy-boto3-fsx (>=1.43.0,<1.44.0)", "mypy-boto3-gamelift (>=1.43.0,<1.44.0)", "mypy-boto3-gameliftstreams (>=1.43.0,<1.44.0)", "mypy-boto3-geo-maps (>=1.43.0,<1.44.0)", "mypy-boto3-geo-places (>=1.43.0,<1.44.0)", "mypy-boto3-geo-routes (>=1.43.0,<1.44.0)", "mypy-boto3-glacier (>=1.43.0,<1.44.0)", "mypy-boto3-globalaccelerator (>=1.43.0,<1.44.0)", "mypy-boto3-glue (>=1.43.0,<1.44.0)", "mypy-boto3-grafana (>=1.43.0,<1.44.0)", "mypy-boto3-greengrass (>=1.43.0,<1.44.0)", "mypy-boto3-greengrassv2 (>=1.43.0,<1.44.0)", "mypy-boto3-groundstation (>=1.43.0,<1.44.0)", "mypy-boto3-guardduty (>=1.43.0,<1.44.0)", "mypy-boto3-health (>=1.43.0,<1.44.0)", "mypy-boto3-healthlake (>=1.43.0,<1.44.0)", "mypy-boto3-iam (>=1.43.0,<1.44.0)", "mypy-boto3-identitystore (>=1.43.0,<1.44.0)", "mypy-boto3-imagebuilder (>=1.43.0,<1.44.0)", "mypy-boto3-importexport (>=1.43.0,<1.44.0)", "mypy-boto3-inspector (>=1.43.0,<1.44.0)", "mypy-boto3-inspector-scan (>=1.43.0,<1.44.0)", "mypy-boto3-inspector2 (>=1.43.0,<1.44.0)", "mypy-boto3-interconnect (>=1.43.0,<1.44.0)", "mypy-boto3-internetmonitor (>=1.43.0,<1.44.0)", "mypy-boto3-invoicing (>=1.43.0,<1.44.0)", "mypy-boto3-iot (>=1.43.0,<1.44.0)", "mypy-boto3-iot-data (>=1.43.0,<1.44.0)", "mypy-boto3-iot-jobs-data (>=1.43.0,<1.44.0)", "mypy-boto3-iot-managed-integrations (>=1.43.0,<1.44.0)", "mypy-boto3-iotdeviceadvisor (>=1.43.0,<1.44.0)", "mypy-boto3-iotfleetwise (>=1.43.0,<1.44.0)", "mypy-boto3-iotsecuretunneling (>=1.43.0,<1.44.0)", "mypy-boto3-iotsitewise (>=1.43.0,<1.44.0)", "mypy-boto3-iotthingsgraph (>=1.43.0,<1.44.0)", "mypy-boto3-iottwinmaker (>=1.43.0,<1.44.0)", "mypy-boto3-iotwireless (>=1.43.0,<1.44.0)", "mypy-boto3-ivs (>=1.43.0,<1.44.0)", "mypy-boto3-ivs-realtime (>=1.43.0,<1.44.0)", "mypy-boto3-ivschat (>=1.43.0,<1.44.0)", "mypy-boto3-kafka (>=1.43.0,<1.44.0)", "mypy-boto3-kafkaconnect (>=1.43.0,<1.44.0)", "mypy-boto3-kendra (>=1.43.0,<1.44.0)", "mypy-boto3-kendra-ranking (>=1.43.0,<1.44.0)", "mypy-boto3-keyspaces (>=1.43.0,<1.44.0)", "mypy-boto3-keyspacesstreams (>=1.43.0,<1.44.0)", "mypy-boto3-kinesis (>=1.43.0,<1.44.0)", "mypy-boto3-kinesis-video-archived-media (>=1.43.0,<1.44.0)", "mypy-boto3-kinesis-video-media (>=1.43.0,<1.44.0)", "mypy-boto3-kinesis-video-signaling (>=1.43.0,<1.44.0)", "mypy-boto3-kinesis-video-webrtc-storage (>=1.43.0,<1.44.0)", "mypy-boto3-kinesisanalytics (>=1.43.0,<1.44.0)", "mypy-boto3-kinesisanalyticsv2 (>=1.43.0,<1.44.0)", "mypy-boto3-kinesisvideo (>=1.43.0,<1.44.0)", "mypy-boto3-kms (>=1.43.0,<1.44.0)", "mypy-boto3-lakeformation (>=1.43.0,<1.44.0)", "mypy-boto3-lambda (>=1.43.0,<1.44.0)", "mypy-boto3-lambda-core (>=1.43.0,<1.44.0)", "mypy-boto3-lambda-microvms (>=1.43.0,<1.44.0)", "mypy-boto3-launch-wizard (>=1.43.0,<1.44.0)", "mypy-boto3-lex-models (>=1.43.0,<1.44.0)", "mypy-boto3-lex-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-lexv2-models (>=1.43.0,<1.44.0)", "mypy-boto3-lexv2-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-license-manager (>=1.43.0,<1.44.0)", "mypy-boto3-license-manager-linux-subscriptions (>=1.43.0,<1.44.0)", "mypy-boto3-license-manager-user-subscriptions (>=1.43.0,<1.44.0)", "mypy-boto3-lightsail (>=1.43.0,<1.44.0)", "mypy-boto3-location (>=1.43.0,<1.44.0)", "mypy-boto3-logs (>=1.43.0,<1.44.0)", "mypy-boto3-lookoutequipment (>=1.43.0,<1.44.0)", "mypy-boto3-m2 (>=1.43.0,<1.44.0)", "mypy-boto3-machinelearning (>=1.43.0,<1.44.0)", "mypy-boto3-macie2 (>=1.43.0,<1.44.0)", "mypy-boto3-mailmanager (>=1.43.0,<1.44.0)", "mypy-boto3-managedblockchain (>=1.43.0,<1.44.0)", "mypy-boto3-managedblockchain-query (>=1.43.0,<1.44.0)", "mypy-boto3-marketplace-agreement (>=1.43.0,<1.44.0)", "mypy-boto3-marketplace-catalog (>=1.43.0,<1.44.0)", "mypy-boto3-marketplace-deployment (>=1.43.0,<1.44.0)", "mypy-boto3-marketplace-discovery (>=1.43.0,<1.44.0)", "mypy-boto3-marketplace-entitlement (>=1.43.0,<1.44.0)", "mypy-boto3-marketplace-reporting (>=1.43.0,<1.44.0)", "mypy-boto3-marketplacecommerceanalytics (>=1.43.0,<1.44.0)", "mypy-boto3-mediaconnect (>=1.43.0,<1.44.0)", "mypy-boto3-mediaconvert (>=1.43.0,<1.44.0)", "mypy-boto3-medialive (>=1.43.0,<1.44.0)", "mypy-boto3-mediapackage (>=1.43.0,<1.44.0)", "mypy-boto3-mediapackage-vod (>=1.43.0,<1.44.0)", "mypy-boto3-mediapackagev2 (>=1.43.0,<1.44.0)", "mypy-boto3-mediastore (>=1.43.0,<1.44.0)", "mypy-boto3-mediastore-data (>=1.43.0,<1.44.0)", "mypy-boto3-mediatailor (>=1.43.0,<1.44.0)", "mypy-boto3-medical-imaging (>=1.43.0,<1.44.0)", "mypy-boto3-memorydb (>=1.43.0,<1.44.0)", "mypy-boto3-meteringmarketplace (>=1.43.0,<1.44.0)", "mypy-boto3-mgh (>=1.43.0,<1.44.0)", "mypy-boto3-mgn (>=1.43.0,<1.44.0)", "mypy-boto3-migration-hub-refactor-spaces (>=1.43.0,<1.44.0)", "mypy-boto3-migrationhub-config (>=1.43.0,<1.44.0)", "mypy-boto3-migrationhuborchestrator (>=1.43.0,<1.44.0)", "mypy-boto3-migrationhubstrategy (>=1.43.0,<1.44.0)", "mypy-boto3-mpa (>=1.43.0,<1.44.0)", "mypy-boto3-mq (>=1.43.0,<1.44.0)", "mypy-boto3-mturk (>=1.43.0,<1.44.0)", "mypy-boto3-mwaa (>=1.43.0,<1.44.0)", "mypy-boto3-mwaa-serverless (>=1.43.0,<1.44.0)", "mypy-boto3-neptune (>=1.43.0,<1.44.0)", "mypy-boto3-neptune-graph (>=1.43.0,<1.44.0)", "mypy-boto3-neptunedata (>=1.43.0,<1.44.0)", "mypy-boto3-network-firewall (>=1.43.0,<1.44.0)", "mypy-boto3-networkflowmonitor (>=1.43.0,<1.44.0)", "mypy-boto3-networkmanager (>=1.43.0,<1.44.0)", "mypy-boto3-networkmonitor (>=1.43.0,<1.44.0)", "mypy-boto3-notifications (>=1.43.0,<1.44.0)", "mypy-boto3-notificationscontacts (>=1.43.0,<1.44.0)", "mypy-boto3-nova-act (>=1.43.0,<1.44.0)", "mypy-boto3-oam (>=1.43.0,<1.44.0)", "mypy-boto3-observabilityadmin (>=1.43.0,<1.44.0)", "mypy-boto3-odb (>=1.43.0,<1.44.0)", "mypy-boto3-omics (>=1.43.0,<1.44.0)", "mypy-boto3-opensearch (>=1.43.0,<1.44.0)", "mypy-boto3-opensearchserverless (>=1.43.0,<1.44.0)", "mypy-boto3-organizations (>=1.43.0,<1.44.0)", "mypy-boto3-osis (>=1.43.0,<1.44.0)", "mypy-boto3-outposts (>=1.43.0,<1.44.0)", "mypy-boto3-partnercentral-account (>=1.43.0,<1.44.0)", "mypy-boto3-partnercentral-benefits (>=1.43.0,<1.44.0)", "mypy-boto3-partnercentral-channel (>=1.43.0,<1.44.0)", "mypy-boto3-partnercentral-revenue-measurement (>=1.43.0,<1.44.0)", "mypy-boto3-partnercentral-selling (>=1.43.0,<1.44.0)", "mypy-boto3-payment-cryptography (>=1.43.0,<1.44.0)", "mypy-boto3-payment-cryptography-data (>=1.43.0,<1.44.0)", "mypy-boto3-pca-connector-ad (>=1.43.0,<1.44.0)", "mypy-boto3-pca-connector-scep (>=1.43.0,<1.44.0)", "mypy-boto3-pcs (>=1.43.0,<1.44.0)", "mypy-boto3-personalize (>=1.43.0,<1.44.0)", "mypy-boto3-personalize-events (>=1.43.0,<1.44.0)", "mypy-boto3-personalize-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-pi (>=1.43.0,<1.44.0)", "mypy-boto3-pinpoint (>=1.43.0,<1.44.0)", "mypy-boto3-pinpoint-email (>=1.43.0,<1.44.0)", "mypy-boto3-pinpoint-sms-voice (>=1.43.0,<1.44.0)", "mypy-boto3-pinpoint-sms-voice-v2 (>=1.43.0,<1.44.0)", "mypy-boto3-pipes (>=1.43.0,<1.44.0)", "mypy-boto3-polly (>=1.43.0,<1.44.0)", "mypy-boto3-pricing (>=1.43.0,<1.44.0)", "mypy-boto3-pricing-plan-manager (>=1.43.0,<1.44.0)", "mypy-boto3-proton (>=1.43.0,<1.44.0)", "mypy-boto3-qapps (>=1.43.0,<1.44.0)", "mypy-boto3-qbusiness (>=1.43.0,<1.44.0)", "mypy-boto3-qconnect (>=1.43.0,<1.44.0)", "mypy-boto3-quicksight (>=1.43.0,<1.44.0)", "mypy-boto3-ram (>=1.43.0,<1.44.0)", "mypy-boto3-rbin (>=1.43.0,<1.44.0)", "mypy-boto3-rds (>=1.43.0,<1.44.0)", "mypy-boto3-rds-data (>=1.43.0,<1.44.0)", "mypy-boto3-redshift (>=1.43.0,<1.44.0)", "mypy-boto3-redshift-data (>=1.43.0,<1.44.0)", "mypy-boto3-redshift-serverless (>=1.43.0,<1.44.0)", "mypy-boto3-rekognition (>=1.43.0,<1.44.0)", "mypy-boto3-repostspace (>=1.43.0,<1.44.0)", "mypy-boto3-resiliencehub (>=1.43.0,<1.44.0)", "mypy-boto3-resiliencehubv2 (>=1.43.0,<1.44.0)", "mypy-boto3-resource-explorer-2 (>=1.43.0,<1.44.0)", "mypy-boto3-resource-groups (>=1.43.0,<1.44.0)", "mypy-boto3-resourcegroupstaggingapi (>=1.43.0,<1.44.0)", "mypy-boto3-rolesanywhere (>=1.43.0,<1.44.0)", "mypy-boto3-route53 (>=1.43.0,<1.44.0)", "mypy-boto3-route53-recovery-cluster (>=1.43.0,<1.44.0)", "mypy-boto3-route53-recovery-control-config (>=1.43.0,<1.44.0)", "mypy-boto3-route53-recovery-readiness (>=1.43.0,<1.44.0)", "mypy-boto3-route53domains (>=1.43.0,<1.44.0)", "mypy-boto3-route53globalresolver (>=1.43.0,<1.44.0)", "mypy-boto3-route53profiles (>=1.43.0,<1.44.0)", "mypy-boto3-route53resolver (>=1.43.0,<1.44.0)", "mypy-boto3-rtbfabric (>=1.43.0,<1.44.0)", "mypy-boto3-rum (>=1.43.0,<1.44.0)", "mypy-boto3-s3 (>=1.43.0,<1.44.0)", "mypy-boto3-s3control (>=1.43.0,<1.44.0)", "mypy-boto3-s3files (>=1.43.0,<1.44.0)", "mypy-boto3-s3outposts (>=1.43.0,<1.44.0)", "mypy-boto3-s3tables (>=1.43.0,<1.44.0)", "mypy-boto3-s3vectors (>=1.43.0,<1.44.0)", "mypy-boto3-sagemaker (>=1.43.0,<1.44.0)", "mypy-boto3-sagemaker-a2i-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-sagemaker-edge (>=1.43.0,<1.44.0)", "mypy-boto3-sagemaker-featurestore-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-sagemaker-geospatial (>=1.43.0,<1.44.0)", "mypy-boto3-sagemaker-metrics (>=1.43.0,<1.44.0)", "mypy-boto3-sagemaker-runtime (>=1.43.0,<1.44.0)", "mypy-boto3-sagemakerjobruntime (>=1.43.0,<1.44.0)", "mypy-boto3-savingsplans (>=1.43.0,<1.44.0)", "mypy-boto3-scheduler (>=1.43.0,<1.44.0)", "mypy-boto3-schemas (>=1.43.0,<1.44.0)", "mypy-boto3-sdb (>=1.43.0,<1.44.0)", "mypy-boto3-secretsmanager (>=1.43.0,<1.44.0)", "mypy-boto3-security-ir (>=1.43.0,<1.44.0)", "mypy-boto3-securityagent (>=1.43.0,<1.44.0)", "mypy-boto3-securityhub (>=1.43.0,<1.44.0)", "mypy-boto3-securitylake (>=1.43.0,<1.44.0)", "mypy-boto3-serverlessrepo (>=1.43.0,<1.44.0)", "mypy-boto3-service-quotas (>=1.43.0,<1.44.0)", "mypy-boto3-servicecatalog (>=1.43.0,<1.44.0)", "mypy-boto3-servicecatalog-appregistry (>=1.43.0,<1.44.0)", "mypy-boto3-servicediscovery (>=1.43.0,<1.44.0)", "mypy-boto3-ses (>=1.43.0,<1.44.0)", "mypy-boto3-sesv2 (>=1.43.0,<1.44.0)", "mypy-boto3-shield (>=1.43.0,<1.44.0)", "mypy-boto3-signer (>=1.43.0,<1.44.0)", "mypy-boto3-signer-data (>=1.43.0,<1.44.0)", "mypy-boto3-signin (>=1.43.0,<1.44.0)", "mypy-boto3-simpledbv2 (>=1.43.0,<1.44.0)", "mypy-boto3-snow-device-management (>=1.43.0,<1.44.0)", "mypy-boto3-snowball (>=1.43.0,<1.44.0)", "mypy-boto3-sns (>=1.43.0,<1.44.0)", "mypy-boto3-socialmessaging (>=1.43.0,<1.44.0)", "mypy-boto3-sqs (>=1.43.0,<1.44.0)", "mypy-boto3-ssm (>=1.43.0,<1.44.0)", "mypy-boto3-ssm-contacts (>=1.43.0,<1.44.0)", "mypy-boto3-ssm-guiconnect (>=1.43.0,<1.44.0)", "mypy-boto3-ssm-incidents (>=1.43.0,<1.44.0)", "mypy-boto3-ssm-quicksetup (>=1.43.0,<1.44.0)", "mypy-boto3-ssm-sap (>=1.43.0,<1.44.0)", "mypy-boto3-sso (>=1.43.0,<1.44.0)", "mypy-boto3-sso-admin (>=1.43.0,<1.44.0)", "mypy-boto3-sso-oidc (>=1.43.0,<1.44.0)", "mypy-boto3-stepfunctions (>=1.43.0,<1.44.0)", "mypy-boto3-storagegateway (>=1.43.0,<1.44.0)", "mypy-boto3-sts (>=1.43.0,<1.44.0)", "mypy-boto3-supplychain (>=1.43.0,<1.44.0)", "mypy-boto3-support (>=1.43.0,<1.44.0)", "mypy-boto3-support-app (>=1.43.0,<1.44.0)", "mypy-boto3-supportauthz (>=1.43.0,<1.44.0)", "mypy-boto3-sustainability (>=1.43.0,<1.44.0)", "mypy-boto3-swf (>=1.43.0,<1.44.0)", "mypy-boto3-synthetics (>=1.43.0,<1.44.0)", "mypy-boto3-taxsettings (>=1.43.0,<1.44.0)", "mypy-boto3-textract (>=1.43.0,<1.44.0)", "mypy-boto3-timestream-influxdb (>=1.43.0,<1.44.0)", "mypy-boto3-timestream-query (>=1.43.0,<1.44.0)", "mypy-boto3-timestream-write (>=1.43.0,<1.44.0)", "mypy-boto3-tnb (>=1.43.0,<1.44.0)", "mypy-boto3-transcribe (>=1.43.0,<1.44.0)", "mypy-boto3-transfer (>=1.43.0,<1.44.0)", "mypy-boto3-translate (>=1.43.0,<1.44.0)", "mypy-boto3-trustedadvisor (>=1.43.0,<1.44.0)", "mypy-boto3-uxc (>=1.43.0,<1.44.0)", "mypy-boto3-verifiedpermissions (>=1.43.0,<1.44.0)", "mypy-boto3-voice-id (>=1.43.0,<1.44.0)", "mypy-boto3-vpc-lattice (>=1.43.0,<1.44.0)", "mypy-boto3-waf (>=1.43.0,<1.44.0)", "mypy-boto3-waf-regional (>=1.43.0,<1.44.0)", "mypy-boto3-wafv2 (>=1.43.0,<1.44.0)", "mypy-boto3-wellarchitected (>=1.43.0,<1.44.0)", "mypy-boto3-wickr (>=1.43.0,<1.44.0)", "mypy-boto3-wisdom (>=1.43.0,<1.44.0)", "mypy-boto3-workdocs (>=1.43.0,<1.44.0)", "mypy-boto3-workmail (>=1.43.0,<1.44.0)", "mypy-boto3-workmailmessageflow (>=1.43.0,<1.44.0)", "mypy-boto3-workspaces (>=1.43.0,<1.44.0)", "mypy-boto3-workspaces-instances (>=1.43.0,<1.44.0)", "mypy-boto3-workspaces-thin-client (>=1.43.0,<1.44.0)", "mypy-boto3-workspaces-web (>=1.43.0,<1.44.0)", "mypy-boto3-xray (>=1.43.0,<1.44.0)"] -amp = ["mypy-boto3-amp (>=1.43.0,<1.44.0)"] -amplify = ["mypy-boto3-amplify (>=1.43.0,<1.44.0)"] -amplifybackend = ["mypy-boto3-amplifybackend (>=1.43.0,<1.44.0)"] -amplifyuibuilder = ["mypy-boto3-amplifyuibuilder (>=1.43.0,<1.44.0)"] -apigateway = ["mypy-boto3-apigateway (>=1.43.0,<1.44.0)"] -apigatewaymanagementapi = ["mypy-boto3-apigatewaymanagementapi (>=1.43.0,<1.44.0)"] -apigatewayv2 = ["mypy-boto3-apigatewayv2 (>=1.43.0,<1.44.0)"] -appconfig = ["mypy-boto3-appconfig (>=1.43.0,<1.44.0)"] -appconfigdata = ["mypy-boto3-appconfigdata (>=1.43.0,<1.44.0)"] -appfabric = ["mypy-boto3-appfabric (>=1.43.0,<1.44.0)"] -appflow = ["mypy-boto3-appflow (>=1.43.0,<1.44.0)"] -appintegrations = ["mypy-boto3-appintegrations (>=1.43.0,<1.44.0)"] -application-autoscaling = ["mypy-boto3-application-autoscaling (>=1.43.0,<1.44.0)"] -application-insights = ["mypy-boto3-application-insights (>=1.43.0,<1.44.0)"] -application-signals = ["mypy-boto3-application-signals (>=1.43.0,<1.44.0)"] -applicationcostprofiler = ["mypy-boto3-applicationcostprofiler (>=1.43.0,<1.44.0)"] -appmesh = ["mypy-boto3-appmesh (>=1.43.0,<1.44.0)"] -apprunner = ["mypy-boto3-apprunner (>=1.43.0,<1.44.0)"] -appstream = ["mypy-boto3-appstream (>=1.43.0,<1.44.0)"] -appsync = ["mypy-boto3-appsync (>=1.43.0,<1.44.0)"] -arc-region-switch = ["mypy-boto3-arc-region-switch (>=1.43.0,<1.44.0)"] -arc-zonal-shift = ["mypy-boto3-arc-zonal-shift (>=1.43.0,<1.44.0)"] -artifact = ["mypy-boto3-artifact (>=1.43.0,<1.44.0)"] -athena = ["mypy-boto3-athena (>=1.43.0,<1.44.0)"] -auditmanager = ["mypy-boto3-auditmanager (>=1.43.0,<1.44.0)"] -autoscaling = ["mypy-boto3-autoscaling (>=1.43.0,<1.44.0)"] -autoscaling-plans = ["mypy-boto3-autoscaling-plans (>=1.43.0,<1.44.0)"] -b2bi = ["mypy-boto3-b2bi (>=1.43.0,<1.44.0)"] -backup = ["mypy-boto3-backup (>=1.43.0,<1.44.0)"] -backup-gateway = ["mypy-boto3-backup-gateway (>=1.43.0,<1.44.0)"] -backupsearch = ["mypy-boto3-backupsearch (>=1.43.0,<1.44.0)"] -batch = ["mypy-boto3-batch (>=1.43.0,<1.44.0)"] -bcm-dashboards = ["mypy-boto3-bcm-dashboards (>=1.43.0,<1.44.0)"] -bcm-data-exports = ["mypy-boto3-bcm-data-exports (>=1.43.0,<1.44.0)"] -bcm-pricing-calculator = ["mypy-boto3-bcm-pricing-calculator (>=1.43.0,<1.44.0)"] -bcm-recommended-actions = ["mypy-boto3-bcm-recommended-actions (>=1.43.0,<1.44.0)"] -bedrock = ["mypy-boto3-bedrock (>=1.43.0,<1.44.0)"] -bedrock-agent = ["mypy-boto3-bedrock-agent (>=1.43.0,<1.44.0)"] -bedrock-agent-runtime = ["mypy-boto3-bedrock-agent-runtime (>=1.43.0,<1.44.0)"] -bedrock-agentcore = ["mypy-boto3-bedrock-agentcore (>=1.43.0,<1.44.0)"] -bedrock-agentcore-control = ["mypy-boto3-bedrock-agentcore-control (>=1.43.0,<1.44.0)"] -bedrock-data-automation = ["mypy-boto3-bedrock-data-automation (>=1.43.0,<1.44.0)"] -bedrock-data-automation-runtime = ["mypy-boto3-bedrock-data-automation-runtime (>=1.43.0,<1.44.0)"] -bedrock-runtime = ["mypy-boto3-bedrock-runtime (>=1.43.0,<1.44.0)"] -billing = ["mypy-boto3-billing (>=1.43.0,<1.44.0)"] -billingconductor = ["mypy-boto3-billingconductor (>=1.43.0,<1.44.0)"] -boto3 = ["boto3 (==1.43.71)"] -braket = ["mypy-boto3-braket (>=1.43.0,<1.44.0)"] -budgets = ["mypy-boto3-budgets (>=1.43.0,<1.44.0)"] -ce = ["mypy-boto3-ce (>=1.43.0,<1.44.0)"] -chatbot = ["mypy-boto3-chatbot (>=1.43.0,<1.44.0)"] -chime = ["mypy-boto3-chime (>=1.43.0,<1.44.0)"] -chime-sdk-identity = ["mypy-boto3-chime-sdk-identity (>=1.43.0,<1.44.0)"] -chime-sdk-media-pipelines = ["mypy-boto3-chime-sdk-media-pipelines (>=1.43.0,<1.44.0)"] -chime-sdk-meetings = ["mypy-boto3-chime-sdk-meetings (>=1.43.0,<1.44.0)"] -chime-sdk-messaging = ["mypy-boto3-chime-sdk-messaging (>=1.43.0,<1.44.0)"] -chime-sdk-voice = ["mypy-boto3-chime-sdk-voice (>=1.43.0,<1.44.0)"] -cleanrooms = ["mypy-boto3-cleanrooms (>=1.43.0,<1.44.0)"] -cleanroomsml = ["mypy-boto3-cleanroomsml (>=1.43.0,<1.44.0)"] -cloud9 = ["mypy-boto3-cloud9 (>=1.43.0,<1.44.0)"] -cloudcontrol = ["mypy-boto3-cloudcontrol (>=1.43.0,<1.44.0)"] -clouddirectory = ["mypy-boto3-clouddirectory (>=1.43.0,<1.44.0)"] -cloudformation = ["mypy-boto3-cloudformation (>=1.43.0,<1.44.0)"] -cloudfront = ["mypy-boto3-cloudfront (>=1.43.0,<1.44.0)"] -cloudfront-keyvaluestore = ["mypy-boto3-cloudfront-keyvaluestore (>=1.43.0,<1.44.0)"] -cloudhsm = ["mypy-boto3-cloudhsm (>=1.43.0,<1.44.0)"] -cloudhsmv2 = ["mypy-boto3-cloudhsmv2 (>=1.43.0,<1.44.0)"] -cloudsearch = ["mypy-boto3-cloudsearch (>=1.43.0,<1.44.0)"] -cloudsearchdomain = ["mypy-boto3-cloudsearchdomain (>=1.43.0,<1.44.0)"] -cloudtrail = ["mypy-boto3-cloudtrail (>=1.43.0,<1.44.0)"] -cloudtrail-data = ["mypy-boto3-cloudtrail-data (>=1.43.0,<1.44.0)"] -cloudwatch = ["mypy-boto3-cloudwatch (>=1.43.0,<1.44.0)"] -codeartifact = ["mypy-boto3-codeartifact (>=1.43.0,<1.44.0)"] -codebuild = ["mypy-boto3-codebuild (>=1.43.0,<1.44.0)"] -codecatalyst = ["mypy-boto3-codecatalyst (>=1.43.0,<1.44.0)"] -codecommit = ["mypy-boto3-codecommit (>=1.43.0,<1.44.0)"] -codeconnections = ["mypy-boto3-codeconnections (>=1.43.0,<1.44.0)"] -codedeploy = ["mypy-boto3-codedeploy (>=1.43.0,<1.44.0)"] -codeguru-reviewer = ["mypy-boto3-codeguru-reviewer (>=1.43.0,<1.44.0)"] -codeguru-security = ["mypy-boto3-codeguru-security (>=1.43.0,<1.44.0)"] -codeguruprofiler = ["mypy-boto3-codeguruprofiler (>=1.43.0,<1.44.0)"] -codepipeline = ["mypy-boto3-codepipeline (>=1.43.0,<1.44.0)"] -codestar-connections = ["mypy-boto3-codestar-connections (>=1.43.0,<1.44.0)"] -codestar-notifications = ["mypy-boto3-codestar-notifications (>=1.43.0,<1.44.0)"] -cognito-identity = ["mypy-boto3-cognito-identity (>=1.43.0,<1.44.0)"] -cognito-idp = ["mypy-boto3-cognito-idp (>=1.43.0,<1.44.0)"] -cognito-sync = ["mypy-boto3-cognito-sync (>=1.43.0,<1.44.0)"] -comprehend = ["mypy-boto3-comprehend (>=1.43.0,<1.44.0)"] -comprehendmedical = ["mypy-boto3-comprehendmedical (>=1.43.0,<1.44.0)"] -compute-optimizer = ["mypy-boto3-compute-optimizer (>=1.43.0,<1.44.0)"] -compute-optimizer-automation = ["mypy-boto3-compute-optimizer-automation (>=1.43.0,<1.44.0)"] -config = ["mypy-boto3-config (>=1.43.0,<1.44.0)"] -connect = ["mypy-boto3-connect (>=1.43.0,<1.44.0)"] -connect-contact-lens = ["mypy-boto3-connect-contact-lens (>=1.43.0,<1.44.0)"] -connectcampaigns = ["mypy-boto3-connectcampaigns (>=1.43.0,<1.44.0)"] -connectcampaignsv2 = ["mypy-boto3-connectcampaignsv2 (>=1.43.0,<1.44.0)"] -connectcases = ["mypy-boto3-connectcases (>=1.43.0,<1.44.0)"] -connecthealth = ["mypy-boto3-connecthealth (>=1.43.0,<1.44.0)"] -connectparticipant = ["mypy-boto3-connectparticipant (>=1.43.0,<1.44.0)"] -controlcatalog = ["mypy-boto3-controlcatalog (>=1.43.0,<1.44.0)"] -controltower = ["mypy-boto3-controltower (>=1.43.0,<1.44.0)"] -cost-optimization-hub = ["mypy-boto3-cost-optimization-hub (>=1.43.0,<1.44.0)"] -cur = ["mypy-boto3-cur (>=1.43.0,<1.44.0)"] -customer-profiles = ["mypy-boto3-customer-profiles (>=1.43.0,<1.44.0)"] -databrew = ["mypy-boto3-databrew (>=1.43.0,<1.44.0)"] -dataexchange = ["mypy-boto3-dataexchange (>=1.43.0,<1.44.0)"] -datapipeline = ["mypy-boto3-datapipeline (>=1.43.0,<1.44.0)"] -datasync = ["mypy-boto3-datasync (>=1.43.0,<1.44.0)"] -datazone = ["mypy-boto3-datazone (>=1.43.0,<1.44.0)"] -dax = ["mypy-boto3-dax (>=1.43.0,<1.44.0)"] -deadline = ["mypy-boto3-deadline (>=1.43.0,<1.44.0)"] -detective = ["mypy-boto3-detective (>=1.43.0,<1.44.0)"] -devicefarm = ["mypy-boto3-devicefarm (>=1.43.0,<1.44.0)"] -devops-agent = ["mypy-boto3-devops-agent (>=1.43.0,<1.44.0)"] -devops-guru = ["mypy-boto3-devops-guru (>=1.43.0,<1.44.0)"] -directconnect = ["mypy-boto3-directconnect (>=1.43.0,<1.44.0)"] -discovery = ["mypy-boto3-discovery (>=1.43.0,<1.44.0)"] -dlm = ["mypy-boto3-dlm (>=1.43.0,<1.44.0)"] -dms = ["mypy-boto3-dms (>=1.43.0,<1.44.0)"] -docdb = ["mypy-boto3-docdb (>=1.43.0,<1.44.0)"] -docdb-elastic = ["mypy-boto3-docdb-elastic (>=1.43.0,<1.44.0)"] -drs = ["mypy-boto3-drs (>=1.43.0,<1.44.0)"] -ds = ["mypy-boto3-ds (>=1.43.0,<1.44.0)"] -ds-data = ["mypy-boto3-ds-data (>=1.43.0,<1.44.0)"] -dsql = ["mypy-boto3-dsql (>=1.43.0,<1.44.0)"] -dynamodb = ["mypy-boto3-dynamodb (>=1.43.0,<1.44.0)"] -dynamodbstreams = ["mypy-boto3-dynamodbstreams (>=1.43.0,<1.44.0)"] -ebs = ["mypy-boto3-ebs (>=1.43.0,<1.44.0)"] -ec2 = ["mypy-boto3-ec2 (>=1.43.0,<1.44.0)"] -ec2-instance-connect = ["mypy-boto3-ec2-instance-connect (>=1.43.0,<1.44.0)"] -ecr = ["mypy-boto3-ecr (>=1.43.0,<1.44.0)"] -ecr-public = ["mypy-boto3-ecr-public (>=1.43.0,<1.44.0)"] -ecs = ["mypy-boto3-ecs (>=1.43.0,<1.44.0)"] -efs = ["mypy-boto3-efs (>=1.43.0,<1.44.0)"] -eks = ["mypy-boto3-eks (>=1.43.0,<1.44.0)"] -eks-auth = ["mypy-boto3-eks-auth (>=1.43.0,<1.44.0)"] -elasticache = ["mypy-boto3-elasticache (>=1.43.0,<1.44.0)"] -elasticbeanstalk = ["mypy-boto3-elasticbeanstalk (>=1.43.0,<1.44.0)"] -elb = ["mypy-boto3-elb (>=1.43.0,<1.44.0)"] -elbv2 = ["mypy-boto3-elbv2 (>=1.43.0,<1.44.0)"] -elementalinference = ["mypy-boto3-elementalinference (>=1.43.0,<1.44.0)"] -emr = ["mypy-boto3-emr (>=1.43.0,<1.44.0)"] -emr-containers = ["mypy-boto3-emr-containers (>=1.43.0,<1.44.0)"] -emr-serverless = ["mypy-boto3-emr-serverless (>=1.43.0,<1.44.0)"] -entityresolution = ["mypy-boto3-entityresolution (>=1.43.0,<1.44.0)"] -es = ["mypy-boto3-es (>=1.43.0,<1.44.0)"] -essential = ["mypy-boto3-cloudformation (>=1.43.0,<1.44.0)", "mypy-boto3-dynamodb (>=1.43.0,<1.44.0)", "mypy-boto3-ec2 (>=1.43.0,<1.44.0)", "mypy-boto3-lambda (>=1.43.0,<1.44.0)", "mypy-boto3-rds (>=1.43.0,<1.44.0)", "mypy-boto3-s3 (>=1.43.0,<1.44.0)", "mypy-boto3-sqs (>=1.43.0,<1.44.0)"] -events = ["mypy-boto3-events (>=1.43.0,<1.44.0)"] -evs = ["mypy-boto3-evs (>=1.43.0,<1.44.0)"] -finspace = ["mypy-boto3-finspace (>=1.43.0,<1.44.0)"] -finspace-data = ["mypy-boto3-finspace-data (>=1.43.0,<1.44.0)"] -firehose = ["mypy-boto3-firehose (>=1.43.0,<1.44.0)"] -fis = ["mypy-boto3-fis (>=1.43.0,<1.44.0)"] -fms = ["mypy-boto3-fms (>=1.43.0,<1.44.0)"] -forecast = ["mypy-boto3-forecast (>=1.43.0,<1.44.0)"] -forecastquery = ["mypy-boto3-forecastquery (>=1.43.0,<1.44.0)"] -frauddetector = ["mypy-boto3-frauddetector (>=1.43.0,<1.44.0)"] -freetier = ["mypy-boto3-freetier (>=1.43.0,<1.44.0)"] -fsx = ["mypy-boto3-fsx (>=1.43.0,<1.44.0)"] -full = ["boto3-stubs-full (>=1.43.0,<1.44.0)"] -gamelift = ["mypy-boto3-gamelift (>=1.43.0,<1.44.0)"] -gameliftstreams = ["mypy-boto3-gameliftstreams (>=1.43.0,<1.44.0)"] -geo-maps = ["mypy-boto3-geo-maps (>=1.43.0,<1.44.0)"] -geo-places = ["mypy-boto3-geo-places (>=1.43.0,<1.44.0)"] -geo-routes = ["mypy-boto3-geo-routes (>=1.43.0,<1.44.0)"] -glacier = ["mypy-boto3-glacier (>=1.43.0,<1.44.0)"] -globalaccelerator = ["mypy-boto3-globalaccelerator (>=1.43.0,<1.44.0)"] -glue = ["mypy-boto3-glue (>=1.43.0,<1.44.0)"] -grafana = ["mypy-boto3-grafana (>=1.43.0,<1.44.0)"] -greengrass = ["mypy-boto3-greengrass (>=1.43.0,<1.44.0)"] -greengrassv2 = ["mypy-boto3-greengrassv2 (>=1.43.0,<1.44.0)"] -groundstation = ["mypy-boto3-groundstation (>=1.43.0,<1.44.0)"] -guardduty = ["mypy-boto3-guardduty (>=1.43.0,<1.44.0)"] -health = ["mypy-boto3-health (>=1.43.0,<1.44.0)"] -healthlake = ["mypy-boto3-healthlake (>=1.43.0,<1.44.0)"] -iam = ["mypy-boto3-iam (>=1.43.0,<1.44.0)"] -identitystore = ["mypy-boto3-identitystore (>=1.43.0,<1.44.0)"] -imagebuilder = ["mypy-boto3-imagebuilder (>=1.43.0,<1.44.0)"] -importexport = ["mypy-boto3-importexport (>=1.43.0,<1.44.0)"] -inspector = ["mypy-boto3-inspector (>=1.43.0,<1.44.0)"] -inspector-scan = ["mypy-boto3-inspector-scan (>=1.43.0,<1.44.0)"] -inspector2 = ["mypy-boto3-inspector2 (>=1.43.0,<1.44.0)"] -interconnect = ["mypy-boto3-interconnect (>=1.43.0,<1.44.0)"] -internetmonitor = ["mypy-boto3-internetmonitor (>=1.43.0,<1.44.0)"] -invoicing = ["mypy-boto3-invoicing (>=1.43.0,<1.44.0)"] -iot = ["mypy-boto3-iot (>=1.43.0,<1.44.0)"] -iot-data = ["mypy-boto3-iot-data (>=1.43.0,<1.44.0)"] -iot-jobs-data = ["mypy-boto3-iot-jobs-data (>=1.43.0,<1.44.0)"] -iot-managed-integrations = ["mypy-boto3-iot-managed-integrations (>=1.43.0,<1.44.0)"] -iotdeviceadvisor = ["mypy-boto3-iotdeviceadvisor (>=1.43.0,<1.44.0)"] -iotfleetwise = ["mypy-boto3-iotfleetwise (>=1.43.0,<1.44.0)"] -iotsecuretunneling = ["mypy-boto3-iotsecuretunneling (>=1.43.0,<1.44.0)"] -iotsitewise = ["mypy-boto3-iotsitewise (>=1.43.0,<1.44.0)"] -iotthingsgraph = ["mypy-boto3-iotthingsgraph (>=1.43.0,<1.44.0)"] -iottwinmaker = ["mypy-boto3-iottwinmaker (>=1.43.0,<1.44.0)"] -iotwireless = ["mypy-boto3-iotwireless (>=1.43.0,<1.44.0)"] -ivs = ["mypy-boto3-ivs (>=1.43.0,<1.44.0)"] -ivs-realtime = ["mypy-boto3-ivs-realtime (>=1.43.0,<1.44.0)"] -ivschat = ["mypy-boto3-ivschat (>=1.43.0,<1.44.0)"] -kafka = ["mypy-boto3-kafka (>=1.43.0,<1.44.0)"] -kafkaconnect = ["mypy-boto3-kafkaconnect (>=1.43.0,<1.44.0)"] -kendra = ["mypy-boto3-kendra (>=1.43.0,<1.44.0)"] -kendra-ranking = ["mypy-boto3-kendra-ranking (>=1.43.0,<1.44.0)"] -keyspaces = ["mypy-boto3-keyspaces (>=1.43.0,<1.44.0)"] -keyspacesstreams = ["mypy-boto3-keyspacesstreams (>=1.43.0,<1.44.0)"] -kinesis = ["mypy-boto3-kinesis (>=1.43.0,<1.44.0)"] -kinesis-video-archived-media = ["mypy-boto3-kinesis-video-archived-media (>=1.43.0,<1.44.0)"] -kinesis-video-media = ["mypy-boto3-kinesis-video-media (>=1.43.0,<1.44.0)"] -kinesis-video-signaling = ["mypy-boto3-kinesis-video-signaling (>=1.43.0,<1.44.0)"] -kinesis-video-webrtc-storage = ["mypy-boto3-kinesis-video-webrtc-storage (>=1.43.0,<1.44.0)"] -kinesisanalytics = ["mypy-boto3-kinesisanalytics (>=1.43.0,<1.44.0)"] -kinesisanalyticsv2 = ["mypy-boto3-kinesisanalyticsv2 (>=1.43.0,<1.44.0)"] -kinesisvideo = ["mypy-boto3-kinesisvideo (>=1.43.0,<1.44.0)"] -kms = ["mypy-boto3-kms (>=1.43.0,<1.44.0)"] -lakeformation = ["mypy-boto3-lakeformation (>=1.43.0,<1.44.0)"] -lambda = ["mypy-boto3-lambda (>=1.43.0,<1.44.0)"] -lambda-core = ["mypy-boto3-lambda-core (>=1.43.0,<1.44.0)"] -lambda-microvms = ["mypy-boto3-lambda-microvms (>=1.43.0,<1.44.0)"] -launch-wizard = ["mypy-boto3-launch-wizard (>=1.43.0,<1.44.0)"] -lex-models = ["mypy-boto3-lex-models (>=1.43.0,<1.44.0)"] -lex-runtime = ["mypy-boto3-lex-runtime (>=1.43.0,<1.44.0)"] -lexv2-models = ["mypy-boto3-lexv2-models (>=1.43.0,<1.44.0)"] -lexv2-runtime = ["mypy-boto3-lexv2-runtime (>=1.43.0,<1.44.0)"] -license-manager = ["mypy-boto3-license-manager (>=1.43.0,<1.44.0)"] -license-manager-linux-subscriptions = ["mypy-boto3-license-manager-linux-subscriptions (>=1.43.0,<1.44.0)"] -license-manager-user-subscriptions = ["mypy-boto3-license-manager-user-subscriptions (>=1.43.0,<1.44.0)"] -lightsail = ["mypy-boto3-lightsail (>=1.43.0,<1.44.0)"] -location = ["mypy-boto3-location (>=1.43.0,<1.44.0)"] -logs = ["mypy-boto3-logs (>=1.43.0,<1.44.0)"] -lookoutequipment = ["mypy-boto3-lookoutequipment (>=1.43.0,<1.44.0)"] -m2 = ["mypy-boto3-m2 (>=1.43.0,<1.44.0)"] -machinelearning = ["mypy-boto3-machinelearning (>=1.43.0,<1.44.0)"] -macie2 = ["mypy-boto3-macie2 (>=1.43.0,<1.44.0)"] -mailmanager = ["mypy-boto3-mailmanager (>=1.43.0,<1.44.0)"] -managedblockchain = ["mypy-boto3-managedblockchain (>=1.43.0,<1.44.0)"] -managedblockchain-query = ["mypy-boto3-managedblockchain-query (>=1.43.0,<1.44.0)"] -marketplace-agreement = ["mypy-boto3-marketplace-agreement (>=1.43.0,<1.44.0)"] -marketplace-catalog = ["mypy-boto3-marketplace-catalog (>=1.43.0,<1.44.0)"] -marketplace-deployment = ["mypy-boto3-marketplace-deployment (>=1.43.0,<1.44.0)"] -marketplace-discovery = ["mypy-boto3-marketplace-discovery (>=1.43.0,<1.44.0)"] -marketplace-entitlement = ["mypy-boto3-marketplace-entitlement (>=1.43.0,<1.44.0)"] -marketplace-reporting = ["mypy-boto3-marketplace-reporting (>=1.43.0,<1.44.0)"] -marketplacecommerceanalytics = ["mypy-boto3-marketplacecommerceanalytics (>=1.43.0,<1.44.0)"] -mediaconnect = ["mypy-boto3-mediaconnect (>=1.43.0,<1.44.0)"] -mediaconvert = ["mypy-boto3-mediaconvert (>=1.43.0,<1.44.0)"] -medialive = ["mypy-boto3-medialive (>=1.43.0,<1.44.0)"] -mediapackage = ["mypy-boto3-mediapackage (>=1.43.0,<1.44.0)"] -mediapackage-vod = ["mypy-boto3-mediapackage-vod (>=1.43.0,<1.44.0)"] -mediapackagev2 = ["mypy-boto3-mediapackagev2 (>=1.43.0,<1.44.0)"] -mediastore = ["mypy-boto3-mediastore (>=1.43.0,<1.44.0)"] -mediastore-data = ["mypy-boto3-mediastore-data (>=1.43.0,<1.44.0)"] -mediatailor = ["mypy-boto3-mediatailor (>=1.43.0,<1.44.0)"] -medical-imaging = ["mypy-boto3-medical-imaging (>=1.43.0,<1.44.0)"] -memorydb = ["mypy-boto3-memorydb (>=1.43.0,<1.44.0)"] -meteringmarketplace = ["mypy-boto3-meteringmarketplace (>=1.43.0,<1.44.0)"] -mgh = ["mypy-boto3-mgh (>=1.43.0,<1.44.0)"] -mgn = ["mypy-boto3-mgn (>=1.43.0,<1.44.0)"] -migration-hub-refactor-spaces = ["mypy-boto3-migration-hub-refactor-spaces (>=1.43.0,<1.44.0)"] -migrationhub-config = ["mypy-boto3-migrationhub-config (>=1.43.0,<1.44.0)"] -migrationhuborchestrator = ["mypy-boto3-migrationhuborchestrator (>=1.43.0,<1.44.0)"] -migrationhubstrategy = ["mypy-boto3-migrationhubstrategy (>=1.43.0,<1.44.0)"] -mpa = ["mypy-boto3-mpa (>=1.43.0,<1.44.0)"] -mq = ["mypy-boto3-mq (>=1.43.0,<1.44.0)"] -mturk = ["mypy-boto3-mturk (>=1.43.0,<1.44.0)"] -mwaa = ["mypy-boto3-mwaa (>=1.43.0,<1.44.0)"] -mwaa-serverless = ["mypy-boto3-mwaa-serverless (>=1.43.0,<1.44.0)"] -neptune = ["mypy-boto3-neptune (>=1.43.0,<1.44.0)"] -neptune-graph = ["mypy-boto3-neptune-graph (>=1.43.0,<1.44.0)"] -neptunedata = ["mypy-boto3-neptunedata (>=1.43.0,<1.44.0)"] -network-firewall = ["mypy-boto3-network-firewall (>=1.43.0,<1.44.0)"] -networkflowmonitor = ["mypy-boto3-networkflowmonitor (>=1.43.0,<1.44.0)"] -networkmanager = ["mypy-boto3-networkmanager (>=1.43.0,<1.44.0)"] -networkmonitor = ["mypy-boto3-networkmonitor (>=1.43.0,<1.44.0)"] -notifications = ["mypy-boto3-notifications (>=1.43.0,<1.44.0)"] -notificationscontacts = ["mypy-boto3-notificationscontacts (>=1.43.0,<1.44.0)"] -nova-act = ["mypy-boto3-nova-act (>=1.43.0,<1.44.0)"] -oam = ["mypy-boto3-oam (>=1.43.0,<1.44.0)"] -observabilityadmin = ["mypy-boto3-observabilityadmin (>=1.43.0,<1.44.0)"] -odb = ["mypy-boto3-odb (>=1.43.0,<1.44.0)"] -omics = ["mypy-boto3-omics (>=1.43.0,<1.44.0)"] -opensearch = ["mypy-boto3-opensearch (>=1.43.0,<1.44.0)"] -opensearchserverless = ["mypy-boto3-opensearchserverless (>=1.43.0,<1.44.0)"] -organizations = ["mypy-boto3-organizations (>=1.43.0,<1.44.0)"] -osis = ["mypy-boto3-osis (>=1.43.0,<1.44.0)"] -outposts = ["mypy-boto3-outposts (>=1.43.0,<1.44.0)"] -partnercentral-account = ["mypy-boto3-partnercentral-account (>=1.43.0,<1.44.0)"] -partnercentral-benefits = ["mypy-boto3-partnercentral-benefits (>=1.43.0,<1.44.0)"] -partnercentral-channel = ["mypy-boto3-partnercentral-channel (>=1.43.0,<1.44.0)"] -partnercentral-revenue-measurement = ["mypy-boto3-partnercentral-revenue-measurement (>=1.43.0,<1.44.0)"] -partnercentral-selling = ["mypy-boto3-partnercentral-selling (>=1.43.0,<1.44.0)"] -payment-cryptography = ["mypy-boto3-payment-cryptography (>=1.43.0,<1.44.0)"] -payment-cryptography-data = ["mypy-boto3-payment-cryptography-data (>=1.43.0,<1.44.0)"] -pca-connector-ad = ["mypy-boto3-pca-connector-ad (>=1.43.0,<1.44.0)"] -pca-connector-scep = ["mypy-boto3-pca-connector-scep (>=1.43.0,<1.44.0)"] -pcs = ["mypy-boto3-pcs (>=1.43.0,<1.44.0)"] -personalize = ["mypy-boto3-personalize (>=1.43.0,<1.44.0)"] -personalize-events = ["mypy-boto3-personalize-events (>=1.43.0,<1.44.0)"] -personalize-runtime = ["mypy-boto3-personalize-runtime (>=1.43.0,<1.44.0)"] -pi = ["mypy-boto3-pi (>=1.43.0,<1.44.0)"] -pinpoint = ["mypy-boto3-pinpoint (>=1.43.0,<1.44.0)"] -pinpoint-email = ["mypy-boto3-pinpoint-email (>=1.43.0,<1.44.0)"] -pinpoint-sms-voice = ["mypy-boto3-pinpoint-sms-voice (>=1.43.0,<1.44.0)"] -pinpoint-sms-voice-v2 = ["mypy-boto3-pinpoint-sms-voice-v2 (>=1.43.0,<1.44.0)"] -pipes = ["mypy-boto3-pipes (>=1.43.0,<1.44.0)"] -polly = ["mypy-boto3-polly (>=1.43.0,<1.44.0)"] -pricing = ["mypy-boto3-pricing (>=1.43.0,<1.44.0)"] -pricing-plan-manager = ["mypy-boto3-pricing-plan-manager (>=1.43.0,<1.44.0)"] -proton = ["mypy-boto3-proton (>=1.43.0,<1.44.0)"] -qapps = ["mypy-boto3-qapps (>=1.43.0,<1.44.0)"] -qbusiness = ["mypy-boto3-qbusiness (>=1.43.0,<1.44.0)"] -qconnect = ["mypy-boto3-qconnect (>=1.43.0,<1.44.0)"] -quicksight = ["mypy-boto3-quicksight (>=1.43.0,<1.44.0)"] -ram = ["mypy-boto3-ram (>=1.43.0,<1.44.0)"] -rbin = ["mypy-boto3-rbin (>=1.43.0,<1.44.0)"] -rds = ["mypy-boto3-rds (>=1.43.0,<1.44.0)"] -rds-data = ["mypy-boto3-rds-data (>=1.43.0,<1.44.0)"] -redshift = ["mypy-boto3-redshift (>=1.43.0,<1.44.0)"] -redshift-data = ["mypy-boto3-redshift-data (>=1.43.0,<1.44.0)"] -redshift-serverless = ["mypy-boto3-redshift-serverless (>=1.43.0,<1.44.0)"] -rekognition = ["mypy-boto3-rekognition (>=1.43.0,<1.44.0)"] -repostspace = ["mypy-boto3-repostspace (>=1.43.0,<1.44.0)"] -resiliencehub = ["mypy-boto3-resiliencehub (>=1.43.0,<1.44.0)"] -resiliencehubv2 = ["mypy-boto3-resiliencehubv2 (>=1.43.0,<1.44.0)"] -resource-explorer-2 = ["mypy-boto3-resource-explorer-2 (>=1.43.0,<1.44.0)"] -resource-groups = ["mypy-boto3-resource-groups (>=1.43.0,<1.44.0)"] -resourcegroupstaggingapi = ["mypy-boto3-resourcegroupstaggingapi (>=1.43.0,<1.44.0)"] -rolesanywhere = ["mypy-boto3-rolesanywhere (>=1.43.0,<1.44.0)"] -route53 = ["mypy-boto3-route53 (>=1.43.0,<1.44.0)"] -route53-recovery-cluster = ["mypy-boto3-route53-recovery-cluster (>=1.43.0,<1.44.0)"] -route53-recovery-control-config = ["mypy-boto3-route53-recovery-control-config (>=1.43.0,<1.44.0)"] -route53-recovery-readiness = ["mypy-boto3-route53-recovery-readiness (>=1.43.0,<1.44.0)"] -route53domains = ["mypy-boto3-route53domains (>=1.43.0,<1.44.0)"] -route53globalresolver = ["mypy-boto3-route53globalresolver (>=1.43.0,<1.44.0)"] -route53profiles = ["mypy-boto3-route53profiles (>=1.43.0,<1.44.0)"] -route53resolver = ["mypy-boto3-route53resolver (>=1.43.0,<1.44.0)"] -rtbfabric = ["mypy-boto3-rtbfabric (>=1.43.0,<1.44.0)"] -rum = ["mypy-boto3-rum (>=1.43.0,<1.44.0)"] -s3 = ["mypy-boto3-s3 (>=1.43.0,<1.44.0)"] -s3control = ["mypy-boto3-s3control (>=1.43.0,<1.44.0)"] -s3files = ["mypy-boto3-s3files (>=1.43.0,<1.44.0)"] -s3outposts = ["mypy-boto3-s3outposts (>=1.43.0,<1.44.0)"] -s3tables = ["mypy-boto3-s3tables (>=1.43.0,<1.44.0)"] -s3vectors = ["mypy-boto3-s3vectors (>=1.43.0,<1.44.0)"] -sagemaker = ["mypy-boto3-sagemaker (>=1.43.0,<1.44.0)"] -sagemaker-a2i-runtime = ["mypy-boto3-sagemaker-a2i-runtime (>=1.43.0,<1.44.0)"] -sagemaker-edge = ["mypy-boto3-sagemaker-edge (>=1.43.0,<1.44.0)"] -sagemaker-featurestore-runtime = ["mypy-boto3-sagemaker-featurestore-runtime (>=1.43.0,<1.44.0)"] -sagemaker-geospatial = ["mypy-boto3-sagemaker-geospatial (>=1.43.0,<1.44.0)"] -sagemaker-metrics = ["mypy-boto3-sagemaker-metrics (>=1.43.0,<1.44.0)"] -sagemaker-runtime = ["mypy-boto3-sagemaker-runtime (>=1.43.0,<1.44.0)"] -sagemakerjobruntime = ["mypy-boto3-sagemakerjobruntime (>=1.43.0,<1.44.0)"] -savingsplans = ["mypy-boto3-savingsplans (>=1.43.0,<1.44.0)"] -scheduler = ["mypy-boto3-scheduler (>=1.43.0,<1.44.0)"] -schemas = ["mypy-boto3-schemas (>=1.43.0,<1.44.0)"] -sdb = ["mypy-boto3-sdb (>=1.43.0,<1.44.0)"] -secretsmanager = ["mypy-boto3-secretsmanager (>=1.43.0,<1.44.0)"] -security-ir = ["mypy-boto3-security-ir (>=1.43.0,<1.44.0)"] -securityagent = ["mypy-boto3-securityagent (>=1.43.0,<1.44.0)"] -securityhub = ["mypy-boto3-securityhub (>=1.43.0,<1.44.0)"] -securitylake = ["mypy-boto3-securitylake (>=1.43.0,<1.44.0)"] -serverlessrepo = ["mypy-boto3-serverlessrepo (>=1.43.0,<1.44.0)"] -service-quotas = ["mypy-boto3-service-quotas (>=1.43.0,<1.44.0)"] -servicecatalog = ["mypy-boto3-servicecatalog (>=1.43.0,<1.44.0)"] -servicecatalog-appregistry = ["mypy-boto3-servicecatalog-appregistry (>=1.43.0,<1.44.0)"] -servicediscovery = ["mypy-boto3-servicediscovery (>=1.43.0,<1.44.0)"] -ses = ["mypy-boto3-ses (>=1.43.0,<1.44.0)"] -sesv2 = ["mypy-boto3-sesv2 (>=1.43.0,<1.44.0)"] -shield = ["mypy-boto3-shield (>=1.43.0,<1.44.0)"] -signer = ["mypy-boto3-signer (>=1.43.0,<1.44.0)"] -signer-data = ["mypy-boto3-signer-data (>=1.43.0,<1.44.0)"] -signin = ["mypy-boto3-signin (>=1.43.0,<1.44.0)"] -simpledbv2 = ["mypy-boto3-simpledbv2 (>=1.43.0,<1.44.0)"] -snow-device-management = ["mypy-boto3-snow-device-management (>=1.43.0,<1.44.0)"] -snowball = ["mypy-boto3-snowball (>=1.43.0,<1.44.0)"] -sns = ["mypy-boto3-sns (>=1.43.0,<1.44.0)"] -socialmessaging = ["mypy-boto3-socialmessaging (>=1.43.0,<1.44.0)"] -sqs = ["mypy-boto3-sqs (>=1.43.0,<1.44.0)"] -ssm = ["mypy-boto3-ssm (>=1.43.0,<1.44.0)"] -ssm-contacts = ["mypy-boto3-ssm-contacts (>=1.43.0,<1.44.0)"] -ssm-guiconnect = ["mypy-boto3-ssm-guiconnect (>=1.43.0,<1.44.0)"] -ssm-incidents = ["mypy-boto3-ssm-incidents (>=1.43.0,<1.44.0)"] -ssm-quicksetup = ["mypy-boto3-ssm-quicksetup (>=1.43.0,<1.44.0)"] -ssm-sap = ["mypy-boto3-ssm-sap (>=1.43.0,<1.44.0)"] -sso = ["mypy-boto3-sso (>=1.43.0,<1.44.0)"] -sso-admin = ["mypy-boto3-sso-admin (>=1.43.0,<1.44.0)"] -sso-oidc = ["mypy-boto3-sso-oidc (>=1.43.0,<1.44.0)"] -stepfunctions = ["mypy-boto3-stepfunctions (>=1.43.0,<1.44.0)"] -storagegateway = ["mypy-boto3-storagegateway (>=1.43.0,<1.44.0)"] -sts = ["mypy-boto3-sts (>=1.43.0,<1.44.0)"] -supplychain = ["mypy-boto3-supplychain (>=1.43.0,<1.44.0)"] -support = ["mypy-boto3-support (>=1.43.0,<1.44.0)"] -support-app = ["mypy-boto3-support-app (>=1.43.0,<1.44.0)"] -supportauthz = ["mypy-boto3-supportauthz (>=1.43.0,<1.44.0)"] -sustainability = ["mypy-boto3-sustainability (>=1.43.0,<1.44.0)"] -swf = ["mypy-boto3-swf (>=1.43.0,<1.44.0)"] -synthetics = ["mypy-boto3-synthetics (>=1.43.0,<1.44.0)"] -taxsettings = ["mypy-boto3-taxsettings (>=1.43.0,<1.44.0)"] -textract = ["mypy-boto3-textract (>=1.43.0,<1.44.0)"] -timestream-influxdb = ["mypy-boto3-timestream-influxdb (>=1.43.0,<1.44.0)"] -timestream-query = ["mypy-boto3-timestream-query (>=1.43.0,<1.44.0)"] -timestream-write = ["mypy-boto3-timestream-write (>=1.43.0,<1.44.0)"] -tnb = ["mypy-boto3-tnb (>=1.43.0,<1.44.0)"] -transcribe = ["mypy-boto3-transcribe (>=1.43.0,<1.44.0)"] -transfer = ["mypy-boto3-transfer (>=1.43.0,<1.44.0)"] -translate = ["mypy-boto3-translate (>=1.43.0,<1.44.0)"] -trustedadvisor = ["mypy-boto3-trustedadvisor (>=1.43.0,<1.44.0)"] -uxc = ["mypy-boto3-uxc (>=1.43.0,<1.44.0)"] -verifiedpermissions = ["mypy-boto3-verifiedpermissions (>=1.43.0,<1.44.0)"] -voice-id = ["mypy-boto3-voice-id (>=1.43.0,<1.44.0)"] -vpc-lattice = ["mypy-boto3-vpc-lattice (>=1.43.0,<1.44.0)"] -waf = ["mypy-boto3-waf (>=1.43.0,<1.44.0)"] -waf-regional = ["mypy-boto3-waf-regional (>=1.43.0,<1.44.0)"] -wafv2 = ["mypy-boto3-wafv2 (>=1.43.0,<1.44.0)"] -wellarchitected = ["mypy-boto3-wellarchitected (>=1.43.0,<1.44.0)"] -wickr = ["mypy-boto3-wickr (>=1.43.0,<1.44.0)"] -wisdom = ["mypy-boto3-wisdom (>=1.43.0,<1.44.0)"] -workdocs = ["mypy-boto3-workdocs (>=1.43.0,<1.44.0)"] -workmail = ["mypy-boto3-workmail (>=1.43.0,<1.44.0)"] -workmailmessageflow = ["mypy-boto3-workmailmessageflow (>=1.43.0,<1.44.0)"] -workspaces = ["mypy-boto3-workspaces (>=1.43.0,<1.44.0)"] -workspaces-instances = ["mypy-boto3-workspaces-instances (>=1.43.0,<1.44.0)"] -workspaces-thin-client = ["mypy-boto3-workspaces-thin-client (>=1.43.0,<1.44.0)"] -workspaces-web = ["mypy-boto3-workspaces-web (>=1.43.0,<1.44.0)"] -xray = ["mypy-boto3-xray (>=1.43.0,<1.44.0)"] - -[[package]] -name = "botocore" -version = "1.43.71" -description = "Low-level, data-driven core of boto 3." -optional = false -python-versions = ">=3.10" -groups = ["main", "dev"] -files = [ - {file = "botocore-1.43.71-py3-none-any.whl", hash = "sha256:7bc3d5ddaca6f68e2eef707714264789048a6f496d375d976c560674f0cd1d1b"}, - {file = "botocore-1.43.71.tar.gz", hash = "sha256:2cde7a55aaac86a2e9a3bcd2ce3fad1a31a4711749e10f350af231e55ccef7ed"}, -] - -[package.dependencies] -jmespath = ">=0.7.1,<2.0.0" -python-dateutil = ">=2.1,<3.0.0" -urllib3 = ">=1.25.4,<2.2.0 || >2.2.0,<3" - -[package.extras] -crt = ["awscrt (==0.36.0)"] - -[[package]] -name = "botocore-stubs" -version = "1.43.67" -description = "Type annotations and code completion for botocore" -optional = false -python-versions = ">=3.10" -groups = ["dev"] -files = [ - {file = "botocore_stubs-1.43.67-py3-none-any.whl", hash = "sha256:c51262bac3341c1cda71f05fa01141fffd3990d7a92c7960e3b755c1bc830373"}, - {file = "botocore_stubs-1.43.67.tar.gz", hash = "sha256:853e74014a1f557055c4ffae5fb38d7c65c7c0520e1aab366cac41d5428f419d"}, -] - -[package.extras] -botocore = ["botocore"] - -[[package]] -name = "certifi" -version = "2026.7.22" -description = "Python package for providing Mozilla's CA Bundle." -optional = false -python-versions = ">=3.7" -groups = ["dev"] -files = [ - {file = "certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775"}, - {file = "certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55"}, -] - -[[package]] -name = "cffi" -version = "2.1.1" -description = "Foreign Function Interface for Python calling C code." -optional = false -python-versions = ">=3.10" -groups = ["dev"] -markers = "platform_python_implementation != \"PyPy\"" -files = [ - {file = "cffi-2.1.1-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be"}, - {file = "cffi-2.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b"}, - {file = "cffi-2.1.1-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004"}, - {file = "cffi-2.1.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9"}, - {file = "cffi-2.1.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98"}, - {file = "cffi-2.1.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9"}, - {file = "cffi-2.1.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6"}, - {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf"}, - {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659"}, - {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9"}, - {file = "cffi-2.1.1-cp310-cp310-win32.whl", hash = "sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41"}, - {file = "cffi-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1"}, - {file = "cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12"}, - {file = "cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1"}, - {file = "cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0"}, - {file = "cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813"}, - {file = "cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990"}, - {file = "cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af"}, - {file = "cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632"}, - {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd"}, - {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a"}, - {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa"}, - {file = "cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3"}, - {file = "cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0"}, - {file = "cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455"}, - {file = "cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0"}, - {file = "cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf"}, - {file = "cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a"}, - {file = "cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890"}, - {file = "cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50"}, - {file = "cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e"}, - {file = "cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf"}, - {file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517"}, - {file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735"}, - {file = "cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e"}, - {file = "cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a"}, - {file = "cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80"}, - {file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e"}, - {file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c"}, - {file = "cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6"}, - {file = "cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971"}, - {file = "cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c"}, - {file = "cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125"}, - {file = "cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264"}, - {file = "cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3"}, - {file = "cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2"}, - {file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b"}, - {file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7"}, - {file = "cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac"}, - {file = "cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d"}, - {file = "cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973"}, - {file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c"}, - {file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb"}, - {file = "cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54"}, - {file = "cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72"}, - {file = "cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1"}, - {file = "cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062"}, - {file = "cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03"}, - {file = "cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96"}, - {file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527"}, - {file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13"}, - {file = "cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c"}, - {file = "cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48"}, - {file = "cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836"}, - {file = "cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3"}, - {file = "cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2"}, - {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94"}, - {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc"}, - {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29"}, - {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676"}, - {file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e"}, - {file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f"}, - {file = "cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4"}, - {file = "cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e"}, - {file = "cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5"}, - {file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d"}, - {file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b"}, - {file = "cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4"}, - {file = "cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8"}, - {file = "cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6"}, - {file = "cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80"}, - {file = "cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779"}, - {file = "cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399"}, - {file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688"}, - {file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7"}, - {file = "cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac"}, - {file = "cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960"}, - {file = "cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1"}, - {file = "cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc"}, - {file = "cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab"}, - {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e"}, - {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358"}, - {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231"}, - {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6"}, - {file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94"}, - {file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5"}, - {file = "cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66"}, - {file = "cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3"}, - {file = "cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692"}, - {file = "cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be"}, -] - -[package.dependencies] -pycparser = {version = "*", markers = "implementation_name != \"PyPy\""} - -[[package]] -name = "charset-normalizer" -version = "3.5.0" -description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." -optional = false -python-versions = ">=3.7" -groups = ["dev"] -files = [ - {file = "charset_normalizer-3.5.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d2478bd3b2ead3962a484fb802891be40d10049fb74f83e09cb4463fad023fea"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7cdded069549b5eae3d5d9bb6c2e5bb4fe83f9b81863e2a193cd747bf197aebb"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:aff38231e3171c578b2c449a01afa44e9ff40844597a32873da102394f63d28e"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4346a693c08b1d0cfc0e3325bfb0ecd4322fb1a6904d68cf416f8da5e981b234"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b787efadba00f5da6fe89513bfbe3852d52ca3a448fdec165765cb3b44a80248"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:143792a43e06dc3b27fc891948406e251502dc19ff9216cd80182b79131be5c5"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d74bcf1cdd8ac8267fb216473ce6b112efa07b163536288094541415084d131c"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3bfbe543d957213fc9a3db4979a8e171b7aa7504c1d737029defdb03a6095a38"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:3587d94b5c9f05c2dc4c3f3d47aba6375ff141a21adae3051d8d4d53e8a937c0"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:a7cb4cd266bd85613367fb85a30cfbf6fe6349919e87e18ca8dba584951bfb8a"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:ffdd7ac514301d0a67f7c23b9f2b431ef909a3c3dd6c3766668d0a6f5900c94e"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:3684ebbdffd51329ac44245d1d227d90b965797aa1a8abd026568a1f6ae88811"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8b8788f114845c01f2b520e0b91ea58d143276cfc0483aa943e815f7b9555c15"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-win32.whl", hash = "sha256:9a1d9b13e5e394e13e3c316f0d910d100b17681ff59797f30da1dba032061296"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-win_amd64.whl", hash = "sha256:5a54587f93f2e289f8faf25b35c997d4cc75cf677485ac6f50c985715989f99c"}, - {file = "charset_normalizer-3.5.0-cp310-cp310-win_arm64.whl", hash = "sha256:38a395079f229a631dece74e24c69c1f612536dd51f345a7d6a98abe2d3e047a"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:e46a37ea7fcf9ae01d71b2e5ece19f1565987f3e308394b829197cbefc061f92"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1cdfed4d7a59333c8220c67dd3be4e7a6c887b67453a64394022dcc919570add"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:9491f594859b68052edebd69e05fb045055a713b57a67974e6c1553b4e503c39"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:420b19411959eec115063229536788e6b32d0a7fa907d6b940317919120d702d"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a565303d118ea3b94a4b6c076bf568069726be414e43b06d58f7070b076ce11d"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:815f143a91983ba3041bba066e492ae3c42de523fb1c699685a1abf3313b7d1b"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c5e981a5ac8641381efe6f0029467500661616a530d27bc6eedfe45f840599f8"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1a573e1e428f93908e79e04b349717f400e720f2f82285f0aaaf3ee0ff7f4c79"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:32e6d56dd825205f81e5c45bcebb4df6a11fb2bbf4969a01ef156d6ced90c224"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:30ae26a1adcd943690dcbbc47f28be762bae9e08ad7442b78c86b1c0dd5a626c"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:5f51a19dc52197a20218b05ec5336d0c6b3b09935f838724722032c8d45dc91a"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:6e44bc2780516b3df986d6fe33103c7080cd9dcd5576fe3cb4b0f64309c8f22b"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:7faa47b56070b3dd6f4898ed28528843ab130d53266cb9948d9b1f3bb1a5c5e8"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-win32.whl", hash = "sha256:830c04a49998b5ed58c8b642c65b7b26419397f52392a64121ba9fd0e95e7f9f"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:8cb9b6892b53bd6d11fa4cde3dbee020b1f0b6656be1fbaa1ec0d4324a7839db"}, - {file = "charset_normalizer-3.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:2403b489c103e9a18c835863fc6dd54361355c8291d4cafdb37492b683440b9b"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:98820e1ceb25c6df7a80c4fd8efa59cb121f99bc7c4c1693ad94a2caff5b311d"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:608553f476fca509537e804c4a71f5eb166ce63b75141f89c2c686ce1aa36956"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6753de11eef42f1c321b26d682957d92c7f7bbce6530f34bbe0f9291dd37cc6f"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0f76dc0a47f94cb9b69d86f01e477f4b0371ca70208b9ccea7e063c41eed9046"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c387c6bf91b4774e359a48a179e2872b8e8bf741e4fde06ba8d1665eb9a4760a"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:14f6904a3cf870abf044df3a8c4924ac6c8ef77e9896586fd37e73ae96cff2af"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0cce46dd29d73e135e8087b96eb62a4aca6d69391b7f97808c6588ebed3178f3"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b476cdb63df22da2b91837593380be3ddbe406f36c506c1c91d80e7196b66288"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1f56ce84b317ef2a59d7d3461891c7597c79247d2192bb8114c68a1a1debfcc0"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:9ce0f885239357379d92fd9a5fddbe20f0e30e0527c29ba69f8e99eeb1304a76"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:96ae7ab5d8155fde927aa0864fbc8ba3cc4fde6d41ab0c7cea9d6012b4978603"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:bf91921009025e96ce57a03ced6d14604fc3baf0530351638e9504a55da6fa3b"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0b2e44e6d42d1a4ff78ccc219a93c5449105d10b16198d1aea581080df8073f9"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-win32.whl", hash = "sha256:deb99535e9bf0bea8e274c6413eb939a21be35a3f492678dba4d5b1f4d70f142"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:e54dd1a66fa4bce0ccaf0db9dde336e49b3eec646dc4c1c0991279369d373a14"}, - {file = "charset_normalizer-3.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:b8ea208b304587d47931b36481342d20336e0d338ab052f8b4305926482598d6"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:5c23fa4f6eccdd601949cb00f3988c01d64e671d8faba356397971077022e144"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:07f6f42b5a6325df35b458004fb5f9f29bf502d89287a33c7cdef3590e31de0f"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8efc3f1563ed431882dd0dc0411b5f8ace1b1b89074981deaf6bd8af77dbe1bc"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:368eb2fc9482158b3a3386e8f01fa61f479c968e9a19ceab8f0188b86b312991"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:826a295a039178479a325be1ae60eded1f0b10f7dda749df59e2440de8f61d64"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70ff1c16eb0eb5ee6bb12739292347f981a5ba764cc4df1bc2e69b0405d4ac3b"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3cfdab178a4add5483e26a9bb1c16d8018ccf39b4be7a3aea6c3979e6828f2ee"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6083d10a846218502d664375b9448508d9fa580bd834567423156c6abfbe899d"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0f211c21aa316cb6e2662e54a1194633a79d98a50a876addacfce7ba5b34b09f"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b08ebf9488c7ff5eff038e48e6ea938178dfd9dcc8598b5ca941e4ae27b20be"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6c95450fce59f00c6d08eff6572ec2e736e5054c9450253afd5748f8416f2eb9"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5780a29823e1d2bec69b7a104ead4195a43f3e97782efaedbf1f79a0157af715"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:054420b5db984971d886e5e4e2c37c760ae6682aedbd066687ff0949d9ed5f08"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:d016dc857136c726958102c3b8a3986acdc65ace6fbf12cfdc09cc4bfa2935b2"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:f2ce3d39fb4a9d674e6639dd5d3146b2e273475d2260f10163228d66fc04433d"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:a5613a3a82c974227bde18f03409e30c467f8065cb56d822e3eb83708a5f223d"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fded2e82ff082e5d8e017e2ddcc1411bd8cb83b8585097fc401ef574f756b888"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:8f006866047c6ec4b627ec144b1e0bbc7427cb31fd7c08d19897d0ac9032af3d"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-win32.whl", hash = "sha256:196e270c4e80827b5072eed7d6aa661d133afada94fe366669f9609e718d305e"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:72982d9958a42f8132bf2d6b90214ed66477295ef1188731f98ae3511c6eeb5a"}, - {file = "charset_normalizer-3.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:0b373bab0b867b68b8eb249da9478cab9181a42993437cd2f5dba5fb0b4fbd1b"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:d95244906ed69d0f79f190893c65e336c15959003e21449256dc05c001b52ea2"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-android_24_x86_64.whl", hash = "sha256:d788e2ded0c4c47efa4d73cfe59eaf975ee32f425219873d2cb3e3fbaa00f636"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:f9f91d3e8382900f3a68fa0ce94294479de9cd2de6bc0c70acd0f0dfd511836b"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d54625cbf4e6b60bf0639728cb8b4cb541e340f6d7cafae5806051a40ddf4c45"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:1f99a8c3a1da5d955edbad18208b3d627bdd54c48a6e739fa877bdca98c686d6"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf1e75dc07a3850b53d1e5f75e04d3ae12afe56284be7821771eaa2466350c73"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:ac5a9cc079c67d75f4ddf343276031879eadbb333d1bb231cce297b8d7b9aae8"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0dfe83c1b4d00abbf433998117a14f56a5c2bc68226c0d331709eed0d1ce539b"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e4e8fa586df2208ef040684751345f10f503834a757c9a74ecd19c1a2f9b1ccd"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:82cc5835997ec78afe293a192e385099355770a7db94b2fb1239d36b32796f1c"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:19e52bda45086df8a4be4bb5910af6f5d9d3b538c78712c8ae09ef10b85bf458"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:3418edd0ecb72a0a3861cf72f31be0ad9b7fe338ce2b58fb5cc80b9aeb792700"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:125ee619611019471b177c70bc3e9d4cda9fad7e01d93523501d3b188df0193a"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:a3ad0e3da22852533858663848608f3f24c0d35e5cde415a4903476f2b4c88ec"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:4ebebb410bc517e1d284c52a123e82704b21e4e7e26a21ebecf7439d0647b8a3"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:91f9f7c151e772acebe489eaec96e96a2877202d7dd144e3f96b8676881715a0"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:401ea6e7af9e7852ed818f64714b579c1935482049670847ca3bd7ba45dc63fb"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:f7496aed56b06325a1ad419c5bf23c6dd042558e874f71dd1b958f3e255f3053"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-win32.whl", hash = "sha256:606a86c1c3196f3738de39a67a7490bbd61cb31c0e0436070bd0c6a48170b38e"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:ec6c464cf45867f66a2273e2214d9199a8fbad5cb95ca0fd45f6a2fe1d9d2cf4"}, - {file = "charset_normalizer-3.5.0-cp314-cp314-win_arm64.whl", hash = "sha256:dc28949de1bb5f7f30a46f15d74ce7ac5aaa63e03c5de04d68f571c7423af834"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:68b7e84ae8239a94f8d2c8f3f3a3a81bcde54805ec8f42a34de927d155688ec6"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:58ca5dc0a0ef99f2801ec0574214c978e9574055bc783830bbb6e7433218609f"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6c57af4084c10cb3286688d65e4c654190ff5edcbc2411d08cdca0a8a44c59a1"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f1619a3cc174a7e3963dd34348e6fceb6e50db0ddeb0031bd7c73a58286454fa"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1328cc57dd4372be1265f68232cee890e087416e3e6e93e6ffb32c2bad4d36a4"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:06f4fb62a9139bef056b8b2da6773c94c2f259f90e4b8e53b166f3d0372d7cf6"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:478650a70a750d75d5add401606c77f77069c32e4ba2c9131dc6cee566962ca0"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:48920bf6fe83eb2226756ac623fa54940487154eb18f80889d5735cf234965c0"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:168a0cb536b5123a77bc42ecf5e0bf6f923d0d9ae43c42a14eb0677c19ac6c19"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:f278e131afa96a3622cef9211c406ea2ad1b68eb06f8837cd443684a40e0ae50"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:d6100f877d2ed95f0856a3fde25334153add94bf2224c43f45f88e7039262aaa"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:4c440122e1ea68b1f8b44a631ebf49c39180f6869b1da22d76e8a724208ec6e9"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e5f834965c2fe589837bac1002e07e25734ff70381903ccd95b3d649e22bfa40"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-win32.whl", hash = "sha256:076cf9d3f3c7e410295c09d96355cf3b1bcae74990034d80e4371e20fe1ba4c6"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:3288a560dc3114d5d2ebe309b1ef43f8af355eafe25856832415c2a8196c9db3"}, - {file = "charset_normalizer-3.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:a284c36b9c6616bf0a8aa4aabba668a0c75ba65ccf40a79868aeaa69ad996897"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:c38d1e9bc2073b0984d2099ea647fd7f6c0d8f83a1e14e0cd32926f16e4c44ce"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c9f45186390aee4d1f26f723c615b67df346766c3b16df000d84d6e374f06757"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:f0fde5e5100c735b2274ab898f0742a5dcde492796296cfbe7e0ad6a4cd1a396"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3d00e18e7bbf47e332ab63903d18bae31efc701b1d8cca0382b97784a621fc44"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5b81980668800dd1c69faad8aea6e85a8cee0e13bcd3bba7671695ff16260293"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9bb3e0d1345b9c0fe73673ea656375f38a78ec679c2edeae0c24800f04798a85"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:2401f7671242e921e604f609d429f6b282ea4ca787a6ffd22ed7372011ddb9d1"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:96720f2aeed3434bc48f4d52fbad64ecc820cfed88915d664780ed9ba09ede78"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:c455829625df983f716cbaecbba77f2d1dc2e0e0ed1638c059cece15a279344b"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:c41b067eddcfa5ee6b1169c287605be7fb6b0ea22bba6474c5bb978a668def4f"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:e31786a947b136329bfdc458c82c06d4ec539b4a4436b7da4df4aafc9902ee80"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:c5c6d47a865147e0ae3322ce92e7fb52ba3169d94b447deda56897ea2aa6fac9"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:c75191e3c8052045179646cb40e280800a4e0bdfda34d9c949c2f268d44e80e4"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-win32.whl", hash = "sha256:83b62410bd36bb1178a7d563e2ee0cf21eb1c980c912ab99c2c78f06227f1731"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-win_amd64.whl", hash = "sha256:e3b9eaa99a6d8c9ace4cd303915947ef55088d4cd87c6676874f98c5c03aa040"}, - {file = "charset_normalizer-3.5.0-cp315-cp315-win_arm64.whl", hash = "sha256:fec352b793cdc183cc9e7e0b6c10fd7bff38ec54ba44cc43599b9b56f7f3db2e"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:c9bde7a960720c8b8e1b5ef7afaa0c9a2f3b55c44abd635b2b29dd066b298e3a"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f8cd1283a9fe6c2065c807e9d5da81afe5e1e004caef39adc0d8ae86dd883698"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1c010dd86d3f4c4433c9634d33ce8147393b270dfa54f217f965540b8ae8e075"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5e68229977b2dea28e7061c0c0630a23f2f9f6e9c6fb38d77d3d6dbfe3768b74"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a60773eb5fda796e6e6f76b9c152d270fe59f9788a51a6ff8ba44082d8548ae4"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d9419f44e568f7fafcdc0b3b5c766a2364e705a9b34fb8a56b431e0d1f3f4258"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:75e243abbb528c1a774390ed71e3f868a9f37b1373442e4bbadd401cfc505ff4"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:54c963ce6404e52255b737e8a06d356fc762d59096ae566203a67cf2b7d050f2"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:63ea0cc840c66670183578c2630d138c0e944aeadfc33f25173ee240f5db780d"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:6c06875a1d4a7537bef70f659b55c6b55b9a47ec3ba8f2db610350c2d9915e6e"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:4253da1b4456b633651a8d59eb1dc7a8a8fa38241014dd7c217b353e547ae394"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:f044cb1cf44012184715f46584658993b5fee9344d71c4b0c455a17a299730c0"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a17864853f7c518ae7d4b368af98f427f9396805476af40af8698560f09d7d97"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-win32.whl", hash = "sha256:9e726478d7a213847860219d74665a6892a643ac93b8f76580f6cf9ed39996b7"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-win_amd64.whl", hash = "sha256:d7229a99120c6c2792d96f4857c2648ce5530e93667a2c2388c5ef69a6b84775"}, - {file = "charset_normalizer-3.5.0-cp315-cp315t-win_arm64.whl", hash = "sha256:527e28a5e751d9e11369b9c5f9ab35c748eb9c109101920c7deb40d6eadf8d03"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:5a4ee37248dfac25107c758bda99d545ce73e60b44d2dd39e4a2bb9f2831e9f5"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a864bdcacd8bff58bb4845304e031f821a3ec64b2b7259f2d409cd49c9e59ca3"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:84b736e3b391601bc47b86da381c749c0f894e9191aaca9f31f30c2632206df3"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6abb1f356fb865baeb6ebc3fadd843e9a96fbf49b9adcca55037f3cceccb7438"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1d366548d2ee28a8cfdcc4296363978cc644a728333be9824d2de4652e83df0a"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d672f329ae504ee240eb39b6effb3318aa8e7e8924c0ce8eee5760b3fad98539"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c54036a518748b6c02e666f6d46c3817561998fb904c3be25b56fb4fe3dc5706"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:22a1889f1c9b752c63c36758a0c2145458e3cadb20fced7a0790002e9dd12b26"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:b7eb3eab5c646d3de7dcb14a7c9caebace5249c5767da39e1761cb1576e521a3"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:2080aa129a28267984cdc902898993d788c995c384e285d0d19199f56760d52e"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:fd68c825548a611158230e2f9222e210ceb2e3391995c0aa5865cbdf3ab4bd49"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:d8a9316f4da85e937242642b537c6d55d7e9287dd38e5634732f8233932aff45"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d90254c8f609338c53ec180fcd4c4f9c16502e238e3fc88ca7fd4c2f38d445b8"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-win32.whl", hash = "sha256:8b3e9e29b8b07cc461b9ce7768db7693a93979d0dadf22046f6f3555ded2f516"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-win_amd64.whl", hash = "sha256:0c8953d9d1617794cfc40d81179571c9ba3805dd029623a15c93f1fb70e60a74"}, - {file = "charset_normalizer-3.5.0-cp37-abi3-win_arm64.whl", hash = "sha256:562d24ca7797c1af8852994950c2e623a907b201fc4b0ed29e92af173d3828ca"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:7ffc43fe52618fcd7abc6ee0b46aea527db10da73305fcc6aaf9710ac7a33ec7"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:301bfc4877c4f4f62b344235ecc58d06c901683801636eef819f88769c315ba2"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:17a0fd0e23961c2c017372e37aabc7ca8fceb9e10ad898977dfb40ad3927baae"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ac68ebfa549cc623e0e9add2937526340c629ccf667b4da85b7ef5f99e70bbd9"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6da562a20a49673fe365b05750e98d03bb2c5f8b8d03562b014c1abb3df739f1"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d22a083497d2f7d06a57172c5b60ee66cedcf304fde5226d4dfdc94f6180f5b1"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c825661dfcf843119ab57cdcac0df7a48e168764c66917bc74f9a42ecb096da9"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:2df26d4134948616be0ece05d0b24d621d3990f37147b5883c52052b613ef1f5"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:69d647cf158eb6bc9c99503292abed1f2079a2de5859f06a403f8aee6417475d"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:d08952c0f14eb56d9dad72a2e17773b5f709c55b28635822d18c4adf38680833"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:85f9e0e2724bbddf05de65e5fb03b73eb23e985b7df4259c1d19feb302eb8dc2"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:dc7f6aca0bdac5e6520c8b6769bda69315fe7cb57f69885f115bc8ca02d1d022"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:74892fe9f33d204860e782e0a2030bb39f9f0af1e7a24f7d5a5b632df311f655"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-win32.whl", hash = "sha256:17db18db9a1374d5b9d9a3252f980b4243b0b4efd1df03fac78bb587f6ce98cd"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-win_amd64.whl", hash = "sha256:9e0213f3f8a2674a6778be299aea1d6dc6dda015aab86f683bca6d78f81f27bb"}, - {file = "charset_normalizer-3.5.0-cp39-cp39-win_arm64.whl", hash = "sha256:d867cefea33acad8e33a3eb408cca7889a9cf999bd5433d962089d5a13b6e75f"}, - {file = "charset_normalizer-3.5.0-py3-none-any.whl", hash = "sha256:993dfcbe75a85a3784abb5084f2c41b915767c90546fcc92803cffa28611baea"}, - {file = "charset_normalizer-3.5.0.tar.gz", hash = "sha256:49bd5feb59b0bf3cbf6ebcf4352e371c95b9da9bacd4449f8b64d0ad2c10a26e"}, -] - -[[package]] -name = "click" -version = "8.5.1" -description = "Composable command line interface toolkit" -optional = false -python-versions = ">=3.10" -groups = ["dev"] -markers = "python_version < \"4.0\"" -files = [ - {file = "click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37"}, - {file = "click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4"}, -] - -[[package]] -name = "colorama" -version = "0.4.6" -description = "Cross-platform colored terminal text." -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" -groups = ["dev"] -markers = "sys_platform == \"win32\"" -files = [ - {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, - {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, -] - -[[package]] -name = "cryptography" -version = "50.0.0" -description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." -optional = false -python-versions = "!=3.9.0,!=3.9.1,>=3.9" -groups = ["dev"] -files = [ - {file = "cryptography-50.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:031e2d5dd4bb9caa3ca9c82e5a197fd8ae680232cee62603d1a813f3f07e3d03"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fd9192b7b70c573d7f214eb1ae35e00d359f6f5e4b27c7e21e30de1fc6204645"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:06a32a980526a6ab9a4b9bf8f7385800791e2bb960903cb6b530e4817509a3b7"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a1b30560f2acc95aa8b2e06e716a13dbfc97314747b80d9707e307f77b40d6b3"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:8d89f3976b10b4ce31118de72329025f70d2c6ead14a8217c5514dd2c6d5a78f"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b42a28c1844fd9de8f3f7d540e36b66f3a9c83fceac7170ebc7a6a19edd9dcae"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:900131fafd8aead39ac7dd3a7e833be754c17a95cfd91221636949fe4eb0aa8a"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:07949c449a1abcf60d1ee6e88956d89404c7df3c8258f46589e912988e551987"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f89831ef99dd7dd169ab06d63a831adb9e20a87aac6d380266bbda5823349169"}, - {file = "cryptography-50.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:82148ec5bddac30b51a5b3c1945075f896fa022cb93f8e4a01e9f6ee95292c5f"}, - {file = "cryptography-50.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1489e263a8048bb8b6a8bac662eb2d402ea5d2b7b4699b72f385f1e2772db105"}, - {file = "cryptography-50.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7cec5b856506da6defb290f30c9ee687d5f5e8cb0bd3f6459dde43b0b4fa40ef"}, - {file = "cryptography-50.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:bd1c592e4d5974f0d08d4888e432157adba757c66da0246918e43677fafa2d30"}, - {file = "cryptography-50.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:49e7d93abdbd2990caced757e5fade25302f719c3c8fb6e6fff2dde98999fc41"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:19736989797678c6af1e55cd49055cdbcb55d8f6b5583ac5335f933aba9101dc"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:80b63928fa35083b33966ce1efb70e5b9607181e49dcd1c22c8c005e319f667f"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:d58c3db7cd6eed54e6c06744db55456b65ebd7492ddeae9c1e93cfca7aa857d3"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:df2a58a472f332225671c35b0a830208b86d004f82baa8530fa3782c85646533"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:11b74db56cdbe3cdee6e3f6982ecb70334fa10dce99ed58bf7894aaaa3b2a037"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f59e38625469987d7ef6d495323c55e7db6c212eaf6112267e0d3b565a2e9c9f"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:ecfed7367f965a0328cfbdd70da860f15441f002f613185668c6e6ebf5a0ac11"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:9aa87839c383bdbab6ef865787a1fb877af8dd03464c4400322726feaaadfc6d"}, - {file = "cryptography-50.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:6ba6a53445bd3cfa809ef3ef5f1589aa6ba08784a1d962bf47d0940e871dab1c"}, - {file = "cryptography-50.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3f5735ffe4996d28b809371756219f5354864902a3b9e7c0b9ee87041209fc9c"}, - {file = "cryptography-50.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:1b4a266766514614f8aa60416e71f2fc6e575d36e7bdc90f644fadb2f4b75b95"}, - {file = "cryptography-50.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:12b9c6996425c76ea6c457ace4f3073e715b8c545add07cd1a8f3a4f90691269"}, - {file = "cryptography-50.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ccdc4a71a4dabae05de219404f9f4abc38e3b58422177ff93d0da05967dafa07"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:910e1d2668e7de9648f2bcee30e180db2a6b15c30f887d7c4c93ddf96e3992e3"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a91296cb61e8df6f86d0c19cc4068228da256bf59bf86049fbd821084565327f"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e722f16708d854fe924790e051061f6704a472c3bac347b6fd88033ea8dd0dc5"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d764dcf130c428ef66786f866dd750f53182bc608813489915e9fc106bb0c82f"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:105110f43a471dbd0060b9c9516cb8a6a79233631a04cc2ba16f28323ac6e025"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:828743d939e9629bc267b8e2d08d8bb67cd4319c771a33d4b18b22dd8fb7440a"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:2a8183b489dc1f7f80f135780fadc1108f14b31b8a40411c7a5b17425f65f28b"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6e7d61120573a7f2cd94cc095f9e81f6967c61ccdf194285aa143ecec8e0b708"}, - {file = "cryptography-50.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:37fdb0d0111f1e2ff07139dfb79f1b49531f8e213c46f1163dd7642979b58c47"}, - {file = "cryptography-50.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87f62a3d3b9888ed0fdde100ec06aa61ca9cd44bad9057d1dff9a516b5f5bb9"}, - {file = "cryptography-50.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:65c2c3add92b45fd0709db8594536aea39c2a67af0e27ffcf049c498501140b7"}, - {file = "cryptography-50.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:d24fead1d4d076e1bfb006dcec392074a3cd8d7b4fc8a595aa64073b2b7a96ba"}, - {file = "cryptography-50.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5e34edd123674534acd70147f0ca331eaa2c74e6325fb2028c886aa26ba0b68c"}, - {file = "cryptography-50.0.0-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:8eb5e1172eb569ea8a872796576e6a67c276351728b6455d5beb01242b027c6a"}, - {file = "cryptography-50.0.0-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:910d11e1a385c654bf738bf3e6b8e6ed5de0f5610fcae2be9e5b398d8081d20e"}, - {file = "cryptography-50.0.0-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:62598a8a57f815db4c6259a4e97d857dab56697e7de8e8ab02352ab74da1995d"}, - {file = "cryptography-50.0.0-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:07479a1cb08219ab719147e742e76090c9c773321959bb94946fffdd397a6437"}, - {file = "cryptography-50.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:c99c003e088647b8a5b7c145d6f78c335f6348332b62e142d411c4b63d1460b9"}, - {file = "cryptography-50.0.0.tar.gz", hash = "sha256:eeac2acb5a20ed25e0ad6d1df9891a520b78b404266b6d11778f25d5d691a6c9"}, -] - -[package.dependencies] -cffi = {version = ">=2.0.0", markers = "platform_python_implementation != \"PyPy\""} -typing-extensions = {version = ">=4.13.2", markers = "python_full_version < \"3.11.0\""} - -[package.extras] -ssh = ["bcrypt (>=3.1.5)"] - -[[package]] -name = "exceptiongroup" -version = "1.3.1" -description = "Backport of PEP 654 (exception groups)" -optional = false -python-versions = ">=3.7" -groups = ["dev"] -markers = "python_version == \"3.10\"" -files = [ - {file = "exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598"}, - {file = "exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219"}, -] - -[package.dependencies] -typing-extensions = {version = ">=4.6.0", markers = "python_version < \"3.13\""} - -[package.extras] -test = ["pytest (>=6)"] - -[[package]] -name = "flask" -version = "3.1.3" -description = "A simple framework for building complex web applications." -optional = false -python-versions = ">=3.9" -groups = ["dev"] -markers = "python_version < \"4.0\"" -files = [ - {file = "flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c"}, - {file = "flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"}, -] - -[package.dependencies] -blinker = ">=1.9.0" -click = ">=8.1.3" -itsdangerous = ">=2.2.0" -jinja2 = ">=3.1.2" -markupsafe = ">=2.1.1" -werkzeug = ">=3.1.0" - -[package.extras] -async = ["asgiref (>=3.2)"] -dotenv = ["python-dotenv"] - -[[package]] -name = "flask-cors" -version = "6.0.5" -description = "A Flask extension simplifying CORS support" -optional = false -python-versions = "<4.0,>=3.9" -groups = ["dev"] -markers = "python_version < \"4.0\"" -files = [ - {file = "flask_cors-6.0.5-py3-none-any.whl", hash = "sha256:68fcf75693e961f3af26683b23c4b9a8fb6b64de17d20d0c37b95e8de7ab2ed8"}, - {file = "flask_cors-6.0.5.tar.gz", hash = "sha256:30c5031552cd59f620ac0c8211dac45b345d3b2df310e7721879e4f46ef9c601"}, -] - -[package.dependencies] -flask = ">=0.9" -typing_extensions = {version = ">=4.6.0", markers = "python_version < \"3.11\""} -Werkzeug = ">=0.7" - -[[package]] -name = "idna" -version = "3.18" -description = "Internationalized Domain Names in Applications (IDNA)" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2"}, - {file = "idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848"}, -] - -[package.extras] -all = ["mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.6.2)"] - -[[package]] -name = "iniconfig" -version = "2.3.0" -description = "brain-dead simple config-ini parsing" -optional = false -python-versions = ">=3.10" -groups = ["dev"] -files = [ - {file = "iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12"}, - {file = "iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730"}, -] - -[[package]] -name = "itsdangerous" -version = "2.2.0" -description = "Safely pass data to untrusted environments and back." -optional = false -python-versions = ">=3.8" -groups = ["dev"] -markers = "python_version < \"4.0\"" -files = [ - {file = "itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef"}, - {file = "itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173"}, -] - -[[package]] -name = "jinja2" -version = "3.1.6" -description = "A very fast and expressive template engine." -optional = false -python-versions = ">=3.7" -groups = ["dev"] -markers = "python_version < \"4.0\"" -files = [ - {file = "jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67"}, - {file = "jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d"}, -] - -[package.dependencies] -MarkupSafe = ">=2.0" - -[package.extras] -i18n = ["Babel (>=2.7)"] - -[[package]] -name = "jmespath" -version = "1.1.0" -description = "JSON Matching Expressions" -optional = false -python-versions = ">=3.9" -groups = ["main", "dev"] -files = [ - {file = "jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64"}, - {file = "jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d"}, -] - -[[package]] -name = "librt" -version = "0.15.0" -description = "Mypyc runtime library" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -markers = "platform_python_implementation != \"PyPy\"" -files = [ - {file = "librt-0.15.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e1a49adf16a7c9d9646816c2946135527197b6fcf4347c7b8b761cf1bfbf4489"}, - {file = "librt-0.15.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:81a398f45b45a59200e13cd5ad1ae1d3f44334de98b148331afe2cdfee701c52"}, - {file = "librt-0.15.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4eafbaff06b9563f8b1c850621ce51605de05208e09d4d71ce490bc972b7b9e8"}, - {file = "librt-0.15.0-cp310-cp310-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:b0411b4066db926b80258c60dcb0e6db4c9cee312eab45b7e8866b17ddf9ada1"}, - {file = "librt-0.15.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:febb1ce6cac545a54e6b769982824e955a700fdd9fbf3a08a3d82c990968b57d"}, - {file = "librt-0.15.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b230acc1c3bfe2d6f2627ba2b95dc92e58aa494600e9722d0e6ccbc931e59702"}, - {file = "librt-0.15.0-cp310-cp310-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6da110e5f314c19ab8478464d02ae18808ae73d522c15260fa4918acdcd64da9"}, - {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:eab9208b00ca55bf75983ec99f7bf13acc746a36102e98953addaad7f7ea1e1b"}, - {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:6c013cd3a1721e69e14380ada97eaa4b7b0cdf1c6b96fa765d4ea47c875088db"}, - {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:567b1c430f8bd560e689421468278ac5941bab4a05303b5d95b6ae10db03f451"}, - {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:29c4cab9df457b19672c39be7f384ebb2bc925c4e2684b8780c222b43eb36389"}, - {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:bccbd8e5b0bffb7106cf18eb1baa3d7194b1cebb3b4b1cdbd4bdb19382a6ee6c"}, - {file = "librt-0.15.0-cp310-cp310-win32.whl", hash = "sha256:8ae493ed5f659a7761c43d42f183db514536073ded9bcf671d2d1df47e29a07e"}, - {file = "librt-0.15.0-cp310-cp310-win_amd64.whl", hash = "sha256:bc25fb356d0c7810bb49ff3df908ad1fda6995d660ab099ded69244ed7ab6053"}, - {file = "librt-0.15.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:823b92cf3c18ecd08afc70c42473888b41b6e8ef5046f3b82c05c154a2fa3d22"}, - {file = "librt-0.15.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c70bc1b602cf59917e8f0c7a2cbc8bcc6fbc14d5486136b00707a79619121d63"}, - {file = "librt-0.15.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:814ff83a25b5fce8b9c80c4dd803153fb5c5599fc74db9e022466938368957ef"}, - {file = "librt-0.15.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:57f5eeb6ad4c180de583b1038e61fe5fbd9796bb69a8a1c1a0c7ddbec4c8c60f"}, - {file = "librt-0.15.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:82909c8f7eb9952656b65d3147afde4cf8e6d5a991eebc86418b5e65843b0ab8"}, - {file = "librt-0.15.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f779070399f991400fc451719e0ea388eb7de313388bada2c127a35de05f798a"}, - {file = "librt-0.15.0-cp311-cp311-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bac89069bc496ebdf4f79ebb57bbd10d0b214c8454225deb672d91002bd17e18"}, - {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:e0d00c708fb2f5822b152429b1ac80a58dbbbc3f6c232c4d13a3f7fcf2ea5b4c"}, - {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6c6624fe268625869485553dd7cc1daf30d22558215bb2a4ff16f67a9801a31a"}, - {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f56b397858a23dacf35ede366ed2212fdc03a6a57a1ad36468ad6e9dc5fac091"}, - {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:4388184646efe2054911c5b00a1077d6d1ee86a95b7e8ba96dc7850a809f3f40"}, - {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:97335f59082f9fe2ce6c2a9cc6433a0114bbb6cd4d5c09dd76c95c68b9f9a8b0"}, - {file = "librt-0.15.0-cp311-cp311-win32.whl", hash = "sha256:83380ffde38062a2e9bb55d83e74474f6614665528b98a6928720fc006dfffbb"}, - {file = "librt-0.15.0-cp311-cp311-win_amd64.whl", hash = "sha256:f75720477ee05d509a310e856cacc8d909adc182f7b91193c207bcc26d7ee6db"}, - {file = "librt-0.15.0-cp311-cp311-win_arm64.whl", hash = "sha256:256237037a3ab001ae8d9803b2d43562a4c3aa38739843694349e4d5ebb0fd56"}, - {file = "librt-0.15.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e87bc679f86a99aa3b26e3c78eeb821a247c9a28eae48eaafcc32c3bf4c3bb9e"}, - {file = "librt-0.15.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:71599e011ac880e8e45d46047d714871894c7d4ab6f25626f8d4f89da21f368d"}, - {file = "librt-0.15.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c802434092b769b1d613ed2e13fac15fbfce1934a74bd10283b03c0fae231cd1"}, - {file = "librt-0.15.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5500eeae393a184d14e1f35645962c27129d20c81afa4069e6ef826ebc2b3aaa"}, - {file = "librt-0.15.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6ecfc32dfb46fb7b565bcd6abf9412acf978775a998273d22888a6d7953730dd"}, - {file = "librt-0.15.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cc46cfd15022e35084355478c9ac809d90b1152222706ac9a7655ec21df6fa"}, - {file = "librt-0.15.0-cp312-cp312-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d5f51401d102c885b9ca509e62c79b1dbff286e1b9b047fde6f763780789356d"}, - {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cc30523e3f1a23fb7511cc659834a0d01a1042bb9de359bc1c131cc4ec6c9656"}, - {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:59fe030d8ae4a57e3fb7756bf35a858de74e04066fc8555c53d0af979132af81"}, - {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5a6526a2a956bbb1e4ae3568c82e650fc99119c66bb011ea60715744955a2b4d"}, - {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:85ea21ec6730194d67156b0e0b5430ccb1d61f8b8b907e39b37f9812b74a13f0"}, - {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1e47b8ba865d7ede071a91a7163073bbaeb72541f1ef8a07d512c45c7b5007f2"}, - {file = "librt-0.15.0-cp312-cp312-win32.whl", hash = "sha256:a5207ec414d1c4a2a7231b2086970dc036f94293cdf338190984958a013a42f1"}, - {file = "librt-0.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:73b30cfa976659b3917c8f6153bdb0591c6a9ec6583599fd24a689b690622022"}, - {file = "librt-0.15.0-cp312-cp312-win_arm64.whl", hash = "sha256:a54cf9e0ef47b96af580849db5471142200568ce1e02cbf416addab551369570"}, - {file = "librt-0.15.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:db13ca398005abcbe538deda87b686d9bd08b7001cf40c4c06b444960ae10a26"}, - {file = "librt-0.15.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:aa1f1995789dca3698bc550aaceb09a51bd5df0a057ff84ff15296cd1975b801"}, - {file = "librt-0.15.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55456ea87d8df21808446d03817be2f65e20391c1c615d9187440dff28cd08dc"}, - {file = "librt-0.15.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5a86a5a08c2235316bdb359d5dbb6ce0abfca7fac06363103e2c5af571d92f95"}, - {file = "librt-0.15.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e56b6a368529bed262da40ce13f8fef590db0479819cca84f16a1f01ac356d0b"}, - {file = "librt-0.15.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:234d8d394721fa0d786af15ebf1f3fb7f3ed82fd1cd0cde45c2f247b5d4281d2"}, - {file = "librt-0.15.0-cp313-cp313-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d8363d7accb0286ac3a0e633f396e93800dafb8150494505daf9515bbda591f3"}, - {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:0f0ee3644d951f31055ad07d77d92520e84505dd7a432cc4cd501dd70ee06785"}, - {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:2cfd1a81a648806e6a7717be4cc4d1bb392fa229752bf8444ba365e381e984d6"}, - {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:a6cd22c9da0d866558e46a041f1cc0c2bbb26b61b137b2347fa834c332e1d101"}, - {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:6d5225ef8801e4ea5e482fa9b5dfb891dd9ef6f6d870f1f25d449ca2c70ac218"}, - {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d28a05796b99f749bf8794f17ba9ba1612d0076b802e9cfc62c554634e9ce3b"}, - {file = "librt-0.15.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:2067ff438048cead9d223ca5675bae2a25e520a7c3e6c1498bf9c6892d22caab"}, - {file = "librt-0.15.0-cp313-cp313-win32.whl", hash = "sha256:1cd3b721f24c206398b9e26da3c3a9c011e6e89d06f318ba8ebefc30f1003890"}, - {file = "librt-0.15.0-cp313-cp313-win_amd64.whl", hash = "sha256:f395a4a9a03ac062dbe9a9f82e0c720502e590a38feee6a757bc82e9c63afbd8"}, - {file = "librt-0.15.0-cp313-cp313-win_arm64.whl", hash = "sha256:0a15cb554761247d84a3ec0cbdf4078d70725384f0e4662c0fa3b26266eb60ad"}, - {file = "librt-0.15.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:f5de7feedc56337a088eb15cd9fafa9938367362221d8cc62c642b7f94821993"}, - {file = "librt-0.15.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:6c0eb900c0e91f4aebe680845242e614f1864edfd44106380d0752ac29522bf8"}, - {file = "librt-0.15.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8c9a650a188e38bac005048cbe6342e81407782944d01934540ab75e417df21"}, - {file = "librt-0.15.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:92bfed8deec93df30286b9fe9e3b1dd17329cc076a192b4ee5ec223841d54953"}, - {file = "librt-0.15.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ec4b19788f835711a2072f9dbe6b03b3bf32ed1f0fb30cf399bdd59d9f0c33fa"}, - {file = "librt-0.15.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d4c7bacb70930f3d0a56f4ecf1be474a1f0d941b01dd73b756f3c256d42cb879"}, - {file = "librt-0.15.0-cp314-cp314-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3e79f05e4a08b4d880342673312bbc895b56df7765605796f15902eb5367d3ae"}, - {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a417149c0cba4d50b61e992e5a15e69eaf96746609b461cc4ed168aeef6b79dd"}, - {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:da7a94d6a3411f579d72aa3e3bc5fbca7ed4549f3dbd7e5de3aa567333374285"}, - {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:856f743ae607f2c1380eccb566c0038a9fb3eabf0fc2be2704d76d9f73557239"}, - {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:779a6e7c894737e5983e7790a9c78c4000c30e23c9aada08081bdbea53b0fa60"}, - {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:96bb17dbe8bab3c0954fbebfc69ed395599de75b6bbc35e3270a878e15d4dd65"}, - {file = "librt-0.15.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:7220697efaa6e5348fc3d18ee7f8563d4bfecd9872b37ffb915bfc1d08840622"}, - {file = "librt-0.15.0-cp314-cp314-win32.whl", hash = "sha256:f54598964d357b1c5ab77cf5d92f21e598fe0e23cdbe9618480807f81b4eba15"}, - {file = "librt-0.15.0-cp314-cp314-win_amd64.whl", hash = "sha256:3ff5893a2c23d886aa9ce786de5ac6ddc74aeeaf90743682b74d920e117d2e28"}, - {file = "librt-0.15.0-cp314-cp314-win_arm64.whl", hash = "sha256:3722a099730704c9a3d70c879fc0f51daec25fe5f1555672d97bc595abeafb95"}, - {file = "librt-0.15.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:38c0c7d4b6fc06c3324b3f9162c8391bfc4fd9dde53afe1033ce7edb48d5a714"}, - {file = "librt-0.15.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8b2fdd7ead3c995c37940a790690660d0ca006c302db26cc51933f6766866fc3"}, - {file = "librt-0.15.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2fde98cf1fc4bac144ce23c2c4c017b924ba714509ea9334977b0b27050c837d"}, - {file = "librt-0.15.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:e3b461183c5fa7681b48560f91515f53a953122fb30c71e07abc67d7ddf58c38"}, - {file = "librt-0.15.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4bbcc257e3babea20a91715c361b24554ec4e8f51aa578568afc230799fe1a19"}, - {file = "librt-0.15.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b845b8d48088fad0cadc84be4b8fda63203be7e9237b71015b3925443c1f35ab"}, - {file = "librt-0.15.0-cp314-cp314t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b30e600e8f337b9bd7f39b86d9fdfedc73cc46e3d0f745931a23a234220bb7e2"}, - {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:64b0c8c35aa4c4ed79896359f3e0b285cbe4e610042106500da4811c322cc108"}, - {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:0da0d94cb802f32a0524653e7201f2cef72d5f700a5407678f5290483d4fcd08"}, - {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:4a6369168d371207339b1e50d4532b06a7121586141f82599505a3f315751d47"}, - {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:c434e072557ade9cbc642d052c89d031efe47d5c9614523619d0d74a02378e81"}, - {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c7eec6a42018bc1d45763b1c162d3d2bf7c3b9a1b0ed30d3e91dcba390efefcc"}, - {file = "librt-0.15.0-cp314-cp314t-win32.whl", hash = "sha256:6912fa5e635d74529ac7cdb1bdf6ca3af4453da8d1edbe0110ee1cb4ad407ebf"}, - {file = "librt-0.15.0-cp314-cp314t-win_amd64.whl", hash = "sha256:8e11699ed745931c395acd3621b07062e0f840efa6935aad87a64ed0995f0915"}, - {file = "librt-0.15.0-cp314-cp314t-win_arm64.whl", hash = "sha256:5d2a91724463bfed4f573cd7a9fdc856d2e230d0c0e5a61416a93481dccd8605"}, - {file = "librt-0.15.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:8443e38dcfcfdbcf5add5118c623efd788d65ac2e25756d6251a54a06a4d0aca"}, - {file = "librt-0.15.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6d15a29033c57490cfe2069097c6fc4049e4e65ffbb749be7dc453b7c4c68965"}, - {file = "librt-0.15.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d2c05c729b589e734c09578bf5964be48a911765484840d017bbc84f49d4c4ad"}, - {file = "librt-0.15.0-cp315-cp315-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:fa60887537e1d0cd2d9982269d33a709bf54b195cd2b9364fc0a758022af5bd9"}, - {file = "librt-0.15.0-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d8bc24219b24c0af375718942ab75e3544b2763085f40f965be4326734ae8328"}, - {file = "librt-0.15.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:86a21a7bd3fe3a419512ef424cc1c020f6771d0b29cfddff36d1635a855e63f0"}, - {file = "librt-0.15.0-cp315-cp315-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dbab647e88d90b3167b91efe7091e248653688ed4337e4f90907a722c7361bb9"}, - {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:d8edcf6f550e918dca779c069b9e156385c60b406f99fc7641f32c52f7193659"}, - {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:8b62076030baa2d8b1501a46bf0e19c27a489aa90671c55665bff7887f7660b0"}, - {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:d00d20d1818e82a07a0ee0aa89a98b17ed7916b92441090b683719cb20a59b6d"}, - {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:4e6ee93fc3cf848dcbf0cce2eca73d8e7dcd0cc2b6df3a529d57750b30a4c55c"}, - {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:32896a0af72508ea979e0acb4e4c04cbeeae04938167950d535c83c45597167d"}, - {file = "librt-0.15.0-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:ec3ba415afaf951f6951b1dd16d3c8e4f540065fc382d7e70b823a79567ca374"}, - {file = "librt-0.15.0-cp315-cp315-win32.whl", hash = "sha256:d2813ba2503764f0450680c533d13df7cff9b49df1411062eded5f67db4195b9"}, - {file = "librt-0.15.0-cp315-cp315-win_amd64.whl", hash = "sha256:b87d67e33afaf265262f2a66db578284b88ee2e6fcd224579cb5c15518677ad8"}, - {file = "librt-0.15.0-cp315-cp315-win_arm64.whl", hash = "sha256:713bd7df21170b982e729e46870f31d6b437bd1a9b4648cffb529bd3c2ec5c4b"}, - {file = "librt-0.15.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:3de789c82752730f94782a5ee518baf9c05edf85733aeaf73bb6e518755cdf54"}, - {file = "librt-0.15.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:e0b5deec9a8664eb722c797241970fd4aa1894d25fda36a1ddac0f7407606bd6"}, - {file = "librt-0.15.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5563302a8359bc2295bb7084d1a8ed1519df96afb30eb2aa4e0bff7b54228988"}, - {file = "librt-0.15.0-cp315-cp315t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:22d6263b9d39d7bbb286fa791945646e3218f1be2d693e36fb630f1d0e59cd13"}, - {file = "librt-0.15.0-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:39ffd14646190c454f0d86e0d256b33f00a87a26ab410e619773b841d0e41416"}, - {file = "librt-0.15.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47318cd3a61401452de11282242937e3e057c4fd3dbaf601e269d0928a06c0a"}, - {file = "librt-0.15.0-cp315-cp315t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a56a1d4f859a82ca5b99fc4b82c9b027b15e3c455c5cd99e7d0719f27bb20b6c"}, - {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:077471b3182db4e17c36ae91555f36a4d2c00080b267f749bcad34a478a9a302"}, - {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:411ca4d1b905b860ceba7570dd6717a71dedaddcc4b0f77ece710aa41ee11f8d"}, - {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1256589e0b0adb31751d685a68bce29d73407ddf4ef05d4188f49d5dcf9566d9"}, - {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:f42b74a53e5f26a0ba0007411a7455b66c67ce4022a39cc1f56fc4efd65bcbab"}, - {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:291bf73caf78b9e88d6fae9bfd693207ff7d832e2fdbe2cf8e746bc13f5f892b"}, - {file = "librt-0.15.0-cp315-cp315t-win32.whl", hash = "sha256:c16d15ee371643ab48dc8248a3e680ebbeca573a13af2c3dd0c985b142d77162"}, - {file = "librt-0.15.0-cp315-cp315t-win_amd64.whl", hash = "sha256:dbd605739f228912dc49027cb764456b9757750bdc2b6b7773164db7096c6fd1"}, - {file = "librt-0.15.0-cp315-cp315t-win_arm64.whl", hash = "sha256:84d244b00604d17df3fc7736c327892d6bba66181254aa4087be807b6c342bdc"}, - {file = "librt-0.15.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:0e2d0c0acf5b0ada7d045912b7cf787c21315c95b38b1fa939ef72d45d366b3d"}, - {file = "librt-0.15.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f9ca190fe9edc0eb08eec558a509a16d28d91c35667b8f043cba40ed5e77a959"}, - {file = "librt-0.15.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:80811e1c42386ea95c6fb30571d3250ad43d7863f883f787f70517f441150e59"}, - {file = "librt-0.15.0-cp39-cp39-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:88c2a17815c266e6d8180204ff62cb739ab869ada4a746d4c505331526ac58f1"}, - {file = "librt-0.15.0-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a5fa8f1f916988d0bf1afea005bda37f56ac41a18016e813ccf0097a8d460ca4"}, - {file = "librt-0.15.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:355e3a4c725225a14262004fc1872a552b9d3634b4f791a0dfc80804aafbfd55"}, - {file = "librt-0.15.0-cp39-cp39-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fc1ed11c4ad0b91af24def2050f2840ea4567828e3dd058fbe608d982f6e5465"}, - {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:1f4ef2e71db33df4309167ed7f1520c4fae5e611226e159fa9cf33f93e6ddb3d"}, - {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:1a1a8cd430c7dd0c083f455cb1b328d7fc682b05c31b940906f7845bdff80881"}, - {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:04d5387b908676c0b8d5d2f5fb58373b4ea382d81f7a6f0fab8ea2a462bb4738"}, - {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:1172c6ad2a88b646e7fe3b480e3fac4ab4418b3443fd8a4061fdd531e0622fc7"}, - {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:52e8db01f603f5da0ca30987479acff98769382efc8e142fa3962395dcf3ffdb"}, - {file = "librt-0.15.0-cp39-cp39-win32.whl", hash = "sha256:e4c911f15a1652ca94ae9f1abd92e74cbb1b3597d2d92fdd556202f94e8cd455"}, - {file = "librt-0.15.0-cp39-cp39-win_amd64.whl", hash = "sha256:68242379c9b65a582b6e97318a1e9fbd6d445e58954f2d437991c4804ab11578"}, - {file = "librt-0.15.0.tar.gz", hash = "sha256:4e66cbe84437497d951b799d3e1551291b6fb3d643820a7014b3655d57a59162"}, -] - -[[package]] -name = "markupsafe" -version = "3.0.3" -description = "Safely add untrusted strings to HTML/XML markup." -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "markupsafe-3.0.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2f981d352f04553a7171b8e44369f2af4055f888dfb147d55e42d29e29e74559"}, - {file = "markupsafe-3.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e1c1493fb6e50ab01d20a22826e57520f1284df32f2d8601fdd90b6304601419"}, - {file = "markupsafe-3.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ba88449deb3de88bd40044603fafffb7bc2b055d626a330323a9ed736661695"}, - {file = "markupsafe-3.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f42d0984e947b8adf7dd6dde396e720934d12c506ce84eea8476409563607591"}, - {file = "markupsafe-3.0.3-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c0c0b3ade1c0b13b936d7970b1d37a57acde9199dc2aecc4c336773e1d86049c"}, - {file = "markupsafe-3.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0303439a41979d9e74d18ff5e2dd8c43ed6c6001fd40e5bf2e43f7bd9bbc523f"}, - {file = "markupsafe-3.0.3-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:d2ee202e79d8ed691ceebae8e0486bd9a2cd4794cec4824e1c99b6f5009502f6"}, - {file = "markupsafe-3.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:177b5253b2834fe3678cb4a5f0059808258584c559193998be2601324fdeafb1"}, - {file = "markupsafe-3.0.3-cp310-cp310-win32.whl", hash = "sha256:2a15a08b17dd94c53a1da0438822d70ebcd13f8c3a95abe3a9ef9f11a94830aa"}, - {file = "markupsafe-3.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:c4ffb7ebf07cfe8931028e3e4c85f0357459a3f9f9490886198848f4fa002ec8"}, - {file = "markupsafe-3.0.3-cp310-cp310-win_arm64.whl", hash = "sha256:e2103a929dfa2fcaf9bb4e7c091983a49c9ac3b19c9061b6d5427dd7d14d81a1"}, - {file = "markupsafe-3.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad"}, - {file = "markupsafe-3.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a"}, - {file = "markupsafe-3.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50"}, - {file = "markupsafe-3.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0bf2a864d67e76e5c9a34dc26ec616a66b9888e25e7b9460e1c76d3293bd9dbf"}, - {file = "markupsafe-3.0.3-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bc51efed119bc9cfdf792cdeaa4d67e8f6fcccab66ed4bfdd6bde3e59bfcbb2f"}, - {file = "markupsafe-3.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:068f375c472b3e7acbe2d5318dea141359e6900156b5b2ba06a30b169086b91a"}, - {file = "markupsafe-3.0.3-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7be7b61bb172e1ed687f1754f8e7484f1c8019780f6f6b0786e76bb01c2ae115"}, - {file = "markupsafe-3.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f9e130248f4462aaa8e2552d547f36ddadbeaa573879158d721bbd33dfe4743a"}, - {file = "markupsafe-3.0.3-cp311-cp311-win32.whl", hash = "sha256:0db14f5dafddbb6d9208827849fad01f1a2609380add406671a26386cdf15a19"}, - {file = "markupsafe-3.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:de8a88e63464af587c950061a5e6a67d3632e36df62b986892331d4620a35c01"}, - {file = "markupsafe-3.0.3-cp311-cp311-win_arm64.whl", hash = "sha256:3b562dd9e9ea93f13d53989d23a7e775fdfd1066c33494ff43f5418bc8c58a5c"}, - {file = "markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e"}, - {file = "markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce"}, - {file = "markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d"}, - {file = "markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d"}, - {file = "markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a"}, - {file = "markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b"}, - {file = "markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f"}, - {file = "markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b"}, - {file = "markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d"}, - {file = "markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c"}, - {file = "markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f"}, - {file = "markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795"}, - {file = "markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219"}, - {file = "markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6"}, - {file = "markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676"}, - {file = "markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9"}, - {file = "markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1"}, - {file = "markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc"}, - {file = "markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12"}, - {file = "markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed"}, - {file = "markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5"}, - {file = "markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485"}, - {file = "markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73"}, - {file = "markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37"}, - {file = "markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19"}, - {file = "markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025"}, - {file = "markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6"}, - {file = "markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f"}, - {file = "markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb"}, - {file = "markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009"}, - {file = "markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354"}, - {file = "markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218"}, - {file = "markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287"}, - {file = "markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe"}, - {file = "markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026"}, - {file = "markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737"}, - {file = "markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97"}, - {file = "markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d"}, - {file = "markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda"}, - {file = "markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf"}, - {file = "markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe"}, - {file = "markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9"}, - {file = "markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581"}, - {file = "markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4"}, - {file = "markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab"}, - {file = "markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175"}, - {file = "markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634"}, - {file = "markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50"}, - {file = "markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e"}, - {file = "markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5"}, - {file = "markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523"}, - {file = "markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc"}, - {file = "markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d"}, - {file = "markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9"}, - {file = "markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa"}, - {file = "markupsafe-3.0.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:15d939a21d546304880945ca1ecb8a039db6b4dc49b2c5a400387cdae6a62e26"}, - {file = "markupsafe-3.0.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f71a396b3bf33ecaa1626c255855702aca4d3d9fea5e051b41ac59a9c1c41edc"}, - {file = "markupsafe-3.0.3-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0f4b68347f8c5eab4a13419215bdfd7f8c9b19f2b25520968adfad23eb0ce60c"}, - {file = "markupsafe-3.0.3-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e8fc20152abba6b83724d7ff268c249fa196d8259ff481f3b1476383f8f24e42"}, - {file = "markupsafe-3.0.3-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:949b8d66bc381ee8b007cd945914c721d9aba8e27f71959d750a46f7c282b20b"}, - {file = "markupsafe-3.0.3-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:3537e01efc9d4dccdf77221fb1cb3b8e1a38d5428920e0657ce299b20324d758"}, - {file = "markupsafe-3.0.3-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:591ae9f2a647529ca990bc681daebdd52c8791ff06c2bfa05b65163e28102ef2"}, - {file = "markupsafe-3.0.3-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:a320721ab5a1aba0a233739394eb907f8c8da5c98c9181d1161e77a0c8e36f2d"}, - {file = "markupsafe-3.0.3-cp39-cp39-win32.whl", hash = "sha256:df2449253ef108a379b8b5d6b43f4b1a8e81a061d6537becd5582fba5f9196d7"}, - {file = "markupsafe-3.0.3-cp39-cp39-win_amd64.whl", hash = "sha256:7c3fb7d25180895632e5d3148dbdc29ea38ccb7fd210aa27acbd1201a1902c6e"}, - {file = "markupsafe-3.0.3-cp39-cp39-win_arm64.whl", hash = "sha256:38664109c14ffc9e7437e86b4dceb442b0096dfe3541d7864d9cbe1da4cf36c8"}, - {file = "markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698"}, -] - -[[package]] -name = "moto" -version = "5.2.2" -description = "A library that allows you to easily mock out tests based on AWS infrastructure" -optional = false -python-versions = ">=3.10" -groups = ["dev"] -files = [ - {file = "moto-5.2.2-py3-none-any.whl", hash = "sha256:3817f1e39721ca833579b921e53e3b68547ace6a34d848c9486fbb5905808de9"}, - {file = "moto-5.2.2.tar.gz", hash = "sha256:aac8023a429e125e91c91f8f4730a67b54f518cda587352f7e67252fe3168f75"}, -] - -[package.dependencies] -boto3 = ">=1.9.201" -botocore = ">=1.20.88,<1.35.45 || >1.35.45,<1.35.46 || >1.35.46" -cryptography = ">=35.0.0" -requests = ">=2.5" -responses = ">=0.15.0,<0.25.5 || >0.25.5" -werkzeug = ">=0.5,<2.2.0 || >2.2.0,<2.2.1 || >2.2.1" -xmltodict = "*" - -[package.extras] -all = ["PyYAML (>=5.1)", "antlr4-python3-runtime", "aws-xray-sdk (>=0.93,!=0.96)", "cfn-lint (>=0.40.0)", "docker (>=3.0.0)", "graphql-core", "joserfc (>=0.9.0)", "jsonpath_ng", "jsonschema", "multipart", "openapi-spec-validator (>=0.5.0)", "py-partiql-parser (==0.6.3)", "pyparsing (>=3.0.7)", "setuptools"] -apigateway = ["PyYAML (>=5.1)", "joserfc (>=0.9.0)", "openapi-spec-validator (>=0.5.0)"] -apigatewayv2 = ["PyYAML (>=5.1)", "openapi-spec-validator (>=0.5.0)"] -appsync = ["graphql-core"] -awslambda = ["docker (>=3.0.0)"] -batch = ["docker (>=3.0.0)"] -cloudformation = ["PyYAML (>=5.1)", "aws-xray-sdk (>=0.93,!=0.96)", "cfn-lint (>=0.40.0)", "docker (>=3.0.0)", "graphql-core", "joserfc (>=0.9.0)", "openapi-spec-validator (>=0.5.0)", "py-partiql-parser (==0.6.3)", "pyparsing (>=3.0.7)", "setuptools"] -cognitoidp = ["joserfc (>=0.9.0)"] -dynamodb = ["docker (>=3.0.0)", "py-partiql-parser (==0.6.3)"] -dynamodbstreams = ["docker (>=3.0.0)", "py-partiql-parser (==0.6.3)"] -events = ["jsonpath_ng"] -glue = ["pyparsing (>=3.0.7)"] -proxy = ["PyYAML (>=5.1)", "antlr4-python3-runtime", "aws-xray-sdk (>=0.93,!=0.96)", "cfn-lint (>=0.40.0)", "docker (>=2.5.1)", "graphql-core", "joserfc (>=0.9.0)", "jsonpath_ng", "multipart", "openapi-spec-validator (>=0.5.0)", "py-partiql-parser (==0.6.3)", "pyparsing (>=3.0.7)", "setuptools"] -quicksight = ["jsonschema"] -resourcegroupstaggingapi = ["PyYAML (>=5.1)", "cfn-lint (>=0.40.0)", "docker (>=3.0.0)", "graphql-core", "joserfc (>=0.9.0)", "openapi-spec-validator (>=0.5.0)", "py-partiql-parser (==0.6.3)", "pyparsing (>=3.0.7)"] -s3 = ["PyYAML (>=5.1)", "py-partiql-parser (==0.6.3)"] -s3crc32c = ["PyYAML (>=5.1)", "crc32c", "py-partiql-parser (==0.6.3)"] -server = ["PyYAML (>=5.1)", "antlr4-python3-runtime", "aws-xray-sdk (>=0.93,!=0.96)", "cfn-lint (>=0.40.0)", "docker (>=3.0.0)", "flask (!=2.2.0,!=2.2.1)", "flask-cors", "graphql-core", "joserfc (>=0.9.0)", "jsonpath_ng", "openapi-spec-validator (>=0.5.0)", "py-partiql-parser (==0.6.3)", "pyparsing (>=3.0.7)", "setuptools"] -ssm = ["PyYAML (>=5.1)"] -stepfunctions = ["antlr4-python3-runtime", "jsonpath_ng"] -xray = ["aws-xray-sdk (>=0.93,!=0.96)", "setuptools"] - -[[package]] -name = "mypy" -version = "1.20.2" -description = "Optional static typing for Python" -optional = false -python-versions = ">=3.10" -groups = ["dev"] -files = [ - {file = "mypy-1.20.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:cf5a4db6dca263010e2c7bff081c89383c72d187ba2cf4c44759aac970e2f0c4"}, - {file = "mypy-1.20.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:7b0e817b518bff7facd7f85ea05b643ad8bdcce684cf29784987b0a7c8e1f997"}, - {file = "mypy-1.20.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97d7b9a485b40f8ca425460e89bf1da2814625b2da627c0dcc6aa46c92631d14"}, - {file = "mypy-1.20.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1e1c12f6d2db3d78b909b5f77513c11eb7f2dd2782b96a3ab6dffc7d44575c99"}, - {file = "mypy-1.20.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:89dce27e142d25ffbc154c1819383b69f2e9234dc4ed4766f42e0e8cb264ab5c"}, - {file = "mypy-1.20.2-cp310-cp310-win_amd64.whl", hash = "sha256:f376e37f9bf2a946872fc5fd1199c99310748e3c26c7a26683f13f8bdb756cbd"}, - {file = "mypy-1.20.2-cp310-cp310-win_arm64.whl", hash = "sha256:6e2b469efd811707bc530fd1effef0f5d6eebcb7fe376affae69025da4b979a2"}, - {file = "mypy-1.20.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4077797a273e56e8843d001e9dfe4ba10e33323d6ade647ff260e5cd97d9758c"}, - {file = "mypy-1.20.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cdecf62abcc4292500d7858aeae87a1f8f1150f4c4dd08fb0b336ee79b2a6df3"}, - {file = "mypy-1.20.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c566c3a88b6ece59b3d70f65bedef17304f48eb52ff040a6a18214e1917b3254"}, - {file = "mypy-1.20.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0deb80d062b2479f2c87ae568f89845afc71d11bc41b04179e58165fd9f31e98"}, - {file = "mypy-1.20.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:bba9ad231e92a3e424b3e56b65aa17704993425bba97e302c832f9466bb85bac"}, - {file = "mypy-1.20.2-cp311-cp311-win_amd64.whl", hash = "sha256:baf593f2765fa3a6b1ef95807dbaa3d25b594f6a52adcc506a6b9cb115e1be67"}, - {file = "mypy-1.20.2-cp311-cp311-win_arm64.whl", hash = "sha256:20175a1c0f49863946ec20b7f63255768058ac4f07d2b9ded6a6b46cfb5a9100"}, - {file = "mypy-1.20.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4dbfcf869f6b0517f70cf0030ba6ea1d6645e132337a7d5204a18d8d5636c02b"}, - {file = "mypy-1.20.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4b6481b228d072315b053210b01ac320e1be243dc17f9e5887ef167f23f5fae4"}, - {file = "mypy-1.20.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34397cdced6b90b836e38182076049fdb41424322e0b0728c946b0939ebdf9f6"}, - {file = "mypy-1.20.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5da6976f20cae27059ea8d0c86e7cef3de720e04c4bb9ee18e3690fdb792066"}, - {file = "mypy-1.20.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:56908d7e08318d39f85b1f0c6cfd47b0cac1a130da677630dac0de3e0623e102"}, - {file = "mypy-1.20.2-cp312-cp312-win_amd64.whl", hash = "sha256:d52ad8d78522da1d308789df651ee5379088e77c76cb1994858d40a426b343b9"}, - {file = "mypy-1.20.2-cp312-cp312-win_arm64.whl", hash = "sha256:785b08db19c9f214dc37d65f7c165d19a30fcecb48abfa30f31b01b5acaabb58"}, - {file = "mypy-1.20.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:edfbfca868cdd6bd8d974a60f8a3682f5565d3f5c99b327640cedd24c4264026"}, - {file = "mypy-1.20.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e2877a02380adfcdbc69071a0f74d6e9dbbf593c0dc9d174e1f223ffd5281943"}, - {file = "mypy-1.20.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7488448de6007cd5177c6cea0517ac33b4c0f5ee9b5e9f2be51ce75511a85517"}, - {file = "mypy-1.20.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bb9c2fa06887e21d6a3a868762acb82aec34e2c6fd0174064f27c93ede68ad15"}, - {file = "mypy-1.20.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9d56a78b646f2e3daa865bc70cd5ec5a46c50045801ca8ff17a0c43abc97e3ee"}, - {file = "mypy-1.20.2-cp313-cp313-win_amd64.whl", hash = "sha256:2a4102b03bb7481d9a91a6da8d174740c9c8c4401024684b9ca3b7cc5e49852f"}, - {file = "mypy-1.20.2-cp313-cp313-win_arm64.whl", hash = "sha256:a95a9248b0c6fd933a442c03c3b113c3b61320086b88e2c444676d3fd1ca3330"}, - {file = "mypy-1.20.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:419413398fe250aae057fd2fe50166b61077083c9b82754c341cf4fd73038f30"}, - {file = "mypy-1.20.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e73c07f23009962885c197ccb9b41356a30cc0e5a1d0c2ea8fd8fb1362d7f924"}, - {file = "mypy-1.20.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c64e5973df366b747646fc98da921f9d6eba9716d57d1db94a83c026a08e0fb"}, - {file = "mypy-1.20.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a65aa591af023864fd08a97da9974e919452cfe19cb146c8a5dc692626445dc"}, - {file = "mypy-1.20.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4fef51b01e638974a6e69885687e9bd40c8d1e09a6cd291cca0619625cf1f558"}, - {file = "mypy-1.20.2-cp314-cp314-win_amd64.whl", hash = "sha256:913485a03f1bcf5d279409a9d2b9ed565c151f61c09f29991e5faa14033da4c8"}, - {file = "mypy-1.20.2-cp314-cp314-win_arm64.whl", hash = "sha256:c3bae4f855d965b5453784300c12ffc63a548304ac7f99e55d4dc7c898673aa3"}, - {file = "mypy-1.20.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2de3dcea53babc1c3237a19002bc3d228ce1833278f093b8d619e06e7cc79609"}, - {file = "mypy-1.20.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:52b176444e2e5054dfcbcb8c75b0b719865c96247b37407184bbfca5c353f2c2"}, - {file = "mypy-1.20.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:688c3312e5dadb573a2c69c82af3a298d43ecf9e6d264e0f95df960b5f6ac19c"}, - {file = "mypy-1.20.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29752dbbf8cc53f89f6ac096d363314333045c257c9c75cbd189ca2de0455744"}, - {file = "mypy-1.20.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:803203d2b6ea644982c644895c2f78b28d0e208bba7b27d9b921e0ec5eb207c6"}, - {file = "mypy-1.20.2-cp314-cp314t-win_amd64.whl", hash = "sha256:9bcb8aa397ff0093c824182fd76a935a9ba7ad097fcbef80ae89bf6c1731d8ec"}, - {file = "mypy-1.20.2-cp314-cp314t-win_arm64.whl", hash = "sha256:e061b58443f1736f8a37c48978d7ab581636d6ab03e3d4f99e3fa90463bb9382"}, - {file = "mypy-1.20.2-py3-none-any.whl", hash = "sha256:a94c5a76ab46c5e6257c7972b6c8cff0574201ca7dc05647e33e795d78680563"}, - {file = "mypy-1.20.2.tar.gz", hash = "sha256:e8222c26daaafd9e8626dec58ae36029f82585890589576f769a650dd20fd665"}, -] - -[package.dependencies] -librt = {version = ">=0.8.0", markers = "platform_python_implementation != \"PyPy\""} -mypy_extensions = ">=1.0.0" -pathspec = ">=1.0.0" -tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} -typing_extensions = [ - {version = ">=4.6.0", markers = "python_version < \"3.15\""}, - {version = ">=4.14.0", markers = "python_version >= \"3.15\""}, -] - -[package.extras] -dmypy = ["psutil (>=4.0)"] -faster-cache = ["orjson"] -install-types = ["pip"] -mypyc = ["setuptools (>=50)"] -native-parser = ["ast-serialize (>=0.1.1,<1.0.0)"] -reports = ["lxml"] - -[[package]] -name = "mypy-boto3-s3" -version = "1.43.66" -description = "Type annotations for boto3 S3 1.43.66 service generated with mypy-boto3-builder 8.12.0" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "mypy_boto3_s3-1.43.66-py3-none-any.whl", hash = "sha256:f9385e190d423690dbc161260dac02439e3b6c9841e992ba6a92d15c1050b3af"}, - {file = "mypy_boto3_s3-1.43.66.tar.gz", hash = "sha256:b2f74763e373b3f3d64cfcd2f00cdb1c10c8a4cefe6d4cdbc1ed4a6ade085c07"}, -] - -[package.dependencies] -typing-extensions = {version = "*", markers = "python_version < \"3.12\""} - -[[package]] -name = "mypy-extensions" -version = "1.1.0" -description = "Type system extensions for programs checked with the mypy type checker." -optional = false -python-versions = ">=3.8" -groups = ["dev"] -files = [ - {file = "mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505"}, - {file = "mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558"}, -] - -[[package]] -name = "packaging" -version = "26.3" -description = "Core utilities for Python packages" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c"}, - {file = "packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79"}, -] - -[[package]] -name = "pathspec" -version = "1.1.1" -description = "Utility library for gitignore style pattern matching of file paths." -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189"}, - {file = "pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a"}, -] - -[package.extras] -hyperscan = ["hyperscan (>=0.7)"] -optional = ["typing-extensions (>=4)"] -re2 = ["google-re2 (>=1.1)"] - -[[package]] -name = "pluggy" -version = "1.6.0" -description = "plugin and hook calling mechanisms for python" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746"}, - {file = "pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3"}, -] - -[package.extras] -dev = ["pre-commit", "tox"] -testing = ["coverage", "pytest", "pytest-benchmark"] - -[[package]] -name = "pycparser" -version = "3.0" -description = "C parser in Python" -optional = false -python-versions = ">=3.10" -groups = ["dev"] -markers = "platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\"" -files = [ - {file = "pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992"}, - {file = "pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29"}, -] - -[[package]] -name = "pygments" -version = "2.20.0" -description = "Pygments is a syntax highlighting package written in Python." -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176"}, - {file = "pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f"}, -] - -[package.extras] -windows-terminal = ["colorama (>=0.4.6)"] - -[[package]] -name = "pytest" -version = "8.4.2" -description = "pytest: simple powerful testing with Python" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "pytest-8.4.2-py3-none-any.whl", hash = "sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79"}, - {file = "pytest-8.4.2.tar.gz", hash = "sha256:86c0d0b93306b961d58d62a4db4879f27fe25513d4b969df351abdddb3c30e01"}, -] - -[package.dependencies] -colorama = {version = ">=0.4", markers = "sys_platform == \"win32\""} -exceptiongroup = {version = ">=1", markers = "python_version < \"3.11\""} -iniconfig = ">=1" -packaging = ">=20" -pluggy = ">=1.5,<2" -pygments = ">=2.7.2" -tomli = {version = ">=1", markers = "python_version < \"3.11\""} - -[package.extras] -dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "requests", "setuptools", "xmlschema"] - -[[package]] -name = "python-dateutil" -version = "2.9.0.post0" -description = "Extensions to the standard Python datetime module" -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" -groups = ["main", "dev"] -files = [ - {file = "python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3"}, - {file = "python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427"}, -] - -[package.dependencies] -six = ">=1.5" - -[[package]] -name = "pyyaml" -version = "6.0.3" -description = "YAML parser and emitter for Python" -optional = false -python-versions = ">=3.8" -groups = ["dev"] -files = [ - {file = "PyYAML-6.0.3-cp38-cp38-macosx_10_13_x86_64.whl", hash = "sha256:c2514fceb77bc5e7a2f7adfaa1feb2fb311607c9cb518dbc378688ec73d8292f"}, - {file = "PyYAML-6.0.3-cp38-cp38-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c57bb8c96f6d1808c030b1687b9b5fb476abaa47f0db9c0101f5e9f394e97f4"}, - {file = "PyYAML-6.0.3-cp38-cp38-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efd7b85f94a6f21e4932043973a7ba2613b059c4a000551892ac9f1d11f5baf3"}, - {file = "PyYAML-6.0.3-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22ba7cfcad58ef3ecddc7ed1db3409af68d023b7f940da23c6c2a1890976eda6"}, - {file = "PyYAML-6.0.3-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:6344df0d5755a2c9a276d4473ae6b90647e216ab4757f8426893b5dd2ac3f369"}, - {file = "PyYAML-6.0.3-cp38-cp38-win32.whl", hash = "sha256:3ff07ec89bae51176c0549bc4c63aa6202991da2d9a6129d7aef7f1407d3f295"}, - {file = "PyYAML-6.0.3-cp38-cp38-win_amd64.whl", hash = "sha256:5cf4e27da7e3fbed4d6c3d8e797387aaad68102272f8f9752883bc32d61cb87b"}, - {file = "pyyaml-6.0.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b"}, - {file = "pyyaml-6.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956"}, - {file = "pyyaml-6.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8"}, - {file = "pyyaml-6.0.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198"}, - {file = "pyyaml-6.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b"}, - {file = "pyyaml-6.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0"}, - {file = "pyyaml-6.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69"}, - {file = "pyyaml-6.0.3-cp310-cp310-win32.whl", hash = "sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e"}, - {file = "pyyaml-6.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c"}, - {file = "pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e"}, - {file = "pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824"}, - {file = "pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c"}, - {file = "pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00"}, - {file = "pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d"}, - {file = "pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a"}, - {file = "pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4"}, - {file = "pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b"}, - {file = "pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf"}, - {file = "pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196"}, - {file = "pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0"}, - {file = "pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28"}, - {file = "pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c"}, - {file = "pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc"}, - {file = "pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e"}, - {file = "pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea"}, - {file = "pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5"}, - {file = "pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b"}, - {file = "pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd"}, - {file = "pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8"}, - {file = "pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1"}, - {file = "pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c"}, - {file = "pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5"}, - {file = "pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6"}, - {file = "pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6"}, - {file = "pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be"}, - {file = "pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26"}, - {file = "pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c"}, - {file = "pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb"}, - {file = "pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac"}, - {file = "pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310"}, - {file = "pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7"}, - {file = "pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788"}, - {file = "pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5"}, - {file = "pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764"}, - {file = "pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35"}, - {file = "pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac"}, - {file = "pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3"}, - {file = "pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3"}, - {file = "pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba"}, - {file = "pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c"}, - {file = "pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702"}, - {file = "pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c"}, - {file = "pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065"}, - {file = "pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65"}, - {file = "pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9"}, - {file = "pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b"}, - {file = "pyyaml-6.0.3-cp39-cp39-macosx_10_13_x86_64.whl", hash = "sha256:b865addae83924361678b652338317d1bd7e79b1f4596f96b96c77a5a34b34da"}, - {file = "pyyaml-6.0.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:c3355370a2c156cffb25e876646f149d5d68f5e0a3ce86a5084dd0b64a994917"}, - {file = "pyyaml-6.0.3-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c5677e12444c15717b902a5798264fa7909e41153cdf9ef7ad571b704a63dd9"}, - {file = "pyyaml-6.0.3-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5ed875a24292240029e4483f9d4a4b8a1ae08843b9c54f43fcc11e404532a8a5"}, - {file = "pyyaml-6.0.3-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0150219816b6a1fa26fb4699fb7daa9caf09eb1999f3b70fb6e786805e80375a"}, - {file = "pyyaml-6.0.3-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:fa160448684b4e94d80416c0fa4aac48967a969efe22931448d853ada8baf926"}, - {file = "pyyaml-6.0.3-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:27c0abcb4a5dac13684a37f76e701e054692a9b2d3064b70f5e4eb54810553d7"}, - {file = "pyyaml-6.0.3-cp39-cp39-win32.whl", hash = "sha256:1ebe39cb5fc479422b83de611d14e2c0d3bb2a18bbcb01f229ab3cfbd8fee7a0"}, - {file = "pyyaml-6.0.3-cp39-cp39-win_amd64.whl", hash = "sha256:2e71d11abed7344e42a8849600193d15b6def118602c4c176f748e4583246007"}, - {file = "pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f"}, -] - -[[package]] -name = "requests" -version = "2.34.2" -description = "Python HTTP for Humans." -optional = false -python-versions = ">=3.10" -groups = ["dev"] -files = [ - {file = "requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0"}, - {file = "requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed"}, -] - -[package.dependencies] -certifi = ">=2023.5.7" -charset_normalizer = ">=2,<4" -idna = ">=2.5,<4" -urllib3 = ">=1.26,<3" - -[package.extras] -socks = ["PySocks (>=1.5.6,!=1.5.7)"] -use-chardet-on-py3 = ["chardet (>=3.0.2,<8)"] - -[[package]] -name = "responses" -version = "0.26.2" -description = "A utility library for mocking out the `requests` Python library." -optional = false -python-versions = ">=3.8" -groups = ["dev"] -files = [ - {file = "responses-0.26.2-py3-none-any.whl", hash = "sha256:6fdfeabd58e5ec473b98dfe02e6d46d3173bd8dd573eff2ccccf1a05a5135364"}, - {file = "responses-0.26.2.tar.gz", hash = "sha256:9c9259b46a8349197edebf43cfa68a87e1a2802ef503ff8b2fecbabc0b45afd8"}, -] - -[package.dependencies] -pyyaml = "*" -requests = ">=2.30.0,<3.0" -urllib3 = ">=1.25.10,<3.0" - -[package.extras] -tests = ["coverage (>=6.0.0)", "flake8", "mypy", "pytest (>=7.0.0)", "pytest-asyncio", "pytest-cov", "pytest-httpserver", "tomli ; python_version < \"3.11\"", "tomli-w", "types-PyYAML", "types-requests"] - -[[package]] -name = "ruff" -version = "0.11.13" -description = "An extremely fast Python linter and code formatter, written in Rust." -optional = false -python-versions = ">=3.7" -groups = ["dev"] -files = [ - {file = "ruff-0.11.13-py3-none-linux_armv6l.whl", hash = "sha256:4bdfbf1240533f40042ec00c9e09a3aade6f8c10b6414cf11b519488d2635d46"}, - {file = "ruff-0.11.13-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:aef9c9ed1b5ca28bb15c7eac83b8670cf3b20b478195bd49c8d756ba0a36cf48"}, - {file = "ruff-0.11.13-py3-none-macosx_11_0_arm64.whl", hash = "sha256:53b15a9dfdce029c842e9a5aebc3855e9ab7771395979ff85b7c1dedb53ddc2b"}, - {file = "ruff-0.11.13-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab153241400789138d13f362c43f7edecc0edfffce2afa6a68434000ecd8f69a"}, - {file = "ruff-0.11.13-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6c51f93029d54a910d3d24f7dd0bb909e31b6cd989a5e4ac513f4eb41629f0dc"}, - {file = "ruff-0.11.13-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1808b3ed53e1a777c2ef733aca9051dc9bf7c99b26ece15cb59a0320fbdbd629"}, - {file = "ruff-0.11.13-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:d28ce58b5ecf0f43c1b71edffabe6ed7f245d5336b17805803312ec9bc665933"}, - {file = "ruff-0.11.13-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:55e4bc3a77842da33c16d55b32c6cac1ec5fb0fbec9c8c513bdce76c4f922165"}, - {file = "ruff-0.11.13-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:633bf2c6f35678c56ec73189ba6fa19ff1c5e4807a78bf60ef487b9dd272cc71"}, - {file = "ruff-0.11.13-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4ffbc82d70424b275b089166310448051afdc6e914fdab90e08df66c43bb5ca9"}, - {file = "ruff-0.11.13-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:4a9ddd3ec62a9a89578c85842b836e4ac832d4a2e0bfaad3b02243f930ceafcc"}, - {file = "ruff-0.11.13-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d237a496e0778d719efb05058c64d28b757c77824e04ffe8796c7436e26712b7"}, - {file = "ruff-0.11.13-py3-none-musllinux_1_2_i686.whl", hash = "sha256:26816a218ca6ef02142343fd24c70f7cd8c5aa6c203bca284407adf675984432"}, - {file = "ruff-0.11.13-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:51c3f95abd9331dc5b87c47ac7f376db5616041173826dfd556cfe3d4977f492"}, - {file = "ruff-0.11.13-py3-none-win32.whl", hash = "sha256:96c27935418e4e8e77a26bb05962817f28b8ef3843a6c6cc49d8783b5507f250"}, - {file = "ruff-0.11.13-py3-none-win_amd64.whl", hash = "sha256:29c3189895a8a6a657b7af4e97d330c8a3afd2c9c8f46c81e2fc5a31866517e3"}, - {file = "ruff-0.11.13-py3-none-win_arm64.whl", hash = "sha256:b4385285e9179d608ff1d2fb9922062663c658605819a6876d8beef0c30b7f3b"}, - {file = "ruff-0.11.13.tar.gz", hash = "sha256:26fa247dc68d1d4e72c179e08889a25ac0c7ba4d78aecfc835d49cbfd60bf514"}, -] - -[[package]] -name = "s3transfer" -version = "0.19.2" -description = "An Amazon S3 Transfer Manager" -optional = false -python-versions = ">=3.10" -groups = ["main", "dev"] -files = [ - {file = "s3transfer-0.19.2-py3-none-any.whl", hash = "sha256:d8168eccca828cbb2cd573675333f3bddd254313a9c42494b84c76b539e8ba25"}, - {file = "s3transfer-0.19.2.tar.gz", hash = "sha256:ba0309fd86be3c27dbf78cdd813c13c5e1df16e5874b99d2535ebbdfb9892993"}, -] - -[package.dependencies] -botocore = ">=1.37.4,<2.0a.0" - -[package.extras] -crt = ["botocore[crt] (>=1.37.4,<2.0a.0)"] - -[[package]] -name = "six" -version = "1.17.0" -description = "Python 2 and 3 compatibility utilities" -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" -groups = ["main", "dev"] -files = [ - {file = "six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274"}, - {file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"}, -] - -[[package]] -name = "tomli" -version = "2.4.1" -description = "A lil' TOML parser" -optional = false -python-versions = ">=3.8" -groups = ["dev"] -markers = "python_version == \"3.10\"" -files = [ - {file = "tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30"}, - {file = "tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a"}, - {file = "tomli-2.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96481a5786729fd470164b47cdb3e0e58062a496f455ee41b4403be77cb5a076"}, - {file = "tomli-2.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a881ab208c0baf688221f8cecc5401bd291d67e38a1ac884d6736cbcd8247e9"}, - {file = "tomli-2.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:47149d5bd38761ac8be13a84864bf0b7b70bc051806bc3669ab1cbc56216b23c"}, - {file = "tomli-2.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ec9bfaf3ad2df51ace80688143a6a4ebc09a248f6ff781a9945e51937008fcbc"}, - {file = "tomli-2.4.1-cp311-cp311-win32.whl", hash = "sha256:ff2983983d34813c1aeb0fa89091e76c3a22889ee83ab27c5eeb45100560c049"}, - {file = "tomli-2.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:5ee18d9ebdb417e384b58fe414e8d6af9f4e7a0ae761519fb50f721de398dd4e"}, - {file = "tomli-2.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:c2541745709bad0264b7d4705ad453b76ccd191e64aa6f0fc66b69a293a45ece"}, - {file = "tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a"}, - {file = "tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085"}, - {file = "tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9"}, - {file = "tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5"}, - {file = "tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585"}, - {file = "tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1"}, - {file = "tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917"}, - {file = "tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9"}, - {file = "tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257"}, - {file = "tomli-2.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:36d2bd2ad5fb9eaddba5226aa02c8ec3fa4f192631e347b3ed28186d43be6b54"}, - {file = "tomli-2.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eb0dc4e38e6a1fd579e5d50369aa2e10acfc9cace504579b2faabb478e76941a"}, - {file = "tomli-2.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7f2c7f2b9ca6bdeef8f0fa897f8e05085923eb091721675170254cbc5b02897"}, - {file = "tomli-2.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f3c6818a1a86dd6dca7ddcaaf76947d5ba31aecc28cb1b67009a5877c9a64f3f"}, - {file = "tomli-2.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d312ef37c91508b0ab2cee7da26ec0b3ed2f03ce12bd87a588d771ae15dcf82d"}, - {file = "tomli-2.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:51529d40e3ca50046d7606fa99ce3956a617f9b36380da3b7f0dd3dd28e68cb5"}, - {file = "tomli-2.4.1-cp313-cp313-win32.whl", hash = "sha256:2190f2e9dd7508d2a90ded5ed369255980a1bcdd58e52f7fe24b8162bf9fedbd"}, - {file = "tomli-2.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d65a2fbf9d2f8352685bc1364177ee3923d6baf5e7f43ea4959d7d8bc326a36"}, - {file = "tomli-2.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:4b605484e43cdc43f0954ddae319fb75f04cc10dd80d830540060ee7cd0243cd"}, - {file = "tomli-2.4.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fd0409a3653af6c147209d267a0e4243f0ae46b011aa978b1080359fddc9b6cf"}, - {file = "tomli-2.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a120733b01c45e9a0c34aeef92bf0cf1d56cfe81ed9d47d562f9ed591a9828ac"}, - {file = "tomli-2.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:559db847dc486944896521f68d8190be1c9e719fced785720d2216fe7022b662"}, - {file = "tomli-2.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01f520d4f53ef97964a240a035ec2a869fe1a37dde002b57ebc4417a27ccd853"}, - {file = "tomli-2.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f94b27a62cfad8496c8d2513e1a222dd446f095fca8987fceef261225538a15"}, - {file = "tomli-2.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede3e6487c5ef5d28634ba3f31f989030ad6af71edfb0055cbbd14189ff240ba"}, - {file = "tomli-2.4.1-cp314-cp314-win32.whl", hash = "sha256:3d48a93ee1c9b79c04bb38772ee1b64dcf18ff43085896ea460ca8dec96f35f6"}, - {file = "tomli-2.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:88dceee75c2c63af144e456745e10101eb67361050196b0b6af5d717254dddf7"}, - {file = "tomli-2.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:b8c198f8c1805dc42708689ed6864951fd2494f924149d3e4bce7710f8eb5232"}, - {file = "tomli-2.4.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d4d8fe59808a54658fcc0160ecfb1b30f9089906c50b23bcb4c69eddc19ec2b4"}, - {file = "tomli-2.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7008df2e7655c495dd12d2a4ad038ff878d4ca4b81fccaf82b714e07eae4402c"}, - {file = "tomli-2.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d8591993e228b0c930c4bb0db464bdad97b3289fb981255d6c9a41aedc84b2d"}, - {file = "tomli-2.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:734e20b57ba95624ecf1841e72b53f6e186355e216e5412de414e3c51e5e3c41"}, - {file = "tomli-2.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8a650c2dbafa08d42e51ba0b62740dae4ecb9338eefa093aa5c78ceb546fcd5c"}, - {file = "tomli-2.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:504aa796fe0569bb43171066009ead363de03675276d2d121ac1a4572397870f"}, - {file = "tomli-2.4.1-cp314-cp314t-win32.whl", hash = "sha256:b1d22e6e9387bf4739fbe23bfa80e93f6b0373a7f1b96c6227c32bef95a4d7a8"}, - {file = "tomli-2.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:2c1c351919aca02858f740c6d33adea0c5deea37f9ecca1cc1ef9e884a619d26"}, - {file = "tomli-2.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:eab21f45c7f66c13f2a9e0e1535309cee140182a9cdae1e041d02e47291e8396"}, - {file = "tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe"}, - {file = "tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f"}, -] - -[[package]] -name = "types-s3transfer" -version = "0.16.0" -description = "Type annotations and code completion for s3transfer" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "types_s3transfer-0.16.0-py3-none-any.whl", hash = "sha256:1c0cd111ecf6e21437cb410f5cddb631bfb2263b77ad973e79b9c6d0cb24e0ef"}, - {file = "types_s3transfer-0.16.0.tar.gz", hash = "sha256:b4636472024c5e2b62278c5b759661efeb52a81851cde5f092f24100b1ecb443"}, -] - -[[package]] -name = "typing-extensions" -version = "4.16.0" -description = "Backported and Experimental Type Hints for Python 3.9+" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8"}, - {file = "typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5"}, -] - -[[package]] -name = "urllib3" -version = "2.7.0" -description = "HTTP library with thread-safe connection pooling, file post, and more." -optional = false -python-versions = ">=3.10" -groups = ["main", "dev"] -files = [ - {file = "urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897"}, - {file = "urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c"}, -] - -[package.extras] -brotli = ["brotli (>=1.2.0) ; platform_python_implementation == \"CPython\"", "brotlicffi (>=1.2.0.0) ; platform_python_implementation != \"CPython\""] -h2 = ["h2 (>=4,<5)"] -socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] -zstd = ["backports-zstd (>=1.0.0) ; python_version < \"3.14\""] - -[[package]] -name = "werkzeug" -version = "3.1.8" -description = "The comprehensive WSGI web application library." -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "werkzeug-3.1.8-py3-none-any.whl", hash = "sha256:63a77fb8892bf28ebc3178683445222aa500e48ebad5ec77b0ad80f8726b1f50"}, - {file = "werkzeug-3.1.8.tar.gz", hash = "sha256:9bad61a4268dac112f1c5cd4630a56ede601b6ed420300677a869083d70a4c44"}, -] - -[package.dependencies] -markupsafe = ">=2.1.1" - -[package.extras] -watchdog = ["watchdog (>=2.3)"] - -[[package]] -name = "xmltodict" -version = "1.0.4" -description = "Makes working with XML feel like you are working with JSON" -optional = false -python-versions = ">=3.9" -groups = ["dev"] -files = [ - {file = "xmltodict-1.0.4-py3-none-any.whl", hash = "sha256:a4a00d300b0e1c59fc2bfccb53d7b2e88c32f200df138a0dd2229f842497026a"}, - {file = "xmltodict-1.0.4.tar.gz", hash = "sha256:6d94c9f834dd9e44514162799d344d815a3a4faec913717a9ecbfa5be1bb8e61"}, -] - -[package.extras] -test = ["pytest", "pytest-cov"] - -[extras] -s3 = ["boto3"] - -[metadata] -lock-version = "2.1" -python-versions = ">=3.10" -content-hash = "4dea3fad344979b3ddecee989a6fcefde414bb933970747f35067687ee469521" diff --git a/poetry.toml b/poetry.toml deleted file mode 100644 index ab1033b..0000000 --- a/poetry.toml +++ /dev/null @@ -1,2 +0,0 @@ -[virtualenvs] -in-project = true diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 9861c41..0000000 --- a/pyproject.toml +++ /dev/null @@ -1,61 +0,0 @@ -[project] -name = "loch" -version = "0.1.0" -description = "Save and restore agent coding sessions across machines" -authors = [{ name = "Mike Lyons", email = "mdl0394@gmail.com" }] -readme = "README.md" -license = "MIT" -requires-python = ">=3.10" -dependencies = [] - -[project.optional-dependencies] -# The SDK is imported lazily inside S3Store._client, so a file:// store never -# touches it at runtime and a default install is 184KB rather than 27MB. -s3 = ["boto3 (>=1.37.31,<2.0.0)"] - -[project.scripts] -loch = "loch.cli:main" - -[build-system] -requires = ["poetry-core>=2.0.0"] -build-backend = "poetry.core.masonry.api" - -[tool.poetry] -packages = [{ include = "loch" }] - -[tool.poetry.group.dev.dependencies] -pytest = "^8.2.2" -mypy = "^1.10.1" -moto = "^5.0.11" -ruff = "^0.11.2" -boto3 = "^1.37.31" -boto3-stubs = "^1.34.145" -mypy-boto3-s3 = "^1.34.105" -# moto's threaded server, which the Rust S3 client is tested against: a real -# HTTP endpoint rather than boto3's in-process mock. flask-cors caps Python -# below 4; the marker keeps that cap on this dev dependency alone rather than -# on loch's own requires-python. -flask = { version = "^3.0", python = ">=3.10,<4.0" } -flask-cors = { version = ">=4.0", python = ">=3.10,<4.0" } - -[tool.pytest.ini_options] -testpaths = ["test"] - -[tool.mypy] -# Pinned to the floor rather than left to follow the running interpreter, so a -# 3.11+ API slipping in fails on a 3.13 laptop and not only in CI. -python_version = "3.10" - -[tool.ruff] -# Linting configuration -line-length = 88 -target-version = "py310" -lint.select = ["E", "F", "I"] -lint.ignore = ["E501"] - -# Formatting configuration -[tool.ruff.format] -quote-style = "double" -indent-style = "space" -line-ending = "auto" -docstring-code-format = true diff --git a/src/blame_html.rs b/src/blame_html.rs index c5ea7a4..ba105a5 100644 --- a/src/blame_html.rs +++ b/src/blame_html.rs @@ -1,5 +1,5 @@ -//! `loch blame --html`, as in `loch/blame_html.py`: the annotated file as one -//! self-contained page. `blame_template.html` is the Python module's +//! `loch blame --html`: the annotated file as one +//! self-contained page. `blame_template.html` was the Python module's //! `TEMPLATE`, extracted verbatim, so it is filled the way `str.format` would //! fill it: `{{`/`}}` are literal braces and `{name}` a field. @@ -65,7 +65,7 @@ fn format_template(fields: &[(&str, &str)]) -> String { out } -/// One conversation or hunk as `cli.py` builds it, in JSON form. +/// Conversations and hunks as `cli::command_blame` builds them, in JSON form. pub fn render( file: &str, conversations: &[Value], diff --git a/src/bundle.rs b/src/bundle.rs index 3ec7cc8..5351ba7 100644 --- a/src/bundle.rs +++ b/src/bundle.rs @@ -1,4 +1,4 @@ -//! The bundle format, as in `loch/bundle.py`. The ref is the SHA-256 of the +//! The bundle format. The ref is the SHA-256 of the //! packed bytes, so two things here must never drift: the JSON is compact and //! unescaped (`separators=(",", ":")`, `ensure_ascii=False`) with absent //! metadata omitted rather than null, and the gzip stream is zlib's own @@ -68,12 +68,12 @@ fn bundle_json(bundle: &Bundle) -> Value { }) } -/// bundle.py's fixed header: OS byte 255 whatever the platform, XFL 2 for +/// A fixed header: OS byte 255 whatever the platform, XFL 2 for /// level 9, mtime 0. const GZIP_HEADER: [u8; 10] = [0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x02, 0xff]; /// Raw deflate at level 9, window 15, memLevel 8, default strategy — the -/// `zlib.compressobj(9, DEFLATED, -15, 8, 0)` bundle.py uses — through zlib +/// `zlib.compressobj(9, DEFLATED, -15, 8, 0)` the Python build used — through zlib /// itself (flate2's zlib backend initialises exactly that), since no other /// deflate reproduces zlib's bytes. zlib's output doesn't depend on how the /// input is chunked, so streaming it is the same as one call. @@ -148,7 +148,7 @@ fn gunzip(data: &[u8]) -> Result, String> { Ok(out) } -/// The error string is what bundle.py's exception would print, for the +/// The error string is what the Python build's exception printed, for the /// failures the harness exercises; anything stranger reads generically. pub fn unpack_bundle(data: &[u8]) -> Result { let raw = gunzip(data)?; @@ -237,7 +237,7 @@ pub fn unpack_bundle(data: &[u8]) -> Result { mod tests { use super::*; - /// The same check bundle.py's test makes: 3.10's gzip.compress output. + /// Python 3.10's gzip.compress output, which refs were defined by. #[test] fn packing_matches_python_310() { let mut data = b"{\"a\":\"".to_vec(); diff --git a/src/claude.rs b/src/claude.rs index 5fa38ff..5e298e6 100644 --- a/src/claude.rs +++ b/src/claude.rs @@ -1,4 +1,4 @@ -//! The Claude Code adapter, as in `loch/claude.py`: where sessions live, how +//! The Claude Code adapter: where sessions live, how //! their directory is named, and what a session's metadata is. use crate::json::{self, Value}; @@ -90,7 +90,7 @@ fn first_string(value: Option<&Value>) -> Option { } } -/// claude.py's `_records`: each line stripped, then parsed; dicts only. +/// Each line stripped, then parsed; dicts only. pub fn records(raw: &str) -> impl Iterator + '_ { raw.split('\n').filter_map(|line| { let line = py::strip(line); @@ -157,7 +157,7 @@ pub fn display_summary(text: Option<&str>) -> Option { pub fn read_session_meta(path: &str) -> Option { let meta = fs::metadata(path).ok()?; - // Replacing rather than strict, as claude.py now does: one undecodable + // Replacing rather than strict: one undecodable // byte must not take down a listing. let raw = py::decode_replace(&fs::read(path).ok()?); let file = path.rsplit('/').next().unwrap_or(path); diff --git a/src/cli.rs b/src/cli.rs index 10b0140..1b58073 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,4 +1,4 @@ -//! Every command, as in `loch/cli.py`: each builds one `Outcome` — payload +//! Every command: each builds one `Outcome` — payload //! and prose together — and `main` renders it. use crate::argparse::{Exit, Nargs, Parser}; @@ -33,7 +33,7 @@ pub fn json_requested() -> bool { pub enum Failure { Error(CommandError), Help(String), - /// What Python's uncaught exception would say: `internal` in JSON mode. + /// A bug rather than a failure a caller can act on: `internal`. Internal(String), } @@ -217,7 +217,7 @@ fn session_payload(meta: &SessionMeta) -> Value { }) } -/// Deliberately not index.py's stored shape: a storage format and a wire +/// Deliberately not index.rs's stored shape: a storage format and a wire /// contract change for different reasons. fn entry_payload(entry: &IndexEntry) -> Value { Value::Object(object! { @@ -269,7 +269,7 @@ pub fn command_list(argv: &[String]) -> Run { )) } -fn current_branch(cwd: &str) -> Option { +pub fn current_branch(cwd: &str) -> Option { let out = trace::git_unchecked(cwd, &["symbolic-ref", "--short", "HEAD"]); let branch = py::strip(&out); (!branch.is_empty()).then(|| branch.to_string()) diff --git a/src/format.rs b/src/format.rs index 01363c8..ba60324 100644 --- a/src/format.rs +++ b/src/format.rs @@ -1,4 +1,4 @@ -//! The loch format's ids and derived files, as in `loch/format.py`. Every id +//! The loch format's ids and derived files. Every id //! is a SHA-256 over `json::canonical` (RFC 8785, integers exact). use crate::json::{self, Map, Value}; diff --git a/src/hook.rs b/src/hook.rs index 47c8e4a..c36c00f 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -1,9 +1,9 @@ //! `loch hook`, run by Claude Code around every Bash call and at every stop — -//! the hook half of `loch/trace.py`. +//! the half of the commit links that runs live. //! -//! The pending-state file is shared across implementations — a session can -//! start its Bash call under one and finish it under the other while a machine -//! switches over — so its name and JSON shape must stay exactly Python's. +//! The pending-state file is the one piece of state a hook call leaves between +//! its two halves. A session can start a Bash call under one loch and finish it +//! under another while a machine upgrades, so keep its name and shape stable. use crate::git::{self, GitError}; use crate::json::{self, Map, Value}; diff --git a/src/index.rs b/src/index.rs index 4ad12f3..d927c83 100644 --- a/src/index.rs +++ b/src/index.rs @@ -1,4 +1,4 @@ -//! Store key layout and derived index entries, as in `loch/index.py`. +//! Store key layout and derived index entries. use crate::bundle::{unpack_bundle, Bundle, BundleSession}; use crate::json::{self, Value}; @@ -38,7 +38,7 @@ pub fn bundle_key(ref_: &str) -> String { format!("{}{}.loch", BUNDLES_PREFIX, ref_) } -fn ref_from_key(key: &str) -> String { +pub fn ref_from_key(key: &str) -> String { key[BUNDLES_PREFIX.len()..key.len() - ".loch".len()].into() } diff --git a/src/ingest.rs b/src/ingest.rs index 6a3b098..b7464e0 100644 --- a/src/ingest.rs +++ b/src/ingest.rs @@ -1,4 +1,4 @@ -//! Claude Code JSONL → loch turns, as in `loch/ingest.py` (the converter). +//! Claude Code JSONL → loch turns (the converter). //! //! Normalizing goes through `rewrite::compile`, the same single pass with the //! same guards restore uses, fed placeholders instead of another machine's @@ -22,11 +22,11 @@ pub fn converter() -> Map { } const PLACEHOLDER_PREFIX: &str = "{{loch:"; -const ESCAPE: &str = "{{loch:esc}}"; -const ROOT: &str = "{{loch:root}}"; -const HOME: &str = "{{loch:home}}"; -const ROOT_SLUG: &str = "{{loch:root-slug}}"; -const SESSION: &str = "{{loch:session}}"; +pub const ESCAPE: &str = "{{loch:esc}}"; +pub const ROOT: &str = "{{loch:root}}"; +pub const HOME: &str = "{{loch:home}}"; +pub const ROOT_SLUG: &str = "{{loch:root-slug}}"; +pub const SESSION: &str = "{{loch:session}}"; /// Record fields that place a record rather than say anything; excluded from /// the hashed payload of system and attachment turns. diff --git a/src/json.rs b/src/json.rs index f8d3102..4362a20 100644 --- a/src/json.rs +++ b/src/json.rs @@ -622,7 +622,7 @@ pub struct NotJson; /// RFC 8785, exactly as `format.canonical` writes it: keys by UTF-16 code /// unit, strings escaped as JSON.stringify does (a lone surrogate as /// `\uXXXX`), numbers as ECMAScript prints them — except that an integer -/// prints exactly at any size, the departure format.py documents. +/// prints exactly at any size, so a 63-bit id inside a tool result is kept. pub fn canonical(value: &Value) -> Result, NotJson> { let mut out = String::new(); write_canonical(&mut out, value)?; diff --git a/src/main.rs b/src/main.rs index c04ff5c..9aae08e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,6 @@ //! `loch`: one static binary for Ness, the VS Code extension and the Claude //! Code hooks to ship. - use loch::cli::{self, Failure}; use loch::output::{emit, emit_error, CommandError, Outcome, JSON_FLAG}; diff --git a/src/output.rs b/src/output.rs index 87714e0..d75c611 100644 --- a/src/output.rs +++ b/src/output.rs @@ -1,4 +1,4 @@ -//! The result envelope and its two renderings, as in `loch/output.py`. +//! The result envelope and its two renderings. use crate::json::{self, Map, Value}; use std::io::Write; diff --git a/src/redact.rs b/src/redact.rs index e4b3cfb..1854a76 100644 --- a/src/redact.rs +++ b/src/redact.rs @@ -1,4 +1,4 @@ -//! Secret scrubbing, as in `loch/redact.py` — best-effort pattern matching +//! Secret scrubbing — best-effort pattern matching //! and nothing more. The patterns are the Python ones with one translation: //! Python's `\s` (`str.isspace`, which includes U+001C..U+001F) is spelled out, //! since the `regex` crate's `\s` is Unicode White_Space and differs from it. @@ -31,7 +31,7 @@ use std::sync::OnceLock; /// The rule names, in priority order: anthropic-key before openai-key, which /// would otherwise claim the same `sk-` prefix. -const NAMES: [&str; 10] = [ +pub const NAMES: [&str; 10] = [ "aws-access-key", "github-token", "slack-token", @@ -285,7 +285,7 @@ pub fn summarize(counts: &IndexMap) -> String { mod tests { use super::*; - /// redact.py's one alternation, verbatim but for `\s`: the oracle. + /// The rules as one alternation, as the Python build ran them: the oracle. fn oracle() -> fancy_regex::Regex { let start = r"(? Vec { raw.split('\n') .filter(|line| !py::strip(line).is_empty()) diff --git a/test/conftest.py b/test/conftest.py deleted file mode 100644 index 7aeb3db..0000000 --- a/test/conftest.py +++ /dev/null @@ -1,8 +0,0 @@ -import pytest - - -@pytest.fixture(autouse=True) -def _no_claude_config_dir(monkeypatch: pytest.MonkeyPatch) -> None: - # Tests point HOME at a temporary directory; a CLAUDE_CONFIG_DIR inherited - # from the developer's shell would send them to the real one instead. - monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) diff --git a/test/equivalence.py b/test/equivalence.py deleted file mode 100644 index 1e9e1ea..0000000 --- a/test/equivalence.py +++ /dev/null @@ -1,382 +0,0 @@ -"""Shared machinery for holding the Rust build to the Python reference. - -Every scenario is built twice at the same path with pinned git dates and file -times, so commit hashes, note objects, the notes ref and session mtimes come -out byte-identical; one copy is driven by `python -m loch.cli`, the other by -the binary named in LOCH_RUST, and everything observable is compared: stdout, -stderr, exit status, and every file the run left behind. - -Two values are random by design — the id `restore --new-id` mints and the -fork `ask` creates — so v4 UUIDs are renamed in order of first appearance -before comparing. Fixture ids are deliberately not v4, so they never are. -""" - -import hashlib -import json -import os -import re -import shutil -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path -from typing import Any - -RUST = os.environ.get("LOCH_RUST") - -SESSION = "11111111-2222-3333-4444-555555555555" -# In the future, so the hook's "committed after the call began" bound admits -# commits made during a call; fixed, so their hashes are too. -NOW = "2031-01-01T00:00:00Z" -PAST = "2020-01-01T00:00:00Z" -MTIME = 1_800_000_000.123456 -EPOCH = "1800000000" - -GENERATED = re.compile( - rb"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}" -) - - -def implementation(name: str) -> list[str]: - if name == "py": - return [sys.executable, "-m", "loch.cli"] - assert RUST is not None - return [os.path.abspath(RUST)] - - -@dataclass -class Run: - stdout: bytes - stderr: bytes - status: int - - -class World: - """One scratch machine: a HOME, a repository, a store, an environment.""" - - def __init__(self, root: Path) -> None: - self.root = root - self.home = root / "home" - self.repo = root / "repo" - self.store = root / "store" - self.home.mkdir(parents=True) - bin_dir = root / "bin" - bin_dir.mkdir() - # `install --local` records `shutil.which("loch")`; both builds must - # find the same one. - (bin_dir / "loch").write_text("#!/bin/sh\n") - (bin_dir / "loch").chmod(0o755) - self.env = { - "PATH": f"{bin_dir}:{os.environ['PATH']}", - "HOME": str(self.home), - "LOCH_STORE": str(self.store), - "TMPDIR": str(root), - "GIT_CONFIG_GLOBAL": str(root / "gitconfig"), - "GIT_CONFIG_NOSYSTEM": "1", - "GIT_AUTHOR_NAME": "Test", - "GIT_AUTHOR_EMAIL": "test@example.com", - "GIT_COMMITTER_NAME": "Test", - "GIT_COMMITTER_EMAIL": "test@example.com", - "GIT_AUTHOR_DATE": NOW, - "GIT_COMMITTER_DATE": NOW, - "SOURCE_DATE_EPOCH": EPOCH, - "PYTHONPATH": str(Path(__file__).resolve().parent.parent), - } - - # -- git --------------------------------------------------------------- - - def git(self, *args: str, cwd: Path | None = None, date: str = NOW) -> str: - env = {**self.env, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} - return subprocess.run( - ["git", "-C", str(cwd or self.repo), *args], - capture_output=True, - text=True, - check=True, - env=env, - ).stdout.strip() - - def init(self, *extra: str) -> None: - self.repo.mkdir(exist_ok=True) - self.git("init", "-q", "-b", "main", *extra) - - def commit(self, message: str, cwd: Path | None = None, date: str = NOW) -> str: - self.git("commit", "-q", "--allow-empty", "-m", message, cwd=cwd, date=date) - return self.git("rev-parse", "HEAD", cwd=cwd) - - def commit_file(self, name: str, text: str, message: str, date: str = NOW) -> str: - path = self.repo / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text) - self.git("add", name) - self.git("commit", "-q", "-m", message, date=date) - return self.git("rev-parse", "HEAD") - - def note(self, commit: str, session: str, call: str) -> None: - body = json.dumps( - { - "loch": 1, - "agent": "claude-code", - "session": session, - "call": call, - "captured": "hook", - }, - sort_keys=True, - separators=(",", ":"), - ) - subprocess.run( - ["git", "-C", str(self.repo), "notes", "--ref", "refs/notes/loch"] - + ["add", "-f", "-m", body, commit], - check=True, - capture_output=True, - env=self.env, - ) - - # -- sessions ------------------------------------------------------------ - - def projects(self) -> Path: - return self.home / ".claude" / "projects" - - def session( - self, - cwd: str, - session_id: str, - records: list[Any], - directory: str | None = None, - raw: bytes = b"", - ) -> Path: - """A transcript filed as Claude files it, with a pinned mtime. Records - that are strings are written as-is, so a scenario can include lines - that aren't JSON.""" - encoded = directory or re.sub(r"[^a-zA-Z0-9]", "-", cwd) - folder = self.projects() / encoded - folder.mkdir(parents=True, exist_ok=True) - path = folder / f"{session_id}.jsonl" - lines = [r if isinstance(r, str) else json.dumps(r) for r in records] - path.write_bytes("\n".join(lines).encode() + b"\n" + raw) - os.utime(path, (MTIME, MTIME)) - return path - - # -- running ------------------------------------------------------------- - - def loch( - self, - impl: str, - *args: str, - stdin: Any = None, - env: dict[str, str] | None = None, - cwd: Path | None = None, - ) -> Run: - data = ( - stdin - if isinstance(stdin, bytes) - else b"" - if stdin is None - else json.dumps(stdin).encode() - ) - merged = {**self.env, **(env or {})} - merged = {k: v for k, v in merged.items() if v is not None} - result = subprocess.run( - [*implementation(impl), *args], - input=data, - capture_output=True, - env=merged, - cwd=str(cwd or self.root), - ) - return Run(result.stdout, result.stderr, result.returncode) - - def event(self, call: str | None = "toolu_1", **fields: Any) -> dict[str, Any]: - body: dict[str, Any] = { - "session_id": SESSION, - "cwd": str(self.repo), - "tool_name": "Bash", - "tool_input": {"command": "git commit -m work"}, - } - if call is not None: - body["tool_use_id"] = call - body.update(fields) - return body - - # -- observing ------------------------------------------------------------- - - def observe(self) -> dict[str, Any]: - """Every file the run can have left behind, keyed by path, with git's - own churn (objects, index, logs) left out in favour of the refs that - matter. The pending state's timestamp is reduced to its type, being - the one value that is the clock and nothing else.""" - seen: dict[str, Any] = {} - for path in sorted(self.root.rglob("*")): - relative = path.relative_to(self.root).as_posix() - parts = relative.split("/") - if ".git" in parts: - at = parts.index(".git") - inside = parts[at + 1 :] - keep = inside[:1] == ["loch"] or ( - inside[:1] == ["worktrees"] and "loch" in inside - ) - if not keep: - continue - if path.is_dir(): - seen[relative] = "dir" - continue - if "/loch/pending/" in f"/{relative}": - try: - state = json.loads(path.read_text()) - except ValueError: - state = path.read_text() - seen[relative] = ( - {"head": state.get("head"), "at": type(state.get("at")).__name__} - if isinstance(state, dict) - else state - ) - continue - seen[relative] = path.read_bytes() - for repo in {self.repo, *self.root.glob("wt*")}: - if (repo / ".git").exists(): - for ref in ("refs/notes/loch", "HEAD"): - seen[f"{repo.name}:{ref}"] = self._git_quiet( - repo, "rev-parse", "-q", "--verify", ref - ) - seen[f"{repo.name}:rewriteRef"] = self._git_quiet( - repo, "config", "--get", "notes.rewriteRef" - ) - return seen - - def _git_quiet(self, repo: Path, *args: str) -> str: - return subprocess.run( - ["git", "-C", str(repo), *args], - capture_output=True, - text=True, - env=self.env, - ).stdout.strip() - - -Scenario = Callable[[World, Callable[..., Run]], list[Run]] - - -class Renamer: - """Generated v4 UUIDs → `UUID-n`, numbered by first appearance.""" - - def __init__(self) -> None: - self.names: dict[bytes, bytes] = {} - - def __call__(self, data: bytes) -> bytes: - def name(match: re.Match[bytes]) -> bytes: - found = match.group(0) - if found not in self.names: - self.names[found] = f"UUID-{len(self.names) + 1}".encode() - return self.names[found] - - return GENERATED.sub(name, data) - - -def normalized( - runs: list[Run], seen: dict[str, Any] -) -> tuple[list[Any], dict[str, Any]]: - rename = Renamer() - out_runs = [ - {"stdout": rename(r.stdout), "stderr": rename(r.stderr), "status": r.status} - for r in runs - ] - out_seen: dict[str, Any] = {} - for key in sorted(seen, key=lambda k: rename(k.encode())): - value = seen[key] - if isinstance(value, bytes): - value = rename(value) - out_seen[rename(key.encode()).decode()] = value - return out_runs, out_seen - - -def digest_of(value: Any) -> str: - """What a failure may show: a hash, never transcript content.""" - if isinstance(value, bytes): - return hashlib.sha256(value).hexdigest()[:16] - return hashlib.sha256(repr(value).encode()).hexdigest()[:16] - - -def quiet_difference(py: Any, rs: Any) -> str: - """Where two observations part, by position and hash only: safe to print - when they were made from real transcripts.""" - py_runs, py_seen = py - rs_runs, rs_seen = rs - for index, (a, b) in enumerate(zip(py_runs, rs_runs)): - for stream in ("stdout", "stderr", "status"): - x, y = a[stream], b[stream] - if x != y: - if isinstance(x, bytes) and isinstance(y, bytes): - at = next( - (i for i, (p, q) in enumerate(zip(x, y)) if p != q), - min(len(x), len(y)), - ) - return f"run {index} {stream}: lengths {len(x)}/{len(y)}, first difference at byte {at}" - return f"run {index} {stream}: {x!r} != {y!r}" - only_py = sorted(set(py_seen) - set(rs_seen)) - only_rs = sorted(set(rs_seen) - set(py_seen)) - if only_py or only_rs: - return f"{len(only_py)} files only in py, {len(only_rs)} only in rs" - for key in py_seen: - if py_seen[key] != rs_seen[key]: - return f"{key}: py {digest_of(py_seen[key])} rs {digest_of(rs_seen[key])}" - return "no difference" - - -def first_difference(py: Any, rs: Any) -> str: - """Where two observations part, named by run index or file path. File - contents are reported by hash: a scenario's files are synthetic, but the - corpus checks share this and theirs are not.""" - py_runs, py_seen = py - rs_runs, rs_seen = rs - for index, (a, b) in enumerate(zip(py_runs, rs_runs)): - for stream in ("stdout", "stderr", "status"): - if a[stream] != b[stream]: - return f"run {index} {stream} differs:\n py: {a[stream]!r}\n rs: {b[stream]!r}" - if len(py_runs) != len(rs_runs): - return f"{len(py_runs)} runs against {len(rs_runs)}" - only_py = sorted(set(py_seen) - set(rs_seen)) - only_rs = sorted(set(rs_seen) - set(py_seen)) - if only_py or only_rs: - return f"files only in py: {only_py}; only in rs: {only_rs}" - for key in py_seen: - if py_seen[key] != rs_seen[key]: - a, b = py_seen[key], rs_seen[key] - if isinstance(a, bytes) and isinstance(b, bytes) and len(a) < 4000: - return f"{key} differs:\n py: {a!r}\n rs: {b!r}" - return f"{key} differs: py {digest_of(a)} rs {digest_of(b)}" - return "no difference" - - -def twin( - tmp_path: Path, - scenario: Scenario, - mix: tuple[str, str] | None = None, - quiet: bool = False, -) -> dict[str, Any]: - """Runs `scenario` once per implementation in identical worlds at the same - path, and asserts nothing observable differs. With `mix`, the second run - alternates implementations call by call — pre under one, post under the - other — which is what a machine switching over mid-session does. `quiet` - reports only hashes, for scenarios over real transcripts.""" - root = tmp_path / "world" - outcomes = [] - plans: list[tuple[str, ...]] = [("py",), ("rs",)] if mix is None else [("py",), mix] - raw_seen: list[dict[str, Any]] = [] - for plan in plans: - if root.exists(): - shutil.rmtree(root) - world = World(root) - calls = iter(range(10_000)) - - def loch( - *args: str, _w: World = world, _p: tuple[str, ...] = plan, **kw: Any - ) -> Run: - return _w.loch(_p[next(calls) % len(_p)], *args, **kw) - - runs = scenario(world, loch) - seen = world.observe() - raw_seen.append(seen) - outcomes.append(normalized(runs, seen)) - if outcomes[0] != outcomes[1]: - if quiet: - raise AssertionError(quiet_difference(outcomes[0], outcomes[1])) - raise AssertionError(first_difference(outcomes[0], outcomes[1])) - return raw_seen[0] diff --git a/test/test_bundle.py b/test/test_bundle.py deleted file mode 100644 index 074d9a9..0000000 --- a/test/test_bundle.py +++ /dev/null @@ -1,88 +0,0 @@ -import gzip -import hashlib - -import pytest - -from loch.bundle import ( - Bundle, - BundleOrigin, - BundleSession, - bundle_ref, - pack_bundle, - unpack_bundle, -) - - -def sample_bundle(git_branch: str | None = "main") -> Bundle: - return Bundle( - version=1, - agent="claude-code", - created_at="2026-08-14T13:27:07.373Z", - origin=BundleOrigin(home="/home/mike", platform="linux", hostname="box"), - sessions=[ - BundleSession( - session_id="abc", - cwd="/home/mike/proj", - git_branch=git_branch, - claude_version="1.0.99", - modified_at="2026-08-14T13:00:00.000Z", - transcript='{"cwd":"/home/mike/proj"}\n', - ) - ], - ) - - -def test_pack_round_trips() -> None: - bundle = sample_bundle() - assert unpack_bundle(pack_bundle(bundle)) == bundle - - -def test_pack_is_deterministic() -> None: - assert pack_bundle(sample_bundle()) == pack_bundle(sample_bundle()) - - -def test_ref_is_the_sha256_of_the_packed_bytes() -> None: - import hashlib - - packed = pack_bundle(sample_bundle()) - assert bundle_ref(packed) == hashlib.sha256(packed).hexdigest() - - -def test_absent_metadata_stays_absent_rather_than_null() -> None: - import gzip - import json - - raw = json.loads(gzip.decompress(pack_bundle(sample_bundle(git_branch=None)))) - assert "gitBranch" not in raw["sessions"][0] - assert ( - unpack_bundle(pack_bundle(sample_bundle(git_branch=None))) - .sessions[0] - .git_branch - is None - ) - - -def test_rejects_an_unsupported_version() -> None: - packed = pack_bundle( - Bundle( - version=2, - agent="claude-code", - created_at="", - origin=BundleOrigin(home="", platform="", hostname=""), - sessions=[], - ) - ) - with pytest.raises(ValueError, match="unsupported bundle version 2"): - unpack_bundle(packed) - - -def test_packing_matches_python_310_on_every_platform() -> None: - from loch.bundle import gzip_deterministic - - data = b'{"a":"' + b"xyz" * 5000 + b'"}' - packed = gzip_deterministic(data) - # What 3.10's gzip.compress(data, 9, mtime=0) produced, OS byte 255 - # included; 3.12 on macOS writes 19 there and Linux 3. - assert packed[:10].hex() == "1f8b08000000000002ff" - assert hashlib.sha256(packed).hexdigest()[:16] == "405552bff938ef58" - assert gzip.decompress(packed) == data diff --git a/test/test_claude.py b/test/test_claude.py deleted file mode 100644 index 0cbb619..0000000 --- a/test/test_claude.py +++ /dev/null @@ -1,278 +0,0 @@ -import json -import os -from pathlib import Path - -import pytest - -from loch.claude import ( - SUMMARY_LIMIT, - encode_cwd, - encode_path, - list_sessions, - projects_dir, - read_session_meta, - resolve_cwd, - session_dir_for, - transcript_cwds, - transcript_path_for, -) -from loch.redact import Redaction, RedactionError - -SECRET = "ghp_" + "a1B2c3D4e5" * 4 - - -def write_session( - home: Path, - cwd: str, - session_id: str, - git_branch: str | None = "main", - summary: str = "hello", -) -> Path: - directory = Path(session_dir_for(cwd, str(home))) - directory.mkdir(parents=True, exist_ok=True) - record: dict[str, object] = { - "type": "user", - "sessionId": session_id, - "cwd": cwd, - "version": "1.0.99", - "message": {"role": "user", "content": summary}, - } - if git_branch is not None: - record["gitBranch"] = git_branch - path = directory / f"{session_id}.jsonl" - path.write_text(json.dumps(record) + "\n", encoding="utf-8") - return path - - -def test_encodes_every_non_alphanumeric_character() -> None: - assert encode_path("/Users/mike/my_proj.v2") == "-Users-mike-my-proj-v2" - - -def test_resolves_symlinks_before_encoding(tmp_path: Path) -> None: - real = tmp_path / "real" - real.mkdir() - link = tmp_path / "link" - link.symlink_to(real) - - assert resolve_cwd(str(link)) == os.path.realpath(str(real)) - assert encode_cwd(str(link)) == encode_path(os.path.realpath(str(real))) - - -def test_keeps_a_path_that_does_not_exist(tmp_path: Path) -> None: - missing = str(tmp_path / "nope") - assert resolve_cwd(missing) == missing - - -def test_transcript_path_lives_under_the_encoded_project_dir(tmp_path: Path) -> None: - path = transcript_path_for("/Users/mike/proj", "abc", str(tmp_path)) - assert path == str( - tmp_path / ".claude" / "projects" / "-Users-mike-proj" / "abc.jsonl" - ) - - -def test_reads_metadata_from_a_transcript(tmp_path: Path) -> None: - path = write_session(tmp_path, "/Users/mike/proj", "abc", summary="do the thing") - - meta = read_session_meta(str(path)) - - assert meta is not None - assert meta.session_id == "abc" - assert meta.cwd == "/Users/mike/proj" - assert meta.git_branch == "main" - assert meta.claude_version == "1.0.99" - assert meta.summary == "do the thing" - assert meta.modified_at.endswith("Z") - - -def test_a_secret_in_the_first_message_never_reaches_the_summary( - tmp_path: Path, -) -> None: - path = write_session( - tmp_path, "/Users/mike/proj", "abc", summary=f"deploy with {SECRET}" - ) - - meta = read_session_meta(str(path)) - - assert meta is not None - assert meta.summary == "deploy with [REDACTED:github-token]" - - -def test_a_secret_is_scrubbed_before_the_summary_is_cut_to_length( - tmp_path: Path, -) -> None: - """Truncating first would leave a fragment too short for any rule to match, - so the tail of a secret would ride along unredacted.""" - padding = "x" * (SUMMARY_LIMIT - 11) + " " - path = write_session( - tmp_path, "/Users/mike/proj", "abc", summary=f"{padding}{SECRET}" - ) - - meta = read_session_meta(str(path)) - - assert meta is not None - assert len(meta.summary or "") == SUMMARY_LIMIT - assert "ghp_" not in (meta.summary or "") - - -def test_a_summary_that_will_not_come_clean_is_dropped_whole( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - def refuse(text: str) -> Redaction: - raise RedactionError("still matching") - - monkeypatch.setattr("loch.claude.redact", refuse) - path = write_session(tmp_path, "/Users/mike/proj", "abc", summary="anything") - - meta = read_session_meta(str(path)) - - assert meta is not None - assert meta.summary == "[REDACTED]" - - -def test_ignores_a_transcript_with_no_cwd(tmp_path: Path) -> None: - path = tmp_path / "empty.jsonl" - path.write_text('{"type":"user"}\n', encoding="utf-8") - assert read_session_meta(str(path)) is None - - -# A session that moved: it began in the main repo and continued in a worktree -# after the agent switched, so the records from before the move stay in the file -# and the first several hundred name a directory the session has left. Claude -# files the transcript under the cwd it ended in. -MAIN = "/Users/mike/apps/harness" -WORKTREE = "/Users/mike/apps/harness-worktrees/feat/send" - - -def write_moved_session( - home: Path, - session_id: str = "abc", - left: str = MAIN, - filed_under: str = WORKTREE, - stale: int = 300, -) -> Path: - def record(cwd: str, branch: str, text: str) -> str: - return json.dumps( - { - "type": "user", - "sessionId": session_id, - "cwd": cwd, - "gitBranch": branch, - "version": "1.0.99", - "message": {"role": "user", "content": text}, - } - ) - - directory = Path(session_dir_for(filed_under, str(home))) - directory.mkdir(parents=True, exist_ok=True) - lines = [record(left, "main", "started here") for _ in range(stale)] - lines.append(record(filed_under, "feat/send", "moved here")) - path = directory / f"{session_id}.jsonl" - path.write_text("\n".join(lines) + "\n", encoding="utf-8") - return path - - -def test_prefers_the_cwd_the_project_directory_is_named_after(tmp_path: Path) -> None: - """The first record's cwd is stale, and the live one first appears well past - any fixed scan window, so the directory is the only disambiguator.""" - path = write_moved_session(tmp_path) - - meta = read_session_meta(str(path)) - - assert meta is not None - assert meta.cwd == WORKTREE - assert meta.other_cwds == (MAIN,) - - -def test_branch_is_read_alongside_the_chosen_cwd(tmp_path: Path) -> None: - """A branch from a directory the session has left is the same defect as the - stale cwd, and it decides which index entry the bundle is filed under.""" - path = write_moved_session(tmp_path) - - meta = read_session_meta(str(path)) - - assert meta is not None - assert meta.git_branch == "feat/send" - - -def test_a_moved_session_is_listed_under_the_branch_it_ended_on( - tmp_path: Path, -) -> None: - write_moved_session(tmp_path) - - assert [ - meta.session_id - for meta in list_sessions(cwd=WORKTREE, branch="feat/send", home=str(tmp_path)) - ] == ["abc"] - assert list_sessions(cwd=WORKTREE, branch="main", home=str(tmp_path)) == [] - - -def test_falls_back_to_the_first_cwd_when_the_directory_matches_nothing( - tmp_path: Path, -) -> None: - """A hand-copied transcript or a renamed directory keeps the old behaviour - rather than dropping the session.""" - directory = tmp_path / "unrelated" - directory.mkdir(parents=True) - path = directory / "abc.jsonl" - path.write_text( - "\n".join( - [ - json.dumps({"cwd": MAIN, "gitBranch": "main"}), - json.dumps({"cwd": WORKTREE, "gitBranch": "feat/send"}), - ] - ), - encoding="utf-8", - ) - - meta = read_session_meta(str(path)) - - assert meta is not None - assert meta.cwd == MAIN - assert meta.other_cwds == (WORKTREE,) - - -def test_transcript_cwds_counts_only_the_top_level_field() -> None: - """`"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( - [ - json.dumps( - {"cwd": MAIN, "toolUseResult": json.dumps({"cwd": "/elsewhere"})} - ), - json.dumps({"cwd": MAIN}), - "", - "not json at all", - ] - ) - - assert transcript_cwds(raw) == {MAIN: 2} - - -def test_lists_and_filters_sessions(tmp_path: Path) -> None: - cwd = "/Users/mike/proj" - write_session(tmp_path, cwd, "one", git_branch="main") - write_session(tmp_path, cwd, "two", git_branch="feature/x") - - every = list_sessions(cwd=cwd, home=str(tmp_path)) - assert {meta.session_id for meta in every} == {"one", "two"} - - by_branch = list_sessions(cwd=cwd, branch="feature/x", home=str(tmp_path)) - assert [meta.session_id for meta in by_branch] == ["two"] - - by_id = list_sessions(cwd=cwd, session_id="one", home=str(tmp_path)) - assert [meta.session_id for meta in by_id] == ["one"] - - assert list_sessions(cwd="/Users/mike/other", home=str(tmp_path)) == [] - - -def test_claude_config_dir_replaces_the_home_default( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setenv("HOME", str(tmp_path / "home")) - monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "work-account")) - assert projects_dir() == str(tmp_path / "work-account" / "projects") - # An explicit home names some other machine's layout, where this - # machine's variable means nothing. - assert projects_dir("/home/other") == "/home/other/.claude/projects" - monkeypatch.setenv("CLAUDE_CONFIG_DIR", "") - assert projects_dir() == str(tmp_path / "home" / ".claude" / "projects") diff --git a/test/test_cli.py b/test/test_cli.py deleted file mode 100644 index df8bf78..0000000 --- a/test/test_cli.py +++ /dev/null @@ -1,1187 +0,0 @@ -import importlib.metadata -import json -import re -import sys -from pathlib import Path -from typing import Any - -import pytest -from test_claude import SECRET, write_moved_session, write_session - -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( - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - home: Path, - *argv: str, -) -> tuple[str, str, int | None]: - monkeypatch.setenv("HOME", str(home)) - monkeypatch.setattr("sys.argv", ["loch", *argv]) - code: int | None = None - try: - main() - except SystemExit as exit_signal: - code = int(exit_signal.code or 0) - captured = capsys.readouterr() - return captured.out, captured.err, code - - -def invoke_json( - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - home: Path, - *argv: str, -) -> tuple[dict[str, Any], str, int | None]: - """Asserts the contract a consumer depends on: stdout is one JSON document - and nothing else. Prose leaking from any helper fails the parse.""" - out, err, code = invoke(monkeypatch, capsys, home, *argv) - assert out.count("\n") == 1 - document = json.loads(out) - assert document["schema"] == 1 - return document, err, code - - -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("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("loch") - - out, _, code = invoke(monkeypatch, capsys, tmp_path, "--version") - assert (out, code) == (f"loch {installed}\n", None) - - document, _, code = invoke_json( - monkeypatch, capsys, tmp_path, "--version", "--json" - ) - assert (document["command"], document["ok"], code) == ("version", True, None) - assert document["version"] == installed - - -def test_version_reports_a_source_checkout_that_was_never_installed( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - def absent(name: str) -> str: - raise importlib.metadata.PackageNotFoundError(name) - - monkeypatch.setattr(importlib.metadata, "version", absent) - document, _, _ = invoke_json(monkeypatch, capsys, tmp_path, "--version", "--json") - assert document["version"] == "unknown" - - -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 == "loch: unknown command 'bogus' (try: loch help)\n" - assert code == 1 - - -def test_list_reports_sessions( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - write_session(home, str(project), "abc", summary="do the thing") - - out, _, _ = invoke(monkeypatch, capsys, home, "list", "--cwd", str(project)) - - assert "1 session(s) for" in out - assert "abc" in out - assert "[main] do the thing" in out - - -def test_list_reports_nothing_for_an_unknown_cwd( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - out, _, _ = invoke( - monkeypatch, capsys, tmp_path / "home", "list", "--cwd", str(tmp_path) - ) - assert out.startswith("no claude-code sessions found for") - - -def test_save_then_restore_onto_another_machine( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - origin_home = tmp_path / "origin-home" - origin_project = tmp_path / "origin" / "proj" - origin_project.mkdir(parents=True) - store = tmp_path / "store" - - transcript = origin_home / "note.txt" - write_session(origin_home, str(origin_project), "abc") - session_path = Path( - transcript_path_for(str(origin_project), "abc", str(origin_home)) - ) - session_path.write_text( - json.dumps( - { - "type": "user", - "sessionId": "abc", - "cwd": str(origin_project.resolve()), - "gitBranch": "main", - "version": "1.0.99", - "message": {"role": "user", "content": "read " + str(transcript)}, - } - ) - + "\n", - encoding="utf-8", - ) - - out, _, _ = invoke( - monkeypatch, - capsys, - origin_home, - "save", - "--cwd", - str(origin_project), - "--store", - str(store), - ) - assert "packed abc [main]" in out - ref = re.search(r"^ref ([0-9a-f]{64})$", out, re.M) - assert ref is not None - assert (store / "bundles" / f"{ref.group(1)}.loch").exists() - assert (store / "index" / "branch" / "main" / ref.group(1)).exists() - - target_home = tmp_path / "target-home" - target_project = tmp_path / "target" / "work" / "proj" - target_project.mkdir(parents=True) - - out, _, _ = invoke( - monkeypatch, - capsys, - target_home, - "restore", - ref.group(1), - "--into", - str(target_project), - "--store", - str(store), - ) - assert "restored abc [main]" in out - assert f"cd {target_project.resolve()} && claude --resume abc" in out - - restored = Path(transcript_path_for(str(target_project), "abc", str(target_home))) - body = restored.read_text(encoding="utf-8") - assert str(target_project.resolve()) in body - assert str(origin_project.resolve()) not in body - assert str(origin_home) not in body - assert str(target_home / "note.txt") in body - - -def test_save_redacts_secrets_without_touching_the_local_transcript( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - store = tmp_path / "store" - secret = "AKIAZZZZZZZZEXAMPLE0" - session_path = write_session( - home, str(project), "abc", summary=f"ran env, saw {secret}" - ) - - out, _, _ = invoke( - monkeypatch, capsys, home, "save", "--cwd", str(project), "--store", str(store) - ) - - assert "redacted 1 secret (aws-access-key ×1)" in out - assert secret not in out - assert secret in session_path.read_text(encoding="utf-8") - - ref = re.search(r"^ref ([0-9a-f]{64})$", out, re.M) - assert ref is not None - bundle = unpack_bundle((store / "bundles" / f"{ref.group(1)}.loch").read_bytes()) - assert secret not in bundle.sessions[0].transcript - assert "[REDACTED:aws-access-key]" in bundle.sessions[0].transcript - - -def test_restore_skips_an_existing_session_unless_forced( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - store = tmp_path / "store" - write_session(home, str(project), "abc") - - out, _, _ = invoke( - monkeypatch, capsys, home, "save", "--cwd", str(project), "--store", str(store) - ) - ref = re.search(r"^ref ([0-9a-f]{64})$", out, re.M) - assert ref is not None - - _, err, code = invoke( - monkeypatch, - capsys, - home, - "restore", - ref.group(1), - "--into", - str(project), - "--store", - str(store), - ) - assert "skipped abc (already exists; --force to overwrite)" in err - assert err.endswith("loch: nothing restored\n") - assert code == 1 - - out, _, _ = invoke( - monkeypatch, - capsys, - home, - "restore", - ref.group(1), - "--into", - str(project), - "--store", - str(store), - "--force", - ) - assert "restored abc [main]" in out - - -def test_restore_with_a_new_id_rewrites_filename_and_records( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - store = tmp_path / "store" - write_session(home, str(project), "abc") - - out, _, _ = invoke( - monkeypatch, capsys, home, "save", "--cwd", str(project), "--store", str(store) - ) - ref = re.search(r"^ref ([0-9a-f]{64})$", out, re.M) - assert ref is not None - - out, _, _ = invoke( - monkeypatch, - capsys, - home, - "restore", - ref.group(1), - "--into", - str(project), - "--store", - str(store), - "--new-id", - ) - - directory = Path(session_dir_for(str(project), str(home))) - minted = [path for path in directory.glob("*.jsonl") if path.stem != "abc"] - assert len(minted) == 1 - record = json.loads(minted[0].read_text(encoding="utf-8").splitlines()[0]) - assert record["sessionId"] == minted[0].stem - - -def test_save_fails_when_nothing_matches( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - _, err, code = invoke( - monkeypatch, - capsys, - tmp_path / "home", - "save", - "--cwd", - str(tmp_path), - "--store", - str(tmp_path / "store"), - ) - assert err.startswith("loch: no claude-code sessions found for") - assert code == 1 - - -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 == "loch: restore requires a bundle ref\n" - assert code == 1 - - -def test_restore_reports_an_unreadable_ref( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - _, err, code = invoke( - monkeypatch, capsys, tmp_path, "restore", "deadbeef", "--store", str(tmp_path) - ) - assert err.startswith("loch: could not read deadbeef from") - assert code == 1 - - -def save_two_branches( - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - home: Path, - project: Path, - store: Path, -) -> str: - project.mkdir(parents=True, exist_ok=True) - write_session(home, str(project), "abc", git_branch="main") - write_session(home, str(project), "def", git_branch="feature/foo") - - out, _, _ = invoke( - monkeypatch, capsys, home, "save", "--cwd", str(project), "--store", str(store) - ) - ref = re.search(r"^ref ([0-9a-f]{64})$", out, re.M) - assert ref is not None - assert "indexed under [feature/foo], [main]" in out - return ref.group(1) - - -def test_list_remote_finds_a_bundle_by_branch( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - ref = save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - - out, _, _ = invoke( - monkeypatch, - capsys, - home, - "list", - "--remote", - "--branch", - "feature/foo", - "--store", - str(store), - ) - assert "1 bundle(s) for [feature/foo]" in out - assert ref in out - assert "1 session(s)" in out - assert "claude 1.0.99" in out - - out, _, _ = invoke( - monkeypatch, - capsys, - home, - "list", - "--remote", - "--branch", - "nope", - "--store", - str(store), - ) - assert out.startswith("no bundles for [nope] in") - - -def test_list_remote_defaults_to_the_branch_you_are_on( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - ref = save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - monkeypatch.setattr("loch.cli.current_branch", lambda cwd: "feature/foo") - - out, _, _ = invoke( - monkeypatch, capsys, home, "list", "--remote", "--store", str(store) - ) - - assert "1 bundle(s) for [feature/foo]" in out - assert ref in out - - -def test_list_remote_all_shows_every_branch( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - - out, _, _ = invoke( - monkeypatch, capsys, home, "list", "--all", "--store", str(store) - ) - - assert out.startswith("1 bundle(s) in") - assert "[feature/foo]" in out - assert "[main]" in out - - -def test_delete_removes_the_bundle_and_its_entries( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - ref = save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - - out, _, _ = invoke(monkeypatch, capsys, home, "delete", ref, "--store", str(store)) - assert f"removed bundles/{ref}.loch" in out - assert f"removed index/branch/feature%2Ffoo/{ref}" in out - - out, _, _ = invoke( - monkeypatch, capsys, home, "list", "--all", "--store", str(store) - ) - assert out.startswith("no bundles in") - - _, err, code = invoke( - monkeypatch, capsys, home, "restore", ref, "--store", str(store) - ) - assert err.startswith(f"loch: could not read {ref} from") - assert code == 1 - - -def test_delete_reports_a_ref_that_is_not_there( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - _, err, code = invoke( - monkeypatch, capsys, tmp_path, "delete", "deadbeef", "--store", str(tmp_path) - ) - assert err.startswith("loch: could not delete deadbeef from") - assert code == 1 - - -def test_reindex_rebuilds_a_wiped_index( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - ref = save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - - for entry in (store / "index").rglob("*"): - if entry.is_file(): - entry.unlink() - - out, _, _ = invoke(monkeypatch, capsys, home, "reindex", "--store", str(store)) - assert "scanned 1 bundle(s) in" in out - assert "wrote 2 index entries, removed 0 stale" in out - - out, _, _ = invoke( - monkeypatch, capsys, home, "list", "--all", "--store", str(store) - ) - assert ref in out - assert "[feature/foo]" in out - assert "[main]" in out - - -def test_json_list_emits_raw_values_not_formatted_columns( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - write_session(home, str(project), "abc", summary="do the thing") - - document, err, code = invoke_json( - monkeypatch, capsys, home, "list", "--json", "--cwd", str(project) - ) - - assert (document["ok"], document["command"], code, err) == (True, "list", None, "") - assert document["remote"] is False - (session,) = document["sessions"] - assert session["sessionId"] == "abc" - assert session["branch"] == "main" - assert isinstance(session["bytes"], int) - assert re.fullmatch(r".*\dZ", session["modifiedAt"]) - - -def test_json_list_carries_a_scrubbed_summary_in_both_renderings( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - """The summary is the only transcript content either rendering prints, and - it reaches a picker row and a pasted bug report without a `save` in between.""" - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - write_session(home, str(project), "abc", summary=f"deploy with {SECRET}") - - document, _, _ = invoke_json( - monkeypatch, capsys, home, "list", "--json", "--cwd", str(project) - ) - out, _, _ = invoke(monkeypatch, capsys, home, "list", "--cwd", str(project)) - - assert document["sessions"][0]["summary"] == "deploy with [REDACTED:github-token]" - assert SECRET not in out - - -def test_json_list_flag_is_accepted_before_the_command( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - write_session(home, str(project), "abc") - - document, _, _ = invoke_json( - monkeypatch, capsys, home, "--json", "list", "--cwd", str(project) - ) - - assert [session["sessionId"] for session in document["sessions"]] == ["abc"] - - -def test_json_list_finding_nothing_is_an_empty_result_not_an_error( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - document, _, code = invoke_json( - monkeypatch, - capsys, - tmp_path / "home", - "list", - "--json", - "--cwd", - str(tmp_path), - ) - - assert document["ok"] is True - assert document["sessions"] == [] - assert code is None - - -def test_json_list_remote_finding_nothing_is_an_empty_result_not_an_error( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - - document, _, code = invoke_json( - monkeypatch, - capsys, - home, - "list", - "--json", - "--remote", - "--branch", - "nope", - "--store", - str(store), - ) - - assert document["ok"] is True - assert document["entries"] == [] - assert document["bundles"] == 0 - assert code is None - - -def test_json_list_remote_reports_entries_by_dimension( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - ref = save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - - document, _, _ = invoke_json( - monkeypatch, capsys, home, "list", "--json", "--all", "--store", str(store) - ) - - assert document["remote"] is True - assert document["all"] is True - assert document["bundles"] == 1 - assert {(entry["dimension"], entry["value"]) for entry in document["entries"]} == { - ("branch", "main"), - ("branch", "feature/foo"), - } - assert all(entry["ref"] == ref for entry in document["entries"]) - assert all(isinstance(entry["bytes"], int) for entry in document["entries"]) - - -def test_json_save_reports_the_ref_and_redaction_counts_without_the_match( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - store = tmp_path / "store" - secret = "AKIAZZZZZZZZEXAMPLE0" - write_session(home, str(project), "abc", summary=f"ran env, saw {secret}") - - document, _, _ = invoke_json( - monkeypatch, - capsys, - home, - "save", - "--json", - "--cwd", - str(project), - "--store", - str(store), - ) - - assert re.fullmatch(r"[0-9a-f]{64}", document["ref"]) - assert ( - document["bytes"] - == (store / "bundles" / f"{document['ref']}.loch").stat().st_size - ) - assert document["store"] == str(store) - assert document["redacted"] == 1 - (session,) = document["sessions"] - assert session["sessionId"] == "abc" - assert session["branch"] == "main" - assert session["redactions"] == {"aws-access-key": 1} - assert document["indexed"] == [ - { - "dimension": "branch", - "value": "main", - "key": f"index/branch/main/{document['ref']}", - } - ] - assert secret not in json.dumps(document) - - -def test_json_save_reports_every_branch_it_indexed( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - store = tmp_path / "store" - write_session(home, str(project), "abc", git_branch="main") - write_session(home, str(project), "def", git_branch="feature/foo") - - document, _, _ = invoke_json( - monkeypatch, - capsys, - home, - "save", - "--json", - "--cwd", - str(project), - "--store", - str(store), - ) - - assert {entry["value"] for entry in document["indexed"]} == {"main", "feature/foo"} - assert {session["sessionId"] for session in document["sessions"]} == {"abc", "def"} - assert document["redacted"] == 0 - - -def test_json_restore_reports_per_session_status_and_resume_commands( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - origin_home = tmp_path / "origin-home" - origin_project = tmp_path / "origin" / "proj" - origin_project.mkdir(parents=True) - store = tmp_path / "store" - write_session(origin_home, str(origin_project), "abc") - - saved, _, _ = invoke_json( - monkeypatch, - capsys, - origin_home, - "save", - "--json", - "--cwd", - str(origin_project), - "--store", - str(store), - ) - - target_home = tmp_path / "target-home" - target_project = tmp_path / "target" / "proj" - target_project.mkdir(parents=True) - - document, err, code = invoke_json( - monkeypatch, - capsys, - target_home, - "restore", - "--json", - saved["ref"], - "--into", - str(target_project), - "--store", - str(store), - ) - - assert (document["ok"], code, err) == (True, None, "") - assert document["cwd"] == str(target_project.resolve()) - assert document["origin"]["home"] == str(origin_home) - (session,) = document["sessions"] - assert session["status"] == "restored" - assert session["sessionId"] == "abc" - assert session["originSessionId"] == "abc" - assert session["residualOriginPaths"] == [] - assert session["resumeCommand"] == ( - f"cd {target_project.resolve()} && claude --resume abc" - ) - assert Path(session["path"]).read_text(encoding="utf-8") - - -def test_json_restore_reports_residual_origin_paths( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - store = tmp_path / "store" - write_session(home, str(project), "abc") - - saved, _, _ = invoke_json( - monkeypatch, - capsys, - home, - "save", - "--json", - "--cwd", - str(project), - "--store", - str(store), - ) - - # Restoring below the origin cwd leaves it a substring of the target, so - # the rewritten transcript still mentions a path from the origin machine. - nested = project / "nested" - nested.mkdir() - document, _, _ = invoke_json( - monkeypatch, - capsys, - home, - "restore", - "--json", - saved["ref"], - "--into", - str(nested), - "--store", - str(store), - ) - - (session,) = document["sessions"] - assert session["residualOriginPaths"] == [str(project.resolve())] - - -def test_a_moved_session_is_saved_and_restored_from_the_cwd_it_ended_in( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - """The whole failure, end to end. A session that began in the main repo and - moved into a worktree used to be saved under the repo it had left, which - keyed the rewrite on the wrong cwd: every worktree record then declined the - cwd pair, fell through to the home pair, and landed on a well-formed path - that exists nowhere. residualOriginPaths stayed empty throughout, which is - why foreignCwds is the field a caller can gate on.""" - origin_home = tmp_path / "origin-home" - main = origin_home / "apps" / "harness" - worktree = origin_home / "apps" / "harness-worktrees" / "feat" / "send" - worktree.mkdir(parents=True) - main.mkdir(parents=True) - store = tmp_path / "store" - write_moved_session(origin_home, "abc", str(main), str(worktree), stale=300) - - saved, _, _ = invoke_json( - monkeypatch, - capsys, - origin_home, - "save", - "--json", - "--cwd", - str(worktree), - "--store", - str(store), - ) - - (packed,) = saved["sessions"] - assert packed["cwd"] == str(worktree) - assert packed["branch"] == "feat/send" - assert [entry["value"] for entry in saved["indexed"]] == ["feat/send"] - - target_home = tmp_path / "target-home" - target = target_home / "apps" / "harness-worktrees" / "feat" / "send" - target.mkdir(parents=True) - - document, err, _ = invoke_json( - monkeypatch, - capsys, - target_home, - "restore", - "--json", - saved["ref"], - "--into", - str(target), - "--store", - str(store), - ) - - (session,) = document["sessions"] - assert session["status"] == "restored" - assert err == "" - - restored = Path(session["path"]).read_text(encoding="utf-8") - assert transcript_cwds(restored)[str(target)] == 1 - # The records from before the move name a genuinely different directory, so - # no single target cwd can satisfy them. They are reported, not hidden. - assert session["residualOriginPaths"] == [] - assert session["foreignCwds"] == { - str(main): {"count": 300, "restored": str(target_home / "apps" / "harness")} - } - - -def test_json_restore_reports_a_skip_as_status_not_as_stderr_prose( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - store = tmp_path / "store" - write_session(home, str(project), "abc") - - saved, _, _ = invoke_json( - monkeypatch, - capsys, - home, - "save", - "--json", - "--cwd", - str(project), - "--store", - str(store), - ) - - document, err, code = invoke_json( - monkeypatch, - capsys, - home, - "restore", - "--json", - saved["ref"], - "--into", - str(project), - "--store", - str(store), - ) - - assert (document["ok"], document["code"], code) == (False, "nothing-restored", 1) - assert err == "" - (session,) = document["sessions"] - assert session["status"] == "skipped" - assert session["resumeCommand"] is None - assert session["path"] == transcript_path_for(str(project), "abc", str(home)) - - -def test_json_delete_reports_the_keys_it_removed( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - ref = save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - - document, _, code = invoke_json( - monkeypatch, capsys, home, "delete", "--json", ref, "--store", str(store) - ) - - assert (document["ok"], code) == (True, None) - assert document["ref"] == ref - assert set(document["removed"]) == { - f"bundles/{ref}.loch", - f"index/branch/main/{ref}", - f"index/branch/feature%2Ffoo/{ref}", - } - - -def test_json_reindex_reports_what_it_scanned_and_wrote( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - store = tmp_path / "store" - save_two_branches(monkeypatch, capsys, home, tmp_path / "proj", store) - - for entry in (store / "index").rglob("*"): - if entry.is_file(): - entry.unlink() - - document, _, _ = invoke_json( - monkeypatch, capsys, home, "reindex", "--json", "--store", str(store) - ) - - assert (document["bundles"], document["entries"], document["removed"]) == (1, 2, 0) - assert document["store"] == str(store) - - -def test_json_failure_is_still_one_parseable_document_on_stdout( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - document, err, code = invoke_json( - monkeypatch, - capsys, - tmp_path / "home", - "save", - "--json", - "--cwd", - str(tmp_path), - "--store", - str(tmp_path / "store"), - ) - - assert (document["ok"], document["code"], code) == (False, "no-sessions", 1) - assert document["error"].startswith("no claude-code sessions found for") - assert err == "" - - -def test_json_separates_a_ref_that_is_absent_from_a_store_that_did_not_answer( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - """The distinction a consumer acts on: an absent ref is terminal, an - unreachable store is worth retrying.""" - document, _, code = invoke_json(monkeypatch, capsys, tmp_path, "restore", "--json") - assert (document["code"], code) == ("missing-ref", 1) - - for command in ("restore", "delete"): - document, _, code = invoke_json( - monkeypatch, - capsys, - tmp_path, - command, - "--json", - "deadbeef", - "--store", - str(tmp_path / "store"), - ) - assert (document["code"], code) == ("bundle-not-found", 1) - - # A file where the store's directory should be: the store cannot answer at - # all, which is a different failure from the object being absent. - blocked = tmp_path / "blocked" - blocked.write_text("not a store", encoding="utf-8") - document, _, code = invoke_json( - monkeypatch, - capsys, - tmp_path, - "restore", - "--json", - "deadbeef", - "--store", - str(blocked), - ) - assert (document["code"], code) == ("store-unreachable", 1) - - -def test_json_separates_an_uninstalled_sdk_from_a_store_that_did_not_answer( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - """A default install has no boto3, and telling a caller to retry a network - problem when the fix is an install is the wrong affordance.""" - monkeypatch.setitem(sys.modules, "boto3", None) - document, _, code = invoke_json( - monkeypatch, - capsys, - tmp_path, - "list", - "--json", - "--remote", - "--store", - "s3://sessions/prefix", - ) - assert (document["code"], code) == ("s3-extra-missing", 1) - 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("loch.store.S3Store._client", refuse) - document, _, code = invoke_json( - monkeypatch, - capsys, - tmp_path, - "list", - "--json", - "--remote", - "--store", - "s3://sessions/prefix", - ) - assert (document["code"], code) == ("store-unreachable", 1) - - -def test_json_reports_a_bundle_that_arrived_but_will_not_unpack( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - store = tmp_path / "store" - bundles = store / "bundles" - bundles.mkdir(parents=True) - (bundles / "deadbeef.loch").write_bytes(b"not a gzip stream") - - document, _, code = invoke_json( - monkeypatch, - capsys, - tmp_path, - "restore", - "--json", - "deadbeef", - "--store", - str(store), - ) - - assert (document["code"], code) == ("bundle-unreadable", 1) - - -def test_json_reports_an_unknown_command_and_a_bad_flag( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - document, err, code = invoke_json(monkeypatch, capsys, tmp_path, "--json", "bogus") - assert (document["command"], document["code"], code) == ( - "bogus", - "unknown-command", - 1, - ) - assert err == "" - - document, err, code = invoke_json( - monkeypatch, capsys, tmp_path, "list", "--json", "--bogus" - ) - assert (document["command"], document["code"], code) == ("list", "usage", 2) - assert err == "" - - -def test_json_help_is_a_document_rather_than_the_usage_block( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - document, _, code = invoke_json(monkeypatch, capsys, tmp_path, "--json") - assert (document["command"], document["ok"], code) == ("help", True, None) - assert document["usage"].startswith("loch — save and restore") - - document, _, code = invoke_json( - monkeypatch, capsys, tmp_path, "save", "--json", "--help" - ) - assert (document["command"], document["ok"], code) == ("save", True, None) - assert "--store" in document["usage"] - - -def test_ingest_writes_a_verified_derived_file_per_session( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - out_dir = tmp_path / "derived" - path = Path(transcript_path_for(str(project), "abc", str(home))) - path.parent.mkdir(parents=True) - path.write_text( - json.dumps( - { - "type": "user", - "uuid": "u-1", - "parentUuid": None, - "sessionId": "abc", - "cwd": str(project.resolve()), - "message": {"role": "user", "content": "hello"}, - } - ) - + "\n", - encoding="utf-8", - ) - - document, err, code = invoke_json( - monkeypatch, - capsys, - home, - "ingest", - "--json", - "--cwd", - str(project), - "--author", - "alice", - "--out", - str(out_dir), - ) - - assert (code, err) == (None, "") - assert document["converter"] == {"id": "claude-code", "version": 1} - [entry] = document["sessions"] - assert entry["turns"] == 1 - derived = read_derived(Path(entry["path"]).read_text(encoding="utf-8").split("\n")) - assert derived.header["author"] == {"kind": "human", "id": "alice"} - assert entry["heads"]["current"] == derived.turns[0].id - - -def test_ingest_fails_when_nothing_matches( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - document, _, code = invoke_json( - monkeypatch, - capsys, - tmp_path / "home", - "ingest", - "--json", - "--cwd", - str(tmp_path), - "--out", - str(tmp_path / "derived"), - ) - - assert (code, document["code"]) == (1, "no-sessions") - - -def test_ingest_rejects_an_unreadable_author_key( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - document, _, code = invoke_json( - monkeypatch, - capsys, - tmp_path / "home", - "ingest", - "--json", - "--author-key", - str(tmp_path / "missing.pub"), - ) - - assert (code, document["code"]) == (1, "author-key-unreadable") - - -def test_an_undecodable_transcript_is_listed_but_not_packed( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - path = write_session(home, str(project), "abc") - path.write_bytes(path.read_bytes() + b'{"type": "user", "x": "\xff"}\n') - - listed, _, _ = invoke_json( - monkeypatch, capsys, home, "list", "--json", "--cwd", str(project) - ) - assert [s["sessionId"] for s in listed["sessions"]] == ["abc"] - - saved, _, code = invoke_json( - monkeypatch, - capsys, - home, - "save", - "--json", - "--cwd", - str(project), - "--store", - str(tmp_path / "store"), - ) - assert code == 1 - assert saved["code"] == "transcript-unreadable" - assert not (tmp_path / "store").exists() - - -def test_source_date_epoch_makes_save_reproducible( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path -) -> None: - home = tmp_path / "home" - project = tmp_path / "proj" - project.mkdir() - write_session(home, str(project), "abc") - monkeypatch.setenv("SOURCE_DATE_EPOCH", "1700000000") - refs = [] - for store in ("a", "b"): - document, _, _ = invoke_json( - monkeypatch, - capsys, - home, - "save", - "--json", - "--cwd", - str(project), - "--store", - str(tmp_path / store), - ) - assert document["createdAt"] == "2023-11-14T22:13:20.000Z" - refs.append(document["ref"]) - assert refs[0] == refs[1] diff --git a/test/test_corpus.py b/test/test_corpus.py deleted file mode 100644 index 3a0052b..0000000 --- a/test/test_corpus.py +++ /dev/null @@ -1,78 +0,0 @@ -"""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_equivalence.py b/test/test_equivalence.py deleted file mode 100644 index 1fefbe2..0000000 --- a/test/test_equivalence.py +++ /dev/null @@ -1,540 +0,0 @@ -"""`loch hook` in the Rust build against the Python reference. - -Opt-in: set LOCH_RUST to a built binary (`cargo build --release` in rust/, then -LOCH_RUST=rust/target/release/loch). See equivalence.py for how a scenario is -run twice and compared. With LOCH_CORPUS=1 as well, the one hook path that -reads a transcript runs against this machine's real ones. -""" - -import json -import os -import random -import shutil -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path -from typing import Any - -import pytest -from equivalence import PAST, RUST, SESSION, Run, Scenario, World, twin - -pytestmark = pytest.mark.skipif(not RUST, reason="set LOCH_RUST to a Rust build") - - -# -- scenarios ---------------------------------------------------------------- - - -def no_commit(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - return [ - loch("hook", "pre-tool", stdin=w.event()), - loch("hook", "post-tool", stdin=w.event()), - ] - - -def one_commit(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - pre = loch("hook", "pre-tool", stdin=w.event()) - w.commit("agent work") - return [pre, loch("hook", "post-tool", stdin=w.event())] - - -def two_commits(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - pre = loch("hook", "pre-tool", stdin=w.event()) - w.commit("one") - w.commit("two") - return [pre, loch("hook", "post-tool", stdin=w.event())] - - -def checkout_is_not_committing(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("base", date=PAST) - w.git("checkout", "-q", "-b", "side") - w.commit("someone else", date=PAST) - w.git("checkout", "-q", "main") - pre = loch("hook", "pre-tool", stdin=w.event()) - w.git("checkout", "-q", "side") - return [pre, loch("hook", "post-tool", stdin=w.event())] - - -def unborn_head(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - pre = loch("hook", "pre-tool", stdin=w.event()) - w.commit("root") - return [pre, loch("hook", "post-tool", stdin=w.event())] - - -def call_from_transcript(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - transcript = w.root / "t.jsonl" - lines = [ - { - "type": "assistant", - "message": { - "content": [ - { - "type": "tool_use", - "id": "toolu_old", - "name": "Bash", - "input": {"command": "git commit -m work"}, - } - ] - }, - }, - "not json", - [1, 2], - {"type": "assistant", "message": {"content": "plain"}}, - { - "type": "assistant", - "message": { - "content": [ - { - "type": "tool_use", - "id": "toolu_new", - "name": "Bash", - "input": {"command": "git commit -m work"}, - }, - { - "type": "tool_use", - "id": "toolu_other", - "name": "Bash", - "input": {"command": "ls"}, - }, - ] - }, - }, - ] - transcript.write_text( - "\n".join(x if isinstance(x, str) else json.dumps(x) for x in lines) + "\n" - ) - event = w.event(call=None, transcript_path=str(transcript)) - pre = loch("hook", "pre-tool", stdin=event) - w.commit("agent work") - return [pre, loch("hook", "post-tool", stdin=event)] - - -def no_call_anywhere(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - event = w.event(call=None) - pre = loch("hook", "pre-tool", stdin=event) - w.commit("agent work") - return [pre, loch("hook", "post-tool", stdin=event)] - - -def worktree(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - wt = w.root / "wt1" - w.git("worktree", "add", "-q", "-b", "feature", str(wt)) - event = w.event(cwd=str(wt / ".")) - pre = loch("hook", "pre-tool", stdin=event) - w.commit("in the worktree", cwd=wt) - return [pre, loch("hook", "post-tool", stdin=event)] - - -def packed_refs(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - w.git("pack-refs", "--all") - pre = loch("hook", "pre-tool", stdin=w.event()) - w.commit("after packing") - w.git("pack-refs", "--all") - return [pre, loch("hook", "post-tool", stdin=w.event())] - - -def detached(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - w.git("checkout", "-q", "--detach") - pre = loch("hook", "pre-tool", stdin=w.event()) - w.commit("detached work") - return [pre, loch("hook", "post-tool", stdin=w.event())] - - -def subdirectory_and_symlink(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - (w.repo / "sub" / "deeper").mkdir(parents=True) - os.symlink(w.repo / "sub", w.root / "link") - event = w.event(cwd=str(w.root / "link" / "deeper")) - pre = loch("hook", "pre-tool", stdin=event) - w.commit("from a subdirectory") - return [pre, loch("hook", "post-tool", stdin=event)] - - -def reftable(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init("--ref-format=reftable") - w.commit("first") - pre = loch("hook", "pre-tool", stdin=w.event()) - w.commit("agent work") - return [pre, loch("hook", "post-tool", stdin=w.event())] - - -def git_dir_variable(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - other = w.root / "elsewhere" - other.mkdir() - env = {"GIT_DIR": str(w.repo / ".git")} - event = w.event(cwd=str(other)) - pre = loch("hook", "pre-tool", stdin=event, env=env) - w.commit("agent work") - return [pre, loch("hook", "post-tool", stdin=event, env=env)] - - -def malformed(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - runs = [] - for stdin in [ - b"not json", - b"[1, 2]", - b"\xff\xfe", - b"", - {**w.event(), "tool_input": "a string"}, - {**w.event(call=None), "tool_input": "a string"}, - {**w.event(call=None), "tool_input": {"command": 5}}, - {k: v for k, v in w.event().items() if k != "session_id"}, - {**w.event(), "session_id": 7}, - {**w.event(), "cwd": str(w.root / "missing")}, - {**w.event(), "cwd": str(w.home)}, - {**w.event(), "cwd": 12}, - ]: - for name in ("pre-tool", "post-tool"): - runs.append(loch("hook", name, stdin=stdin)) - runs.append(loch("hook", "bogus", stdin=w.event())) - runs.append(loch("hook", stdin=w.event())) - return runs - - -def stale_state(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - pending = w.repo / ".git" / "loch" / "pending" - pending.mkdir(parents=True) - (pending / "toolu_a").write_text("[]") - (pending / "toolu_b").write_text('{"head": "x"}') - (pending / "toolu_c").write_text("garbage") - runs = [] - w.commit("moved") - for call in ("toolu_a", "toolu_b", "toolu_c", "toolu_missing"): - runs.append(loch("hook", "post-tool", stdin=w.event(call=call))) - return runs - - -def json_mode(w: World, loch: Callable[..., Run]) -> list[Run]: - w.init() - w.commit("first") - return [ - loch("hook", "pre-tool", "--json", stdin=w.event()), - loch("--json", "hook", "post-tool", stdin=w.event()), - loch("--version"), - loch("--version", "--json"), - loch("version", "--json"), - loch("--json", "-V"), - loch("nonsense"), - loch("nonsense", "--json"), - ] - - -def stop(w: World, loch: Callable[..., Run]) -> list[Run]: - project = w.home / ".claude" / "projects" / "-repo" - project.mkdir(parents=True) - transcript = project / f"{SESSION}.jsonl" - transcript.write_bytes(b'{"type": "user"}\n\xff not utf-8\n') - event = {"session_id": SESSION, "transcript_path": str(transcript)} - uri = "file://" + str(w.root / "file store").replace(" ", "%20") - return [ - loch("hook", "stop", stdin=event), - loch("hook", "stop", stdin=event, env={"LOCH_STORE": uri}), - loch("hook", "stop", stdin=event, env={"LOCH_STORE": "relative/store"}), - loch("hook", "stop", stdin={**event, "transcript_path": str(w.root / "gone")}), - loch("hook", "stop", stdin={"session_id": SESSION}), - loch("hook", "stop", stdin={**event, "session_id": 3}), - ] - - -def stop_default_store(w: World, loch: Callable[..., Run]) -> list[Run]: - project = w.home / ".claude" / "projects" / "-repo" - project.mkdir(parents=True) - transcript = project / f"{SESSION}.jsonl" - transcript.write_text('{"type": "user"}\n') - event = {"session_id": SESSION, "transcript_path": str(transcript)} - run = loch("hook", "stop", stdin=event, env={"LOCH_STORE": ""}) - # Moved where observe() compares stores. - snapshot = w.home / ".loch" / "store" - if snapshot.exists(): - shutil.copytree(snapshot, w.store) - return [run] - - -SCENARIOS = [ - no_commit, - one_commit, - two_commits, - checkout_is_not_committing, - unborn_head, - call_from_transcript, - no_call_anywhere, - worktree, - packed_refs, - detached, - subdirectory_and_symlink, - reftable, - git_dir_variable, - malformed, - stale_state, - json_mode, - stop, - stop_default_store, -] - - -@pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda s: s.__name__) -def test_hook_matches_python(tmp_path: Path, scenario: Scenario) -> None: - twin(tmp_path, scenario) - - -@pytest.mark.parametrize( - "mix", [("py", "rs"), ("rs", "py")], ids=["py-then-rs", "rs-then-py"] -) -@pytest.mark.parametrize( - "scenario", - [one_commit, two_commits, unborn_head, call_from_transcript, worktree], - ids=lambda s: s.__name__, -) -def test_switching_over_mid_call( - tmp_path: Path, scenario: Scenario, mix: tuple[str, str] -) -> None: - """A Bash call whose pre hook ran under one implementation and whose post - hook ran under the other, as happens the moment a machine switches.""" - twin(tmp_path, scenario, mix=mix) - - -@dataclass -class S3: - signed: bool - endpoint: str - access_key: str - secret_key: str - client: Any - - -@pytest.fixture(params=["signed", "unsigned"]) -def s3(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> Any: - """A real HTTP endpoint rather than boto3's in-process mock, since the Rust - build signs its own requests. "signed" turns moto's IAM auth on, so a - wrong signature is refused rather than waved through; the first four - actions, which create the user who signs everything after, go unchecked. - - "unsigned" exists because moto's verifier rejects boto3's own correct - signature on a key holding a space or `+`, so key encoding — which real - project directories exercise — can only be compared with auth off.""" - import urllib.request - - import boto3 - import moto.settings - from moto.core.responses import ActionAuthenticatorMixin - from moto.server import ThreadedMotoServer - - server = ThreadedMotoServer(ip_address="127.0.0.1", port=0) - server.start() - host, port = server.get_host_and_port() - endpoint = f"http://{host}:{port}" - # moto's state belongs to the process, not the server; start clean. - urllib.request.urlopen(urllib.request.Request(f"{endpoint}/moto-api/reset", b"")) - if request.param == "signed": - monkeypatch.setattr(moto.settings, "INITIAL_NO_AUTH_ACTION_COUNT", 4) - monkeypatch.setattr(ActionAuthenticatorMixin, "request_count", 0) - iam = boto3.client( - "iam", - endpoint_url=endpoint, - region_name="us-east-1", - aws_access_key_id="bootstrap", - aws_secret_access_key="bootstrap", - ) - iam.create_user(UserName="loch") - key = iam.create_access_key(UserName="loch")["AccessKey"] - iam.put_user_policy( - UserName="loch", - PolicyName="s3", - PolicyDocument=json.dumps( - { - "Version": "2012-10-17", - "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}], - } - ), - ) - client = boto3.client( - "s3", - endpoint_url=endpoint, - region_name="us-east-1", - aws_access_key_id=key["AccessKeyId"], - aws_secret_access_key=key["SecretAccessKey"], - ) - client.create_bucket(Bucket="loch-test") - yield S3( - request.param == "signed", - endpoint, - key["AccessKeyId"], - key["SecretAccessKey"], - client, - ) - server.stop() - - -def test_stop_snapshots_into_s3_identically(tmp_path: Path, s3: S3) -> None: - """Each implementation snapshots under its own prefix of one bucket; the - keys and bytes beneath must match, and a bad secret must write nothing.""" - world = World(tmp_path / "world") - name = "-Users-x-repo" if s3.signed else "-a b+c%" - project = world.home / ".claude" / "projects" / name - project.mkdir(parents=True) - transcript = project / f"{SESSION}.jsonl" - transcript.write_bytes(b'{"type": "user"}\n\xff raw bytes \xe2\x9c\x93\n') - event = {"session_id": SESSION, "transcript_path": str(transcript)} - signed = { - "AWS_ACCESS_KEY_ID": s3.access_key, - "LOCH_S3_ENDPOINT": s3.endpoint, - "LOCH_S3_REGION": "us-east-1", - "AWS_SHARED_CREDENTIALS_FILE": os.devnull, - "AWS_CONFIG_FILE": os.devnull, - } - - contents: dict[str, dict[str, bytes]] = {} - for impl in ("py", "rs"): - runs = [ - world.loch( - impl, - "hook", - "stop", - stdin=event, - env={ - **signed, - "AWS_SECRET_ACCESS_KEY": s3.secret_key, - "LOCH_STORE": f"s3://loch-test/{impl}/", - }, - ), - world.loch( - impl, - "hook", - "stop", - stdin=event, - env={ - **signed, - "AWS_SECRET_ACCESS_KEY": "wrong", - "LOCH_STORE": f"s3://loch-test/{impl}-badly-signed", - }, - ), - world.loch( - impl, - "hook", - "stop", - stdin=event, - env={ - **{k: v for k, v in signed.items() if k != "AWS_ACCESS_KEY_ID"}, - "LOCH_STORE": f"s3://loch-test/{impl}-anonymous", - }, - ), - ] - # A hook may never fail its tool call, whatever the store says. - assert [(r.stdout, r.stderr, r.status) for r in runs] == [(b"", b"", 0)] * len( - runs - ) - # Unprefixed: moto's verifier also rejects boto3's own signature on a - # listing whose prefix holds a `/`. - listed = s3.client.list_objects_v2(Bucket="loch-test") - contents[impl] = { - item["Key"]: s3.client.get_object(Bucket="loch-test", Key=item["Key"])[ - "Body" - ].read() - for item in listed.get("Contents", []) - if item["Key"].startswith(f"{impl}/") - } - assert list(contents["py"]) == [ - f"py/transcripts/claude-code/{name}/{SESSION}.jsonl" - ] - assert list(contents["py"].values()) == [transcript.read_bytes()] - assert {k.replace("rs/", "py/", 1): v for k, v in contents["rs"].items()} == ( - contents["py"] - ) - if s3.signed: - # Neither the bad secret nor the absent key got anything in. - every = s3.client.list_objects_v2(Bucket="loch-test").get("Contents", []) - assert sorted(item["Key"].split("/")[0] for item in every) == ["py", "rs"] - - -# -- corpus ------------------------------------------------------------------- - - -def _corpus_cases(limit: int) -> list[tuple[str, str]]: - from loch.claude import projects_dir - - root = Path(projects_dir()) - transcripts = sorted(root.glob("*/*.jsonl")) if root.is_dir() else [] - random.Random(0).shuffle(transcripts) - cases = [] - for path in transcripts: - commands = [] - for line in path.read_bytes().split(b"\n"): - if b'"Bash"' not in line: - continue - try: - record = json.loads(line) - except ValueError: - continue - content = (record.get("message") or {}).get("content") - for block in content if isinstance(content, list) else []: - if ( - isinstance(block, dict) - and block.get("type") == "tool_use" - and block.get("name") == "Bash" - and isinstance((block.get("input") or {}).get("command"), str) - ): - commands.append(block["input"]["command"]) - if commands: - cases.append((str(path), random.Random(path.name).choice(commands))) - if len(cases) >= limit: - break - return cases - - -@pytest.mark.skipif(os.environ.get("LOCH_CORPUS") != "1", reason="set LOCH_CORPUS=1") -def test_call_recovery_matches_on_real_transcripts(tmp_path: Path) -> None: - """The one hook path that reads a transcript, on real ones: a commit made - by a call whose payload lacks tool_use_id must be noted with the same call - id by both implementations.""" - cases = _corpus_cases(int(os.environ.get("LOCH_CORPUS_LIMIT", "150"))) - assert cases, "no transcripts with Bash calls on this machine" - mismatched = [] - unnoted = 0 - for index, (path, command) in enumerate(cases): - session = Path(path).stem - - def scenario( - w: World, loch: Callable[..., Run], _p: str = path, _c: str = command - ) -> list[Run]: - w.init() - w.commit("first") - event = w.event(call=None, transcript_path=_p, tool_input={"command": _c}) - pre = loch("hook", "pre-tool", stdin=event) - w.commit("agent work") - return [pre, loch("hook", "post-tool", stdin=event)] - - try: - seen = twin(tmp_path / str(index), scenario) - except AssertionError: - mismatched.append(session) - continue - # Agreeing that nothing happened would pass vacuously. - unnoted += not seen["repo:refs/notes/loch"] - assert not unnoted, f"{unnoted}/{len(cases)} cases wrote no note" - assert not mismatched, ( - f"{len(mismatched)}/{len(cases)} sessions differ: {mismatched}" - ) diff --git a/test/test_equivalence_commands.py b/test/test_equivalence_commands.py deleted file mode 100644 index 100313a..0000000 --- a/test/test_equivalence_commands.py +++ /dev/null @@ -1,841 +0,0 @@ -"""Every command but `hook` in the Rust build against the Python reference. - -Opt-in with LOCH_RUST, like test_equivalence.py; the machinery is in -equivalence.py. Each scenario runs its commands in both renderings where the -two differ, since prose and payload are built separately and either can drift. -""" - -import gzip -import json -import os -import re -from collections.abc import Callable -from pathlib import Path -from typing import Any - -import pytest -from equivalence import MTIME, PAST, RUST, SESSION, Run, Scenario, World, twin - -pytestmark = pytest.mark.skipif(not RUST, reason="set LOCH_RUST to a Rust build") - -Loch = Callable[..., Run] - -OTHER = "22222222-3333-4444-5555-666666666666" -THIRD = "33333333-4444-5555-6666-777777777777" -SECRET = "ghp_" + "a1B2c3D4e5" * 4 - - -def both(loch: Loch, *args: str, **kw: Any) -> list[Run]: - """A command in text mode and in JSON mode.""" - return [loch(*args, **kw), loch(*args, "--json", **kw)] - - -def user(cwd: str, text: Any, branch: str | None = "main", **extra: Any) -> dict: - record: dict[str, Any] = { - "type": "user", - "uuid": extra.pop("uuid", "u1"), - "parentUuid": extra.pop("parent", None), - "sessionId": extra.pop("session", SESSION), - "cwd": cwd, - "version": "2.1.0", - "timestamp": "2026-01-01T00:00:00.000Z", - "message": {"role": "user", "content": text}, - } - if branch is not None: - record["gitBranch"] = branch - record.update(extra) - return record - - -def assistant( - cwd: str, blocks: list[Any], uuid: str, parent: str, **extra: Any -) -> dict: - record = { - "type": "assistant", - "uuid": uuid, - "parentUuid": parent, - "sessionId": extra.pop("session", SESSION), - "cwd": cwd, - "gitBranch": extra.pop("branch", "main"), - "version": "2.1.0", - "timestamp": extra.pop("timestamp", "2026-01-01T00:00:05.000Z"), - "message": { - "id": "msg_1", - "model": "claude-x", - "role": "assistant", - "content": blocks, - }, - } - record.update(extra) - return record - - -def project(w: World) -> str: - path = w.root / "proj" - path.mkdir(exist_ok=True) - return str(path) - - -def rich_sessions(w: World) -> str: - """Sessions with what list, save and ingest each have to get right: a - secret, odd whitespace, a non-ASCII summary, two branches, a session that - moved directories, a lone surrogate escape and a line that isn't JSON.""" - cwd = project(w) - w.session( - cwd, - SESSION, - [ - user(cwd, f"deploy with {SECRET}\tand
then é 😀", uuid="a1"), - assistant( - cwd, [{"type": "text", "text": f"ok {cwd}/src and ~"}], "a2", "a1" - ), - "not json {", - {"type": "ai-title", "aiTitle": "Deploying"}, - user( - cwd, - [{"type": "tool_result", "tool_use_id": "t1", "content": "done"}], - uuid="a3", - parent="a2", - ), - ], - ) - w.session( - cwd, - OTHER, - [ - user( - f"{cwd}-old", "before the move", branch="old", uuid="b1", session=OTHER - ), - user( - cwd, - [{"type": "text", "text": "after \\ud83d the move"}], - branch="feature/x", - uuid="b2", - parent="b1", - session=OTHER, - ), - '{"type": "user", "uuid": "b3", "parentUuid": "b2", "cwd": "' - + cwd - + '", "message": {"content": "lone \\ud83d"}}', - { - "type": "system", - "subtype": "turn_duration", - "uuid": "b4", - "parentUuid": "b3", - "cwd": cwd, - "durationMs": 5, - }, - {"type": "custom-title", "customTitle": "Moved"}, - ], - ) - w.session( - cwd, THIRD, [user(cwd, "no branch here", branch=None, uuid="c1", session=THIRD)] - ) - return cwd - - -# -- help, version, usage ------------------------------------------------------- - -COMMANDS = [ - "list", - "save", - "restore", - "delete", - "reindex", - "ingest", - "install", - "blame", - "log", - "ask", - "backfill", -] - -BAD_ARGUMENTS = [ - ["-h"], - ["--help"], - ["--bogus"], - ["--cwd"], - ["--store"], - ["--s", "x"], - ["--st=x"], - ["--json=1"], - ["--force=yes"], - ["-x"], - ["-hx"], - ["--", "-h"], - ["a", "b", "c"], - ["-5"], - ["--into", "-5"], -] - - -def usage(w: World, loch: Loch) -> list[Run]: - runs = [] - for command in COMMANDS: - for argv in BAD_ARGUMENTS: - runs += both(loch, command, *argv) - return runs - - -def usage_narrow(w: World, loch: Loch) -> list[Run]: - """Usage lines wrap at the terminal width, which COLUMNS sets.""" - runs = [] - for columns in ("40", "60", "12"): - for command in COMMANDS: - runs.append(loch(command, "-h", env={"COLUMNS": columns})) - runs.append(loch(command, "--bogus", env={"COLUMNS": columns})) - return runs - - -def top_level(w: World, loch: Loch) -> list[Run]: - return [ - *both(loch), - *both(loch, "help"), - *both(loch, "--help"), - *both(loch, "-h"), - *both(loch, "--version"), - *both(loch, "-V"), - *both(loch, "version"), - *both(loch, "nonsense"), - loch("--json"), - loch("--json", "--json"), - loch("list", "--json", "--json", "--cwd", project(w)), - ] - - -# -- list ----------------------------------------------------------------------- - - -def listing(w: World, loch: Loch) -> list[Run]: - cwd = rich_sessions(w) - (w.root / "empty").mkdir() - return [ - *both(loch, "list", "--cwd", cwd), - *both(loch, "list", "--cwd", cwd, "--branch", "main"), - *both(loch, "list", "--cwd", cwd, "--branch", "feature/x"), - *both(loch, "list", "--cwd", cwd, "--branch", "none-such"), - *both(loch, "list", "--cwd", str(w.root / "empty")), - *both(loch, "list", "--cwd", str(w.root / "missing")), - *both(loch, "list", cwd=Path(cwd)), - *both( - loch, - "list", - "--cwd", - cwd, - env={"CLAUDE_CONFIG_DIR": str(w.root / "other-config")}, - ), - ] - - -def listing_via_symlink(w: World, loch: Loch) -> list[Run]: - cwd = rich_sessions(w) - os.symlink(cwd, w.root / "link") - return both(loch, "list", "--cwd", str(w.root / "link")) - - -def listing_config_dir(w: World, loch: Loch) -> list[Run]: - cwd = project(w) - config = w.root / "work-account" - folder = config / "projects" / re.sub(r"[^a-zA-Z0-9]", "-", cwd) - folder.mkdir(parents=True) - (folder / f"{SESSION}.jsonl").write_text( - json.dumps(user(cwd, "in another account")) + "\n" - ) - os.utime(folder / f"{SESSION}.jsonl", (MTIME, MTIME)) - return both(loch, "list", "--cwd", cwd, env={"CLAUDE_CONFIG_DIR": str(config)}) - - -def listing_bad_bytes(w: World, loch: Loch) -> list[Run]: - cwd = project(w) - w.session(cwd, SESSION, [user(cwd, "fine")], raw=b'{"type": "user", "x": "\xff"}\n') - return [ - *both(loch, "list", "--cwd", cwd), - *both(loch, "save", "--cwd", cwd), - ] - - -# -- save, list --remote, restore, delete, reindex -------------------------------------- - - -def save_and_list_remote(w: World, loch: Loch) -> list[Run]: - cwd = rich_sessions(w) - runs = [ - *both(loch, "save", "--cwd", cwd), - loch("save", "--cwd", cwd, "--branch", "feature/x", "--json"), - loch("save", "--cwd", cwd, "--session", THIRD), - *both(loch, "save", "--cwd", cwd, "--branch", "none-such"), - *both(loch, "save", "--cwd", str(w.root / "missing")), - loch("save", "--cwd", cwd, "--store", "relative-store", "--json", cwd=w.root), - loch("save", "--cwd", cwd, "--store", f"file://{w.root}/uri%20store"), - ] - os.makedirs(w.repo, exist_ok=True) - w.init() - w.commit("first") - w.git("checkout", "-q", "-b", "feature/x") - for args in ( - ["--remote"], - ["--remote", "--cwd", str(w.repo)], - ["--remote", "--branch", "main"], - ["--remote", "--branch", "none-such"], - ["--all"], - ["--store", str(w.store), "--branch", "feature/x"], - ["--remote", "--store", str(w.root / "nowhere")], - ): - runs += both(loch, "list", *args, cwd=w.repo) - runs += both(loch, "list", "--remote", "--cwd", str(w.root)) - return runs - - -def bundle_ref(w: World) -> str: - bundles = sorted((w.store / "bundles").glob("*.loch")) - return bundles[0].stem - - -def restore(w: World, loch: Loch) -> list[Run]: - cwd = rich_sessions(w) - runs = [loch("save", "--cwd", cwd)] - ref = bundle_ref(w) - target = w.root / "elsewhere" - target.mkdir() - runs += [ - *both(loch, "restore", ref, "--into", str(target)), - # Everything is there now: skipped, so nothing restored. - *both(loch, "restore", ref, "--into", str(target)), - *both(loch, "restore", ref, "--into", str(target), "--force"), - *both(loch, "restore", ref, "--into", str(target), "--new-id"), - *both(loch, "restore"), - *both(loch, "restore", "0" * 64), - *both(loch, "restore", ref, "--store", str(w.root / "nowhere")), - ] - # Another machine: a different home, so the home pair rewrites too. - other_home = w.root / "other-home" - other_home.mkdir() - runs += both( - loch, - "restore", - ref, - "--into", - str(target), - "--force", - env={"HOME": str(other_home)}, - ) - return runs - - -def restore_unreadable(w: World, loch: Loch) -> list[Run]: - bundles = w.store / "bundles" - bundles.mkdir(parents=True) - (bundles / f"{'a' * 64}.loch").write_bytes(b"garbage") - (bundles / f"{'b' * 64}.loch").write_bytes(b"") - (bundles / f"{'c' * 64}.loch").write_bytes( - gzip.compress(json.dumps({"version": 2}).encode(), mtime=0) - ) - (bundles / f"{'d' * 64}.loch").write_bytes( - gzip.compress(json.dumps({"version": "1"}).encode(), mtime=0) - ) - runs = [] - for letter in "abcd": - runs += both(loch, "restore", letter * 64) - return runs - - -def delete_and_reindex(w: World, loch: Loch) -> list[Run]: - cwd = rich_sessions(w) - runs = [loch("save", "--cwd", cwd), loch("save", "--cwd", cwd, "--branch", "main")] - refs = sorted(p.stem for p in (w.store / "bundles").glob("*.loch")) - stale = w.store / "index" / "branch" / "gone" / ("f" * 64) - stale.parent.mkdir(parents=True) - stale.write_text("{}") - (w.store / "bundles" / "notes.txt").write_text("not a bundle") - runs += [ - *both(loch, "reindex"), - *both(loch, "reindex"), - *both(loch, "delete", refs[0]), - *both(loch, "delete", refs[0]), - *both(loch, "delete"), - *both(loch, "list", "--all"), - *both(loch, "reindex", "--store", str(w.root / "empty-store")), - ] - return runs - - -# -- ingest ---------------------------------------------------------------------- - - -def ingest(w: World, loch: Loch) -> list[Run]: - cwd = rich_sessions(w) - key = w.root / "id_ed25519.pub" - key.write_text( - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGq7k5Pi0VGa1sYhVPLvlXHjjhVQrDsWlvS4sUVJmPB0 me\n" - ) - bad = w.root / "bad.pub" - bad.write_text("ssh-ed25519 not*base64\n") - one = w.root / "one.pub" - one.write_text("just-one-field\n") - padding = w.root / "padding.pub" - padding.write_text("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5\n") - sidecar = w.projects() / re.sub(r"[^a-zA-Z0-9]", "-", cwd) / SESSION / "subagents" - sidecar.mkdir(parents=True) - (sidecar / "agent-1.jsonl").write_text('{"type": "user"}\n') - return [ - *both(loch, "ingest", "--cwd", cwd), - *both( - loch, - "ingest", - "--cwd", - cwd, - "--out", - str(w.root / "out"), - "--author", - "me@example.com", - ), - *both( - loch, - "ingest", - "--cwd", - cwd, - "--out", - str(w.root / "keyed"), - "--author-key", - str(key), - ), - *both(loch, "ingest", "--cwd", cwd, "--author-key", str(bad)), - *both(loch, "ingest", "--cwd", cwd, "--author-key", str(one)), - *both(loch, "ingest", "--cwd", cwd, "--author-key", str(padding)), - *both( - loch, "ingest", "--cwd", cwd, "--author-key", str(w.root / "missing.pub") - ), - *both(loch, "ingest", "--cwd", cwd, "--author", "x", "--author-key", str(key)), - *both( - loch, - "ingest", - "--cwd", - cwd, - "--session", - OTHER, - "--out", - str(w.root / "one"), - ), - *both(loch, "ingest", "--cwd", str(w.root / "missing")), - ] - - -def ingest_graph(w: World, loch: Loch) -> list[Run]: - """The converter's harder cases: a rewind that leaves a branch, a - resubmitted identical turn, a compaction boundary, a dangling parent, - records out of file order, a cycle, and every block type.""" - cwd = project(w) - blocks = [ - {"type": "thinking", "thinking": "hm", "signature": "sig"}, - {"type": "redacted_thinking", "data": "x"}, - { - "type": "tool_use", - "id": "t1", - "name": "Bash", - "input": {"command": f"ls {cwd}"}, - }, - {"type": "image", "source": {"type": "base64", "data": "AAAA"}}, - {"type": "server_tool_use", "id": "s1"}, - "a bare string", - {"type": "text", "text": "literal {{loch:root}} placeholder"}, - ] - records = [ - user(cwd, "start", uuid="r1"), - assistant(cwd, blocks, "r2", "r1"), - user( - cwd, - [ - { - "type": "tool_result", - "tool_use_id": "t1", - "content": [{"type": "text", "text": f"{cwd}/a"}], - "is_error": True, - } - ], - uuid="r3", - parent="r2", - ), - user(cwd, "branch A", uuid="r4", parent="r3"), - user(cwd, "branch B", uuid="r5", parent="r3"), - user(cwd, "branch A", uuid="r6", parent="r3"), - { - "type": "system", - "subtype": "compact_boundary", - "uuid": "r7", - "parentUuid": None, - "logicalParentUuid": "r5", - "cwd": cwd, - "content": "compacted", - }, - user(cwd, "summary", uuid="r8", parent="r7", isCompactSummary=True), - user(cwd, "orphan", uuid="r9", parent="never-seen"), - user(cwd, "child before parent", uuid="r10", parent="r11"), - user(cwd, "parent after child", uuid="r11", parent="r8"), - user(cwd, "cycle one", uuid="r12", parent="r13"), - user(cwd, "cycle two", uuid="r13", parent="r12"), - { - "type": "attachment", - "uuid": "r14", - "parentUuid": "r11", - "cwd": cwd, - "attachment": {"path": f"{cwd}/f", "keyed": {f"{cwd}/k": 1}}, - }, - { - "type": "system", - "subtype": "api_error", - "uuid": "r15", - "parentUuid": "r14", - "cwd": cwd, - "timestamp": "t", - }, - { - "type": "system", - "subtype": "stray", - "uuid": "r16", - "parentUuid": "nowhere", - "cwd": cwd, - }, - user(cwd, "meta", uuid="r17", parent="r15", isMeta=True), - {"type": "last-prompt", "leafUuid": "r4"}, - {"type": "user", "uuid": 5, "message": {"content": "non-string uuid"}}, - { - "type": "user", - "uuid": "r18", - "parentUuid": "r17", - "cwd": cwd, - "message": { - "content": [ - {"type": "text", "text": 1.5e300}, - {"type": "text", "text": 123456789012345678901234567890}, - ] - }, - }, - ] - w.session(cwd, SESSION, records) - return both(loch, "ingest", "--cwd", cwd, "--out", str(w.root / "derived")) - - -def ingest_from_home(w: World, loch: Loch) -> list[Run]: - """A session run from the home directory itself is a root, not a home.""" - cwd = str(w.home) - w.session(cwd, SESSION, [user(cwd, f"in {cwd}/x")]) - return both(loch, "ingest", "--cwd", cwd, "--out", str(w.root / "derived")) - - -# -- install ------------------------------------------------------------------------- - - -def install(w: World, loch: Loch) -> list[Run]: - w.init() - w.commit("first") - settings = w.repo / ".claude" - settings.mkdir() - (settings / "settings.json").write_text( - json.dumps( - {"model": "x", "n": 1.50, "é": "ü", "hooks": {"Stop": [{"hooks": []}]}} - ) - ) - return [ - *both(loch, "install", cwd=w.repo), - *both(loch, "install", cwd=w.repo), - *both(loch, "install", "--local", cwd=w.repo), - loch("install", "--command", "/opt/loch", "--cwd", str(w.repo)), - *both(loch, "install", cwd=w.root), - ] - - -# -- blame, log, ask, backfill ------------------------------------------------------ - - -def traced_repo(w: World) -> dict[str, str]: - """A repository whose commits link to a real-shaped transcript: two - requests in one session, one commit each, plus one unlinked commit and an - uncommitted edit.""" - w.init() - repo = str(w.repo) - base = w.commit_file("app.py", "one\ntwo\nthree\n", "unlinked start", date=PAST) - first = w.commit_file( - "app.py", "one\nTWO\nthree\nfour\n", "agent: two", date="2026-01-01T00:00:12Z" - ) - second = w.commit_file( - "app.py", - "one\nTWO\nthree\nfour\nfive\n", - "agent: five", - date="2026-01-01T00:01:12Z", - ) - w.commit_file("other.txt", "x\n", "agent: other", date="2026-01-01T00:02:12Z") - (w.repo / "app.py").write_text("one\nTWO\nthree\nfour\nfive\nsix\n") - records = [ - user(repo, "please change two “quote”", uuid="q1"), - assistant( - repo, - [ - { - "type": "tool_use", - "id": "toolu_a", - "name": "Bash", - "input": {"command": "git commit -m 'agent: two'"}, - } - ], - "q2", - "q1", - timestamp="2026-01-01T00:00:10.000Z", - ), - user( - repo, - [{"type": "tool_result", "tool_use_id": "toolu_a", "content": "ok"}], - uuid="q3", - parent="q2", - timestamp="2026-01-01T00:00:14.000Z", - ), - user(repo, "ignored", uuid="q4", parent="q3"), - user(repo, "now add five", uuid="q5", parent="q4"), - assistant( - repo, - [ - { - "type": "tool_use", - "id": "toolu_b", - "name": "Bash", - "input": {"command": "git commit -m 'agent: five'"}, - }, - { - "type": "tool_use", - "id": "toolu_c", - "name": "Bash", - "input": {"command": "git commit -m 'agent: other'"}, - }, - ], - "q6", - "q5", - timestamp="2026-01-01T00:01:10.000Z", - ), - user( - repo, - [{"type": "tool_result", "tool_use_id": "toolu_b", "content": "ok"}], - uuid="q7", - parent="q6", - timestamp="2026-01-01T00:01:14.000Z", - ), - user( - repo, - [{"type": "tool_result", "tool_use_id": "toolu_c", "content": "ok"}], - uuid="q8", - parent="q7", - timestamp="2026-01-01T00:02:14.000Z", - ), - {"type": "ai-title", "aiTitle": "Edit app"}, - { - "type": "user", - "uuid": "q9", - "parentUuid": "q8", - "cwd": repo, - "costs": [1e-05, 1e16, 0.5, 1e22, -0.0], - "message": {"content": "floats"}, - }, - ] - w.session(repo, SESSION, records) - return {"base": base, "first": first, "second": second} - - -def blame_and_log(w: World, loch: Loch) -> list[Run]: - commits = traced_repo(w) - w.note(commits["first"], SESSION, "toolu_a") - w.note(commits["second"], SESSION, "toolu_b") - w.note(commits["base"], "99999999-0000-0000-0000-000000000000", "toolu_gone") - runs = [] - for args in ( - ["blame", "app.py"], - ["blame", "other.txt"], - ["blame", "missing.py"], - ["blame", "app.py", "--html", str(w.root / "page.html"), "--no-open"], - ["blame", "app.py", "--html", "--no-open"], - [ - "blame", - "app.py", - "--html", - str(w.root / "lines.html"), - "--lines", - "1-2, 5", - "--no-open", - ], - [ - "blame", - "app.py", - "--html", - str(w.root / "bad.html"), - "--lines", - "x-1", - "--no-open", - ], - ["log", "app.py"], - ["log", "app.py:2"], - ["log", "app.py:2-4"], - ["log", "app.py:9"], - ["log", "app.py:0"], - ["log", "app.py:3-2"], - ["log", "app.py:x"], - ["log", "nope"], - ["log", "other.txt"], - ): - runs += both(loch, *args, cwd=w.repo) - runs += both(loch, "blame", str(w.root / "outside.txt"), cwd=w.root) - return runs - - -def ask(w: World, loch: Loch) -> list[Run]: - commits = traced_repo(w) - w.note(commits["first"], SESSION, "toolu_a") - w.note(commits["second"], SESSION, "toolu_b") - w.note(commits["base"], "99999999-0000-0000-0000-000000000000", "toolu_gone") - runs = [] - for args in ( - ["ask", commits["first"], "--no-launch"], - ["ask", "app.py:5", "why five?", "--no-launch", "--at-commit"], - ["ask", "app.py:2", "--at-commit", "--no-launch"], - ["ask", "app.py:6", "--no-launch"], - ["ask", "app.py:1", "--no-launch"], - ["ask", "app.py:99", "--no-launch"], - ["ask", "HEAD~3", "--no-launch"], - ["ask", "nonsense-rev", "--no-launch"], - ["ask", commits["first"], "--json"], - ): - runs += both(loch, *args, cwd=w.repo) - return runs - - -def ask_from_store(w: World, loch: Loch) -> list[Run]: - """A transcript Claude has deleted is found in the store's snapshot.""" - commits = traced_repo(w) - w.note(commits["second"], SESSION, "toolu_b") - transcript = next(w.projects().glob(f"*/{SESSION}.jsonl")) - runs = [ - loch( - "hook", - "stop", - stdin={"session_id": SESSION, "transcript_path": str(transcript)}, - ) - ] - transcript.unlink() - runs += both(loch, "ask", "app.py:5", "--no-launch", cwd=w.repo) - runs += both(loch, "blame", "app.py", cwd=w.repo) - return runs - - -def backfill(w: World, loch: Loch) -> list[Run]: - traced_repo(w) - w.git("checkout", "-q", "-b", "side") - # Two calls in different sessions bracket this one: ambiguous, so unlinked. - w.commit_file("x.txt", "x\n", "agent: two", date="2026-01-01T00:00:12Z") - runs = both(loch, "backfill", cwd=w.repo) - runs += both(loch, "backfill", "--revision", "main", cwd=w.repo) - runs += both(loch, "backfill", "--revision", "no-such-rev", cwd=w.repo) - runs += both(loch, "backfill", "--cwd", str(w.root)) - return runs - - -SCENARIOS: list[Scenario] = [ - usage, - usage_narrow, - top_level, - listing, - listing_via_symlink, - listing_config_dir, - listing_bad_bytes, - save_and_list_remote, - restore, - restore_unreadable, - delete_and_reindex, - ingest, - ingest_graph, - ingest_from_home, - install, - blame_and_log, - ask, - ask_from_store, - backfill, -] - - -@pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda s: s.__name__) -def test_command_matches_python(tmp_path: Path, scenario: Scenario) -> None: - twin(tmp_path, scenario) - - -def test_s3_store_matches_python(tmp_path: Path) -> None: - """The bundle commands against an S3 endpoint rather than a directory: - both builds' requests go to one moto server, reset between them. Auth is - off, because moto's verifier rejects boto3's own correct signatures on - the prefixed listings these commands make; signing is pinned to AWS's - published examples in s3.rs instead, and checked with auth on by the - stop-hook test.""" - import urllib.request - - import boto3 - from equivalence import first_difference, normalized - from moto.server import ThreadedMotoServer - - server = ThreadedMotoServer(ip_address="127.0.0.1", port=0) - server.start() - host, port = server.get_host_and_port() - endpoint = f"http://{host}:{port}" - credentials = { - "AWS_ACCESS_KEY_ID": "testing", - "AWS_SECRET_ACCESS_KEY": "testing", - "AWS_SHARED_CREDENTIALS_FILE": os.devnull, - "AWS_CONFIG_FILE": os.devnull, - "LOCH_S3_ENDPOINT": endpoint, - "LOCH_S3_REGION": "us-east-1", - "LOCH_STORE": "s3://loch-test/team/", - } - outcomes = [] - try: - for impl in ("py", "rs"): - urllib.request.urlopen( - urllib.request.Request(f"{endpoint}/moto-api/reset", b"") - ) - boto3.client( - "s3", - endpoint_url=endpoint, - region_name="us-east-1", - aws_access_key_id="testing", - aws_secret_access_key="testing", - ).create_bucket(Bucket="loch-test") - root = tmp_path / "world" - if root.exists(): - import shutil - - shutil.rmtree(root) - w = World(root) - cwd = rich_sessions(w) - - def loch(*args: str, _w: World = w, _impl: str = impl, **kw: Any) -> Run: - env = {**credentials, **kw.pop("env", {})} - return _w.loch(_impl, *args, env=env, **kw) - - runs = [*both(loch, "save", "--cwd", cwd)] - listed = json.loads(loch("list", "--all", "--json").stdout) - ref = listed["entries"][0]["ref"] - target = w.root / "target" - target.mkdir() - runs += [ - *both(loch, "list", "--all"), - *both(loch, "list", "--remote", "--branch", "feature/x"), - *both(loch, "restore", ref, "--into", str(target)), - *both(loch, "restore", "0" * 64), - *both(loch, "reindex"), - *both(loch, "delete", ref), - *both(loch, "delete", ref), - *both(loch, "list", "--all"), - *both(loch, "save", "--cwd", cwd, env={"AWS_ACCESS_KEY_ID": ""}), - *both( - loch, - "list", - "--all", - env={"LOCH_S3_ENDPOINT": "http://127.0.0.1:9"}, - ), - ] - outcomes.append(normalized(runs, w.observe())) - finally: - server.stop() - assert outcomes[0] == outcomes[1], first_difference(outcomes[0], outcomes[1]) diff --git a/test/test_equivalence_corpus.py b/test/test_equivalence_corpus.py deleted file mode 100644 index d76da7f..0000000 --- a/test/test_equivalence_corpus.py +++ /dev/null @@ -1,127 +0,0 @@ -"""The Rust build against the Python reference on this machine's real -transcripts: every project directory is listed, saved, restored onto a -different home and ingested by both builds, and everything they write is -compared. - -Opt-in twice over — LOCH_RUST and LOCH_CORPUS=1 — and read-only towards -`~/.claude`: restores go to a temporary HOME, stores and derived files to a -temporary directory. Content never leaves memory; a failure names the project -directory, the command, and a byte offset or a hash. -""" - -import os -import re -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path - -import pytest -from equivalence import RUST, Run, World, twin - -from loch.claude import projects_dir, read_session_meta - -pytestmark = pytest.mark.skipif( - not RUST or os.environ.get("LOCH_CORPUS") != "1", - reason="set LOCH_RUST and LOCH_CORPUS=1", -) - -REAL_HOME = str(Path.home()) - - -def project_cwds() -> list[tuple[str, str]]: - """(directory name, the cwd its sessions are filed under), as list would - be asked for it. A directory whose name no session's cwd encodes to — a - hand-copied one — can't be reached by --cwd and is skipped.""" - root = Path(projects_dir()) - found = [] - for directory in sorted(root.iterdir()) if root.is_dir() else []: - for transcript in sorted(directory.glob("*.jsonl")): - meta = read_session_meta(str(transcript)) - if meta and re.sub(r"[^a-zA-Z0-9]", "-", meta.cwd) == directory.name: - found.append((directory.name, meta.cwd)) - break - limit = int(os.environ.get("LOCH_CORPUS_DIRS", "0")) - return found[:limit] if limit else found - - -def test_no_transcript_uses_the_surrogate_mapping_range() -> None: - """The Rust build carries lone surrogates in U+10F800..U+10FFFF (py.rs); - a transcript holding those code points literally would be misread.""" - reserved = re.compile("[\U0010f800-\U0010ffff]") - hits = [ - path.parent.name - for path in Path(projects_dir()).glob("*/*.jsonl") - if reserved.search(path.read_bytes().decode("utf-8", "surrogateescape")) - ] - assert not hits, f"{len(hits)} transcripts use the reserved range: {hits[:5]}" - - -def check_directory(root: Path, cwd: str) -> str | None: - """Both builds over one project directory; None if they agree.""" - real = {"HOME": REAL_HOME, "CLAUDE_CONFIG_DIR": os.environ.get("CLAUDE_CONFIG_DIR")} - - def scenario(w: World, loch) -> list[Run]: # type: ignore[no-untyped-def] - store = str(w.root / "store") - runs = [ - loch("list", "--cwd", cwd, env=real), - loch("list", "--cwd", cwd, "--json", env=real), - loch("save", "--cwd", cwd, "--store", store, "--json", env=real), - loch( - "ingest", - "--cwd", - cwd, - "--out", - str(w.root / "derived"), - "--json", - env=real, - ), - ] - bundles = sorted((w.root / "store" / "bundles").glob("*.loch")) - if bundles: - target = w.root / "target" - target.mkdir() - # The temporary home: a different machine, and nowhere real. - runs.append( - loch( - "restore", - bundles[0].stem, - "--store", - store, - "--into", - str(target), - "--json", - ) - ) - return runs - - try: - twin(root, scenario, quiet=True) - except AssertionError as error: - return str(error) - finally: - import shutil - - shutil.rmtree(root, ignore_errors=True) - return None - - -def test_every_project_directory_matches(tmp_path: Path) -> None: - """In parallel — LOCH_CORPUS_JOBS, default every core — since the - reference's redaction makes a serial run over a busy machine take hours.""" - cases = project_cwds() - assert cases, "no Claude Code sessions on this machine" - jobs = int(os.environ.get("LOCH_CORPUS_JOBS", str(os.cpu_count() or 1))) - with ThreadPoolExecutor(max_workers=jobs) as pool: - results = list( - pool.map( - lambda item: check_directory(tmp_path / str(item[0]), item[1][1]), - enumerate(cases), - ) - ) - mismatched = [ - f"{directory}: {result}" - for (directory, _), result in zip(cases, results) - if result is not None - ] - assert not mismatched, ( - f"{len(mismatched)}/{len(cases)} directories differ:\n" + "\n".join(mismatched) - ) diff --git a/test/test_format.py b/test/test_format.py deleted file mode 100644 index b23c80b..0000000 --- a/test/test_format.py +++ /dev/null @@ -1,165 +0,0 @@ -import pytest - -from loch.format import ( - Derived, - FormatError, - Turn, - canonical, - content_id, - digest, - make_turn, - pack_derived, - read_derived, -) - -HUMAN = {"kind": "human", "id": "alice"} - - -def header() -> dict[str, object]: - return {"loch": 1, "converter": {"id": "test", "version": 1}} - - -def test_canonical_is_independent_of_key_order() -> None: - assert canonical({"b": 1, "a": [1, {"d": 2, "c": 3}]}) == canonical( - {"a": [1, {"c": 3, "d": 2}], "b": 1} - ) - - -def test_canonical_is_compact_and_keeps_non_ascii() -> None: - assert canonical({"a": "é", "b": [1, 2]}) == '{"a":"é","b":[1,2]}'.encode() - - -def test_canonical_refuses_nan() -> None: - with pytest.raises(ValueError): - canonical({"x": float("nan")}) - - -def test_turn_id_covers_the_content_hash_not_the_content() -> None: - turn = make_turn("message", HUMAN, [], [{"type": "text", "text": "hi"}]) - - assert turn.core["content"] == content_id([{"type": "text", "text": "hi"}]) - assert "blocks" not in turn.core - assert turn.id == digest(turn.core) - - -def test_facts_do_not_change_identity() -> None: - blocks = [{"type": "text", "text": "hi"}] - plain = make_turn("message", HUMAN, [], blocks) - annotated = make_turn("message", HUMAN, [], blocks, {"timestamp": "2026"}) - - assert plain.id == annotated.id - - -def test_parents_and_author_change_identity() -> None: - blocks = [{"type": "text", "text": "hi"}] - root = make_turn("message", HUMAN, [], blocks) - - assert make_turn("message", HUMAN, [root.id], blocks).id != root.id - assert make_turn("message", {"kind": "human"}, [], blocks).id != root.id - - -def chain() -> Derived: - first = make_turn("message", HUMAN, [], [{"type": "text", "text": "a"}]) - second = make_turn("message", HUMAN, [first.id], [{"type": "text", "text": "b"}]) - return Derived( - header=header(), - turns=[first, second], - heads={"current": second.id, "leaves": [second.id]}, - ) - - -def test_round_trips_byte_for_byte() -> None: - packed = pack_derived(chain()) - assert pack_derived(read_derived(packed.decode().split("\n"))) == packed - - -def test_reads_a_tombstoned_turn_and_still_verifies_its_id() -> None: - derived = chain() - tombstoned = Turn( - id=derived.turns[0].id, core=derived.turns[0].core, blocks=None, facts={} - ) - packed = pack_derived( - Derived(derived.header, [tombstoned, derived.turns[1]], derived.heads) - ) - - back = read_derived(packed.decode().split("\n")) - - assert back.turns[0].blocks is None - assert back.turns[0].id == derived.turns[0].id - - -def test_rejects_content_that_does_not_match_its_hash() -> None: - derived = chain() - forged = Turn( - id=derived.turns[0].id, - core=derived.turns[0].core, - blocks=[{"type": "text", "text": "forged"}], - ) - packed = pack_derived(Derived(derived.header, [forged], {})) - - with pytest.raises(FormatError, match="content does not match"): - read_derived(packed.decode().split("\n")) - - -def test_rejects_an_id_that_does_not_match_its_core() -> None: - derived = chain() - turn = derived.turns[0] - forged = Turn(id=digest({"other": 1}), core=turn.core, blocks=turn.blocks) - packed = pack_derived(Derived(derived.header, [forged], {})) - - with pytest.raises(FormatError, match="does not hash to its id"): - read_derived(packed.decode().split("\n")) - - -def test_rejects_a_turn_before_its_parent() -> None: - derived = chain() - packed = pack_derived( - Derived(derived.header, list(reversed(derived.turns)), derived.heads) - ) - - with pytest.raises(FormatError, match="precedes its parent"): - read_derived(packed.decode().split("\n")) - - -def test_rejects_an_unknown_format_version() -> None: - with pytest.raises(FormatError, match="unsupported loch format 2"): - read_derived(['{"type":"header","loch":2}']) - - -@pytest.mark.parametrize( - ("value", "expected"), - [ - (1e21, "1e+21"), - (1e20, "100000000000000000000"), - (1e16, "10000000000000000"), - (0.00001, "0.00001"), - (1e-7, "1e-7"), - (1.5e-7, "1.5e-7"), - (100.0, "100"), - (-0.0, "0"), - (5e-324, "5e-324"), - (1.7976931348623157e308, "1.7976931348623157e+308"), - (333333333.3333333, "333333333.3333333"), - (-1.5, "-1.5"), - ], -) -def test_numbers_print_as_ecmascript_does(value: float, expected: str) -> None: - assert canonical(value) == expected.encode() - - -def test_integers_stay_exact_beyond_double_precision() -> None: - assert canonical(2**70) == b"1180591620717411303424" - - -def test_keys_sort_by_utf16_code_units() -> None: - assert canonical({"￿": 1, "\U0001f600": 2, "a": 3}) == ( - '{"a":3,"\U0001f600":2,"￿":1}'.encode() - ) - - -def test_a_lone_surrogate_is_escaped() -> None: - assert canonical("x\ud83d") == b'"x\\ud83d"' - - -def test_control_characters_escape_as_json_stringify_does() -> None: - assert canonical('a\x01"\\\n') == b'"a\\u0001\\"\\\\\\n"' diff --git a/test/test_git.py b/test/test_git.py deleted file mode 100644 index 772f9ba..0000000 --- a/test/test_git.py +++ /dev/null @@ -1,19 +0,0 @@ -import subprocess -from pathlib import Path - -from loch.git import current_branch - - -def test_current_branch_reads_the_checkout(tmp_path: Path) -> None: - repo = tmp_path / "repo" - repo.mkdir() - subprocess.run( - ["git", "init", "-q", "-b", "feature/foo", str(repo)], - check=True, - capture_output=True, - ) - assert current_branch(str(repo)) == "feature/foo" - - -def test_current_branch_is_none_outside_a_repo(tmp_path: Path) -> None: - assert current_branch(str(tmp_path)) is None diff --git a/test/test_index.py b/test/test_index.py deleted file mode 100644 index be1705d..0000000 --- a/test/test_index.py +++ /dev/null @@ -1,231 +0,0 @@ -from pathlib import Path - -import boto3 -import pytest -from moto import mock_aws - -from loch.bundle import ( - BUNDLE_VERSION, - Bundle, - BundleOrigin, - BundleSession, - bundle_ref, - pack_bundle, -) -from loch.index import ( - BRANCH, - bundle_key, - decode_segment, - delete_bundle, - dimension_prefix, - encode_segment, - entries_for, - index_bundle, - index_key, - load_entries, - ref_from_key, - reindex, - value_prefix, -) -from loch.store import FileStore, MissingObject, S3Store - - -def session(session_id: str, branch: str | None, cwd: str = "/repo") -> BundleSession: - return BundleSession( - session_id=session_id, - cwd=cwd, - git_branch=branch, - claude_version="1.0.99", - modified_at="2026-08-15T12:00:00.000Z", - transcript="{}\n", - ) - - -def make_bundle( - *sessions: BundleSession, created_at: str = "2026-08-15T12:00:00.000Z" -) -> Bundle: - return Bundle( - version=BUNDLE_VERSION, - agent="claude-code", - created_at=created_at, - origin=BundleOrigin(home="/home/origin", platform="linux", hostname="box"), - sessions=list(sessions), - ) - - -def store_with(tmp_path: Path, bundle: Bundle) -> tuple[FileStore, str, int]: - store = FileStore(str(tmp_path / "store")) - packed = pack_bundle(bundle) - ref = bundle_ref(packed) - store.put(bundle_key(ref), packed) - index_bundle(store, bundle, ref, len(packed)) - return store, ref, len(packed) - - -def test_encoding_keeps_a_slashed_branch_in_one_segment() -> None: - assert encode_segment("feature/foo") == "feature%2Ffoo" - assert "/" not in encode_segment("feature/foo/bar") - assert decode_segment(encode_segment("feature/foo")) == "feature/foo" - - -def test_encoding_distinguishes_branches_claudes_scheme_would_collide() -> None: - assert encode_segment("feature/foo") != encode_segment("feature-foo") - assert encode_segment("feature-foo") == "feature-foo" - - -def test_encoding_round_trips_an_absent_value() -> None: - assert decode_segment(encode_segment(None)) is None - assert "/" not in encode_segment(None) - - -def test_keys_follow_the_dimension_layout() -> None: - assert bundle_key("abc") == "bundles/abc.loch" - assert ref_from_key(bundle_key("abc")) == "abc" - assert index_key(BRANCH, "feature/foo", "abc") == "index/branch/feature%2Ffoo/abc" - assert value_prefix(BRANCH, "main") == "index/branch/main/" - assert dimension_prefix(BRANCH) == "index/branch/" - - -def test_a_bundle_spanning_branches_is_indexed_under_each() -> None: - bundle = make_bundle( - session("one", "main"), - session("two", "feature/foo"), - session("three", "feature/foo"), - ) - entries = entries_for(bundle, "abc", 512) - - assert [(entry.value, entry.sessions) for entry in entries] == [ - ("feature/foo", 2), - ("main", 1), - ] - assert {entry.ref for entry in entries} == {"abc"} - assert entries[0].bytes == 512 - assert entries[0].cwd == "/repo" - assert entries[0].claude_version == "1.0.99" - assert entries[0].agent == "claude-code" - - -def test_a_branchless_session_still_gets_an_entry() -> None: - entries = entries_for(make_bundle(session("one", None)), "abc", 1) - assert entries[0].value is None - assert index_key(BRANCH, None, "abc").count("/") == 3 - - -def test_entries_are_readable_without_fetching_the_bundle(tmp_path: Path) -> None: - bundle = make_bundle(session("one", "main"), session("two", "feature/foo")) - store, ref, size = store_with(tmp_path, bundle) - - on_branch = load_entries(store, value_prefix(BRANCH, "feature/foo")) - assert [entry.ref for entry in on_branch] == [ref] - assert on_branch[0].sessions == 1 - assert on_branch[0].bytes == size - - assert len(load_entries(store, dimension_prefix(BRANCH))) == 2 - assert load_entries(store, value_prefix(BRANCH, "nope")) == [] - - -def test_entries_come_back_newest_first(tmp_path: Path) -> None: - store = FileStore(str(tmp_path / "store")) - for created_at, session_id in ( - ("2026-08-01T00:00:00.000Z", "old"), - ("2026-08-14T00:00:00.000Z", "new"), - ): - bundle = make_bundle(session(session_id, "main"), created_at=created_at) - packed = pack_bundle(bundle) - index_bundle(store, bundle, bundle_ref(packed), len(packed)) - - assert [ - entry.created_at for entry in load_entries(store, dimension_prefix(BRANCH)) - ] == [ - "2026-08-14T00:00:00.000Z", - "2026-08-01T00:00:00.000Z", - ] - - -def test_delete_removes_the_bundle_and_every_entry_it_produced(tmp_path: Path) -> None: - bundle = make_bundle(session("one", "main"), session("two", "feature/foo")) - store, ref, _ = store_with(tmp_path, bundle) - - removed = delete_bundle(store, ref) - - assert bundle_key(ref) in removed - assert index_key(BRANCH, "feature/foo", ref) in removed - assert store.list("") == [] - - -def test_delete_leaves_other_bundles_indexed(tmp_path: Path) -> None: - store = FileStore(str(tmp_path / "store")) - refs = [] - for session_id in ("one", "two"): - bundle = make_bundle(session(session_id, "main")) - packed = pack_bundle(bundle) - ref = bundle_ref(packed) - store.put(bundle_key(ref), packed) - index_bundle(store, bundle, ref, len(packed)) - refs.append(ref) - - delete_bundle(store, refs[0]) - - assert [entry.ref for entry in load_entries(store, dimension_prefix(BRANCH))] == [ - refs[1] - ] - - -def test_delete_reports_a_missing_ref(tmp_path: Path) -> None: - store = FileStore(str(tmp_path / "store")) - with pytest.raises(MissingObject): - delete_bundle(store, "nope") - - -def test_reindex_rebuilds_the_index_from_the_bundles_alone(tmp_path: Path) -> None: - bundle = make_bundle(session("one", "main"), session("two", "feature/foo")) - store, ref, _ = store_with(tmp_path, bundle) - before = load_entries(store, dimension_prefix(BRANCH)) - - for key in store.list("index/"): - store.delete(key) - assert load_entries(store, dimension_prefix(BRANCH)) == [] - - result = reindex(store) - - assert result.bundles == 1 - assert result.entries == 2 - assert load_entries(store, dimension_prefix(BRANCH)) == before - - -def test_reindex_drops_entries_no_bundle_backs(tmp_path: Path) -> None: - bundle = make_bundle(session("one", "main")) - store, ref, _ = store_with(tmp_path, bundle) - orphan = index_key(BRANCH, "gone", "deadbeef") - store.put(orphan, b'{"ref":"deadbeef","dimension":"branch","value":"gone"}') - - result = reindex(store) - - assert result.removed == 1 - assert orphan not in store.list("index/") - assert store.list(value_prefix(BRANCH, "main")) == [index_key(BRANCH, "main", ref)] - - -@mock_aws -def test_an_encoded_branch_survives_a_round_trip_through_s3( - 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("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") - bundle = make_bundle(session("one", "feature/foo")) - packed = pack_bundle(bundle) - ref = bundle_ref(packed) - store.put(bundle_key(ref), packed) - index_bundle(store, bundle, ref, len(packed)) - - entries = load_entries(store, value_prefix(BRANCH, "feature/foo")) - assert [entry.value for entry in entries] == ["feature/foo"] - - delete_bundle(store, ref) - assert store.list("") == [] diff --git a/test/test_ingest.py b/test/test_ingest.py deleted file mode 100644 index 64b6a53..0000000 --- a/test/test_ingest.py +++ /dev/null @@ -1,403 +0,0 @@ -import base64 -import hashlib -import json -from pathlib import Path -from typing import Any - -import pytest - -from loch.format import pack_derived, read_derived -from loch.ingest import ( - ESCAPE, - HOME, - ROOT, - ROOT_SLUG, - SESSION, - AuthorKeyError, - Origin, - convert, - ingest, - ssh_author_id, -) -from loch.rewrite import RewriteSpec, rewrite_transcript - -HOME_DIR = "/Users/origin" -CWD = "/Users/origin/code/repo" -SESSION_ID = "11111111-1111-1111-1111-111111111111" -ORIGIN = Origin(CWD, HOME_DIR, SESSION_ID) -HUMAN = {"kind": "human"} - - -def record(uuid: str, parent: str | None, kind: str, **fields: Any) -> dict[str, Any]: - base: dict[str, Any] = { - "type": kind, - "uuid": uuid, - "parentUuid": parent, - "sessionId": SESSION_ID, - "cwd": CWD, - "gitBranch": "main", - "version": "2.0.0", - "timestamp": f"2026-01-01T00:00:{uuid[-2:]}Z", - } - base.update(fields) - return base - - -def user(uuid: str, parent: str | None, content: Any, **fields: Any) -> dict[str, Any]: - return record( - uuid, parent, "user", message={"role": "user", "content": content}, **fields - ) - - -def assistant( - uuid: str, parent: str | None, blocks: list[Any], message_id: str = "msg_1" -) -> dict[str, Any]: - message = {"id": message_id, "role": "assistant", "model": "m", "content": blocks} - return record(uuid, parent, "assistant", message=message) - - -def jsonl(*records: dict[str, Any]) -> str: - return "".join(json.dumps(r) + "\n" for r in records) - - -def session() -> str: - """A prompt, an assistant message split across two records (thinking, - then a tool call), the tool result, and a reply — the shape Claude Code - writes for one tool-using exchange.""" - return jsonl( - {"type": "custom-title", "customTitle": "demo", "sessionId": SESSION_ID}, - user("u-01", None, f"look at {CWD}/src/main.py"), - assistant("a-02", "u-01", [{"type": "thinking", "thinking": "hmm"}]), - assistant( - "a-03", - "a-02", - [ - { - "type": "tool_use", - "id": "toolu_1", - "name": "Read", - "input": {"file_path": f"{CWD}/src/main.py"}, - } - ], - ), - user( - "u-04", - "a-03", - [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "print()"}], - toolUseResult={"file": {"filePath": f"{CWD}/src/main.py"}}, - ), - assistant("a-05", "u-04", [{"type": "text", "text": "done"}], "msg_2"), - {"type": "last-prompt", "leafUuid": "a-05", "sessionId": SESSION_ID}, - ) - - -def test_one_turn_per_chain_record_linked_by_parent() -> None: - turns, heads, _ = convert(session(), ORIGIN, HUMAN) - - assert [turn.core["kind"] for turn in turns] == [ - "message", - "message", - "message", - "tool-result", - "message", - ] - for parent, child in zip(turns, turns[1:]): - assert child.core["parents"] == [parent.id] - assert turns[0].core["parents"] == [] - assert heads == {"current": turns[-1].id, "leaves": [turns[-1].id]} - - -def test_authors_follow_who_produced_the_record() -> None: - turns, _, _ = convert(session(), ORIGIN, {"kind": "human", "id": "alice"}) - - assert [turn.core["author"]["kind"] for turn in turns] == [ - "human", - "agent", - "agent", - "tool", - "agent", - ] - assert turns[0].core["author"] == {"kind": "human", "id": "alice"} - - -def test_split_assistant_message_is_regrouped_by_message_id_fact() -> None: - turns, _, _ = convert(session(), ORIGIN, HUMAN) - - assert [turn.facts.get("messageId") for turn in turns] == [ - None, - "msg_1", - "msg_1", - None, - "msg_2", - ] - - -def test_blocks_are_normalized_to_loch_shapes() -> None: - turns, _, _ = convert(session(), ORIGIN, HUMAN) - - assert turns[1].blocks == [{"type": "thinking", "text": "hmm"}] - assert turns[2].blocks == [ - { - "type": "tool-call", - "call": "toolu_1", - "name": "Read", - "input": {"file_path": f"{ROOT}/src/main.py"}, - } - ] - assert turns[3].blocks == [ - { - "type": "tool-result", - "call": "toolu_1", - "content": [{"type": "text", "text": "print()"}], - } - ] - - -def test_machine_specific_strings_become_placeholders() -> None: - raw = jsonl( - user( - "u-01", - None, - f"{CWD}/a {HOME_DIR}/.zshrc " - f"{HOME_DIR}/.claude/projects/-Users-origin-code-repo/{SESSION_ID}.jsonl " - "literal {{loch:root}}", - ) - ) - turns, _, _ = convert(raw, ORIGIN, HUMAN) - - assert turns[0].blocks == [ - { - "type": "text", - "text": f"{ROOT}/a {HOME}/.zshrc " - f"{HOME}/.claude/projects/{ROOT_SLUG}/{SESSION}.jsonl " - f"literal {ESCAPE}root}}}}", - } - ] - assert turns[0].facts["cwd"] == ROOT - - -def test_sibling_of_the_root_is_not_taken_for_it() -> None: - raw = jsonl(user("u-01", None, f"{CWD}-worktrees/feature/x")) - turns, _, _ = convert(raw, ORIGIN, HUMAN) - - assert turns[0].blocks == [ - {"type": "text", "text": f"{HOME}/code/repo-worktrees/feature/x"} - ] - - -def test_turn_ids_survive_a_restore_to_another_machine() -> None: - target = Origin( - "/home/bob/src/repo", "/home/bob", "2" * 8 + "-2222-2222-2222-" + "2" * 12 - ) - spec = RewriteSpec( - origin_cwd=CWD, - origin_home=HOME_DIR, - target_cwd=target.cwd, - target_home=target.home, - origin_session_id=SESSION_ID, - target_session_id=target.session_id, - ) - original = convert(session(), ORIGIN, HUMAN) - copied = convert(rewrite_transcript(session(), spec), target, HUMAN) - - assert [t.id for t in copied[0]] == [t.id for t in original[0]] - assert copied[1] == original[1] - - -def test_timestamps_and_record_uuids_are_facts_not_identity() -> None: - renamed = session().replace("u-01", "x-99").replace("00:01Z", "09:09Z") - original, _, _ = convert(session(), ORIGIN, HUMAN) - changed, _, _ = convert(renamed, ORIGIN, HUMAN) - - assert [t.id for t in changed] == [t.id for t in original] - assert changed[0].facts["uuid"] == "x-99" - - -def test_a_rewind_leaves_two_heads() -> None: - raw = jsonl( - user("u-01", None, "start"), - assistant("a-02", "u-01", [{"type": "text", "text": "first try"}], "m1"), - assistant("a-03", "u-01", [{"type": "text", "text": "second try"}], "m2"), - {"type": "last-prompt", "leafUuid": "a-02", "sessionId": SESSION_ID}, - ) - turns, heads, _ = convert(raw, ORIGIN, HUMAN) - - assert heads["leaves"] == [turns[1].id, turns[2].id] - assert heads["current"] == turns[1].id - - -def test_identical_resubmission_from_the_same_point_is_one_turn() -> None: - raw = jsonl( - user("u-01", None, "start"), - user("u-02", "u-01", "again"), - user("u-03", "u-01", "again"), - ) - turns, _, _ = convert(raw, ORIGIN, HUMAN) - - assert len(turns) == 2 - assert turns[1].facts["alsoUuids"] == ["u-03"] - - -def test_compaction_boundary_follows_its_logical_parent() -> None: - raw = jsonl( - user("u-01", None, "long conversation"), - record( - "s-02", - None, - "system", - subtype="compact_boundary", - logicalParentUuid="u-01", - content="Conversation compacted", - ), - user("u-03", "s-02", "summary of before", isCompactSummary=True), - ) - turns, heads, _ = convert(raw, ORIGIN, HUMAN) - - assert [t.core["kind"] for t in turns] == ["message", "compaction", "context"] - assert turns[1].core["parents"] == [turns[0].id] - assert heads["leaves"] == [turns[2].id] - - -def test_dangling_parent_becomes_a_root_and_says_so() -> None: - raw = jsonl(user("u-02", "u-gone", "orphan")) - turns, _, _ = convert(raw, ORIGIN, HUMAN) - - assert turns[0].core["parents"] == [] - assert turns[0].facts["danglingParent"] == "u-gone" - - -def test_a_child_written_before_its_parent_still_links() -> None: - raw = jsonl(user("u-02", "u-01", "child"), user("u-01", None, "parent")) - turns, _, _ = convert(raw, ORIGIN, HUMAN) - - assert turns[0].facts["uuid"] == "u-01" - assert turns[1].core["parents"] == [turns[0].id] - - -def test_unknown_blocks_and_records_pass_through_or_stay_out() -> None: - raw = jsonl( - {"type": "cost-state", "totalCostUSD": 1.0, "sessionId": SESSION_ID}, - assistant("a-01", None, [{"type": "future_block", "x": 1}]), - ) - turns, _, _ = convert(raw, ORIGIN, HUMAN) - - assert len(turns) == 1 - assert turns[0].blocks == [ - {"type": "x-claude-code:block", "block": {"type": "future_block", "x": 1}} - ] - - -def test_attachment_payload_excludes_the_record_envelope() -> None: - raw = jsonl( - record("t-01", None, "attachment", attachment={"type": "todo", "items": []}) - ) - turns, _, _ = convert(raw, ORIGIN, HUMAN) - - assert turns[0].core["kind"] == "context" - assert turns[0].blocks == [ - { - "type": "x-claude-code:attachment", - "attachment": {"attachment": {"type": "todo", "items": []}}, - } - ] - - -def write(tmp_path: Path, raw: str) -> Path: - path = tmp_path / f"{SESSION_ID}.jsonl" - path.write_text(raw, encoding="utf-8") - return path - - -def test_source_manifest_hashes_the_transcript_and_its_sidecar(tmp_path: Path) -> None: - path = write(tmp_path, session()) - sidecar = tmp_path / SESSION_ID / "subagents" - sidecar.mkdir(parents=True) - (sidecar / "agent-a.jsonl").write_text("{}\n", encoding="utf-8") - - derived = ingest(str(path), ORIGIN) - - files = derived.header["source"]["files"] - assert [f["path"] for f in files] == [ - "sidecar/subagents/agent-a.jsonl", - "transcript.jsonl", - ] - assert derived.header["source"]["id"].startswith("sha256:") - assert derived.header["session"] == {"title": "demo"} - - -def test_ingest_is_idempotent_and_reads_back_verified(tmp_path: Path) -> None: - path = write(tmp_path, session()) - - first = pack_derived(ingest(str(path), ORIGIN, "alice")) - second = pack_derived(ingest(str(path), ORIGIN, "alice")) - - assert first == second - assert pack_derived(read_derived(first.decode().split("\n"))) == first - - -def test_appending_to_a_session_keeps_every_earlier_turn_id(tmp_path: Path) -> None: - before = convert(session(), ORIGIN, HUMAN)[0] - grown = session() + jsonl(user("u-06", "a-05", "and then?")) - after = convert(grown, ORIGIN, HUMAN)[0] - - assert [t.id for t in after[: len(before)]] == [t.id for t in before] - - -def test_events_fold_into_the_turn_they_follow() -> None: - raw = jsonl( - user("u-01", None, "start"), - record("s-02", "u-01", "system", subtype="stop_hook_summary", hookCount=1), - assistant("a-03", "s-02", [{"type": "text", "text": "reply"}]), - {"type": "last-prompt", "leafUuid": "s-02", "sessionId": SESSION_ID}, - ) - turns, heads, _ = convert(raw, ORIGIN, HUMAN) - - assert [t.core["kind"] for t in turns] == ["message", "message"] - assert turns[1].core["parents"] == [turns[0].id] - [event] = turns[0].facts["events"] - assert event["type"] == "x-claude-code:system" - assert event["system"] == {"subtype": "stop_hook_summary", "hookCount": 1} - assert heads["current"] == turns[0].id - - -def test_events_do_not_change_the_ids_around_them() -> None: - plain = jsonl( - user("u-01", None, "start"), - assistant("a-03", "u-01", [{"type": "text", "text": "reply"}]), - ) - with_event = jsonl( - user("u-01", None, "start"), - record("s-02", "u-01", "system", subtype="turn_duration", durationMs=5), - assistant("a-03", "s-02", [{"type": "text", "text": "reply"}]), - ) - - assert [t.id for t in convert(with_event, ORIGIN, HUMAN)[0]] == [ - t.id for t in convert(plain, ORIGIN, HUMAN)[0] - ] - - -def test_an_event_with_no_turn_before_it_is_kept_at_session_level() -> None: - raw = jsonl( - record("s-01", None, "system", subtype="informational", content="hi"), - user("u-02", "s-01", "start"), - ) - turns, _, session = convert(raw, ORIGIN, HUMAN) - - assert len(turns) == 1 - assert session["events"][0]["system"]["subtype"] == "informational" - - -def test_ssh_author_id_is_the_ssh_keygen_fingerprint_of_the_key_blob() -> None: - """ssh-keygen -l hashes the decoded key blob with SHA-256 and prints it as - unpadded base64; checked against ssh-keygen by hand on a real key.""" - blob = b"\x00\x00\x00\x0bssh-ed25519" + bytes(range(32)) - line = "ssh-ed25519 " + base64.b64encode(blob).decode() + " me@host" - expected = base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=") - - assert ssh_author_id(line) == f"ssh:SHA256:{expected}" - assert ssh_author_id(line.rsplit(" ", 1)[0]) == ssh_author_id(line) - - -def test_ssh_author_id_rejects_something_that_is_not_a_key() -> None: - with pytest.raises(AuthorKeyError): - ssh_author_id("not-a-key") diff --git a/test/test_output.py b/test/test_output.py deleted file mode 100644 index c9ed15b..0000000 --- a/test/test_output.py +++ /dev/null @@ -1,61 +0,0 @@ -import json - -import pytest - -from loch.output import SCHEMA, CommandError, Result, document, emit, emit_error - - -def test_a_success_envelope_carries_no_error_fields() -> None: - body = document("save", True, {"ref": "abc"}) - assert body == {"schema": SCHEMA, "ok": True, "command": "save", "ref": "abc"} - - -def test_a_failure_envelope_carries_the_stable_code() -> None: - body = document("restore", False, {"ref": "abc"}, "nothing-restored", "nothing") - assert body["ok"] is False - assert body["code"] == "nothing-restored" - assert body["error"] == "nothing" - assert body["ref"] == "abc" - - -def test_json_mode_writes_one_document_and_leaves_stderr_alone( - capsys: pytest.CaptureFixture[str], -) -> None: - emit(Result("list", {"sessions": []}, text="prose", warnings=("warned\n",)), True) - - out, err = capsys.readouterr() - assert json.loads(out)["sessions"] == [] - assert out.count("\n") == 1 - assert err == "" - - -def test_text_mode_writes_prose_and_warnings_to_their_own_streams( - capsys: pytest.CaptureFixture[str], -) -> None: - emit( - Result("list", {"sessions": []}, text="prose\n", warnings=("warned\n",)), False - ) - - out, err = capsys.readouterr() - assert out == "prose\n" - assert err == "warned\n" - - -def test_an_error_exits_nonzero_in_both_modes( - capsys: pytest.CaptureFixture[str], -) -> None: - error = CommandError("usage", "bad flag", exit_status=2) - - with pytest.raises(SystemExit) as failure: - emit_error("list", error, True) - out, err = capsys.readouterr() - assert failure.value.code == 2 - assert json.loads(out)["code"] == "usage" - assert err == "" - - with pytest.raises(SystemExit) as failure: - emit_error("list", error, False) - out, err = capsys.readouterr() - assert failure.value.code == 2 - assert out == "" - assert err == "loch: bad flag\n" diff --git a/test/test_redact.py b/test/test_redact.py deleted file mode 100644 index f6c52eb..0000000 --- a/test/test_redact.py +++ /dev/null @@ -1,149 +0,0 @@ -import json - -import pytest - -from loch.redact import RULES, RedactionError, Rule, redact, scan, summarize - -# Structurally valid, obviously synthetic. Nothing here is or was a credential. -FAKE = { - "aws-access-key": "AKIAZZZZZZZZEXAMPLE0", - "github-token": "ghp_" + "A0" * 20, - # Split, and with non-numeric segments, so the literal in this file does - # not match GitHub's push-protection pattern for a real Slack token. - "slack-token": "xoxb-" + "EXAMPLE-NOT-A-REAL-TOKEN-" + "Z" * 12, - "stripe-key": "sk_live_" + "0" * 24, - "anthropic-key": "sk-ant-api03-" + "x" * 24, - "openai-key": "sk-proj-" + "y" * 24, - "google-api-key": "AIza" + "B" * 35, - "jwt": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmYWtlIn0.c2lnbmF0dXJl", - "private-key-block": ( - "-----BEGIN RSA PRIVATE KEY-----\\nMIIBOgIBAAJBAKfake\\n" - "-----END RSA PRIVATE KEY-----" - ), -} - - -def line(**fields: object) -> str: - return json.dumps(fields, separators=(",", ":")) - - -@pytest.mark.parametrize("name", sorted(FAKE)) -def test_each_rule_matches_and_removes_the_secret(name: str) -> None: - out = redact(f"the value is {FAKE[name]} ok") - - assert out.counts == {name: 1} - assert FAKE[name] not in out.text - assert f"[REDACTED:{name}]" in out.text - - -def test_an_env_assignment_keeps_the_name_and_drops_the_value() -> None: - out = redact("AWS_SECRET_ACCESS_KEY=wJalrFAKEfakeFAKEfakeFAKEfakeFAKEfake0000") - - assert out.text == "AWS_SECRET_ACCESS_KEY=[REDACTED:env-assignment]" - assert out.counts == {"env-assignment": 1} - - -def test_an_env_assignment_is_found_inside_a_json_string_value() -> None: - out = redact(line(GITHUB_TOKEN="ghs_notarealtokenatall000000")) - - assert json.loads(out.text) == {"GITHUB_TOKEN": "[REDACTED:env-assignment]"} - - -def test_redacted_lines_still_parse_as_json() -> None: - raw = "\n".join( - [ - line(type="user", message=f"my key is {FAKE['aws-access-key']}"), - line(type="assistant", toolUseResult=f"PASSWORD={'p' * 20}"), - line(type="assistant", toolUseResult=FAKE["private-key-block"]), - ] - ) - - out = redact(raw) - - for redacted_line in out.text.splitlines(): - json.loads(redacted_line) - assert sum(out.counts.values()) == 3 - - -def test_a_redaction_token_is_not_itself_redacted() -> None: - once = redact(f"AWS_SECRET_ACCESS_KEY={'z' * 40} and {FAKE['github-token']}") - twice = redact(once.text) - - assert twice.text == once.text - assert twice.counts == {} - - -def test_the_longest_match_wins_between_overlapping_prefixes() -> None: - out = redact(FAKE["anthropic-key"]) - - assert out.counts == {"anthropic-key": 1} - - -def test_verification_rejects_a_rule_that_leaves_its_own_match_behind() -> None: - # A rule whose replacement still matches: the token contains "AKIA..." only - # because the rule keeps the text it was supposed to remove. - broken = (Rule("keeps-the-secret", r"(?PAKIA[0-9A-Z]{16})"),) - - with pytest.raises(RedactionError, match="still match after redaction"): - redact(FAKE["aws-access-key"], rules=broken) - - -def test_ordinary_transcript_content_survives_untouched() -> None: - innocuous = "\n".join( - [ - line(cwd="/Users/mike/Programming/personal/apps/lochy"), - 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/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), - ] - ) - - out = redact(innocuous) - - assert out.text == innocuous - assert out.counts == {} - - -def test_a_key_prefix_landing_mid_word_is_not_a_key() -> None: - out = redact( - "\n".join( - [ - line(diff=".task-container-header { flex: 1; }"), - line(blob="PiW6ADDuAAAAAAAAAAAAAAAAAAAAACCAAAAAAAAAAAAAAAAAAAAA"), - line(css="risk-assessment-panel-collapsed-state"), - ] - ) - ) - - assert out.counts == {} - - -def test_a_short_or_path_like_value_is_not_treated_as_a_secret() -> None: - out = redact("TOKEN: no\nSECRET_PATH=/Users/mike/.config/creds\nTOKEN_DIR=~/keys") - - assert out.counts == {} - - -def test_scan_reports_what_a_redacted_transcript_no_longer_contains() -> None: - raw = f"{FAKE['jwt']} {FAKE['stripe-key']}" - - assert scan(raw) == {"jwt": 1, "stripe-key": 1} - assert scan(redact(raw).text) == {} - - -def test_summarize_names_each_rule_without_quoting_the_secret() -> None: - assert summarize({}) == "" - assert summarize({"jwt": 1}) == "redacted 1 secret (jwt ×1)" - assert ( - summarize({"env-assignment": 3, "aws-access-key": 1}) - == "redacted 4 secrets (aws-access-key ×1, env-assignment ×3)" - ) - - -def test_every_rule_has_a_token_safe_name() -> None: - for rule in RULES: - assert not set(rule.name) & set('"\\\n') diff --git a/test/test_rewrite.py b/test/test_rewrite.py deleted file mode 100644 index ab92abb..0000000 --- a/test/test_rewrite.py +++ /dev/null @@ -1,238 +0,0 @@ -import json - -from loch.rewrite import ( - ForeignCwd, - RewriteSpec, - foreign_cwds, - residual_origin_paths, - rewrite_transcript, -) - -CROSS_MACHINE = RewriteSpec( - origin_cwd="/Users/mike/proj", - origin_home="/Users/mike", - target_cwd="/Users/alice/work/proj", - target_home="/Users/alice", -) - - -def dumps(value: object) -> str: - return json.dumps(value, separators=(",", ":")) - - -def test_rewrites_the_cwd_field_and_paths_inside_tool_results() -> None: - raw = "\n".join( - [ - dumps({"type": "user", "cwd": "/Users/mike/proj", "gitBranch": "main"}), - dumps( - {"type": "assistant", "toolUseResult": "read /Users/mike/proj/src/a.py"} - ), - ] - ) - - out = rewrite_transcript(raw, CROSS_MACHINE) - - assert '"cwd":"/Users/alice/work/proj"' in out - assert "/Users/alice/work/proj/src/a.py" in out - assert "/Users/mike" not in out - - -def test_does_not_double_rewrite_a_cwd_nested_under_the_home_directory() -> None: - raw = dumps( - {"cwd": "/Users/mike/proj", "config": "/Users/mike/.claude/settings.json"} - ) - - out = rewrite_transcript(raw, CROSS_MACHINE) - - assert '"cwd":"/Users/alice/work/proj"' in out - assert "/Users/alice/.claude/settings.json" in out - assert "/Users/alice/work/proj/.claude/settings.json" not in out - - -def test_rewrites_the_encoded_project_directory_form() -> None: - raw = dumps({"note": "~/.claude/projects/-Users-mike-proj/abc.jsonl"}) - - out = rewrite_transcript(raw, CROSS_MACHINE) - - assert "-Users-alice-work-proj" in out - assert "-Users-mike-proj" not in out - - -def test_rewrites_the_session_id_when_a_new_one_is_minted() -> None: - raw = dumps({"sessionId": "old-id", "uuid": "x"}) - - out = rewrite_transcript( - raw, - RewriteSpec( - origin_cwd=CROSS_MACHINE.origin_cwd, - origin_home=CROSS_MACHINE.origin_home, - target_cwd=CROSS_MACHINE.target_cwd, - target_home=CROSS_MACHINE.target_home, - origin_session_id="old-id", - target_session_id="new-id", - ), - ) - - assert '"sessionId":"new-id"' in out - - -def test_leaves_the_transcript_untouched_when_origin_and_target_match() -> None: - same_machine = RewriteSpec( - origin_cwd="/Users/mike/proj", - origin_home="/Users/mike", - target_cwd="/Users/mike/proj", - target_home="/Users/mike", - ) - raw = dumps({"cwd": "/Users/mike/proj"}) - - assert rewrite_transcript(raw, same_machine) == raw - - -def test_residual_reports_nothing_when_the_rewrite_was_complete() -> None: - out = rewrite_transcript(dumps({"cwd": "/Users/mike/proj"}), CROSS_MACHINE) - assert residual_origin_paths(out, CROSS_MACHINE) == [] - - -def test_residual_reports_origin_paths_that_survived() -> None: - assert residual_origin_paths( - "stale /Users/mike/elsewhere/file.py", CROSS_MACHINE - ) == ["/Users/mike"] - - -# Harness puts every worktree at `-worktrees/`, a sibling of the -# repo, so a session whose cwd is the main repo shares a prefix with every -# worktree path in the same transcript. -HARNESS_LAYOUT = RewriteSpec( - origin_cwd="/Users/mike/apps/harness", - origin_home="/Users/mike", - target_cwd="/private/tmp/dest-worktrees/feat/send", - target_home="/Users/mike", -) - - -def test_leaves_a_sibling_directory_that_only_extends_the_cwd() -> None: - sibling = "/Users/mike/apps/harness-worktrees/feat/send" - - out = rewrite_transcript(dumps({"cwd": sibling}), HARNESS_LAYOUT) - - assert out == dumps({"cwd": sibling}) - - -def test_a_skipped_sibling_becomes_a_visible_residual() -> None: - raw = dumps({"cwd": "/Users/mike/apps/harness-worktrees/feat/send"}) - - out = rewrite_transcript(raw, HARNESS_LAYOUT) - - assert residual_origin_paths(out, HARNESS_LAYOUT) == ["/Users/mike/apps/harness"] - - -def test_rewrites_the_real_cwd_while_leaving_its_sibling_alone() -> None: - raw = "\n".join( - [ - dumps({"cwd": "/Users/mike/apps/harness"}), - dumps({"cwd": "/Users/mike/apps/harness-worktrees/feat/send"}), - dumps({"toolUseResult": "read /Users/mike/apps/harness/src/main.py"}), - ] - ) - - out = rewrite_transcript(raw, HARNESS_LAYOUT) - - assert out.splitlines() == [ - dumps({"cwd": "/private/tmp/dest-worktrees/feat/send"}), - dumps({"cwd": "/Users/mike/apps/harness-worktrees/feat/send"}), - dumps( - {"toolUseResult": "read /private/tmp/dest-worktrees/feat/send/src/main.py"} - ), - ] - - -def test_leaves_a_home_directory_that_only_extends_the_origin_home() -> None: - raw = dumps({"path": "/Users/mikey/notes.txt"}) - - assert rewrite_transcript(raw, CROSS_MACHINE) == raw - - -def test_falls_through_to_the_home_pair_when_the_cwd_pair_fails_its_guard() -> None: - out = rewrite_transcript( - dumps({"path": "/Users/mike/projector/a.py"}), CROSS_MACHINE - ) - - assert out == dumps({"path": "/Users/alice/projector/a.py"}) - - -def test_rewrites_the_encoded_slug_only_as_a_complete_component() -> None: - raw = dumps( - { - "own": "~/.claude/projects/-Users-mike-proj/abc.jsonl", - "sibling": "~/.claude/projects/-Users-mike-proj-worktrees-feat-send/d.jsonl", - } - ) - - out = rewrite_transcript(raw, CROSS_MACHINE) - - assert "projects/-Users-alice-work-proj/abc.jsonl" in out - assert "projects/-Users-mike-proj-worktrees-feat-send/d.jsonl" in out - - -def test_foreign_cwds_is_empty_when_every_record_reaches_the_target() -> None: - assert foreign_cwds(dumps({"cwd": "/Users/mike/proj"}), CROSS_MACHINE) == {} - - -def test_foreign_cwds_catches_what_residual_paths_cannot_see() -> None: - """The failure that reported success: a cwd the spec was not keyed on - declines the cwd pair, falls through to the home pair, and lands as a - well-formed path on this machine that isn't there. The origin marker is - consumed on the way, so residual_origin_paths comes back clean.""" - raw = "\n".join( - [ - dumps({"cwd": "/Users/mike/proj"}), - dumps({"cwd": "/Users/mike/other"}), - dumps({"cwd": "/Users/mike/other"}), - ] - ) - - out = rewrite_transcript(raw, CROSS_MACHINE) - - assert "/Users/alice/other" in out - assert residual_origin_paths(out, CROSS_MACHINE) == [] - assert foreign_cwds(raw, CROSS_MACHINE) == { - "/Users/mike/other": ForeignCwd(count=2, restored="/Users/alice/other") - } - - -def test_foreign_cwds_keys_on_the_origin_rather_than_a_reversal() -> None: - """The origin path is the left-hand side of any mapping a caller states, - and it survives losslessly only before the rewrite. Recovering it from the - restored value would mean assuming a leading target home came from the - origin's — right most of the time, silently wrong otherwise, which is the - failure this branch exists to stop.""" - raw = dumps({"cwd": "/Users/mike/other"}) - - (origin,) = foreign_cwds(raw, CROSS_MACHINE) - - assert origin == "/Users/mike/other" - assert origin in raw - assert origin not in rewrite_transcript(raw, CROSS_MACHINE) - - -def test_foreign_cwds_ignores_a_cwd_nested_in_tool_output() -> None: - """`"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( - { - "cwd": "/Users/mike/proj", - "toolUseResult": dumps({"cwd": "/somewhere/else"}), - } - ) - - assert foreign_cwds(raw, CROSS_MACHINE) == {} - - -def test_still_rewrites_a_path_at_every_ordinary_terminator() -> None: - for terminator in ('"', "/", "\\", " ", ":", ",", "\n", ")", "'", ""): - raw = f"/Users/mike/proj{terminator}" - - assert rewrite_transcript(raw, CROSS_MACHINE) == ( - f"/Users/alice/work/proj{terminator}" - ) diff --git a/test/test_store.py b/test/test_store.py deleted file mode 100644 index bd9c821..0000000 --- a/test/test_store.py +++ /dev/null @@ -1,209 +0,0 @@ -import os -import sys -from pathlib import Path - -import boto3 -import pytest -from moto import mock_aws - -from loch.store import ( - DEFAULT_STORE, - FileStore, - MissingDependency, - MissingObject, - S3Store, - create_store, - resolve_store_uri, -) - - -@pytest.fixture -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("LOCH_S3_ENDPOINT", raising=False) - monkeypatch.delenv("LOCH_S3_REGION", raising=False) - - -def test_file_store_round_trips(tmp_path: Path) -> None: - store = FileStore(str(tmp_path / "store")) - store.put("abc.loch", b"payload") - assert store.get("abc.loch") == b"payload" - assert store.describe() == str(tmp_path / "store") - - -def test_file_store_lists_by_prefix_and_deletes(tmp_path: Path) -> None: - store = FileStore(str(tmp_path / "store")) - store.put("bundles/abc.loch", b"a") - store.put("index/branch/main/abc", b"b") - store.put("index/branch/feature%2Ffoo/abc", b"c") - - assert store.list("") == [ - "bundles/abc.loch", - "index/branch/feature%2Ffoo/abc", - "index/branch/main/abc", - ] - assert store.list("index/branch/ma") == ["index/branch/main/abc"] - assert store.list("nothing/") == [] - - store.delete("index/branch/main/abc") - store.delete("index/branch/main/abc") - assert store.list("index/") == ["index/branch/feature%2Ffoo/abc"] - - -def test_file_store_lists_nothing_before_anything_is_written(tmp_path: Path) -> None: - assert FileStore(str(tmp_path / "missing")).list("") == [] - - -def test_file_store_reports_an_absent_object_as_missing_not_as_an_os_error( - tmp_path: Path, -) -> None: - store = FileStore(str(tmp_path / "store")) - with pytest.raises(MissingObject): - store.get("bundles/nope.loch") - - -def test_file_store_lets_an_unreachable_root_surface_as_itself( - tmp_path: Path, -) -> None: - """A store that can't answer is not a store answering "absent" — the - caller retries one and gives up on the other.""" - blocked = tmp_path / "blocked" - blocked.write_text("not a directory", encoding="utf-8") - - with pytest.raises(OSError) as failure: - FileStore(str(blocked)).get("bundles/nope.loch") - assert not isinstance(failure.value, MissingObject) - - -def test_create_store_parses_uris(tmp_path: Path) -> None: - assert isinstance(create_store(str(tmp_path)), FileStore) - assert create_store(f"file://{tmp_path}").describe() == str(tmp_path) - assert create_store("relative/path").describe() == os.path.abspath("relative/path") - - s3 = create_store("s3://bucket/sessions/") - assert isinstance(s3, S3Store) - assert s3.describe() == "s3://bucket/sessions" - assert create_store("s3://bucket").describe() == "s3://bucket/" - - -def test_create_store_rejects_a_bucketless_s3_uri() -> None: - with pytest.raises(ValueError, match="invalid S3 store URI"): - create_store("s3:///sessions") - - -def test_resolve_store_uri_prefers_explicit_then_env( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.delenv("LOCH_STORE", raising=False) - assert resolve_store_uri() == DEFAULT_STORE - monkeypatch.setenv("LOCH_STORE", "s3://from-env/x") - assert resolve_store_uri() == "s3://from-env/x" - assert resolve_store_uri("/explicit") == "/explicit" - - -@mock_aws -def test_s3_store_round_trips(aws_credentials: None) -> None: - boto3.client("s3", region_name="us-east-1").create_bucket(Bucket="sessions") - - store = S3Store("sessions", "bundles") - store.put("abc.loch", b"payload") - - assert store.get("abc.loch") == b"payload" - stored = boto3.client("s3", region_name="us-east-1").get_object( - Bucket="sessions", Key="bundles/abc.loch" - ) - assert stored["ContentType"] == "application/gzip" - - -@mock_aws -def test_s3_store_reports_an_absent_key_as_missing(aws_credentials: None) -> None: - boto3.client("s3", region_name="us-east-1").create_bucket(Bucket="sessions") - - with pytest.raises(MissingObject): - S3Store("sessions", "bundles").get("abc.loch") - - -def test_s3_store_reports_an_uninstalled_sdk_as_such( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """boto3 is an optional extra, so the SDK being absent is an ordinary - outcome on a default install rather than a broken environment. None in - sys.modules is what an import of an uninstalled package looks like.""" - monkeypatch.setitem(sys.modules, "boto3", None) - - for call in ( - lambda: S3Store("sessions", "bundles").get("abc.loch"), - lambda: S3Store("sessions", "bundles").put("abc.loch", b"payload"), - lambda: S3Store("sessions", "bundles").list(""), - lambda: S3Store("sessions", "bundles").delete("abc.loch"), - ): - with pytest.raises(MissingDependency, match=r"loch\[s3\]"): - call() - - -@mock_aws -def test_s3_store_lets_a_missing_bucket_surface_as_itself( - aws_credentials: None, -) -> None: - from botocore.exceptions import ClientError - - with pytest.raises(ClientError): - S3Store("no-such-bucket", "bundles").get("abc.loch") - - -@mock_aws -def test_s3_store_without_a_prefix(aws_credentials: None) -> None: - boto3.client("s3", region_name="us-east-1").create_bucket(Bucket="sessions") - - store = S3Store("sessions", "") - store.put("abc.loch", b"payload") - - stored = boto3.client("s3", region_name="us-east-1").list_objects_v2( - Bucket="sessions" - ) - assert [item["Key"] for item in stored["Contents"]] == ["abc.loch"] - - -@mock_aws -def test_s3_store_lists_by_prefix_and_deletes(aws_credentials: None) -> None: - boto3.client("s3", region_name="us-east-1").create_bucket(Bucket="sessions") - - store = S3Store("sessions", "bundles") - store.put("bundles/abc.loch", b"a") - store.put("index/branch/main/abc", b"b") - - assert store.list("") == ["bundles/abc.loch", "index/branch/main/abc"] - assert store.list("index/") == ["index/branch/main/abc"] - - store.delete("index/branch/main/abc") - store.delete("index/branch/main/abc") - assert store.list("") == ["bundles/abc.loch"] - - -@mock_aws -def test_s3_store_lists_past_the_first_page(aws_credentials: None) -> None: - client = boto3.client("s3", region_name="us-east-1") - client.create_bucket(Bucket="sessions") - for number in range(1001): - client.put_object( - Bucket="sessions", Key=f"index/branch/main/{number:04d}", Body=b"" - ) - - assert len(S3Store("sessions", "").list("index/")) == 1001 - - -@mock_aws -def test_s3_store_honours_the_region_override( - aws_credentials: None, monkeypatch: pytest.MonkeyPatch -) -> None: - 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"}, - ) - - store = S3Store("sessions", "") - store.put("abc.loch", b"payload") - assert store.get("abc.loch") == b"payload" diff --git a/test/test_trace.py b/test/test_trace.py deleted file mode 100644 index ff9738f..0000000 --- a/test/test_trace.py +++ /dev/null @@ -1,366 +0,0 @@ -import json -import os -import subprocess -from pathlib import Path -from typing import Any - -import pytest - -from loch.claude import transcript_path_for -from loch.cli import main -from loch.store import FileStore -from loch.trace import ( - Resolver, - backfill, - fork_session, - hook_post_tool, - hook_pre_tool, - install_hooks, - read_note, - snapshot_transcript, -) - -SESSION = "11111111-2222-3333-4444-555555555555" -CALL = "toolu_commit" - - -@pytest.fixture -def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Path]: - home = tmp_path / "home" - repo = tmp_path / "repo" - home.mkdir() - repo.mkdir() - monkeypatch.setenv("HOME", str(home)) - for name in ("AUTHOR", "COMMITTER"): - monkeypatch.setenv(f"GIT_{name}_NAME", "Test") - monkeypatch.setenv(f"GIT_{name}_EMAIL", "test@example.com") - monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "gitconfig")) - run(repo, "init", "-q", "-b", "main") - return {"home": home, "repo": repo, "tmp": tmp_path} - - -def run(repo: Path, *args: str, date: str | None = None) -> str: - extra = {"GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} if date else {} - return subprocess.run( - ["git", "-C", str(repo), *args], - capture_output=True, - text=True, - check=True, - env={**os.environ, **extra}, - ).stdout.strip() - - -def commit( - repo: Path, name: str, text: str, message: str, date: str | None = None -) -> str: - (repo / name).write_text(text) - run(repo, "add", name) - run(repo, "commit", "-q", "-m", message, date=date) - return run(repo, "rev-parse", "HEAD") - - -def transcript(repo: Path, command: str, prompt: str = "please add the file") -> str: - """human prompt -> assistant Bash call -> its result, as Claude writes it.""" - records: list[dict[str, Any]] = [ - { - "type": "user", - "uuid": "u1", - "parentUuid": None, - "sessionId": SESSION, - "cwd": str(repo), - "timestamp": "2026-01-01T00:00:00.000Z", - "message": {"role": "user", "content": prompt}, - }, - { - "type": "assistant", - "uuid": "a1", - "parentUuid": "u1", - "sessionId": SESSION, - "cwd": str(repo), - "timestamp": "2026-01-01T00:00:10.000Z", - "message": { - "id": "msg1", - "role": "assistant", - "content": [ - { - "type": "tool_use", - "id": CALL, - "name": "Bash", - "input": {"command": command}, - } - ], - }, - }, - { - "type": "user", - "uuid": "r1", - "parentUuid": "a1", - "sessionId": SESSION, - "cwd": str(repo), - "timestamp": "2026-01-01T00:00:20.000Z", - "message": { - "role": "user", - "content": [ - {"type": "tool_result", "tool_use_id": CALL, "content": "ok"} - ], - }, - }, - ] - path = transcript_path_for(str(repo), SESSION) - os.makedirs(os.path.dirname(path), exist_ok=True) - Path(path).write_text("".join(json.dumps(record) + "\n" for record in records)) - return path - - -def event(repo: Path, **fields: Any) -> dict[str, Any]: - return { - "session_id": SESSION, - "cwd": str(repo), - "tool_name": "Bash", - "tool_use_id": CALL, - "tool_input": {"command": "git commit"}, - **fields, - } - - -def test_hooks_note_exactly_the_commits_a_call_made(env: dict[str, Path]) -> None: - repo = env["repo"] - old = commit(repo, "a.txt", "a\n", "old work", date="2020-01-01T00:00:00Z") - run(repo, "checkout", "-q", "-b", "side") - other = commit(repo, "b.txt", "b\n", "someone else", date="2020-01-02T00:00:00Z") - run(repo, "checkout", "-q", "main") - - hook_pre_tool(event(repo)) - made = commit(repo, "c.txt", "c\n", "agent work") - assert hook_post_tool(event(repo)) == [made] - assert read_note(str(repo), made) == { - "loch": 1, - "agent": "claude-code", - "session": SESSION, - "call": CALL, - "captured": "hook", - } - - # Moving HEAD onto commits someone else made is not making them. - hook_pre_tool(event(repo, tool_use_id="toolu_checkout")) - run(repo, "checkout", "-q", "side") - assert hook_post_tool(event(repo, tool_use_id="toolu_checkout")) == [] - assert read_note(str(repo), other) is None - assert read_note(str(repo), old) is None - - -def test_a_call_that_leaves_head_alone_notes_nothing(env: dict[str, Path]) -> None: - repo = env["repo"] - commit(repo, "a.txt", "a\n", "first") - hook_pre_tool(event(repo)) - assert hook_post_tool(event(repo)) == [] - - -def test_hook_command_never_fails( - env: dict[str, Path], - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - import io - - monkeypatch.setattr("sys.stdin", io.StringIO("not json")) - monkeypatch.setattr("sys.argv", ["loch", "hook", "post-tool"]) - main() - assert capsys.readouterr().out == "" - - -def test_install_is_idempotent_and_keeps_existing_settings(tmp_path: Path) -> None: - settings = tmp_path / ".claude" / "settings.json" - settings.parent.mkdir() - settings.write_text(json.dumps({"model": "x", "hooks": {"Stop": [{"hooks": []}]}})) - assert install_hooks(str(settings), "loch") == [ - "PreToolUse", - "PostToolUse", - "Stop", - ] - assert install_hooks(str(settings), "loch") == [] - written = json.loads(settings.read_text()) - assert written["model"] == "x" - assert written["hooks"]["PreToolUse"][0]["matcher"] == "Bash" - assert len(written["hooks"]["Stop"]) == 2 - - -def test_stop_snapshots_the_transcript(env: dict[str, Path]) -> None: - path = transcript(env["repo"], "git commit -m 'x'") - store = FileStore(str(env["tmp"] / "store")) - key = snapshot_transcript({"session_id": SESSION, "transcript_path": path}, store) - assert key is not None - assert store.get(key) == Path(path).read_bytes() - - -def test_a_deleted_transcript_is_found_in_the_store(env: dict[str, Path]) -> None: - repo = env["repo"] - path = transcript(repo, "git commit -m 'add a'") - hook_pre_tool(event(repo)) - sha = commit(repo, "a.txt", "a\n", "add a") - hook_post_tool(event(repo)) - store = FileStore(str(env["tmp"] / "store")) - snapshot_transcript({"session_id": SESSION, "transcript_path": path}, store) - os.remove(path) - - link = Resolver(str(repo), store).resolve(sha) - assert link is not None and link.transcript is not None - assert link.prompt == "please add the file" - - -def test_backfill_links_only_an_exact_match(env: dict[str, Path]) -> None: - repo = env["repo"] - # The transcript's call ran 00:00:10-00:00:20; these straddle it. - inside = commit(repo, "a.txt", "a\n", "add a", date="2026-01-01T00:00:15Z") - outside = commit(repo, "b.txt", "b\n", "add a", date="2026-01-01T05:00:00Z") - unnamed = commit(repo, "c.txt", "c\n", "add c", date="2026-01-01T00:00:15Z") - transcript(repo, 'git add a.txt && git commit -m "add a"') - - seen: list[tuple[int, int, int, int]] = [] - linked = backfill(str(repo), "HEAD", lambda *step: seen.append(step)) - assert [sha for sha, _ in linked] == [inside] - # One step per transcript, ending with everything read. - assert seen and seen[-1][0] == seen[-1][1] and seen[-1][2] == seen[-1][3] > 0 - note = read_note(str(repo), inside) - assert note is not None and note["captured"] == "backfill" - assert read_note(str(repo), outside) is None - assert read_note(str(repo), unnamed) is None - assert backfill(str(repo), "HEAD") == [] - - -def test_blame_names_the_prompt_behind_each_line( - env: dict[str, Path], - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - repo = env["repo"] - commit(repo, "f.txt", "human line\n", "by hand") - transcript(repo, "git commit -am 'agent'", prompt="make it two lines") - hook_pre_tool(event(repo)) - sha = commit(repo, "f.txt", "human line\nagent line\n", "agent") - hook_post_tool(event(repo)) - - monkeypatch.chdir(repo) - monkeypatch.setattr("sys.argv", ["loch", "blame", "f.txt", "--json"]) - main() - hunks = json.loads(capsys.readouterr().out)["hunks"] - assert [(h["start"], h["conversation"] is None) for h in hunks] == [ - (1, True), - (2, False), - ] - assert hunks[1]["commit"] == sha - assert hunks[1]["conversation"]["prompt"] == "make it two lines" - assert hunks[1]["conversation"]["turn"].startswith("sha256:") - - -def test_log_finds_conversations_blame_has_painted_over( - env: dict[str, Path], - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - repo = env["repo"] - first = commit(repo, "f.txt", "one\nother\n", "by hand") - transcript(repo, "git commit -am 'agent'", prompt="reword line one") - hook_pre_tool(event(repo)) - agent = commit(repo, "f.txt", "uno\nother\n", "agent") - hook_post_tool(event(repo)) - last = commit(repo, "f.txt", "ONE\nother\n", "by hand again") - commit(repo, "f.txt", "ONE\nelse\n", "only line two") - - def log(target: str) -> dict[str, Any]: - monkeypatch.setattr("sys.argv", ["loch", "log", target, "--json"]) - main() - result: dict[str, Any] = json.loads(capsys.readouterr().out) - return result - - monkeypatch.chdir(repo) - # blame of line 1 sees only `last`; its history still holds the agent. - line = log("f.txt:1") - assert [c["commit"] for c in line["commits"]] == [last, agent, first] - assert [c["conversation"] is None for c in line["commits"]] == [True, False, True] - assert line["lines"] == {"start": 1, "end": 1} - assert [c["prompt"] for c in line["conversations"]] == ["reword line one"] - assert line["conversations"][0]["commits"] == [agent] - assert len(log("f.txt")["commits"]) == 4 - - monkeypatch.setattr("sys.argv", ["loch", "log", "f.txt:9", "--json"]) - with pytest.raises(SystemExit): - main() - assert json.loads(capsys.readouterr().out)["code"] == "usage" - - -def test_fork_cuts_after_the_whole_round_and_leaves_the_original( - env: dict[str, Path], -) -> None: - repo = env["repo"] - path = transcript(repo, "git commit") - records = [json.loads(line) for line in Path(path).read_text().splitlines()] - # A parallel second call in the same message, with its result after ours, - # then the conversation carrying on past the commit. - second = json.loads(json.dumps(records[1])) - second.update(uuid="a2", parentUuid="a1") - second["message"]["content"][0]["id"] = "toolu_other" - result_one = dict(records[2], parentUuid="a2") - result_two = json.loads(json.dumps(records[2])) - result_two.update(uuid="r2", parentUuid="r1") - result_two["message"]["content"][0]["tool_use_id"] = "toolu_other" - later = dict(records[0], uuid="u2", parentUuid="r2", message={"content": "more"}) - lines = [records[0], records[1], second, result_one, result_two, later] - original = "".join(json.dumps(record) + "\n" for record in lines) - Path(path).write_text(original) - - target = env["tmp"] / "elsewhere" - target.mkdir() - fork = fork_session(path, str(target), call=CALL) - - assert Path(path).read_text() == original - forked = [json.loads(line) for line in Path(fork.path).read_text().splitlines()] - assert [r.get("uuid") for r in forked] == ["u1", "a1", "a2", "r1", "r2", None] - assert {r["sessionId"] for r in forked} == {fork.session_id} - assert {r["cwd"] for r in forked if "cwd" in r} == {str(target)} - assert forked[-1]["type"] == "custom-title" - assert fork.path == transcript_path_for(str(target), fork.session_id) - - -def test_fork_without_a_call_runs_to_the_end_of_the_conversation( - env: dict[str, Path], -) -> None: - repo = env["repo"] - path = transcript(repo, "git commit") - records = [json.loads(line) for line in Path(path).read_text().splitlines()] - later = dict(records[0], uuid="u2", parentUuid="r1", message={"content": "more"}) - Path(path).write_text( - "".join(json.dumps(record) + "\n" for record in [*records, later]) - ) - - fork = fork_session(path, str(repo)) - forked = [json.loads(line) for line in Path(fork.path).read_text().splitlines()] - assert [r.get("uuid") for r in forked] == ["u1", "a1", "r1", "u2", None] - - -def test_blame_html_marks_every_line_with_its_conversation( - env: dict[str, Path], - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - repo = env["repo"] - commit(repo, "f.txt", "human line\n", "by hand") - transcript(repo, "git commit -am 'agent'", prompt="make it lines") - hook_pre_tool(event(repo)) - commit(repo, "f.txt", "human line\nagent line\n", "agent") - hook_post_tool(event(repo)) - (repo / "f.txt").write_text("human line\nagent line\nwork in progress\n") - - page = env["tmp"] / "blame.html" - monkeypatch.chdir(repo) - monkeypatch.setattr( - "sys.argv", ["loch", "blame", "f.txt", "--html", str(page), "--no-open"] - ) - main() - assert capsys.readouterr().out == f"wrote {page}\n" - html = page.read_text() - assert '" not in html.split("