diff --git a/.claude/settings.json b/.claude/settings.json index 78ddf77..ae81577 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,33 +1,31 @@ { "hooks": { - "PreToolUse": [ + "Stop": [ { "hooks": [ { "type": "command", - "command": "loch hook pre-tool 2>/dev/null || true" + "command": "loch hook stop 2>/dev/null || true" } - ], - "matcher": "Bash" + ] } ], - "PostToolUse": [ + "UserPromptSubmit": [ { "hooks": [ { "type": "command", - "command": "loch hook post-tool 2>/dev/null || true" + "command": "loch hook prompt 2>/dev/null || true" } - ], - "matcher": "Bash" + ] } ], - "Stop": [ + "SessionEnd": [ { "hooks": [ { "type": "command", - "command": "loch hook stop 2>/dev/null || true" + "command": "loch hook end 2>/dev/null || true" } ] } 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/test.yml b/.github/workflows/test.yml index df13ae2..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,29 +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"] + # 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 }} 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 + # rustup ships on both runner images and installs the version + # 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 --locked -- -D warnings + - run: cargo test --release --locked diff --git a/.gitignore b/.gitignore index 6f88f15..de3e2fc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,7 @@ -.venv/ -__pycache__/ -*.pyc -.mypy_cache/ -.ruff_cache/ -.pytest_cache/ -dist/ -*.loch -!test/fixtures/*.loch +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 a7bab5c..5d051f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -66,13 +66,77 @@ a reviewer wants one ref to pull. `save` filters by cwd/branch/session and packs everything matching. **Link at branch level, not per commit — for bundles.** A reviewer asks -"what produced this PR," not "what produced commit abc123." Commit-level -pointers would drag in squash-merge, rebase, and `post-rewrite` handling for -no benefit. (Nothing writes git pointers yet — this is the intended shape.) -The conversation graph is the exception: forking at a turn needs the disk -state *at that turn*, so turns get per-commit pins kept alive by refs, which -is precisely the squash/rebase problem this avoided, taken on deliberately -(SPEC.md §10). +"what produced this PR," not "what produced commit abc123," so bundles are +filed by branch. Nothing writes git pointers for bundles. + +**Attribution by content, not by commit.** Which turn wrote a line is +recorded by snapshotting the workspace at each turn's start and end and +hashing the lines the turn added (`attribution.rs`, SPEC.md §10), never in +git. The first design put a git note on each commit an agent made, and a +squash merge destroyed every one of them: a note annotates one commit id, and +a squash makes a new commit out of several, so #2's notes ended up on commits +`main` doesn't contain. Rebases, cherry-picks and amends do the same thing +more quietly. What should be remembered is "this text was written by this +turn," which no history rewrite changes, so that is what is recorded, and the +records live in the store, which also keeps them deletable (above). Four +requirements fixed the rest of the design: + +- **Every edit counts, however it was made.** More than half of an agent's + edits go through the shell (`sed`, generators, formatters, scripts), and the + harness may have no edit tool to observe. So capture looks at the files, not + the tools: anything that lands on disk during a turn is the turn's. +- **Per turn, not per tool call.** A turn is the unit anyone asks about, and + per-turn boundaries are available from far more harnesses (a turn-end hook, + or transcript timestamps) than per-call ones. Claude Code's + `UserPromptSubmit` and `Stop` hooks are the two moments needed. The old + pre/post-tool hooks, which ran twice per shell command, are gone, and + `install` removes them. +- **Every turn gets closed by someone.** Claude Code runs no `Stop` for a + cancelled turn and nothing for a crash, so the cancelled turn's edits would + become the next turn's baseline and belong to nobody. A session's state + therefore says whether its turn is open, and the next `prompt` — or + `SessionEnd`, the third hook — closes it first, marked `interrupted`. Every + state and record file is written aside and renamed, so a hook killed + mid-write leaves the old file or the new one, never half of either. +- **No background process.** Snapshots are taken on demand with a stat cache, + the way git's index works: files whose size and mtime are unchanged aren't + read again. A harness with no hooks gets coarser attribution, never a + daemon. +- **A person editing during a turn is not a concern.** Their changes in that + window are the turn's. Changes between turns are not, provided the prompt + hook ran. + +Git is still *read*, never written: for a project's identity (its root +commit, the same on every clone and immune to history rewrites), for `list`'s +default branch, for a file's earlier names (`git log --follow`, so blame finds +turns that wrote it before a rename), and by `backfill`. + +**History from before the hooks is backfilled, honestly labelled.** +`loch backfill` rebuilds turns from what survives, marked `backfilled`: +- **The transcripts' `Edit`/`Write`/`MultiEdit` calls,** which carry the exact + text written. Failed edits are skipped. Fragment edits (part of a line) + can't match a full line and are missed. +- **The commits the agent made,** whose diffs catch shell edits. A commit is + credited only on an exact match: an old git note naming the call, or + exactly one Bash call — across every session — containing the commit's + subject and bracketing its time. A contested commit stays unlinked, since a + wrong link looks exactly like a right one. A commit's lines that the same + session's tool edits already explain are left to those edits, the more + precise source. + +Hook-recorded turns are never replaced, and a re-run replaces only earlier +backfilled turns. On this repository it rebuilt 21 turns across 2 sessions, +and with rename-following, files written before the crate moved out of +`rust/` went from 1–16% attributed to 96–99%. + +**Snapshots are disposable, so they are collected.** Nothing reads a snapshot +once its turn is diffed; blame works from the records' hashes. A +mark-and-sweep keeps each workspace's latest snapshot and each live session's +turn start, and deletes whatever else is more than an hour old. It runs from +the hooks every 50 snapshots, like `git gc --auto`, or as `loch gc`. Steady +state is about one compressed copy of each project plus the turns in flight. +`ask` resumes the conversation against today's files; restoring a turn's +exact files was considered and isn't wanted. **No single index object.** A shared `index.json` would need read-modify-write on every save, so two machines saving concurrently would @@ -92,7 +156,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 @@ -141,35 +210,51 @@ 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) -└── test_*.py # one module per source module +src/ +├── main.rs # argv handling, dispatch, the two renderers' entry point +├── cli.rs # every command: list/save/restore/delete/reindex/ingest/install/ +│ # blame/log/ask/backfill/gc/hook/help/version +├── claude.rs # Claude Code adapter: path encoding, session discovery, metadata +├── 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 +├── snapshot.rs # on-demand workspace snapshots with a stat cache, like git's index +├── attribution.rs # per-turn added lines, edit records, and blame's matcher +├── backfill.rs # turns from before the hooks, from transcripts and commits +├── hook.rs # `loch hook prompt|stop|end`: turn boundaries, closing, collection +├── trace.rs # install, finding transcripts, describing turns, ask's fork +├── git.rs # git by subprocess: a project's root commit, the current branch +├── 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 +├── trace.rs # hooks, blame, log and ask end to end, squash and clone included +├── backfill.rs # backfill's two sources, contested commits, renames +└── corpus.rs # opt-in, against this machine's transcripts (LOCH_CORPUS=1) +examples/bench_hook.rs # per-call wall clock of `loch hook`, any number of binaries +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). @@ -210,8 +295,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 @@ -260,13 +345,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 @@ -276,7 +364,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. @@ -338,7 +426,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 @@ -353,7 +441,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 @@ -371,7 +459,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 @@ -382,7 +470,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 @@ -397,12 +485,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 @@ -416,8 +505,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 @@ -432,7 +521,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`. @@ -447,7 +536,7 @@ So every command takes `--json`, accepted either before or after the subcommand, and answers with exactly one document on stdout: ```json -{"schema": 1, "ok": true, "command": "save", "ref": "...", "bytes": 331, ...} +{"schema": 2, "ok": true, "command": "save", "ref": "...", "bytes": 331, ...} ``` `schema` is the envelope version. It exists so a consumer can detect a @@ -463,7 +552,7 @@ prose that describes it will rot the first time someone edits the prose. **Failures are documents, on stdout.** ```json -{"schema": 1, "ok": false, "command": "restore", "code": "nothing-restored", +{"schema": 2, "ok": false, "command": "restore", "code": "nothing-restored", "error": "nothing restored", "sessions": [{"status": "skipped", ...}]} ``` @@ -480,46 +569,43 @@ 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 | -| `s3-extra-missing` | an `s3://` store on an install without the `s3` extra | | `bundle-unreadable` | the bytes arrived and won't unpack | | `nothing-restored` | every session in the bundle was skipped | | `author-key-unreadable` | `ingest --author-key` named a file that isn't an OpenSSH public key | -| `not-a-repository` | `install`/`blame`/`log`/`ask`/`backfill` outside a git repository | -| `not-linked` | `ask` on a commit with no conversation note, or an uncommitted line | -| `transcript-missing` | the note exists but the transcript is in neither Claude's directory nor the store | -| `call-not-found` | the transcript has no result for the noted tool call | -| `git-failed` | a git command failed | +| `file-unreadable` | `blame`/`log`/`ask` named a file that can't be read | +| `not-linked` | `ask` on a line no recorded turn wrote | +| `transcript-missing` | a turn wrote the line but its transcript is in neither Claude's directory nor the store | +| `turn-not-found` | the transcript no longer holds the record a turn ended on | | `unknown-command` | no such subcommand | | `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. @@ -540,62 +626,167 @@ 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. +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 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), 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. +- **Timestamps:** a naive (offset-less) ISO timestamp is read as UTC. + Transcripts always carry `Z`. +- **Windows** has never been built. + +## Performance + +**Hooks run at a turn's boundaries, not around every shell command.** The +git-notes design needed a hook around every Bash call (73ms each in Python, +then 3ms in Rust with a native HEAD reader that is now gone). Attribution +needs a snapshot at the turn's start and end: one walk of the workspace, a +`stat` per file, and a read only of files whose size or mtime changed. A +project's first snapshot reads everything once. Measured with +`examples/bench_hook.rs` (median of 20, one file changed per turn): + +| files | `prompt` | `stop` | +| --- | --- | --- | +| 2,000 | 43ms | 50ms | +| 20,000 | 75ms | 134ms | + +**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 + 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. + +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 +kinds don't justify an async runtime and several MB. The signer is pinned to +AWS's two published examples (a header-signed GET and a signed query +string). Listings send `encoding-type=url` and decode the keys, so a key +with any character survives the XML. A store that doesn't answer fails +after 20s rather than holding a turn. The tests that need an endpoint are +`#[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 @@ -648,8 +839,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 @@ -682,28 +873,38 @@ 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. - -**Blame and ask (`trace.py`) are a working demo on this repository.** All 12 -commits whose sessions still existed were backfilled exactly; the 50 from -August have no conversation left, because Claude Code had already deleted -their transcripts (`cleanupPeriodDays`, default 30) — the reason the stop -hook snapshots every session into the store. Backfill could not have used -commit hashes from tool output: `git commit -q` prints none, which is why -hooks capture links live. A fork made by `ask` was resumed with -`claude --resume -p` and answered from the original conversation. Known gaps: -the fork resumes in the current checkout rather than a worktree at the commit -(a pin, §10); the transcript snapshot is one mutable key per session rather -than content-addressed `raw/`; subagent sidecars aren't snapshotted; -backfill reads every transcript on the machine (~25s on 750MB). The hook -input's `tool_use_id` is used when present and otherwise recovered from the -transcript by command; which one current Claude Code sends hasn't been -observed, since hooks only load at session start. +**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, log and ask run on content attribution.** Verified end to end in +`tests/trace.rs`: +- **Shell edits count.** Lines changed by `sed` and a file written by a + generator are attributed to the turn that ran them, with no edit tool + involved. +- **History rewrites don't matter.** After a squash, a fresh clone with an + empty HOME and only the store in common blames the same lines to the same + turns, and finds the transcripts in the store. +- **A person's text isn't the agent's.** A line someone later rewrote is + unattributed, a re-indented one keeps its turn, and a person's lone `}` is + not credited to the agent. +- **Cut-short turns keep their edits.** A cancelled turn is closed by the + next prompt, a crash followed by `--resume` likewise, and quitting mid-turn + by `SessionEnd`. +- **Collection is safe.** It removes earlier turns' snapshots and a killed + write's leftovers, while an open turn's start survives until it's + abandoned. + +The notes written under the old design, on this repository only, are not +migrated: they sit on commits `main` no longer contains. + +Known gaps: +- **A crash nobody resumes** loses its turn's attribution: nothing ever says + when that turn ended. Its state expires after 7 days. +- **Sessions running at once in one workspace** each record the other's + changes as their own. +- **The transcript snapshot** is one mutable key per session rather than + content-addressed `raw/`, and subagent sidecars aren't snapshotted. The rename from lochy carried no compatibility shim: `LOCHY_STORE`, `LOCHY_S3_ENDPOINT`, `LOCHY_S3_REGION` and the `~/.lochy/store` default are @@ -733,18 +934,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`. +- 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/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..cd89c49 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,944 @@ +# This file is automatically @generated by Cargo. +# 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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + +[[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" +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 = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[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", + "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]] +name = "equivalent" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "libz-sys", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "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 = "globset" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f98b0d85522dc0a824cfebbc9594ff4a9b289c568bea0370319dfbdf20ccdd2d" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "hashbrown" +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 = "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 = "ignore" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "484be5657551d7868d67587df967fb4fcbe9d266a761cc855aaa148fda0b3cc7" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "loch" +version = "0.1.0" +dependencies = [ + "fancy-regex", + "flate2", + "getrandom", + "hmac", + "ignore", + "indexmap", + "libc", + "libz-sys", + "regex", + "sha2", + "similar", + "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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[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 = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[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 0.52.0", +] + +[[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 = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[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 = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "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" +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 = "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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[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 = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[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-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[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", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b23c1ac --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "loch" +version = "0.1.0" +edition = "2021" +rust-version = "1.91" +license = "MIT" +description = "Save and restore agent coding sessions across machines" +publish = false + +[[bin]] +name = "loch" +path = "src/main.rs" + +[dependencies] +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. +flate2 = { version = "1", default-features = false, features = ["zlib"] } +libz-sys = { version = "1", default-features = false, features = ["static", "libc"] } # flate2's backend, built from source and linked statically +getrandom = "0.2" +# Walks a workspace the way git sees it: .gitignore, nested ignores, the global +# excludes file. Used by snapshots, which must skip what the user ignores. +ignore = "0.4" +# Line diffs between a turn's start and end snapshots. +similar = "2" +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" + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 +strip = true +panic = "abort" diff --git a/README.md b/README.md index de6c8ac..ee21025 100644 --- a/README.md +++ b/README.md @@ -15,37 +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. +**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 +cargo build --release # target/release/loch +cargo test --release ``` ## Use @@ -81,21 +80,20 @@ sessions produces a single ref. ## Blame a line back to its conversation ```sh -loch install # once per repo: Claude Code hooks, committed in .claude/ -loch backfill # link commits made before the hooks, where it can be exact +loch install # once per project: Claude Code hooks, committed in .claude/ -loch blame loch/format.py -# 102-112 6eb7b0d Canonicalize per RFC 8785, fold agent events into facts -# session 37d467e5 "loch-format-v1" — asked: "none of those seem like open questions…" -loch blame --html loch/format.py # the whole file in a browser, tinted by conversation +loch blame src/format.rs +# 102-112 2026-11-18 session 37d467e5 "loch-format-v1" — asked: "none of those seem like open questions…" +# 113-120 not written in a recorded turn +loch blame --html src/format.rs # the whole file in a browser, tinted by conversation -loch log loch/format.py:105 # every conversation that ever changed line 105 -loch log loch/format.py:90-120 # ...or a range, followed through edits and moves -loch log loch/format.py # ...or the whole file, followed through renames +loch log src/format.rs:105 # the turns that wrote what line 105 says now +loch log src/format.rs:90-120 # ...or a range +loch log src/format.rs # ...or every turn that ever changed the file -loch ask loch/format.py:105 "why not just json.dumps?" +loch ask src/format.rs:105 "why not just json.dumps?" # forks the conversation that wrote line 105 and resumes it in Claude Code, -# from where it ended; --at-commit stops it just after the commit instead +# from where it ended; --at-turn stops it at the end of the turn that wrote it ``` `blame --html` writes the same thing as a page and opens it: every line of the @@ -103,13 +101,29 @@ file tinted by the conversation that wrote it, a key of what each one asked, and a line's `loch ask` command a click away. `--lines 1-20,90-120` limits it to an excerpt. -With the hooks installed, every commit an agent makes gets a git note on -`refs/notes/loch` naming the session and tool call that made it, and every -session's transcript is copied into the store when it stops — Claude Code -deletes its own after 30 days. Notes hold no transcript text; share them with -`git push origin refs/notes/loch`. `ask` never touches the original session: -it writes a new one holding the conversation, filed under -the current checkout, so the follow-up sees today's code, not the commit's. +**How it knows.** The hooks snapshot the project's files when you send a +prompt and again when the agent stops, and record which lines the turn added — +whether it used an edit tool, `sed`, a code generator or a formatter, since all +of them land on disk the same way. Those records go to the store as hashes of +the lines, not the code, and blame finds a line's turn by matching the text in +front of it. Nothing is written to git, so a squash merge, a rebase or a +cherry-pick loses nothing, and a teammate pointed at the same store sees the +same answers in their own clone. A line someone later rewrites by hand is, by +design, no longer the agent's. A turn you cancel, or one cut short by a crash, +is closed by your next prompt or by the session ending, so its edits are still +its own. Each session's transcript is copied into the store too — Claude Code +deletes its own after 30 days. + +For history from before the hooks, `loch backfill` rebuilds what it can from +the transcripts' edit calls and the commits the agent made, and marks those +turns as backfilled. + +Snapshots are only needed until a turn is recorded, so loch deletes old ones +itself every 50 snapshots, keeping about one compressed copy of each project; +`loch gc` does it on demand. + +`ask` never touches the original session: it writes a new one holding the +conversation, so the follow-up sees today's code. ## Scripting it @@ -118,7 +132,7 @@ document on stdout instead of the text above: ```sh loch save --json --branch feature/checkout-flow --store /tmp/outbound -# {"schema":1,"ok":true,"command":"save","ref":"10482276...","bytes":4712, +# {"schema":2,"ok":true,"command":"save","ref":"10482276...","bytes":4712, # "redacted":2,"sessions":[{"sessionId":"e71cdcb1-...","branch":"feature/checkout-flow", # "redactions":{"aws-access-key":1,"jwt":1}}],"indexed":[...]} @@ -126,26 +140,26 @@ ref=$(loch save --json --store /tmp/outbound | jq -r .ref) loch restore --json "$ref" --into /path/to/repo --store /tmp/outbound loch --version --json -# {"schema":1,"ok":true,"command":"version","version":"0.1.0"} +# {"schema":2,"ok":true,"command":"version","version":"0.1.0"} ``` Failures are documents too, on stdout, so one stream carries both outcomes: ```sh loch restore --json deadbeef --store /tmp/outbound; echo "exit $?" -# {"schema":1,"ok":false,"command":"restore","code":"bundle-not-found", +# {"schema":2,"ok":false,"command":"restore","code":"bundle-not-found", # "error":"could not read deadbeef from /tmp/outbound: ..."} # exit 1 ``` 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/SPEC.md b/SPEC.md index 8936337..54750b1 100644 --- a/SPEC.md +++ b/SPEC.md @@ -1,8 +1,9 @@ # loch format, version 1 **Status: draft.** The derived-file format and the Claude Code converter -(§3–§8) are implemented in `loch/format.py` and `loch/ingest.py`. The storage, -pin and native-turn sections (§9–§11) describe intended shapes that nothing +(§3–§8) are implemented in `src/format.rs` and `src/ingest.rs`, and workspace +attribution (§10) in `src/snapshot.rs` and `src/attribution.rs`. The storage +and native-turn sections (§9, §11) describe intended shapes that nothing writes yet. Questions this draft doesn't settle are collected in §13 rather than guessed at. @@ -277,40 +278,113 @@ content/ content object turns/ turn core ``` -## 10. Git pins (partly implemented) - -**Implemented: commit to turn.** A git note on `refs/notes/loch` links a -commit to the tool call that made it: +## 10. Workspace attribution + +Which turn wrote which lines of a project, recorded without git and found +again by content, so that squashing, rebasing, cherry-picking and cloning +lose nothing. + +**Capture.** At the start and end of each turn the workspace is snapshotted. +The turn's changes are what differs between the two, however the agent made +them: an edit tool, a shell command, a generator, a formatter it ran. +- **The workspace root** is the nearest ancestor of the session's cwd holding a + `.git` entry, read as a marker only, or the cwd itself where there is none. + Symlinks are resolved first. +- **What counts as a file:** every regular file the user's ignore rules let + through (`.gitignore`, nested ignores, the global excludes file), with or + without a repository; `.git` itself is never one. +- **Roots that are refused:** `/`, the home directory, and any root holding + more than 100,000 files. +- **Snapshots are content-addressed and local.** A snapshot's id is the + SHA-256 of its manifest, one `\t\t` line per + file, sorted by path. +- **Turn boundaries** come from the harness: Claude Code's `UserPromptSubmit` + and `Stop` hooks, and `SessionEnd`. A harness with only an end-of-turn signal uses each + turn's end snapshot as the next turn's start. With no signal at all, a + change is attributed to the span between two snapshots. +- **Repeated stops are one turn.** Claude Code can stop more than once for one + prompt; those stops are one turn, measured from where it began. +- **Every turn gets closed.** Claude Code runs no `Stop` for a cancelled turn + and nothing at all for a crash. A turn still open when the session's next + prompt arrives, or when the session ends, is closed then, marked + `interrupted`, ending where the workspace stands at that moment; otherwise + its edits would become the next turn's baseline and belong to nobody. When + the next prompt's own record is already in the transcript, it is excluded + from the interrupted turn. A crashed session that is never resumed is the + one case nothing closes. + +**What a turn added.** For each file whose content changed, a line diff +(Myers) from the start to the end snapshot gives the inserted and replaced +lines. Consecutive ones form a hunk. A new file contributes all of its +lines; a binary file (any NUL, or not UTF-8) and a deleted file contribute +none. + +**Line hash.** The first 8 bytes of SHA-256 over the line with surrounding +whitespace removed, as 16 lowercase hex digits. Whitespace is excluded so a +formatter re-indenting a turn's code doesn't sever the link. + +**Edit record.** One JSON document per session holds every turn's hunks: ```json -{"loch": 1, "agent": "claude-code", "session": "", "call": "", "captured": "hook"} +{"loch": 1, "agent": "claude-code", "session": "", + "project": "git:", "root": "", + "turns": [{"promptUuid": "", "endUuid": "", + "started": "", "ended": "", + "prompt": "", + "interrupted": false, + "files": [{"path": "", + "hunks": [{"start": 12, "lines": ["", ...]}]}]}]} ``` -`captured` is `hook` when Claude Code hooks recorded it as the commit was made -(HEAD before and after each Bash call, bounded by commit time so a checkout -isn't mistaken for authorship), or `backfill` when it was matched afterwards: -exactly one Bash call whose command holds the commit's subject and whose run -brackets the commit's author or committer time. The note names the agent's own -ids, not a turn id, because it is written before any ingest; a reader resolves -it to the turn holding that `tool-call`. Notes carry no transcript text, so they -are envelopes in the §9 sense. `notes.rewriteRef` makes amend and rebase carry -them over. - -The rest is the original design, not yet built. +- **What it carries:** hashes, plus the one field of transcript content `list` + already carries (the prompt's first 120 characters, redacted). No code. +- **Where each turn begins and ends:** `promptUuid` and `endUuid` name the + agent's own transcript records. +- **`project`** is the same on every clone and worktree. For a git repository + it is `git:` plus the repository's root commit (the smallest, if there are + several): read once, and immune to anything later history does. Anywhere + else it is `dir:` plus the root's directory name, which is weaker. -A pin links a turn to the commit the working tree was at: +**Store layout:** -```json -{"pin": "sha256:", "repo": "", "commit": ""} +``` +edits//.json the record, rewritten each turn +index/file// derived: which sessions touched a file ``` -- **Pins are annotations, not part of the core.** Pinning a turn later - doesn't change its id. -- **Each pinned commit is kept alive by a ref** - (`refs/loch/pins/`), so a squash or rebase can't garbage-collect - the disk state a fork would check out. -- Forking at a turn is: check out its pin in a new worktree, emit the - transcript up to that turn, resume. +The index is derived, like every index entry (§9's rules for the store +apply): `reindex` rebuilds it from the records. + +**Matching.** To attribute a file's current lines: +1. **Gather candidates.** Every turn of every record that changed this + project-relative path. +2. **Hash** each current line as above. +3. **Claim runs.** A hunk claims a maximal run of the current file's + consecutive lines whose hashes equal consecutive hunk lines, provided at + least one line in the run is not *weak*. A weak line has fewer than three + alphanumeric characters: a brace, a blank, `end`. A run is what + attributes; one `}` matching proves nothing. +4. **Apply oldest first.** Turns are applied in order of `ended`, so the most + recent turn to write a line's text owns it. + +A line no hunk claims was not written by a recorded turn. That includes a +line someone rewrote after the agent wrote it, which is the intended answer. + +**Snapshots are disposable.** Nothing reads a snapshot once its turn has +been diffed, since blame works from the hashes in the records alone, so a +collector keeps only what a future diff needs. Mark and sweep, from two kinds +of root: +- **each workspace's latest snapshot,** the next turn's baseline; +- **each live session's turn start.** A session's state untouched for 7 days + belongs to a crash nobody resumed, and stops being a root. + +Everything else written more than an hour ago is deleted. The hour covers +another session's hook that has snapshotted but not yet recorded the id. The +collector runs from the hooks once 50 snapshots have accumulated, as +`git gc --auto` does, and never in the background. + +`ask` resumes a conversation against today's files, not the files as they +stood when the turn ended; restoring those was considered and isn't wanted. ## 11. Native turns (not yet implemented) diff --git a/examples/bench_hook.rs b/examples/bench_hook.rs new file mode 100644 index 0000000..b3f435d --- /dev/null +++ b/examples/bench_hook.rs @@ -0,0 +1,137 @@ +//! Wall-clock cost of `loch hook` per turn, for any number of loch binaries. +//! +//! cargo run --release --example bench_hook -- [--runs N] [--files N] ... +//! +//! Each binary runs against its own scratch repository of `--files` files +//! (default 2000) with the events Claude Code sends at a turn's boundaries. +//! Two cases: `prompt`, which snapshots, and `stop`, which snapshots, diffs +//! the turn's one changed file and writes the edit record. 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, files: 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.join("src")).expect("scratch dir"); + git(&repo, &["init", "-q", "-b", "main"], &root); + for i in 0..files { + let body = format!("fn item_{}() -> usize {{\n {}\n}}\n", i, i); + std::fs::write(repo.join(format!("src/f{}.rs", i)), body).expect("write"); + } + let transcript = root.join("transcript.jsonl"); + let mut prompt = Vec::new(); + let mut stop = Vec::new(); + for i in 0..runs { + let line = format!( + r#"{{"type": "user", "uuid": "p{}", "message": {{"content": "turn {}"}}}}"#, + i, i + ); + let mut text = std::fs::read_to_string(&transcript).unwrap_or_default(); + text.push_str(&line); + text.push('\n'); + std::fs::write(&transcript, text).expect("transcript"); + let event = format!( + r#"{{"session_id": "{}", "cwd": "{}", "transcript_path": "{}"}}"#, + SESSION, + repo.display(), + transcript.display() + ); + prompt.push(run(loch, "prompt", &event, &root)); + std::fs::write( + repo.join("src/f0.rs"), + format!("fn changed() -> usize {{ {} }}\n", i), + ) + .expect("edit"); + stop.push(run(loch, "stop", &event, &root)); + } + let _ = std::fs::remove_dir_all(&root); + vec![("prompt", prompt), ("stop", stop)] +} + +fn main() { + let mut args: Vec = std::env::args().skip(1).collect(); + let mut runs = 40; + let mut files = 2000; + while let Some(flag) = args.first().cloned().filter(|a| a.starts_with("--")) { + let value: usize = args.get(1).and_then(|n| n.parse().ok()).expect("a number"); + match flag.as_str() { + "--runs" => runs = value, + "--files" => files = value, + _ => panic!("unknown flag {}", flag), + } + args.drain(..2); + } + assert!( + !args.is_empty(), + "usage: bench_hook [--runs N] [--files N] [ ...]" + ); + println!( + "{:<48} {:<12} {:>9} {:>9}", + "binary", "case", "median", "p90" + ); + for loch in &args { + for (case, mut samples) in bench(loch, runs, files) { + 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/bundle.py b/loch/bundle.py deleted file mode 100644 index 0a9aa6f..0000000 --- a/loch/bundle.py +++ /dev/null @@ -1,103 +0,0 @@ -import gzip -import hashlib -import json -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], - } - - -def pack_bundle(bundle: Bundle) -> bytes: - encoded = json.dumps( - _bundle_to_json(bundle), separators=(",", ":"), ensure_ascii=False - ).encode("utf-8") - return gzip.compress(encoded, compresslevel=9, mtime=0) - - -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 02fd0ab..0000000 --- a/loch/claude.py +++ /dev/null @@ -1,232 +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 projects_dir(home: str | None = None) -> str: - return os.path.join(home if home is not None else home_dir(), ".claude", "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) - raw = Path(path).read_text(encoding="utf-8") - 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 853aeec..0000000 --- a/loch/cli.py +++ /dev/null @@ -1,1211 +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, - 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 - LOCH_S3_ENDPOINT custom endpoint (R2, MinIO, ...) - LOCH_S3_REGION region override - -Derived conversation files go to ~/.loch/derived unless --out says otherwise. - -`install` adds Claude Code hooks to a repository that note, on every commit an -agent makes, the conversation and tool call that made it (git notes on -refs/notes/loch), and snapshot each session's transcript into the store. -`blame` shows which conversation wrote each line, `log` every conversation -that changed a file or line range over its history; `ask` forks that -conversation and resumes it in Claude Code — from its end, or with ---at-commit from just after the commit. -""" - - -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 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: - scrubbed = redact(Path(meta.path).read_text(encoding="utf-8")) - 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(time.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 " - "neither in ~/.claude/projects nor in the store", - ) - fork = fork_session( - link.transcript, - root, - call=link.call if args.at_commit else None, - title=f"loch ask {commit[:7]}", - ) - - command = ["claude", "--resume", fork.session_id] - if args.question: - command.append(args.question) - payload = { - "commit": commit, - "conversation": link.payload(), - "fork": { - "sessionId": fork.session_id, - "path": fork.path, - "cwd": fork.cwd, - "records": fork.records, - }, - "at": "commit" if args.at_commit else "end", - "launch": command, - } - where = "just after it" if args.at_commit else "to its end" - text = ( - f"forked session {fork.origin_session[:8]}, which made {commit[:7]}, " - f"{where}: {fork.records} records, as {fork.session_id}\n" - ) - if args.no_launch or as_json: - return Result( - command="ask", - payload=payload, - text=text + f"resume with: cd {root} && {' '.join(command)}\n", - ) - sys.stderr.write(text) - os.chdir(root) - os.execvp("claude", command) - - -def _progress_meter() -> Callable[[int, int, int, int], None] | None: - """A one-line counter on stderr, for a person watching a terminal only. - - JSON mode keeps stderr empty, and a pipe or log file would get every - redraw as garbage, so both get nothing. - """ - if JSON_FLAG in sys.argv or not sys.stderr.isatty(): - return None - last = [0.0] - - def meter(done: int, total: int, read: int, size: int) -> None: - now = time.monotonic() - if done < total and now - last[0] < 0.1: - return - last[0] = now - percent = 100 * read // size if size else 100 - sys.stderr.write( - f"\rscanning transcripts {done}/{total} " - f"({format_bytes(read)} of {format_bytes(size)}, {percent}%)\033[K" - ) - if done == total: - sys.stderr.write("\n") - sys.stderr.flush() - - return meter - - -def command_backfill(argv: list[str]) -> Result: - parser = _parser("backfill") - parser.add_argument("--cwd") - # Branches rather than --all, which would walk refs/notes/loch too. - parser.add_argument("--revision", default="--branches") - args = parser.parse_args(argv) - - with trace_errors(): - root = repo_root(args.cwd or os.getcwd()) - linked = backfill(root, args.revision, _progress_meter()) - rows = [ - {"commit": sha, "session": call.session_id, "call": call.call} - for sha, call in linked - ] - text = "".join( - f" {sha[:7]} session {call.session_id[:8]}\n" for sha, call in linked - ) - text += f"linked {len(linked)} commit(s)\n" - return Result(command="backfill", payload={"linked": rows}, text=text) - - -def command_help(argv: list[str]) -> Result: - return Result(command="help", payload={"usage": USAGE}, text=USAGE) - - -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/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" } +} diff --git a/poetry.lock b/poetry.lock deleted file mode 100644 index b4f7f48..0000000 --- a/poetry.lock +++ /dev/null @@ -1,1776 +0,0 @@ -# This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand. - -[[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 = "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 = "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 = "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 = "0a5327e0095579ffa9380634d5ab43070793163140cba0c2437b005bbad6f8ac" 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 d1dfbc0..0000000 --- a/pyproject.toml +++ /dev/null @@ -1,55 +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" - -[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/release.sh b/release.sh index bfdc24e..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,42 +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 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 +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 + 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 - echo "==> dry run: pyproject.toml restored, nothing pushed" + git checkout -- Cargo.toml Cargo.lock + echo "==> dry run: version restored, nothing pushed" exit 0 fi @@ -75,5 +66,5 @@ cat <, + 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 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) + )); + 0 + } else { + out.push_str(&format!("{}{}\n", " ".repeat(indent), header)); + 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/src/attribution.rs b/src/attribution.rs new file mode 100644 index 0000000..49b473c --- /dev/null +++ b/src/attribution.rs @@ -0,0 +1,600 @@ +//! Which turn wrote which lines, recorded without git and found again by +//! content. +//! +//! At the start and end of every turn the workspace is snapshotted +//! (`snapshot.rs`), and the lines the turn added are what differs between the +//! two. However the agent made the change — an edit tool, `sed`, a generator +//! it ran, a formatter — it lands on disk the same way, which is the point: +//! this sees all of them and needs nothing from the harness but two moments. +//! +//! Each added line is recorded as a hash of its trimmed text, grouped into the +//! hunks the diff found, in one **edit record** per session in the store. +//! Hashes, not text: the record says which turn wrote a line without carrying +//! the code. Blame finds a line's turn by hashing the file in front of it and +//! matching runs of lines against those hunks, so the link survives anything +//! that keeps the text — a squash, a rebase, a cherry-pick, another clone — +//! and is lost by exactly what should lose it: someone rewriting the line. + +use crate::index; +use crate::json::{self, Value}; +use crate::object; +use crate::snapshot::{self, SnapshotError}; +use crate::store::{Store, StoreError}; +use crate::sys; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::fs; + +pub const RECORD_VERSION: i64 = 1; + +/// The index dimension edit records are filed under, by `:`. +pub const FILE: &str = "file"; + +pub fn edits_key(agent: &str, session: &str) -> String { + format!("edits/{}/{}.json", agent, session) +} + +pub const EDITS_PREFIX: &str = "edits/"; + +/// A line's identity: its text without surrounding whitespace, so a formatter +/// re-indenting the agent's code doesn't sever the link. +pub fn line_hash(line: &str) -> String { + let digest = Sha256::digest(line.trim().as_bytes()); + digest[..8].iter().map(|b| format!("{:02x}", b)).collect() +} + +/// A line that says too little to be evidence on its own — a brace, a blank, +/// `end` — which every file has dozens of. It can join a run that something +/// distinctive anchors, never start one. +pub fn is_weak(line: &str) -> bool { + let trimmed = line.trim(); + trimmed.chars().filter(|c| c.is_alphanumeric()).count() < 3 +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Hunk { + /// 1-based line in the file as the turn left it. + pub start: usize, + pub lines: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct FileChange { + pub path: String, + pub hunks: Vec, +} + +/// Text, if a blob is text: UTF-8 with no NUL in it. +fn text_of(data: &[u8]) -> Option { + if data.contains(&0) { + return None; + } + String::from_utf8(data.to_vec()).ok() +} + +/// The lines each changed file gained between two snapshots. A file that is +/// new counts as gaining all of its lines; a deleted or binary file has none +/// to attribute. +pub fn diff(before: Option<&str>, after: &str) -> Result, SnapshotError> { + let old: HashMap = match before { + Some(id) => snapshot::read_snapshot(id)? + .into_iter() + .map(|e| (e.path, e.hash)) + .collect(), + None => HashMap::new(), + }; + let mut changes = Vec::new(); + for entry in snapshot::read_snapshot(after)? { + let previous = old.get(&entry.path); + if previous == Some(&entry.hash) { + continue; + } + let Some(new_text) = text_of(&snapshot::read_object(&entry.hash)?) else { + continue; + }; + let old_text = match previous { + Some(hash) => text_of(&snapshot::read_object(hash)?).unwrap_or_default(), + None => String::new(), + }; + let hunks = added_hunks(&old_text, &new_text); + if !hunks.is_empty() { + changes.push(FileChange { + path: entry.path, + hunks, + }); + } + } + Ok(changes) +} + +/// The runs of lines `new` has that `old` doesn't, by line diff. +pub fn added_hunks(old: &str, new: &str) -> Vec { + let diff = similar::TextDiff::from_lines(old, new); + let mut hunks: Vec = Vec::new(); + for op in diff.ops() { + let range = op.new_range(); + let inserted = matches!( + op.tag(), + similar::DiffTag::Insert | similar::DiffTag::Replace + ); + if !inserted || range.is_empty() { + continue; + } + let lines: Vec = new + .lines() + .skip(range.start) + .take(range.len()) + .map(line_hash) + .collect(); + hunks.push(Hunk { + start: range.start + 1, + lines, + }); + } + hunks +} + +#[derive(Clone, Debug, PartialEq)] +pub struct TurnRecord { + /// The transcript record of the prompt that began the turn, and the last + /// record when it ended: where `ask` cuts a fork. + pub prompt_uuid: Option, + pub end_uuid: Option, + pub started: Option, + pub ended: String, + /// The first 120 characters of the prompt, redacted — the same one field + /// of transcript content `list` carries, so blame can say what was asked + /// without fetching the transcript. + pub prompt: Option, + /// The turn was cut short — cancelled, or the session crashed — and was + /// closed by the next prompt or the session's end rather than by `Stop`, + /// so it ends where the workspace stood then. + pub interrupted: bool, + /// Reconstructed afterwards by `loch backfill` from the transcript and + /// the agent's commits, rather than recorded by the hooks as it happened. + pub backfilled: bool, + pub files: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct EditRecord { + pub agent: String, + pub session: String, + pub project: String, + pub root: String, + pub turns: Vec, +} + +fn opt(value: &Option) -> Value { + Value::opt_str(value.as_deref()) +} + +impl EditRecord { + pub fn to_json(&self) -> Value { + let turns: Vec = self + .turns + .iter() + .map(|turn| { + let files: Vec = turn + .files + .iter() + .map(|file| { + let hunks: Vec = file + .hunks + .iter() + .map(|hunk| { + Value::Object(object! { + "start" => hunk.start, + "lines" => hunk.lines.iter().map(|l| Value::str(l.as_str())).collect::>(), + }) + }) + .collect(); + Value::Object(object! {"path" => file.path.as_str(), "hunks" => hunks}) + }) + .collect(); + Value::Object(object! { + "promptUuid" => opt(&turn.prompt_uuid), + "endUuid" => opt(&turn.end_uuid), + "started" => opt(&turn.started), + "ended" => turn.ended.as_str(), + "prompt" => opt(&turn.prompt), + "interrupted" => turn.interrupted, + "backfilled" => turn.backfilled, + "files" => files, + }) + }) + .collect(); + Value::Object(object! { + "loch" => RECORD_VERSION, + "agent" => self.agent.as_str(), + "session" => self.session.as_str(), + "project" => self.project.as_str(), + "root" => self.root.as_str(), + "turns" => turns, + }) + } + + pub fn from_json(value: &Value) -> Option { + let text = |v: &Value, key: &str| v.get(key).and_then(Value::as_str).map(str::to_string); + if value.get("loch").and_then(Value::as_i64) != Some(RECORD_VERSION) { + return None; + } + let mut turns = Vec::new(); + for turn in value.get("turns")?.as_array()? { + let mut files = Vec::new(); + for file in turn.get("files")?.as_array()? { + let mut hunks = Vec::new(); + for hunk in file.get("hunks")?.as_array()? { + hunks.push(Hunk { + start: hunk.get("start")?.as_i64()? as usize, + lines: hunk + .get("lines")? + .as_array()? + .iter() + .filter_map(|l| l.as_str().map(str::to_string)) + .collect(), + }); + } + files.push(FileChange { + path: text(file, "path")?, + hunks, + }); + } + turns.push(TurnRecord { + prompt_uuid: text(turn, "promptUuid"), + end_uuid: text(turn, "endUuid"), + started: text(turn, "started"), + ended: text(turn, "ended")?, + prompt: text(turn, "prompt"), + interrupted: turn.get("interrupted").is_some_and(Value::truthy), + backfilled: turn.get("backfilled").is_some_and(Value::truthy), + files, + }); + } + Some(EditRecord { + agent: text(value, "agent")?, + session: text(value, "session")?, + project: text(value, "project")?, + root: text(value, "root").unwrap_or_default(), + turns, + }) + } + + /// Every path any turn changed, each once. + pub fn paths(&self) -> Vec { + let mut paths: Vec = self + .turns + .iter() + .flat_map(|t| t.files.iter().map(|f| f.path.clone())) + .collect(); + paths.sort(); + paths.dedup(); + paths + } +} + +/// Which project a workspace belongs to, the same on every clone and +/// worktree of it, so a teammate's blame finds your turns. For a git +/// repository that is its root commit — read once, nothing written, and +/// immune to anything later history does. Anything else is known by its +/// directory's name, which is weaker and the best available. +pub fn project_id(root: &str) -> String { + if snapshot::has_git_marker(root) { + if let Ok(out) = crate::git::git(root, &["rev-list", "--max-parents=0", "HEAD"], None) { + let mut roots: Vec<&str> = out + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .collect(); + roots.sort(); + if let Some(first) = roots.first() { + return format!("git:{}", first); + } + } + } + format!("dir:{}", sys::basename(root)) +} + +pub fn file_value(project: &str, path: &str) -> String { + format!("{}:{}", project, path) +} + +// -- local copies ------------------------------------------------------------------ + +fn local_path(agent: &str, session: &str) -> std::path::PathBuf { + snapshot::loch_home() + .join("edits") + .join(agent) + .join(format!("{}.json", session)) +} + +/// The record as this machine last wrote it. The store gets a copy at every +/// turn's end; this one is what survives a store that didn't answer, and the +/// next turn's upload carries everything since. +pub fn load_local(agent: &str, session: &str) -> Option { + let text = fs::read_to_string(local_path(agent, session)).ok()?; + EditRecord::from_json(&json::loads(&text).ok()?) +} + +pub fn save_local(record: &EditRecord) -> std::io::Result<()> { + let path = local_path(&record.agent, &record.session); + snapshot::write_atomically( + &path, + json::dumps(&record.to_json(), json::COMPACT_UNICODE).as_bytes(), + ) +} + +fn local_records() -> Vec { + let mut records = Vec::new(); + let Ok(agents) = fs::read_dir(snapshot::loch_home().join("edits")) else { + return records; + }; + for agent in agents.flatten() { + let Ok(files) = fs::read_dir(agent.path()) else { + continue; + }; + for file in files.flatten() { + if let Some(record) = fs::read_to_string(file.path()) + .ok() + .and_then(|t| json::loads(&t).ok()) + .and_then(|v| EditRecord::from_json(&v)) + { + records.push(record); + } + } + } + records +} + +// -- the store ----------------------------------------------------------------------- + +/// The record first, then an index entry per file it touched — the same +/// order `save` keeps, for the same reason: an entry is derived from the +/// record, so a failure part-way leaves a record `reindex` can re-derive from +/// rather than an entry pointing at nothing. +pub fn publish(store: &dyn Store, record: &EditRecord) -> Result<(), StoreError> { + let body = json::dumps(&record.to_json(), json::COMPACT_UNICODE); + store.put(&edits_key(&record.agent, &record.session), body.as_bytes())?; + for path in record.paths() { + let key = index::index_key( + FILE, + Some(&file_value(&record.project, &path)), + &record.session, + ); + let entry = + object! {"agent" => record.agent.as_str(), "session" => record.session.as_str()}; + store.put( + &key, + json::dumps(&Value::Object(entry), json::DEFAULT).as_bytes(), + )?; + } + Ok(()) +} + +/// Every edit record that changed `path` in `project`: the store's, by its +/// file index, and this machine's own, which may hold turns the store hasn't +/// been sent yet. Where both have a session, the one with more turns wins. +pub fn records_for(store: Option<&dyn Store>, project: &str, path: &str) -> Vec { + let mut by_session: HashMap = HashMap::new(); + let mut keep = |record: EditRecord| { + let better = by_session + .get(&record.session) + .is_none_or(|have| record.turns.len() > have.turns.len()); + if better { + by_session.insert(record.session.clone(), record); + } + }; + if let Some(store) = store { + let prefix = index::value_prefix(FILE, Some(&file_value(project, path))); + for key in store.list(&prefix).unwrap_or_default() { + let Some(entry) = store + .get(&key) + .ok() + .and_then(|data| String::from_utf8(data).ok()) + .and_then(|text| json::loads(&text).ok()) + else { + continue; + }; + let (Some(agent), Some(session)) = ( + entry.get("agent").and_then(Value::as_str), + entry.get("session").and_then(Value::as_str), + ) else { + continue; + }; + if let Some(record) = store + .get(&edits_key(agent, session)) + .ok() + .and_then(|data| String::from_utf8(data).ok()) + .and_then(|text| json::loads(&text).ok()) + .and_then(|v| EditRecord::from_json(&v)) + { + keep(record); + } + } + } + for record in local_records() { + if record.project == project && record.paths().iter().any(|p| p == path) { + keep(record); + } + } + let mut records: Vec = by_session.into_values().collect(); + records.sort_by(|a, b| a.session.cmp(&b.session)); + records +} + +/// Re-derives the file index from the records, for `reindex`. Returns the +/// keys written. +pub fn reindex_files(store: &dyn Store) -> Result, StoreError> { + let mut written = Vec::new(); + for key in store.list(EDITS_PREFIX)? { + let Some(record) = String::from_utf8(store.get(&key)?) + .ok() + .and_then(|text| json::loads(&text).ok()) + .and_then(|v| EditRecord::from_json(&v)) + else { + continue; + }; + publish(store, &record)?; + for path in record.paths() { + written.push(index::index_key( + FILE, + Some(&file_value(&record.project, &path)), + &record.session, + )); + } + } + Ok(written) +} + +// -- blame ------------------------------------------------------------------------------- + +/// A turn, as blame points at one. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct TurnRef { + pub record: usize, + pub turn: usize, +} + +/// For each line of `text`, the turn that most recently wrote it, if any. +/// +/// A turn's hunk claims a run of the file's lines when the run's hashes equal +/// a run of the hunk's, consecutively, and at least one of them is not weak. +/// Runs rather than single lines, because one line of `return None` proves +/// nothing and five consecutive lines a turn wrote together prove a lot. +/// Turns are applied oldest first, so a later turn that rewrote the same text +/// takes it: blame answers "who last wrote this", as git's does. +/// +/// `paths` is every name the file has had: a turn recorded it under the name +/// it had then, and a rename since must not sever the link. +pub fn attribute(text: &str, paths: &[String], records: &[EditRecord]) -> Vec> { + let lines: Vec<&str> = text.lines().collect(); + let hashes: Vec = lines.iter().map(|l| line_hash(l)).collect(); + let weak: Vec = lines.iter().map(|l| is_weak(l)).collect(); + let mut at: HashMap<&str, Vec> = HashMap::new(); + for (i, hash) in hashes.iter().enumerate() { + at.entry(hash.as_str()).or_default().push(i); + } + + let mut turns: Vec<(TurnRef, &TurnRecord)> = records + .iter() + .enumerate() + .flat_map(|(r, record)| { + record + .turns + .iter() + .enumerate() + .map(move |(t, turn)| (TurnRef { record: r, turn: t }, turn)) + }) + .collect(); + turns.sort_by(|a, b| a.1.ended.cmp(&b.1.ended)); + + let mut owner: Vec> = vec![None; lines.len()]; + for (reference, turn) in turns { + for file in turn.files.iter().filter(|f| paths.contains(&f.path)) { + for hunk in &file.hunks { + for (j, hash) in hunk.lines.iter().enumerate() { + for &i in at.get(hash.as_str()).map(Vec::as_slice).unwrap_or(&[]) { + // Only from the start of a run: the line before + // matching too means an earlier start covers it. + let continues = i > 0 && j > 0 && hashes[i - 1] == hunk.lines[j - 1]; + if continues { + continue; + } + let mut length = 0; + while i + length < hashes.len() + && j + length < hunk.lines.len() + && hashes[i + length] == hunk.lines[j + length] + { + length += 1; + } + if (i..i + length).any(|k| !weak[k]) { + for slot in &mut owner[i..i + length] { + *slot = Some(reference); + } + } + } + } + } + } + } + owner +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn added_lines_are_what_the_turn_wrote() { + let hunks = added_hunks("a\nb\nc\n", "a\nB\nb\nc\nd\n"); + assert_eq!( + hunks, + vec![ + Hunk { + start: 2, + lines: vec![line_hash("B")] + }, + Hunk { + start: 5, + lines: vec![line_hash("d")] + }, + ] + ); + } + + fn record(turns: Vec<(&str, Vec<&str>)>) -> EditRecord { + EditRecord { + agent: "claude-code".into(), + session: "s".into(), + project: "p".into(), + root: "/r".into(), + turns: turns + .into_iter() + .map(|(ended, lines)| TurnRecord { + prompt_uuid: None, + end_uuid: None, + started: None, + ended: ended.into(), + prompt: None, + interrupted: false, + backfilled: false, + files: vec![FileChange { + path: "f.py".into(), + hunks: vec![Hunk { + start: 1, + lines: lines.into_iter().map(line_hash).collect(), + }], + }], + }) + .collect(), + } + } + + #[test] + fn a_lone_weak_line_is_not_evidence_but_joins_a_run() { + let records = vec![record(vec![("1", vec!["def go():", " return 1", "}"])])]; + let owners = attribute( + "}\nx = 1\ndef go():\n return 1\n}\n", + &["f.py".into()], + &records, + ); + let claimed: Vec = owners.iter().map(Option::is_some).collect(); + assert_eq!(claimed, vec![false, false, true, true, true]); + } + + #[test] + fn the_latest_writer_of_identical_text_wins() { + let records = vec![record(vec![ + ("2", vec!["value = compute()"]), + ("1", vec!["value = compute()"]), + ])]; + let owners = attribute("value = compute()\n", &["f.py".into()], &records); + assert_eq!(owners, vec![Some(TurnRef { record: 0, turn: 0 })]); + } + + #[test] + fn reindentation_keeps_the_link() { + let records = vec![record(vec![("1", vec!["return compute(x)"])])]; + assert!(attribute(" return compute(x)\n", &["f.py".into()], &records)[0].is_some()); + } +} diff --git a/src/backfill.rs b/src/backfill.rs new file mode 100644 index 0000000..bea6727 --- /dev/null +++ b/src/backfill.rs @@ -0,0 +1,490 @@ +//! Attribution for history made before the hooks: edit records reconstructed +//! from what survives — the transcripts, and the commits the agent made. +//! +//! The hooks see every edit because they watch the files. Afterwards the files +//! are long past, so this works from two weaker sources and says which turns +//! it built (`backfilled`): +//! +//! 1. **The transcript's own edit calls.** An `Edit`, `Write` or `MultiEdit` +//! carries the exact text it wrote, so its lines are its turn's exactly. +//! What a transcript can't show is what a shell command did to a file. +//! 2. **The commits the agent made.** A commit's diff holds every line it +//! added, however written, which is what catches shell edits. A commit is +//! credited to a turn only on an exact match: exactly one Bash call in the +//! transcript contains the commit's subject and brackets its author or +//! committer time — or a git note from the old design names the call. A +//! commit can hold several earlier turns' work, so its lines that a tool +//! edit in the same session already explains are left to that edit. +//! +//! Turns the hooks recorded are never touched, and re-running replaces only +//! what an earlier backfill wrote. + +use crate::attribution::{self, EditRecord, FileChange, Hunk, TurnRecord}; +use crate::claude::{self, display_summary, AGENT}; +use crate::git; +use crate::hook::{is_human_prompt, prompt_text}; +use crate::json::{self, Map, Value}; +use crate::snapshot; +use crate::store::Store; +use crate::sys; +use crate::trace::{self, content, py_str}; +use std::collections::{HashMap, HashSet}; +use std::fs; + +/// How far a commit's time may sit outside the Bash call that made it: git +/// records whole seconds and transcripts milliseconds, and a hook is slow. +const CLOCK_SLACK: f64 = 2.0; + +/// The tools whose inputs hold the text they wrote. +const EDIT_TOOLS: &[&str] = &["Edit", "Write", "MultiEdit"]; + +/// One turn of a transcript, as backfill reads it. +#[derive(Default)] +struct Turn { + prompt_uuid: Option, + prompt: Option, + started: Option, + end_uuid: Option, + ended: Option, + /// (absolute path, text written) for each successful edit call. + edits: Vec<(String, String)>, + /// Bash calls that could have committed: (call id, command, start, end). + calls: Vec<(String, String, f64, f64)>, +} + +fn seconds(stamp: Option<&str>) -> Option { + sys::iso_seconds(stamp?) +} + +/// A transcript split at its human prompts, each turn holding what it wrote. +fn turns_of(path: &str) -> Vec { + let records = trace::read_records(path); + // Results first, so an edit that failed contributes nothing. + let mut failed: HashSet = HashSet::new(); + let mut finished: HashMap = HashMap::new(); + for record in &records { + let stamp = seconds(record.get("timestamp").and_then(Value::as_str)); + for block in content(record) { + if !block.get("type").is_some_and(|t| t.is_str("tool_result")) { + continue; + } + let id = py_str(block.get("tool_use_id")); + if block.get("is_error").is_some_and(Value::truthy) { + failed.insert(id.clone()); + } + if let Some(stamp) = stamp { + finished.insert(id, stamp); + } + } + } + + let mut turns: Vec = Vec::new(); + for record in &records { + let Some(Value::Str(uuid)) = record.get("uuid") else { + continue; + }; + let stamp = record + .get("timestamp") + .and_then(Value::as_str) + .map(str::to_string); + if is_human_prompt(record) { + turns.push(Turn { + prompt_uuid: Some(uuid.clone()), + prompt: display_summary(prompt_text(record).as_deref()), + started: stamp.clone(), + ..Turn::default() + }); + } + let Some(turn) = turns.last_mut() else { + continue; + }; + turn.end_uuid = Some(uuid.clone()); + turn.ended = stamp.clone(); + for block in content(record) { + if !block.get("type").is_some_and(|t| t.is_str("tool_use")) { + continue; + } + let id = py_str(block.get("id")); + let name = block.get("name").and_then(Value::as_str).unwrap_or(""); + let input = block.get("input").and_then(Value::as_object); + if EDIT_TOOLS.contains(&name) && !failed.contains(&id) { + if let Some(input) = input { + collect_edits(name, input, &mut turn.edits); + } + } else if name == "Bash" { + let command = input.map(|i| py_str(i.get("command"))).unwrap_or_default(); + let started = seconds(stamp.as_deref()); + if let (true, Some(started), Some(&ended)) = + (command.contains("commit"), started, finished.get(&id)) + { + turn.calls.push((id, command, started, ended)); + } + } + } + } + turns +} + +fn collect_edits(tool: &str, input: &Map, into: &mut Vec<(String, String)>) { + let Some(path) = input.get("file_path").and_then(Value::as_str) else { + return; + }; + let text = |key: &str, from: &Map| from.get(key).and_then(Value::as_str).map(str::to_string); + match tool { + "Write" => into.extend(text("content", input).map(|t| (path.to_string(), t))), + "Edit" => into.extend(text("new_string", input).map(|t| (path.to_string(), t))), + "MultiEdit" => { + for edit in input + .get("edits") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + if let Some(edit) = edit.as_object() { + into.extend(text("new_string", edit).map(|t| (path.to_string(), t))); + } + } + } + _ => {} + } +} + +/// `path` relative to `root`, if it lies inside it. +fn inside(path: &str, root: &str) -> Option { + let rest = path.strip_prefix(root)?.strip_prefix('/')?; + (!rest.is_empty()).then(|| rest.to_string()) +} + +/// The lines a commit added, per file, as hunks of line hashes. +fn commit_hunks(root: &str, commit: &str) -> Vec { + let Ok(diff) = git::git( + root, + &[ + "show", + "--format=", + "--unified=0", + "--no-color", + "--no-renames", + commit, + ], + None, + ) else { + return Vec::new(); + }; + let mut changes: Vec = Vec::new(); + let mut file: Option = None; + for line in diff.lines() { + if let Some(path) = line.strip_prefix("+++ ") { + file = path.strip_prefix("b/").map(str::to_string); + continue; + } + if line.starts_with("@@") { + let start = line + .split_whitespace() + .find(|part| part.starts_with('+')) + .and_then(|part| part[1..].split(',').next()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + if let Some(path) = &file { + match changes.iter_mut().find(|c| &c.path == path) { + Some(change) => change.hunks.push(Hunk { + start, + lines: Vec::new(), + }), + None => changes.push(FileChange { + path: path.clone(), + hunks: vec![Hunk { + start, + lines: Vec::new(), + }], + }), + } + } + continue; + } + if let (Some(added), Some(path)) = (line.strip_prefix('+'), &file) { + if let Some(hunk) = changes + .iter_mut() + .find(|c| &c.path == path) + .and_then(|c| c.hunks.last_mut()) + { + hunk.lines.push(attribution::line_hash(added)); + } + } + } + changes.retain(|c| c.hunks.iter().any(|h| !h.lines.is_empty())); + changes +} + +/// A commit in the repository, with what it was called and when. +struct Commit { + sha: String, + times: [f64; 2], + subject: String, +} + +fn commits(root: &str) -> Vec { + let listing = git::git( + root, + &["log", "--all", "--format=%H%x00%at%x00%ct%x00%s"], + None, + ) + .unwrap_or_default(); + listing + .lines() + .filter_map(|line| { + let parts: Vec<&str> = line.splitn(4, '\0').collect(); + let time = |s: &str| s.parse::().ok(); + if parts.len() != 4 || parts[3].is_empty() { + return None; + } + Some(Commit { + sha: parts[0].into(), + times: [time(parts[1])?, time(parts[2])?], + subject: parts[3].into(), + }) + }) + .collect() +} + +/// `(session, call) → commit` from the old design's notes, which named the +/// call exactly and so need no matching. +fn old_notes(root: &str) -> HashMap<(String, String), Vec> { + let mut found: HashMap<(String, String), Vec> = HashMap::new(); + let listing = git::git_unchecked(root, &["notes", "--ref", "refs/notes/loch", "list"]) + .unwrap_or_default(); + for line in listing.lines() { + let Some(commit) = line.split_whitespace().nth(1) else { + continue; + }; + let text = git::git_unchecked(root, &["notes", "--ref", "refs/notes/loch", "show", commit]) + .unwrap_or_default(); + if let Ok(note) = json::loads(text.trim()) { + let (Some(session), Some(call)) = ( + note.get("session").and_then(Value::as_str), + note.get("call").and_then(Value::as_str), + ) else { + continue; + }; + found + .entry((session.into(), call.into())) + .or_default() + .push(commit.into()); + } + } + found +} + +/// The transcripts that might hold this project's history: every local +/// session whose working directory lay inside `root`. +fn transcripts_for(root: &str) -> Vec<(String, String)> { + let mut found = Vec::new(); + let projects = claude::projects_dir(None); + let Ok(dirs) = fs::read_dir(&projects) else { + return found; + }; + for dir in dirs.flatten() { + let Ok(files) = fs::read_dir(dir.path()) else { + continue; + }; + for file in files.flatten() { + let path = file.path().to_string_lossy().into_owned(); + if !path.ends_with(".jsonl") { + continue; + } + let Some(meta) = claude::read_session_meta(&path) else { + continue; + }; + let within = std::iter::once(&meta.cwd) + .chain(&meta.other_cwds) + .any(|cwd| cwd == root || inside(cwd, root).is_some()); + if within { + found.push((meta.session_id, path)); + } + } + } + found.sort(); + found +} + +#[derive(Default)] +pub struct Backfilled { + pub session: String, + pub turns: usize, + pub edit_lines: usize, + pub commit_lines: usize, + pub commits: usize, +} + +/// Which commit each Bash call made, by the exact-match rule: the old +/// design's note if one names the call; otherwise every commit whose subject +/// the command contains and whose time the call brackets, credited only if no +/// other call — in any session — matches it too. A wrong link would send +/// `ask` into the wrong conversation and look exactly like a right one, so an +/// ambiguous commit stays unlinked. +fn credit( + sessions: &[(String, Vec)], + history: &[Commit], + notes: &HashMap<(String, String), Vec>, +) -> HashMap<(String, String), Vec> { + let mut claims: HashMap<&str, HashSet<(String, String)>> = HashMap::new(); + let mut credited: HashMap<(String, String), Vec> = HashMap::new(); + for (session, turns) in sessions { + for (call, command, started, ended) in turns.iter().flat_map(|t| t.calls.iter()) { + let key = (session.clone(), call.clone()); + if let Some(noted) = notes.get(&key) { + credited.insert(key, noted.clone()); + continue; + } + for commit in history { + let brackets = commit + .times + .iter() + .any(|&t| started - CLOCK_SLACK <= t && t <= ended + CLOCK_SLACK); + if brackets && command.contains(&commit.subject) { + claims.entry(&commit.sha).or_default().insert(key.clone()); + } + } + } + } + let noted: HashSet<&String> = credited.values().flatten().collect(); + let mut matched: HashMap<(String, String), Vec> = HashMap::new(); + for (sha, claimants) in claims { + if claimants.len() == 1 && !noted.contains(&sha.to_string()) { + let key = claimants.into_iter().next().expect("one claimant"); + matched.entry(key).or_default().push(sha.to_string()); + } + } + for (key, shas) in matched { + credited.entry(key).or_default().extend(shas); + } + credited +} + +/// Rebuilds the backfilled part of every session that worked in the +/// workspace at `cwd`, and publishes the records. +pub fn backfill(cwd: &str, store: Option<&dyn Store>) -> Vec { + let root = snapshot::workspace_root(cwd); + let project = attribution::project_id(&root); + let in_git = snapshot::has_git_marker(&root); + let history = if in_git { commits(&root) } else { Vec::new() }; + let notes = if in_git { + old_notes(&root) + } else { + HashMap::new() + }; + let sessions: Vec<(String, Vec)> = transcripts_for(&root) + .into_iter() + .map(|(session, path)| (session, turns_of(&path))) + .collect(); + let credited = credit(&sessions, &history, ¬es); + + let mut results = Vec::new(); + for (session, turns) in sessions { + // Every line a tool edit in this session wrote: a commit's share is + // what these don't already explain. + let tool_lines: HashSet = turns + .iter() + .flat_map(|t| t.edits.iter()) + .flat_map(|(_, text)| text.lines().map(attribution::line_hash).collect::>()) + .collect(); + + let mut built = Vec::new(); + let mut result = Backfilled { + session: session.clone(), + ..Backfilled::default() + }; + for turn in turns { + let mut files: Vec = Vec::new(); + for (file, text) in &turn.edits { + let Some(relative) = inside(file, &root) else { + continue; + }; + let lines: Vec = text.lines().map(attribution::line_hash).collect(); + result.edit_lines += lines.len(); + push(&mut files, &relative, Hunk { start: 0, lines }); + } + for (call, ..) in &turn.calls { + let made = credited + .get(&(session.clone(), call.clone())) + .cloned() + .unwrap_or_default(); + for sha in made { + result.commits += 1; + for change in commit_hunks(&root, &sha) { + for hunk in change.hunks { + let lines: Vec = hunk + .lines + .into_iter() + .filter(|h| !tool_lines.contains(h)) + .collect(); + if lines.is_empty() { + continue; + } + result.commit_lines += lines.len(); + push( + &mut files, + &change.path, + Hunk { + start: hunk.start, + lines, + }, + ); + } + } + } + } + if files.is_empty() { + continue; + } + result.turns += 1; + built.push(TurnRecord { + prompt_uuid: turn.prompt_uuid, + end_uuid: turn.end_uuid, + started: turn.started, + ended: turn.ended.unwrap_or_default(), + prompt: turn.prompt, + interrupted: false, + backfilled: true, + files, + }); + } + if built.is_empty() { + continue; + } + let mut record = attribution::load_local(AGENT, &session).unwrap_or_else(|| EditRecord { + agent: AGENT.into(), + session: session.clone(), + project: project.clone(), + root: root.clone(), + turns: Vec::new(), + }); + // The hooks' own turns stand; an earlier backfill's are replaced. + record.turns.retain(|t| !t.backfilled); + let recorded: HashSet> = + record.turns.iter().map(|t| t.prompt_uuid.clone()).collect(); + record.turns.extend( + built + .into_iter() + .filter(|t| !recorded.contains(&t.prompt_uuid)), + ); + record.turns.sort_by(|a, b| a.ended.cmp(&b.ended)); + if attribution::save_local(&record).is_ok() { + if let Some(store) = store { + let _ = attribution::publish(store, &record); + } + } + results.push(result); + } + results +} + +fn push(files: &mut Vec, path: &str, hunk: Hunk) { + match files.iter_mut().find(|f| f.path == path) { + Some(file) => file.hunks.push(hunk), + None => files.push(FileChange { + path: path.into(), + hunks: vec![hunk], + }), + } +} diff --git a/src/blame_html.rs b/src/blame_html.rs new file mode 100644 index 0000000..d7ec54f --- /dev/null +++ b/src/blame_html.rs @@ -0,0 +1,256 @@ +//! `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. + +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 +} + +/// Conversations and hunks as `cli::command_blame` builds them, 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 ended = entry.get("ended").and_then(Value::as_str).unwrap_or(""); + 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(py::truncate(ended, 10)) + )); + } + + 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/loch/blame_html.py b/src/blame_template.html similarity index 55% rename from loch/blame_html.py rename to src/blame_template.html index d8cd47c..5129a77 100644 --- a/loch/blame_html.py +++ b/src/blame_template.html @@ -1,133 +1,4 @@ -"""`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 = """ + @@ -270,4 +141,3 @@ def parse_ranges(spec: str) -> list[tuple[int, int]]: -""" diff --git a/src/bundle.rs b/src/bundle.rs new file mode 100644 index 0000000..5351ba7 --- /dev/null +++ b/src/bundle.rs @@ -0,0 +1,249 @@ +//! 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 +//! 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::>(), + }) +} + +/// 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)` 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. +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 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)?; + 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::*; + + /// 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(); + data.extend(b"xyz".repeat(5000)); + data.extend(b"\"}"); + let packed = gzip_deterministic(&data); + assert_eq!(&bundle_ref(&packed)[..16], "405552bff938ef58"); + } +} diff --git a/src/claude.rs b/src/claude.rs new file mode 100644 index 0000000..5e298e6 --- /dev/null +++ b/src/claude.rs @@ -0,0 +1,241 @@ +//! The Claude Code adapter: where sessions live, how +//! their directory is named, and what a session's metadata is. + +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 { + 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. +pub fn config_dir(home: Option<&str>) -> String { + if home.is_none() { + 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); + 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, + } +} + +/// 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() +} + +/// 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() +} + +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(), + }) +} + +pub fn read_session_meta(path: &str) -> Option { + let meta = fs::metadata(path).ok()?; + // 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); + 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/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..dbf906f --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,1613 @@ +//! Every command: each builds one `Outcome` — payload +//! and prose together — and `main` renders it. + +use crate::argparse::{Exit, Nargs, Parser}; +use crate::attribution::{self, EditRecord}; +use crate::blame_html; +use crate::bundle::{self, Bundle, BundleOrigin, BundleSession, BUNDLE_VERSION}; +use crate::claude::{ + self, home_dir, list_sessions, resolve_cwd, transcript_path_for, SessionMeta, AGENT, +}; +use crate::format; +use crate::index::{self, IndexEntry, IndexError, BRANCH}; +use crate::ingest::{self, Origin}; +use crate::json::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::snapshot; +use crate::store::{create_store, resolve_store_uri, Store, StoreError}; +use crate::sys; +use crate::trace::{self, Link, Resolver, TraceError}; +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), + /// A bug rather than a failure a caller can act on: `internal`. + 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 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.rs'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, + )) +} + +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()) +} + +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::creation_time()), + 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 described = format!("could not reindex {}", store.describe()); + let result = index::reindex(store.as_ref()).map_err(|e| index_error(&described, e))?; + // The file index, re-derived from the edit records the same way, with + // entries no record accounts for removed. + let stale: std::collections::BTreeSet = store + .list(&index::dimension_prefix(attribution::FILE)) + .map_err(|e| store_error(&described, e))? + .into_iter() + .collect(); + let written: std::collections::BTreeSet = attribution::reindex_files(store.as_ref()) + .map_err(|e| store_error(&described, e))? + .into_iter() + .collect(); + let gone: Vec<&String> = stale.difference(&written).collect(); + for key in &gone { + store.delete(key).map_err(|e| store_error(&described, e))?; + } + Ok(Outcome::with( + "reindex", + object! { + "store" => store.describe(), + "bundles" => result.bundles, + "entries" => result.entries, + "removed" => result.removed, + "fileEntries" => written.len(), + "fileRemoved" => gone.len(), + }, + format!( + "scanned {} bundle(s) in {}\nwrote {} index entries, removed {} stale\nwrote {} file entries, removed {} stale\n", + result.bundles, + store.describe(), + result.entries, + result.removed, + written.len(), + gone.len() + ), + )) +} + +// -- 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 cwd = args + .str("cwd") + .filter(|c| !c.is_empty()) + .unwrap_or_else(sys::getcwd); + let root = snapshot::workspace_root(&cwd); + 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 installed = trace::install_hooks(&settings, &command) + .map_err(|trace::InstallError::Internal(m)| Failure::Internal(m))?; + let mut text = if installed.added.is_empty() { + format!("loch hooks already installed in {}\n", settings) + } else { + format!( + "installed loch hooks ({}) in {}\n", + installed.added.join(", "), + settings + ) + }; + if !installed.removed.is_empty() { + text.push_str(&format!( + "removed the old per-command hooks ({})\n", + installed.removed.join(", ") + )); + } + text.push_str("restart Claude Code sessions here to pick them up\n"); + Ok(Outcome::with( + "install", + object! { + "settings" => settings.as_str(), + "command" => command.as_str(), + "added" => strings(&installed.added), + "removed" => strings(&installed.removed), + }, + text, + )) +} + +// -- 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 "not written in a recorded turn".into(); + }; + 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(), + }; + let missing = if link.transcript.is_none() { + " (transcript not available)" + } else { + "" + }; + format!( + "{} session {}{}{}{}", + py::truncate(&link.ended, 10), + py::truncate(&link.session_id, 8), + title, + prompt, + missing + ) +} + +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 +} + +/// A file as attribution sees it: its text, and the project and relative path +/// its turns were recorded under. +struct Located { + text: String, + project: String, + relative: String, + /// `relative` and every earlier name git knows the file by. + names: Vec, + records: Vec, +} + +/// The names a file has had, newest first, by git's rename tracking — read +/// only, and only where there is a repository to ask. +fn past_names(root: &str, relative: &str) -> Vec { + let mut names = vec![relative.to_string()]; + if snapshot::has_git_marker(root) { + let log = trace::git_unchecked( + root, + &[ + "log", + "--follow", + "--name-only", + "--format=", + "--", + relative, + ], + ); + for name in log.lines().map(str::trim).filter(|n| !n.is_empty()) { + if !names.iter().any(|n| n == name) { + names.push(name.to_string()); + } + } + } + names +} + +/// Every record that wrote the file under any of its names, one per session, +/// the one with more turns winning where two copies of a session meet. +fn records_named(store: Option<&dyn Store>, project: &str, names: &[String]) -> Vec { + let mut by_session: HashMap = HashMap::new(); + for name in names { + for record in attribution::records_for(store, project, name) { + let better = by_session + .get(&record.session) + .is_none_or(|have| record.turns.len() > have.turns.len()); + if better { + by_session.insert(record.session.clone(), record); + } + } + } + let mut records: Vec = by_session.into_values().collect(); + records.sort_by(|a, b| a.session.cmp(&b.session)); + records +} + +/// Finds the records that wrote `file`. In a git checkout the root is the +/// checkout and the project its root commit, so there is one answer. Anywhere +/// else a session's root was the directory it ran in, which may be any +/// ancestor of the file, so each is tried, nearest first, until one has +/// records; with none, the nearest is the answer. +fn locate(file: &str, store: Option<&dyn Store>) -> std::result::Result { + let absolute = sys::abspath(file); + let text = match fs::read(&absolute) { + Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(), + Err(error) => { + return err( + "file-unreadable", + format!("{}: {}", file, sys::os_error(&error, file)), + ) + } + }; + let real = sys::realpath_strict(&absolute).unwrap_or(absolute); + let root = snapshot::workspace_root(&sys::dirname(&real)); + let mut candidates = vec![root.clone()]; + if !snapshot::has_git_marker(&root) { + let mut dir = sys::dirname(&root); + while dir.len() > 1 { + candidates.push(dir.clone()); + dir = sys::dirname(&dir); + } + } + let mut first = None; + for candidate in candidates { + let project = attribution::project_id(&candidate); + let relative = sys::relpath(&real, &candidate); + let names = past_names(&candidate, &relative); + let records = records_named(store, &project, &names); + if !records.is_empty() { + return Ok(Located { + text, + project, + relative, + names, + records, + }); + } + first.get_or_insert((project, relative, names)); + } + let (project, relative, names) = first.expect("there is always one candidate"); + Ok(Located { + text, + project, + relative, + names, + records: Vec::new(), + }) +} + +struct Blamed { + located: Located, + /// Per line, an index into `links`. + owners: Vec>, + links: Vec, +} + +fn blame_file(file: &str, store: Option<&dyn Store>) -> std::result::Result { + let located = locate(file, store)?; + let owners = attribution::attribute(&located.text, &located.names, &located.records); + let mut resolver = Resolver::new(store); + let mut index_of: HashMap = HashMap::new(); + let mut links = Vec::new(); + let mut indices = Vec::with_capacity(owners.len()); + for owner in &owners { + indices.push(match owner { + None => None, + Some(reference) => { + if !index_of.contains_key(reference) { + let link = resolver + .describe(&located.records[reference.record], reference.turn) + .map_err(Failure::Internal)?; + index_of.insert(*reference, links.len()); + links.push(link); + } + Some(index_of[reference]) + } + }); + } + Ok(Blamed { + located, + owners: indices, + links, + }) +} + +/// Consecutive lines with one owner, 1-based: (start, end, owner). +fn runs(owners: &[Option]) -> Vec<(usize, usize, Option)> { + let mut runs: Vec<(usize, usize, Option)> = Vec::new(); + for (i, owner) in owners.iter().enumerate() { + match runs.last_mut() { + Some(last) if last.2 == *owner => last.1 = i + 1, + _ => runs.push((i + 1, i + 1, *owner)), + } + } + runs +} + +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 store = store_or_none(args.str("store").as_deref()); + let blamed = blame_file(&file, store.as_deref())?; + + // One mark per turn, handed out in order of first appearance in the file, + // so A is always the first conversation you read. + let marks: Vec = (0..blamed.links.len()).map(mark).collect(); + let legend: Vec = blamed + .links + .iter() + .zip(&marks) + .map(|(link, letter)| { + let mut entry = object! {"mark" => letter.as_str()}; + entry.extend(link.payload()); + Value::Object(entry) + }) + .collect(); + let spans = runs(&blamed.owners); + let rows: Vec = spans + .iter() + .map(|&(start, end, owner)| { + Value::Object(object! { + "start" => start, + "end" => end, + "mark" => owner.map_or("·", |o| marks[o].as_str()), + "conversation" => owner.map_or(Value::Null, |o| Value::Object(blamed.links[o].payload())), + }) + }) + .collect(); + + let mut text = format!("{}\n", file); + for &(start, end, owner) in &spans { + let span = if end > start { + format!("{}-{}", start, end) + } else { + start.to_string() + }; + text.push_str(&format!( + " {} {}\n", + right(&span, 9), + link_text(owner.map(|o| &blamed.links[o])) + )); + } + let attributed = blamed.owners.iter().filter(|o| o.is_some()).count(); + text.push_str(&format!( + "\n{} of {} line(s) written in a recorded turn; follow one up with: loch ask {}:\n", + attributed, + blamed.owners.len(), + file + )); + + let mut payload = object! { + "file" => file.as_str(), + "path" => blamed.located.relative.as_str(), + "project" => blamed.located.project.as_str(), + "conversations" => legend.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 lines: HashMap = blamed + .located + .text + .lines() + .enumerate() + .map(|(i, line)| (i + 1, line.to_string())) + .collect(); + let page = blame_html::render(&file, &legend, &rows, &lines, visible.as_deref()); + let target = if html.is_empty() { + sys::join( + &sys::gettempdir(), + &format!("loch-blame-{}.html", sys::basename(&file)), + ) + } else { + html + }; + fs::write(&target, page.as_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 line_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) = line_target(&args.str("target").unwrap_or_default())?; + let store = store_or_none(args.str("store").as_deref()); + let blamed = blame_file(&file, store.as_deref())?; + if let Some((_, last)) = lines { + if last > blamed.owners.len() { + return err( + "usage", + format!("{} has {} lines, not {}", file, blamed.owners.len(), last), + ); + } + } + + // A range asks who wrote what is there now; a whole file asks every turn + // that ever changed it, including ones whose lines are gone. + let mut resolver = Resolver::new(store.as_deref()); + let mut links: Vec = match lines { + Some((first, last)) => { + let mut seen = Vec::new(); + for owner in blamed.owners[first - 1..last].iter().flatten() { + if !seen.contains(owner) { + seen.push(*owner); + } + } + seen.into_iter().map(|o| blamed.links[o].clone()).collect() + } + None => { + let mut all = Vec::new(); + for record in &blamed.located.records { + for (index, turn) in record.turns.iter().enumerate() { + if turn + .files + .iter() + .any(|f| blamed.located.names.contains(&f.path)) + { + all.push( + resolver + .describe(record, index) + .map_err(Failure::Internal)?, + ); + } + } + } + all + } + }; + links.sort_by(|a, b| b.ended.cmp(&a.ended)); + + let span = match lines { + None => String::new(), + Some((a, b)) if a == b => format!(":{}", a), + Some((a, b)) => format!(":{}-{}", a, b), + }; + let mut text = format!("{}{}: {} turn(s), newest first\n", file, span, links.len()); + for link in &links { + text.push_str(&format!(" {}\n", link_text(Some(link)))); + } + if !links.is_empty() { + text.push_str(&format!("\nfollow one up with: loch ask {}:\n", file)); + } + 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" => links.iter().map(|l| Value::Object(l.payload())).collect::>(), + }, + text, + )) +} + +pub fn command_ask(argv: &[String]) -> Run { + let mut p = parser("ask"); + p.positional("target", Nargs::One) + .positional("question", Nargs::Optional) + .flag("--at-turn", None) + .flag("--no-launch", None) + .option("--store"); + let args = p.parse(argv)?; + let as_json = json_requested(); + let target = args.str("target").unwrap_or_default(); + let (file, line) = match line_target(&target)? { + (file, Some((line, _))) => (file, line), + (_, None) => return err("usage", format!("{} is not :", target)), + }; + let store = store_or_none(args.str("store").as_deref()); + let blamed = blame_file(&file, store.as_deref())?; + if line > blamed.owners.len() { + return err( + "usage", + format!("{} has {} lines, not {}", file, blamed.owners.len(), line), + ); + } + let Some(owner) = blamed.owners[line - 1] else { + return err( + "not-linked", + format!("{} was not written in a recorded turn", target), + ); + }; + let link = blamed.links[owner].clone(); + let Some(transcript) = &link.transcript else { + return err( + "transcript-missing", + format!( + "session {} wrote it, but its transcript is neither in {} nor in the store", + link.session_id, + claude::projects_dir(None) + ), + ); + }; + let at_turn = args.flag("at_turn"); + let cwd = blamed + .located + .records + .iter() + .find(|r| r.session == link.session_id) + .map(|r| r.root.clone()) + .filter(|root| Path::new(root).is_dir()) + .unwrap_or_else(sys::getcwd); + let fork = trace::fork_session( + transcript, + &cwd, + if at_turn { + link.end_uuid.as_deref() + } else { + None + }, + Some(&format!("loch ask {}", target)), + ) + .map_err(|e| match e { + trace::ForkError::Trace(t) => Failure::from(t), + trace::ForkError::Internal(m) => Failure::Internal(m), + })?; + + let 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! { + "target" => target.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 at_turn { "turn" } else { "end" }, + "launch" => strings(&command), + }; + let text = format!( + "forked session {}, which wrote {}, {}: {} records, as {}\n", + py::truncate(&fork.origin_session, 8), + target, + if at_turn { + "at the end of that turn" + } 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, + fork.cwd, + command.join(" ") + ), + )); + } + eprint!("{}", text); + exec_claude(&fork.cwd, &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(); + let code = error.raw_os_error().unwrap_or(0); + Err(Failure::Internal(format!( + "[Errno {}] {}: '{}'", + code, + sys::strerror(code), + 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 ---------------------------------------------------------------------- + +/// Reconstructs attribution for turns from before the hooks, from the +/// transcripts' edit calls and the commits the agent made. +pub fn command_backfill(argv: &[String]) -> Run { + let mut p = parser("backfill"); + p.option("--cwd").option("--store"); + let args = p.parse(argv)?; + let cwd = args + .str("cwd") + .filter(|c| !c.is_empty()) + .unwrap_or_else(sys::getcwd); + let root = snapshot::workspace_root(&cwd); + let store = store_or_none(args.str("store").as_deref()); + let results = crate::backfill::backfill(&cwd, store.as_deref()); + let mut text = String::new(); + for r in &results { + text.push_str(&format!( + " session {} {} turn(s): {} line(s) from edits, {} from {} commit(s)\n", + py::truncate(&r.session, 8), + r.turns, + r.edit_lines, + r.commit_lines, + r.commits + )); + } + let turns: usize = results.iter().map(|r| r.turns).sum(); + text.push_str(&format!( + "backfilled {} turn(s) across {} session(s) in {}\n", + turns, + results.len(), + root + )); + Ok(Outcome::with( + "backfill", + object! { + "root" => root.as_str(), + "project" => attribution::project_id(&root), + "turns" => turns, + "sessions" => results.iter().map(|r| Value::Object(object! { + "session" => r.session.as_str(), + "turns" => r.turns, + "editLines" => r.edit_lines, + "commitLines" => r.commit_lines, + "commits" => r.commits, + })).collect::>(), + }, + text, + )) +} + +// -- gc ------------------------------------------------------------------------------ + +/// Deletes the snapshots nothing needs: the hooks do this on their own every +/// `COLLECT_EVERY` snapshots, and this runs it now. +pub fn command_gc(argv: &[String]) -> Run { + let p = parser("gc"); + p.parse(argv)?; + let collected = crate::hook::collect().map_err(|e| Failure::Internal(e.0))?; + Ok(Outcome::with( + "gc", + object! { + "kept" => collected.kept, + "removed" => collected.removed, + "bytes" => collected.bytes as i64, + }, + format!( + "removed {} object(s), {}; kept {}\n", + collected.removed, + format_bytes(collected.bytes), + collected.kept + ), + )) +} + +// -- 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), + "hook" => command_hook(argv), + "gc" => command_gc(argv), + "backfill" => command_backfill(argv), + "help" => command_help(argv), + "version" => command_version(argv), + _ => return None, + }) +} diff --git a/src/format.rs b/src/format.rs new file mode 100644 index 0000000..ba60324 --- /dev/null +++ b/src/format.rs @@ -0,0 +1,124 @@ +//! 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}; +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/src/git.rs b/src/git.rs new file mode 100644 index 0000000..c1e5d7d --- /dev/null +++ b/src/git.rs @@ -0,0 +1,60 @@ +//! Git, by subprocess, for the little loch still asks it: a project's root +//! commit (its identity across clones) and the branch `list` defaults to. +//! Nothing loch records is written to git. + +use std::io::Write; +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(), + )) +} diff --git a/src/hook.rs b/src/hook.rs new file mode 100644 index 0000000..a842a6b --- /dev/null +++ b/src/hook.rs @@ -0,0 +1,446 @@ +//! `loch hook`, run by the agent's harness at a turn's boundaries: `prompt` +//! when one is submitted, `stop` when the agent finishes, `end` when the +//! session ends. +//! +//! `prompt` snapshots the workspace; `stop` snapshots it again and records the +//! lines the turn added (see `attribution.rs`) in the session's edit record, +//! and copies the transcript into the store, since Claude Code deletes +//! transcripts after `cleanupPeriodDays` (30 by default). +//! +//! **Every turn gets closed by someone.** Claude Code runs no `Stop` when a +//! turn is cancelled, and a crash runs nothing at all. Left alone, the next +//! prompt's snapshot would take the unfinished turn's edits as its baseline +//! and they would belong to nobody. So a session's state says whether its turn +//! is still open, and whichever hook comes next — the next `prompt`, or `end` +//! on exit — closes it first, marked interrupted, ending where the workspace +//! stands then. A crash that is never resumed is the one case nothing closes; +//! its start snapshot stops being kept after `ABANDONED`. +//! +//! A hook must never fail the turn it belongs to, so every error is swallowed +//! and nothing is written to stdout: a hook that breaks the agent gets +//! uninstalled. + +use crate::attribution::{self, EditRecord, TurnRecord}; +use crate::claude::{display_summary, AGENT}; +use crate::json::{self, Map, Value}; +use crate::object; +use crate::snapshot; +use crate::store::{self, Store}; +use crate::sys; +use crate::trace::{self, content}; +use std::fs; +use std::path::PathBuf; + +/// How long an open turn's start snapshot is kept for a session that never +/// came back to close it. +pub const ABANDONED: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600); + +/// Any failure: the hook swallows them all, so all that matters about one is +/// where it stopped. +pub struct Stop; + +impl From for Stop { + fn from(_: std::io::Error) -> Self { + Stop + } +} + +impl From for Stop { + fn from(_: snapshot::SnapshotError) -> Self { + Stop + } +} + +fn event_cwd(event: &Map) -> String { + match event.get("cwd") { + Some(Value::Str(text)) if !text.is_empty() => text.clone(), + _ => sys::getcwd(), + } +} + +fn session_of(event: &Map) -> Result { + match event.get("session_id") { + Some(Value::Str(id)) if !id.is_empty() && !id.contains('/') => Ok(id.clone()), + _ => Err(Stop), + } +} + +fn transcript_of(event: &Map) -> Option { + match event.get("transcript_path") { + Some(Value::Str(path)) => Some(path.clone()), + _ => None, + } +} + +// -- session state -------------------------------------------------------------- + +fn sessions_dir() -> PathBuf { + snapshot::loch_home().join("sessions") +} + +fn state_path(session: &str) -> PathBuf { + sessions_dir().join(format!("{}.json", session)) +} + +/// What a session's hooks hand each other between processes. +struct State { + root: String, + /// A turn has begun and not been closed. + open: bool, + /// Where the open turn began, or where the last closed one did — kept so + /// a second `Stop` for the same prompt can be measured from the start. + turn_start: String, +} + +fn read_state(session: &str) -> Option { + let value = json::loads(&fs::read_to_string(state_path(session)).ok()?).ok()?; + Some(State { + root: value.get("root")?.as_str()?.to_string(), + open: value.get("open").is_some_and(Value::truthy), + turn_start: value.get("turnStart")?.as_str()?.to_string(), + }) +} + +fn write_state(session: &str, state: &State) -> Result<(), Stop> { + let body = Value::Object(object! { + "root" => state.root.as_str(), + "open" => state.open, + "turnStart" => state.turn_start.as_str(), + }); + snapshot::write_atomically( + &state_path(session), + json::dumps(&body, json::DEFAULT).as_bytes(), + )?; + Ok(()) +} + +// -- reading the transcript ------------------------------------------------------- + +/// What the transcript says about a turn: the prompt that began it and the +/// last record written. +#[derive(Default)] +pub struct TurnInfo { + pub prompt_uuid: Option, + pub prompt: Option, + pub started: Option, + pub end_uuid: Option, + pub ended: Option, +} + +/// A record a person typed: a user message that is neither a tool's result +/// nor Claude Code's own bookkeeping. +pub fn is_human_prompt(record: &Map) -> bool { + if !record.get("type").is_some_and(|t| t.is_str("user")) { + return false; + } + if record.get("isMeta").is_some_and(Value::truthy) + || record.get("isCompactSummary").is_some_and(Value::truthy) + { + return false; + } + match record.get("message").and_then(|m| m.get("content")) { + Some(Value::Str(_)) => true, + Some(Value::Array(_)) => !content(record) + .iter() + .any(|b| b.get("type").is_some_and(|t| t.is_str("tool_result"))), + _ => false, + } +} + +pub fn prompt_text(record: &Map) -> Option { + match record.get("message")?.get("content")? { + Value::Str(text) => Some(text.clone()), + Value::Array(_) => content(record) + .iter() + .find_map(|block| match block.get("text") { + Some(Value::Str(text)) if !text.is_empty() => Some(text.clone()), + _ => None, + }), + _ => None, + } +} + +/// The turn the transcript ends with. When the hook closing it belongs to the +/// *next* prompt, that prompt may already be written; `excluding` names it, +/// and it and everything after are left out. +pub fn current_turn(transcript: &str, excluding: Option<&str>) -> TurnInfo { + let records: Vec = trace::read_records(transcript) + .into_iter() + .filter(|r| matches!(r.get("uuid"), Some(Value::Str(_)))) + .collect(); + let mut end = records.len(); + if let Some(next) = excluding { + if let Some(at) = records.iter().rposition(is_human_prompt) { + if prompt_text(&records[at]).as_deref() == Some(next) { + end = at; + } + } + } + let mut info = TurnInfo::default(); + for record in &records[..end] { + let uuid = record + .get("uuid") + .and_then(Value::as_str) + .map(str::to_string); + let stamp = record + .get("timestamp") + .and_then(Value::as_str) + .map(str::to_string); + if is_human_prompt(record) { + info.prompt_uuid = uuid.clone(); + info.prompt = display_summary(prompt_text(record).as_deref()); + info.started = stamp.clone(); + } + info.end_uuid = uuid; + info.ended = stamp; + } + info +} + +// -- closing a turn ------------------------------------------------------------------ + +/// Records the turn that began at `start` and ends now, in the session's edit +/// record, and returns the snapshot it ended at. +fn close_turn( + session: &str, + root: &str, + start: Option<&str>, + info: TurnInfo, + interrupted: bool, + store: Option<&dyn Store>, +) -> Result { + let end = snapshot::snapshot(root)?; + let mut record = attribution::load_local(AGENT, session).unwrap_or_else(|| EditRecord { + agent: AGENT.into(), + session: session.into(), + project: attribution::project_id(root), + root: root.into(), + turns: Vec::new(), + }); + // With no baseline at all, everything in the workspace would look new; the + // turn is recorded with nothing attributed, as the baseline for the next. + let files = match start { + Some(start) => attribution::diff(Some(start), &end)?, + None => Vec::new(), + }; + // Claude Code can stop more than once for one prompt; that is still one + // turn, and the caller measured it from where it began. + let same_turn = info.prompt_uuid.is_some() + && record.turns.last().map(|t| &t.prompt_uuid) == Some(&info.prompt_uuid); + if same_turn { + record.turns.pop(); + } + record.turns.push(TurnRecord { + prompt_uuid: info.prompt_uuid, + end_uuid: info.end_uuid, + started: info.started, + ended: info.ended.unwrap_or_else(|| sys::iso_timestamp(sys::now())), + prompt: info.prompt, + interrupted, + backfilled: false, + files, + }); + attribution::save_local(&record)?; + if let Some(store) = store { + let _ = attribution::publish(store, &record); + } + Ok(end) +} + +/// The session's last closed turn's prompt, to recognise a repeated `Stop`. +fn last_prompt(session: &str) -> Option { + attribution::load_local(AGENT, session)? + .turns + .last()? + .prompt_uuid + .clone() +} + +/// A turn begins. A turn still open from before — cancelled, or a crash then +/// `--resume` — is closed first, so its edits are its own and not this +/// turn's baseline. +pub fn prompt(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { + let session = session_of(event)?; + let root = snapshot::workspace_root(&event_cwd(event)); + if let Some(state) = read_state(&session).filter(|s| s.open) { + if snapshot::snapshottable(&state.root) { + let next = match event.get("prompt") { + Some(Value::Str(text)) => Some(text.as_str()), + _ => None, + }; + let info = transcript_of(event) + .map(|t| current_turn(&t, next)) + .unwrap_or_default(); + close_turn( + &session, + &state.root, + Some(&state.turn_start), + info, + true, + store, + )?; + } + } + if !snapshot::snapshottable(&root) { + return Ok(()); + } + let start = snapshot::snapshot(&root)?; + write_state( + &session, + &State { + root, + open: true, + turn_start: start, + }, + ) +} + +/// The agent finished: record what the turn changed, and keep the transcript. +pub fn stop(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { + if let Some(store) = store { + let _ = snapshot_transcript(event, store); + } + let session = session_of(event)?; + let state = read_state(&session); + let root = match &state { + Some(state) => state.root.clone(), + None => snapshot::workspace_root(&event_cwd(event)), + }; + if !snapshot::snapshottable(&root) { + return Ok(()); + } + let info = transcript_of(event) + .map(|t| current_turn(&t, None)) + .unwrap_or_default(); + let repeated = info.prompt_uuid.is_some() && last_prompt(&session) == info.prompt_uuid; + // The turn's own start if it has one — an open turn, or a repeated stop of + // the last one. Otherwise no prompt hook ran (installed mid-session, or a + // harness without one), and the workspace's last snapshot is the best + // baseline there is; it is read before taking the next, which replaces it. + let start = match &state { + Some(state) if state.open || repeated => Some(state.turn_start.clone()), + _ => snapshot::latest(&root), + }; + close_turn(&session, &root, start.as_deref(), info, false, store)?; + if let Some(start) = start { + write_state( + &session, + &State { + root, + open: false, + turn_start: start, + }, + )?; + } + Ok(()) +} + +/// The session is over. A turn still open was cut short; close it, and let +/// the session's state go, so nothing it held is kept any longer. +pub fn end(event: &Map, store: Option<&dyn Store>) -> Result<(), Stop> { + let session = session_of(event)?; + if let Some(state) = read_state(&session).filter(|s| s.open) { + if snapshot::snapshottable(&state.root) { + let info = transcript_of(event) + .map(|t| current_turn(&t, None)) + .unwrap_or_default(); + close_turn( + &session, + &state.root, + Some(&state.turn_start), + info, + true, + store, + )?; + } + } + if let Some(store) = store { + let _ = snapshot_transcript(event, store); + } + let _ = fs::remove_file(state_path(&session)); + Ok(()) +} + +// -- collection ------------------------------------------------------------------------ + +/// Every snapshot something still needs: each workspace's latest, and each +/// live session's turn start. A session's state that has sat untouched past +/// `ABANDONED` belongs to a crash nobody resumed; it is deleted, and what it +/// held goes with the next collection. +pub fn roots() -> Vec { + let mut roots = snapshot::workspace_roots(); + let now = std::time::SystemTime::now(); + let Ok(entries) = fs::read_dir(sessions_dir()) else { + return roots; + }; + for entry in entries.flatten() { + let path = entry.path(); + let age = fs::metadata(&path) + .and_then(|m| m.modified()) + .ok() + .and_then(|modified| now.duration_since(modified).ok()); + if age.is_some_and(|age| age > ABANDONED) { + let _ = fs::remove_file(&path); + continue; + } + let session = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + if let Some(state) = read_state(&session) { + roots.push(state.turn_start); + } + } + roots +} + +pub fn collect() -> Result { + snapshot::collect(&roots()) +} + +/// Copies the live transcript into the store. 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::Str(path)), Some(Value::Str(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 project = sys::basename(&sys::dirname(path)); + let key = format!( + "{}{}/{}.jsonl", + trace::transcripts_prefix(), + project, + session_id + ); + store.put(&key, &data).map_err(|_| Stop)?; + Ok(Some(key)) +} + +/// Run by the harness with the event as JSON on stdin. +pub fn run(name: &str, stdin: &[u8]) { + let Ok(text) = std::str::from_utf8(stdin) else { + return; + }; + let text = if text.is_empty() { "{}" } else { text }; + let Ok(Value::Object(event)) = json::loads(text) else { + return; + }; + let store = || store::create_store(&store::resolve_store_uri(None)).ok(); + let _ = match name { + "prompt" => prompt(&event, store().as_deref()), + "stop" => stop(&event, store().as_deref()), + "end" => end(&event, store().as_deref()), + // The tool-call hooks the git-notes design used. A settings file can + // still name them until `install` is re-run; they do nothing. + _ => return, + }; + // Collection rides on the hooks, as `git gc --auto` rides on commands: + // the check is a counter read, and the work runs once in many turns. + if snapshot::collection_due() { + let _ = collect(); + } +} diff --git a/src/index.rs b/src/index.rs new file mode 100644 index 0000000..086c190 --- /dev/null +++ b/src/index.rs @@ -0,0 +1,282 @@ +//! Store key layout and derived index entries. + +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_) +} + +pub 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) +} + +/// Rebuilds the branch dimension from the bundles. Other dimensions are +/// derived from other sources (`file`, from edit records) and are left alone. +pub fn reindex(store: &dyn Store) -> Result { + let stale: BTreeSet = store.list(&dimension_prefix(BRANCH))?.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/src/ingest.rs b/src/ingest.rs new file mode 100644 index 0000000..b7464e0 --- /dev/null +++ b/src/ingest.rs @@ -0,0 +1,694 @@ +//! 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 +//! 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:"; +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. +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)`: 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 bytes = text.as_bytes(); + if bytes.first() == Some(&b'=') { + return Err("Leading padding not allowed".into()); + } + let mut out = Vec::new(); + 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; + } + } + } + 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. +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" + ); + 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/src/json.rs b/src/json.rs new file mode 100644 index 0000000..76434b8 --- /dev/null +++ b/src/json.rs @@ -0,0 +1,830 @@ +//! 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_object_mut(&mut self) -> Option<&mut 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) +} + +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, 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)?; + 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\ude00\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/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..c2fd6f0 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,28 @@ +//! 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 attribution; +pub mod backfill; +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 snapshot; +pub mod store; +pub mod sys; +pub mod trace; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..9aae08e --- /dev/null +++ b/src/main.rs @@ -0,0 +1,54 @@ +//! `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}; + +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, 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); + } + 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 cli::dispatch(&command, rest) { + Some(result) => result, + None => Err(Failure::Error(CommandError::new( + "unknown-command", + format!("unknown command '{}' (try: loch help)", command), + ))), + }; + match result { + Ok(outcome) => emit(outcome, 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), + // 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 { + error.prose = Some(format!("loch: internal error: {}\n", message)); + } + emit_error(&command, error, as_json) + } + } +} diff --git a/src/output.rs b/src/output.rs new file mode 100644 index 0000000..d35d109 --- /dev/null +++ b/src/output.rs @@ -0,0 +1,138 @@ +//! The result envelope and its two renderings. + +use crate::json::{self, Map, Value}; +use std::io::Write; + +pub const SCHEMA: i64 = 2; + +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(), + } + } + + 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 warnings: Vec, + 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(), + warnings: Vec::new(), + exit_status: 1, + prose: None, + } + } +} + +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::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::str(code)); + body.insert("error".into(), Value::str(error)); + } + for (key, value) in payload { + body.insert(key, value); + } + 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)); + 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 { + write_text(&mut stderr, warning); + } + 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) -> ! { + if as_json { + write_document(&document( + command, + false, + error.payload, + 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)); + write_text(&mut stderr, &prose); + } + let _ = std::io::stdout().flush(); + std::process::exit(error.exit_status); +} + +fn write_document(body: &Value) { + 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(); +} diff --git a/src/py.rs b/src/py.rs new file mode 100644 index 0000000..1b827ab --- /dev/null +++ b/src/py.rs @@ -0,0 +1,179 @@ +//! 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/src/redact.rs b/src/redact.rs new file mode 100644 index 0000000..1854a76 --- /dev/null +++ b/src/redact.rs @@ -0,0 +1,441 @@ +//! 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. +//! +//! 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 indexmap::IndexMap; +use regex::Regex; +use std::sync::OnceLock; + +/// The rule names, in priority order: anthropic-key before openai-key, which +/// would otherwise claim the same `sk-` prefix. +pub 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_]*", + 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 + ) +} + +struct Engine { + rules: Vec<(Regex, bool, bool)>, + keyword: Regex, + env: fancy_regex::Regex, +} + +fn engine() -> &'static Engine { + static ENGINE: OnceLock = OnceLock::new(); + ENGINE.get_or_init(|| Engine { + rules: prefixed() + .iter() + .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); + +pub struct Redaction { + pub text: String, + /// Rule name → count, in order of each rule's first match. + pub counts: IndexMap, +} + +pub fn scan(text: &str) -> IndexMap { + let mut counts = IndexMap::new(); + for (index, _) in engine().matches(text) { + *counts.entry(NAMES[index].to_string()).or_insert(0) += 1; + } + counts +} + +pub fn redact(text: &str) -> Result { + let mut counts: IndexMap = IndexMap::new(); + let mut out = String::with_capacity(text.len()); + let mut last = 0; + for (index, found) in engine().matches(text) { + let name = NAMES[index]; + *counts.entry(name.to_string()).or_insert(0) += 1; + out.push_str(&text[last..found.start]); + out.push_str(&text[found.start..found.keep]); + out.push_str(&format!("[REDACTED:{}]", name)); + last = found.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::*; + + /// The rules as one alternation, as the Python build ran them: 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)); + 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/src/rewrite.rs b/src/rewrite.rs new file mode 100644 index 0000000..1b72375 --- /dev/null +++ b/src/rewrite.rs @@ -0,0 +1,197 @@ +//! Path rewriting — 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/src/s3.rs b/src/s3.rs new file mode 100644 index 0000000..328a884 --- /dev/null +++ b/src/s3.rs @@ -0,0 +1,637 @@ +//! 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; 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. +//! +//! 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}; +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. +const TIMEOUT: Duration = Duration::from_secs(20); + +pub struct S3Store { + bucket: String, + prefix: String, +} + +struct Response { + status: u16, + body: Vec, +} + +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) + } + } + + 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("Unable to locate credentials".into()))?; + let region = region(); + 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( + method, + &target, + &query_string, + extra, + body, + &credentials, + ®ion, + now, + ); + let url = if query.is_empty() { + target.url() + } else { + 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) + .build() + .request(method, &url); + for (name, value) in &headers { + if name != "host" { + request = request.set(name, value); + } + } + 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(|_| ()) + } + + 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 { + // 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(&crate::index::unquote(&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, + 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: 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()) + { + 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(bucket, true), + encoded.unwrap_or_default() + ), + } + } + None if bucket.contains('.') => Target { + scheme: "https".into(), + host: format!("s3.{}.amazonaws.com", region), + path: format!("/{}{}", bucket, encoded.unwrap_or_default()), + }, + None => Target { + scheme: "https".into(), + host: format!("{}.s3.{}.amazonaws.com", bucket, region), + path: encoded.unwrap_or_else(|| "/".into()), + }, + } + } + + fn url(&self) -> String { + format!("{}://{}{}", self.scheme, self.host, self.path) + } +} + +/// 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'~' => { + out.push(byte as char) + } + b'/' if !encode_slash => out.push('/'), + _ => out.push_str(&format!("%{:02X}", byte)), + } + } + out +} + +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(|(k, v)| format!("{}={}", k, v)) + .collect::>() + .join("&") +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{:02x}", b)).collect() +} + +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. +#[allow(clippy::too_many_arguments)] +fn sign( + method: &str, + target: &Target, + query: &str, + 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, query, 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. +fn amz_date(seconds: u64) -> String { + let c = crate::sys::civil(seconds as i64); + format!( + "{:04}{:02}{:02}T{:02}{:02}{:02}Z", + c.year, c.month, c.day, c.hour, c.minute, c.second + ) +} + +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, + }; + 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" + ); + } + + /// 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("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/src/snapshot.rs b/src/snapshot.rs new file mode 100644 index 0000000..ab83a5d --- /dev/null +++ b/src/snapshot.rs @@ -0,0 +1,444 @@ +//! Snapshots of a workspace's files, taken on demand the way git's index is: +//! nothing runs between snapshots. +//! +//! A snapshot is the sorted list of every file loch can see in the workspace +//! (what `.gitignore` and friends don't exclude) with each one's content hash. +//! Its id is the hash of that list, so an unchanged workspace snapshots to the +//! same id. Contents live once each in `~/.loch/objects`, addressed by hash and +//! shared across workspaces, which is what makes a second worktree of the same +//! repository nearly free. +//! +//! **The stat cache is the whole performance story.** A file whose size and +//! mtime match the last snapshot's is not read again. Git's one trap applies: +//! a file rewritten within the same mtime tick as the snapshot that recorded it +//! looks unchanged. So an entry is only trusted when its mtime is comfortably +//! older than the snapshot that cached it; anything newer is rehashed. + +use crate::claude::home_dir; +use crate::sys; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::fs; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; + +/// A file modified this close to the snapshot that cached it is rehashed next +/// time regardless of its stat: the racily-clean window. +const RACY_NANOS: i128 = 2_000_000_000; + +#[derive(Debug)] +pub struct SnapshotError(pub String); + +fn io(error: std::io::Error, path: &Path) -> SnapshotError { + SnapshotError(sys::os_error(&error, &path.to_string_lossy())) +} + +pub fn loch_home() -> PathBuf { + PathBuf::from(home_dir()).join(".loch") +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{:02x}", b)).collect() +} + +pub fn content_hash(data: &[u8]) -> String { + hex(&Sha256::digest(data)) +} + +/// The directory a session's files are relative to: the nearest ancestor of +/// `cwd` holding a `.git` entry — a marker, read like any other file; nothing +/// asks git — or `cwd` itself where there is none. Symlinks are resolved, as +/// Claude resolves them, so one checkout has one root however it was entered. +pub fn workspace_root(cwd: &str) -> String { + let start = sys::realpath_strict(cwd).unwrap_or_else(|| sys::abspath(cwd)); + let mut dir = Path::new(&start); + loop { + if dir.join(".git").exists() { + return dir.to_string_lossy().into_owned(); + } + match dir.parent() { + Some(parent) => dir = parent, + None => return start, + } + } +} + +/// Whether `root` has a `.git` marker, so that a project id can come from it. +pub fn has_git_marker(root: &str) -> bool { + Path::new(root).join(".git").exists() +} + +/// Writes `path` aside and renames it into place, so a hook killed mid-write +/// — Claude Code's hook timeout, a crash — leaves the old file or the new one, +/// never half of either. The leftover aside file is swept by `collect`. +pub fn write_atomically(path: &Path, data: &[u8]) -> std::io::Result<()> { + let parent = path.parent().expect("written files have a directory"); + fs::create_dir_all(parent)?; + let name = path.file_name().expect("a file name").to_string_lossy(); + let staged = parent.join(format!(".{}.{}{}", name, TMP_MARK, std::process::id())); + fs::write(&staged, data)?; + fs::rename(&staged, path) +} + +const TMP_MARK: &str = "tmp"; + +fn object_path(hash: &str) -> PathBuf { + loch_home() + .join("objects") + .join(&hash[..2]) + .join(&hash[2..]) +} + +fn write_object(hash: &str, data: &[u8]) -> Result<(), SnapshotError> { + let path = object_path(hash); + if path.exists() { + return Ok(()); + } + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(data).expect("writing to a Vec"); + let compressed = encoder.finish().expect("finishing into a Vec"); + write_atomically(&path, &compressed).map_err(|e| io(e, &path)) +} + +pub fn read_object(hash: &str) -> Result, SnapshotError> { + let path = object_path(hash); + let compressed = fs::read(&path).map_err(|e| io(e, &path))?; + let mut out = Vec::new(); + flate2::read::ZlibDecoder::new(&compressed[..]) + .read_to_end(&mut out) + .map_err(|e| io(e, &path))?; + Ok(out) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + pub path: String, + pub hash: String, + pub size: u64, +} + +fn manifest_bytes(entries: &[Entry]) -> Vec { + let mut out = String::new(); + for entry in entries { + out.push_str(&format!("{}\t{}\t{}\n", entry.hash, entry.size, entry.path)); + } + out.into_bytes() +} + +/// A snapshot's files, sorted by path. +pub fn read_snapshot(id: &str) -> Result, SnapshotError> { + let text = String::from_utf8(read_object(id)?) + .map_err(|_| SnapshotError(format!("snapshot {} is not UTF-8", id)))?; + let mut entries = Vec::new(); + for line in text.lines() { + let mut parts = line.splitn(3, '\t'); + let (Some(hash), Some(size), Some(path)) = (parts.next(), parts.next(), parts.next()) + else { + return Err(SnapshotError(format!("snapshot {} is malformed", id))); + }; + entries.push(Entry { + path: path.into(), + hash: hash.into(), + size: size.parse().unwrap_or(0), + }); + } + Ok(entries) +} + +/// Per-workspace state: the stat cache and the id of its latest snapshot. +fn state_dir(root: &str) -> PathBuf { + loch_home() + .join("workspaces") + .join(&content_hash(root.as_bytes())[..16]) +} + +struct Cached { + size: u64, + mtime: i128, + hash: String, +} + +fn load_cache(root: &str) -> (HashMap, i128) { + let Ok(text) = fs::read_to_string(state_dir(root).join("index")) else { + return (HashMap::new(), 0); + }; + let mut lines = text.lines(); + let taken: i128 = lines.next().and_then(|l| l.parse().ok()).unwrap_or(0); + let mut cache = HashMap::new(); + for line in lines { + let mut parts = line.splitn(4, '\t'); + if let (Some(size), Some(mtime), Some(hash), Some(path)) = + (parts.next(), parts.next(), parts.next(), parts.next()) + { + if let (Ok(size), Ok(mtime)) = (size.parse(), mtime.parse()) { + cache.insert( + path.to_string(), + Cached { + size, + mtime, + hash: hash.into(), + }, + ); + } + } + } + (cache, taken) +} + +fn save_cache(root: &str, taken: i128, cache: &[(String, Cached)]) -> Result<(), SnapshotError> { + let dir = state_dir(root); + let mut text = format!("{}\n", taken); + for (path, cached) in cache { + text.push_str(&format!( + "{}\t{}\t{}\t{}\n", + cached.size, cached.mtime, cached.hash, path + )); + } + let path = dir.join("index"); + write_atomically(&path, text.as_bytes()).map_err(|e| io(e, &path)) +} + +/// The latest snapshot taken of `root`, by any session. +pub fn latest(root: &str) -> Option { + fs::read_to_string(state_dir(root).join("latest")) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +fn mtime_nanos(meta: &fs::Metadata) -> i128 { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + meta.mtime() as i128 * 1_000_000_000 + meta.mtime_nsec() as i128 + } + #[cfg(not(unix))] + { + meta.modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_nanos() as i128) + .unwrap_or(0) + } +} + +fn now_nanos() -> i128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos() as i128) + .unwrap_or(0) +} + +/// Every regular file under `root` that the user's ignore rules let through, +/// as relative paths with `/` separators. `.git` itself is never a file of +/// the workspace; dotfiles otherwise are (`.github`, `.env.example`). +/// Stops after `limit` files, so an enormous directory costs a bounded walk. +pub fn visible_files(root: &str, limit: usize) -> Vec<(String, PathBuf)> { + let mut files = Vec::new(); + let walker = ignore::WalkBuilder::new(root) + .hidden(false) + .git_ignore(true) + .git_global(true) + .git_exclude(true) + // Honour .gitignore whether or not this is a git repository. + .require_git(false) + .follow_links(false) + .filter_entry(|entry| entry.file_name() != ".git") + .build(); + for entry in walker.flatten() { + if !entry.file_type().is_some_and(|t| t.is_file()) { + continue; + } + let Ok(relative) = entry.path().strip_prefix(root) else { + continue; + }; + let relative = relative + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/"); + files.push((relative, entry.path().to_path_buf())); + if files.len() >= limit { + break; + } + } + files.sort_by(|a, b| a.0.cmp(&b.0)); + files +} + +/// More files than this and it isn't a project: a session started in a +/// directory full of unrelated things. Snapshotting it would cost minutes on +/// every turn, so attribution is declined instead. +pub const MAX_FILES: usize = 100_000; + +/// Whether a root is one loch will snapshot at all. Sessions run from `/` and +/// from the home directory are real — one machine had 486 in `/` — and walking +/// either is a walk of everything. +pub fn snapshottable(root: &str) -> bool { + let home = sys::realpath_strict(&home_dir()).unwrap_or_else(home_dir); + root != "/" && root != home && !root.is_empty() +} + +/// Snapshots `root` and returns the snapshot's id. +pub fn snapshot(root: &str) -> Result { + if !snapshottable(root) { + return Err(SnapshotError(format!( + "{} is not a project to snapshot", + root + ))); + } + let files = visible_files(root, MAX_FILES + 1); + if files.len() > MAX_FILES { + return Err(SnapshotError(format!( + "{} holds more than {} files", + root, MAX_FILES + ))); + } + let (cache, cache_taken) = load_cache(root); + let taken = now_nanos(); + let mut entries = Vec::new(); + let mut fresh: Vec<(String, Cached)> = Vec::new(); + for (relative, path) in files { + let Ok(meta) = fs::metadata(&path) else { + continue; + }; + let size = meta.len(); + let mtime = mtime_nanos(&meta); + let trusted = cache + .get(&relative) + .filter(|c| c.size == size && c.mtime == mtime && mtime + RACY_NANOS < cache_taken); + let hash = match trusted { + Some(cached) => cached.hash.clone(), + None => { + let Ok(data) = fs::read(&path) else { + continue; + }; + let hash = content_hash(&data); + write_object(&hash, &data)?; + hash + } + }; + entries.push(Entry { + path: relative.clone(), + hash: hash.clone(), + size, + }); + fresh.push((relative, Cached { size, mtime, hash })); + } + let manifest = manifest_bytes(&entries); + let id = content_hash(&manifest); + write_object(&id, &manifest)?; + save_cache(root, taken, &fresh)?; + let latest = state_dir(root).join("latest"); + write_atomically(&latest, id.as_bytes()).map_err(|e| io(e, &latest))?; + count_snapshot(); + Ok(id) +} + +// -- collection ------------------------------------------------------------------- + +/// Snapshots taken since the last collection, so the hooks can collect the +/// way `git gc --auto` does: a cheap check on every run, real work rarely. +fn counter_path() -> PathBuf { + loch_home().join("snapshots-since-collect") +} + +fn count_snapshot() { + let path = counter_path(); + let count: u64 = fs::read_to_string(&path) + .ok() + .and_then(|t| t.trim().parse().ok()) + .unwrap_or(0); + let _ = write_atomically(&path, (count + 1).to_string().as_bytes()); +} + +/// How many snapshots between automatic collections. +pub const COLLECT_EVERY: u64 = 50; + +pub fn collection_due() -> bool { + fs::read_to_string(counter_path()) + .ok() + .and_then(|t| t.trim().parse::().ok()) + .is_some_and(|count| count >= COLLECT_EVERY) +} + +/// Anything written this recently is kept whether or not a root reaches it: +/// another session's hook may have just snapshotted and not yet recorded the +/// id anywhere a collection can see. +pub const GRACE: std::time::Duration = std::time::Duration::from_secs(3600); + +/// The snapshot of every workspace's latest state: the baseline for each +/// workspace's next turn, and so always a root. +pub fn workspace_roots() -> Vec { + let Ok(entries) = fs::read_dir(loch_home().join("workspaces")) else { + return Vec::new(); + }; + entries + .flatten() + .filter_map(|entry| fs::read_to_string(entry.path().join("latest")).ok()) + .map(|id| id.trim().to_string()) + .filter(|id| !id.is_empty()) + .collect() +} + +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Collected { + pub kept: usize, + pub removed: usize, + pub bytes: u64, +} + +fn is_old(path: &Path, now: std::time::SystemTime) -> bool { + fs::metadata(path) + .and_then(|m| m.modified()) + .ok() + .and_then(|modified| now.duration_since(modified).ok()) + .is_some_and(|age| age > GRACE) +} + +/// Mark and sweep: every object `roots` reach — a snapshot's manifest and +/// the contents it lists — is kept; every other object older than `GRACE` is +/// deleted, as are aside files a killed write left behind. Blame never reads +/// a snapshot (the edit records hold hashes), so nothing else needs one. +pub fn collect(roots: &[String]) -> Result { + let mut reachable: std::collections::HashSet = std::collections::HashSet::new(); + for root in roots { + // A root that is already gone, or unreadable, protects nothing. + let Ok(entries) = read_snapshot(root) else { + continue; + }; + reachable.insert(root.clone()); + reachable.extend(entries.into_iter().map(|e| e.hash)); + } + let now = std::time::SystemTime::now(); + let mut collected = Collected::default(); + let objects = loch_home().join("objects"); + let Ok(prefixes) = fs::read_dir(&objects) else { + let _ = write_atomically(&counter_path(), b"0"); + return Ok(collected); + }; + for prefix in prefixes.flatten() { + let Ok(files) = fs::read_dir(prefix.path()) else { + continue; + }; + let head = prefix.file_name().to_string_lossy().into_owned(); + for file in files.flatten() { + let name = file.file_name().to_string_lossy().into_owned(); + let path = file.path(); + let aside = name.starts_with('.') && name.contains(TMP_MARK); + let kept = !aside && reachable.contains(&format!("{}{}", head, name)); + if kept || !is_old(&path, now) { + collected.kept += 1; + continue; + } + let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0); + if fs::remove_file(&path).is_ok() { + collected.removed += 1; + collected.bytes += size; + } + } + let _ = fs::remove_dir(prefix.path()); + } + let _ = write_atomically(&counter_path(), b"0"); + Ok(collected) +} diff --git a/src/store.rs b/src/store.rs new file mode 100644 index 0000000..ff73c75 --- /dev/null +++ b/src/store.rs @@ -0,0 +1,188 @@ +//! The store interface: 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::Path; + +/// 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)] +pub enum StoreError { + /// 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), +} + +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: String, +} + +impl FileStore { + 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.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); + } + } +} + +pub fn default_store() -> String { + sys::join(&sys::join(&home_dir(), ".loch"), "store") +} + +pub fn resolve_store_uri(explicit: Option<&str>) -> String { + if let Some(uri) = explicit { + return uri.to_string(); + } + std::env::var("LOCH_STORE").unwrap_or_else(|_| default_store()) +} + +#[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(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); + 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)))); + } + if uri.starts_with('/') { + return Ok(Box::new(FileStore::new(uri))); + } + Ok(Box::new(FileStore::new(sys::abspath(uri)))) +} + +/// `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(""); + crate::index::unquote(path) +} + +#[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"); + } +} diff --git a/src/sys.rs b/src/sys.rs new file mode 100644 index 0000000..59dfb62 --- /dev/null +++ b/src/sys.rs @@ -0,0 +1,481 @@ +//! 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) +} + +/// `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 { + #[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/src/trace.rs b/src/trace.rs new file mode 100644 index 0000000..a0e46ba --- /dev/null +++ b/src/trace.rs @@ -0,0 +1,561 @@ +//! From a turn back to its conversation: installing the hooks that record +//! turns, finding a session's transcript wherever it survives, describing a +//! turn for blame, and forking the conversation for `ask`. +//! +//! What a turn changed is recorded by the hooks (`hook.rs`) and matched by +//! content (`attribution.rs`); nothing here reads or writes git history. + +use crate::attribution::{EditRecord, TurnRecord}; +use crate::claude::{self, 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 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(), + } + } +} + +/// Git's stdout whatever its exit status; empty if git can't run. +pub fn git_unchecked(cwd: &str, args: &[&str]) -> String { + gitio::git_unchecked(cwd, args).unwrap_or_default() +} + +/// `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)) => json::float_repr(*f), + Some(Value::Str(s)) => s.clone(), + Some(other) => json::dumps(other, json::DEFAULT), + } +} + +// -- install ------------------------------------------------------------------ + +/// A turn's two moments, which is all attribution needs, and the session's +/// end, which closes a turn a cancel left open. +const HOOK_EVENTS: &[(&str, &str)] = &[ + ("UserPromptSubmit", "prompt"), + ("Stop", "stop"), + ("SessionEnd", "end"), +]; + +/// What earlier versions of `install` wrote around every Bash call, for the +/// git-notes design. Removed on install, so they stop costing a process each. +const RETIRED: &[&str] = &["pre-tool", "post-tool"]; + +#[derive(Debug)] +pub enum InstallError { + Internal(String), +} + +pub struct Installed { + pub added: Vec, + pub removed: Vec, +} + +fn hook_line(command: &str, name: &str) -> String { + // A checkout whose machine lacks loch gets a silent no-op rather than an + // error on every turn, since the settings file is committed. + format!("{} hook {} 2>/dev/null || true", command, name) +} + +fn is_retired(line: &str) -> bool { + RETIRED + .iter() + .any(|name| line.ends_with(&format!(" hook {} 2>/dev/null || true", name))) +} + +/// Adds loch's hooks to a Claude Code settings file, keeping whatever else is +/// there, and takes out the ones it no longer uses. Re-running changes +/// nothing. +pub fn install_hooks( + settings_path: &str, + command: &str, +) -> std::result::Result { + 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 removed = Vec::new(); + for (event, groups) in hooks.iter_mut() { + let Value::Array(groups) = groups else { + continue; + }; + for group in groups.iter_mut() { + if let Some(Value::Array(entries)) = + group.as_object_mut().and_then(|g| g.get_mut("hooks")) + { + let before = entries.len(); + entries.retain(|entry| { + !entry + .get("command") + .and_then(Value::as_str) + .is_some_and(is_retired) + }); + if entries.len() < before { + removed.push(event.clone()); + } + } + } + // A group the retired line was alone in would be an empty husk. + groups.retain(|group| { + group + .get("hooks") + .and_then(Value::as_array) + .is_none_or(|entries| !entries.is_empty()) + }); + } + hooks.retain(|_, groups| groups.as_array().is_none_or(|g| !g.is_empty())); + + let mut added = Vec::new(); + for (event, name) in HOOK_EVENTS { + let line = hook_line(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; + } + groups.push(Value::Object(object! { + "hooks" => vec![Value::Object(object! {"type" => "command", "command" => line.as_str()})], + })); + 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)))?; + removed.dedup(); + Ok(Installed { added, removed }) +} + +// -- transcripts ---------------------------------------------------------------- + +/// A line is skipped when blank but parsed unstripped — unlike +/// `claude::records`, 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) +} + +// -- describing a turn ------------------------------------------------------------- + +/// A turn blame pointed at, with what can be said about its conversation. +#[derive(Clone)] +pub struct Link { + pub session_id: String, + pub agent: String, + pub index: usize, + pub ended: String, + pub prompt_uuid: Option, + pub end_uuid: Option, + pub transcript: Option, + /// The loch-format id of the turn holding the prompt, and of the root of + /// its conversation, when the transcript could be ingested. + pub turn: Option, + pub conversation: Option, + pub title: Option, + pub prompt: Option, + pub backfilled: bool, +} + +impl Link { + pub fn payload(&self) -> Map { + object! { + "session" => self.session_id.as_str(), + "agent" => self.agent.as_str(), + "index" => self.index, + "ended" => self.ended.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()), + "backfilled" => self.backfilled, + } + } +} + +/// Describes turns, ingesting each session's transcript once however many +/// lines point into it. +pub struct Resolver<'a> { + store: Option<&'a dyn Store>, + sessions: HashMap, Vec, Map)>, +} + +impl<'a> Resolver<'a> { + pub fn new(store: Option<&'a dyn Store>) -> Self { + Resolver { + 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(), + }; + if let Ok(derived) = ingest::ingest(path, &origin, None) { + turns = derived.turns; + header = derived.header; + } + } + } + self.sessions + .insert(session_id.into(), (path, turns, header)); + } + Ok(&self.sessions[session_id]) + } + + pub fn describe( + &mut self, + record: &EditRecord, + index: usize, + ) -> std::result::Result { + let turn: &TurnRecord = &record.turns[index]; + let (path, turns, header) = self.session(&record.session)?; + // The loch turn whose source record is the prompt that began this + // turn — or that a resubmitted identical prompt folded into. + let holds = |candidate: &&Turn, uuid: &str| { + candidate.facts.get("uuid").is_some_and(|u| u.is_str(uuid)) + || candidate + .facts + .get("alsoUuids") + .and_then(Value::as_array) + .is_some_and(|also| also.iter().any(|u| u.is_str(uuid))) + }; + let found = turn + .prompt_uuid + .as_deref() + .and_then(|uuid| turns.iter().find(|candidate| holds(candidate, uuid))); + let by_id: HashMap<&str, &Turn> = turns.iter().map(|t| (t.id.as_str(), t)).collect(); + let mut conversation = None; + let mut walker = found; + while let Some(current) = walker { + 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(Link { + session_id: record.session.clone(), + agent: record.agent.clone(), + index, + ended: turn.ended.clone(), + prompt_uuid: turn.prompt_uuid.clone(), + end_uuid: turn.end_uuid.clone(), + transcript: path.clone(), + turn: found.map(|t| t.id.clone()), + conversation, + title: title_of("title").or_else(|| title_of("aiTitle")), + prompt: turn.prompt.clone(), + backfilled: turn.backfilled, + }) + } +} + +// -- 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 `cut` it holds the conversation to its end — the last record +/// written, which after a rewind is the branch the session was left on. With +/// one, it ends at that record: the last of the turn being asked about. +pub fn fork_session( + transcript: &str, + target_cwd: &str, + cut: Option<&str>, + title: Option<&str>, +) -> 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(); + if records.is_empty() { + return Err(ForkError::Trace(TraceError::new( + "turn-not-found", + "the transcript holds no records", + ))); + } + let leaf = match cut { + None => records.len() - 1, + Some(cut) => match records.iter().rposition(|r| uuid(r) == cut) { + Some(leaf) => leaf, + None => { + return Err(ForkError::Trace(TraceError::new( + "turn-not-found", + format!("the transcript has no record {}", cut), + ))) + } + }, + }; + write_fork(transcript, &raw, &records, leaf, target_cwd, title) +} + +#[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, + }) +} diff --git a/src/usage.txt b/src/usage.txt new file mode 100644 index 0000000..27f2c88 --- /dev/null +++ b/src/usage.txt @@ -0,0 +1,48 @@ +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-turn] [--no-launch] + [--store ] + loch backfill [--cwd ] [--store ] + attribute turns from before the hooks + loch gc delete snapshots nothing needs (the hooks + also do this every 50 snapshots) + loch hook prompt | stop | end (run by the agent's harness) + 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 that snapshot the workspace when a prompt is +submitted, when the agent stops and when the session ends, and record which lines each turn added — +however it added them — in the store, along with the session's transcript. +Nothing is written to git, so squashes and rebases don't lose anything. +`blame` shows which turn wrote each line, `log` every turn that changed a file +or line range; `ask` forks that conversation and resumes it in Claude Code — +from its end, or with --at-turn from the end of the turn that wrote the line. diff --git a/test/test_bundle.py b/test/test_bundle.py deleted file mode 100644 index 8fb9b8c..0000000 --- a/test/test_bundle.py +++ /dev/null @@ -1,73 +0,0 @@ -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) diff --git a/test/test_claude.py b/test/test_claude.py deleted file mode 100644 index a71bd54..0000000 --- a/test/test_claude.py +++ /dev/null @@ -1,264 +0,0 @@ -import json -import os -from pathlib import Path - -import pytest - -from loch.claude import ( - SUMMARY_LIMIT, - encode_cwd, - encode_path, - list_sessions, - 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)) == [] diff --git a/test/test_cli.py b/test/test_cli.py deleted file mode 100644 index 932f149..0000000 --- a/test/test_cli.py +++ /dev/null @@ -1,1131 +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") 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_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("