diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml new file mode 100644 index 0000000..8349101 --- /dev/null +++ b/.forgejo/workflows/ci.yml @@ -0,0 +1,70 @@ +name: ci + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: -D warnings + +jobs: + verify: + runs-on: rust + steps: + - uses: actions/checkout@v4 + + # The runner image carries a toolchain, but the repository's pinned one is + # what the tests must run against. + - name: Toolchain + run: | + if ! command -v rustup >/dev/null 2>&1; then + echo "rustup is absent from the runner image" >&2 + exit 1 + fi + rustup show + rustc --version + + # The pipeline reproduces committed artifacts byte for byte, so the tests + # read the real corpus in the checkout. Nothing here calls a model or + # reaches the network. + - name: Format + run: cargo fmt --check + + - name: Lint + run: cargo clippy --locked --all-targets -- -D warnings + + - name: Test + run: cargo test --locked + + - name: Workbench + run: | + if command -v node >/dev/null 2>&1; then + node --test tests/workbench.test.cjs + else + echo "node is absent from the runner image; workbench tests skipped" >&2 + fi + + - name: Whitespace + run: git diff --check + + # The binary must build and run where no interpreter is installed. This is the + # claim the project makes, so it is a gate rather than an assertion. + binary: + runs-on: rust + steps: + - uses: actions/checkout@v4 + - name: Build + run: cargo build --locked --release -p tranche-cli + - name: The command tree opens + run: ./target/release/tranche --help + - name: A root without reports is refused, not crashed + run: | + set +e + ./target/release/tranche --root "$(mktemp -d)" cluster >/dev/null 2>err.txt + status=$? + set -e + test "$status" -ne 0 + ! grep -qi 'panic' err.txt diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml new file mode 100644 index 0000000..e8ab89f --- /dev/null +++ b/.forgejo/workflows/release.yml @@ -0,0 +1,144 @@ +name: release + +on: + push: + tags: ["v*"] + workflow_dispatch: + inputs: + tag: + description: "Existing v-prefixed tag to publish (backfill)" + required: true + +env: + RELEASE_TAG: ${{ inputs.tag || github.ref_name }} + BIN: tranche + TARGET: x86_64-unknown-linux-gnu + +jobs: + verify: + runs-on: rust + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.ref_name }} + - run: rustup show + - run: cargo fmt --check + - run: cargo clippy --locked --all-targets -- -D warnings + - run: cargo test --locked + + build: + needs: verify + runs-on: rust + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.ref_name }} + - name: Build + run: cargo build --locked --release --target "$TARGET" -p tranche-cli + - name: Exercise it before shipping it + run: | + "./target/$TARGET/release/$BIN" --help + version="${RELEASE_TAG#v}" + reported=$("./target/$TARGET/release/$BIN" --version | awk '{print $NF}') + test "$reported" = "$version" || { + echo "the binary reports $reported but the tag is $version" >&2 + exit 1 + } + - name: Package + run: | + name="$BIN-$RELEASE_TAG-$TARGET" + mkdir -p "dist/$name" + cp "target/$TARGET/release/$BIN" "dist/$name/" + cp README.md LICENSE "dist/$name/" + tar -C dist -czf "dist/$name.tar.gz" "$name" + (cd dist && sha256sum "$name.tar.gz" > "$name.tar.gz.sha256") + ls -l dist + - uses: https://data.forgejo.org/forgejo/upload-artifact@v4 + with: + name: dist + path: dist/* + if-no-files-found: error + + publish: + needs: build + runs-on: rust + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.ref_name }} + + - uses: https://data.forgejo.org/forgejo/download-artifact@v4 + with: + name: dist + path: dist + + # The notes are the tagged version's own CHANGELOG section: the generator + # owns CHANGELOG.md, so the release can never drift from it. + - name: Extract the tagged CHANGELOG section + run: | + version="${RELEASE_TAG#v}" + body=$(awk -v ver="$version" ' + $0 ~ ("^## \\[" ver "\\][ (]") {found=1; next} + found && /^## \[/ {exit} + found {print} + ' CHANGELOG.md) + if [ -z "$(printf '%s' "$body" | tr -d '[:space:]')" ]; then + echo "No CHANGELOG section for ${version} — cut the release with commit-and-tag-version first." >&2 + exit 1 + fi + printf '%s\n' "$body" > release-notes.md + + # Forgejo publishes with a token, not the `gh` client. The tag already + # exists locally, so the release is created against it by name. + - name: Create the Forgejo release + env: + TOKEN: ${{ secrets.FORGEJO_TOKEN }} + SERVER: ${{ github.server_url }} + REPOSITORY: ${{ github.repository }} + run: | + # Escape the notes into a JSON string with awk rather than pulling in + # an encoder: a release job should need nothing but the toolchain. + notes=$(awk '{gsub(/\\/,"\\\\"); gsub(/"/,"\\\""); printf "%s\\n", $0}' release-notes.md) + payload=$(printf '{"tag_name":"%s","name":"%s","body":"%s","draft":false}' \ + "$RELEASE_TAG" "$RELEASE_TAG" "$notes") + exists=$(curl -s -o /dev/null -w '%{http_code}' \ + -H "Authorization: token $TOKEN" \ + "$SERVER/api/v1/repos/$REPOSITORY/releases/tags/$RELEASE_TAG") + if [ "$exists" = "200" ]; then + curl -fsS -X PATCH -H "Authorization: token $TOKEN" \ + -H 'Content-Type: application/json' -d "$payload" \ + "$SERVER/api/v1/repos/$REPOSITORY/releases/tags/$RELEASE_TAG" > /dev/null + else + curl -fsS -X POST -H "Authorization: token $TOKEN" \ + -H 'Content-Type: application/json' -d "$payload" \ + "$SERVER/api/v1/repos/$REPOSITORY/releases" > /dev/null + fi + + - name: Attach the archive and its checksum + env: + TOKEN: ${{ secrets.FORGEJO_TOKEN }} + SERVER: ${{ github.server_url }} + REPOSITORY: ${{ github.repository }} + run: | + for asset in dist/*.tar.gz dist/*.sha256; do + curl -fsS -X POST -H "Authorization: token $TOKEN" \ + -F "attachment=@$asset" \ + "$SERVER/api/v1/repos/$REPOSITORY/releases/tags/$RELEASE_TAG/assets?name=$(basename "$asset")" \ + > /dev/null + echo "attached $(basename "$asset")" + done + + - name: Prove the release is complete + env: + TOKEN: ${{ secrets.FORGEJO_TOKEN }} + SERVER: ${{ github.server_url }} + REPOSITORY: ${{ github.repository }} + run: | + curl -fsS -H "Authorization: token $TOKEN" \ + "$SERVER/api/v1/repos/$REPOSITORY/releases/tags/$RELEASE_TAG" \ + | grep -o '"name":"[^"]*"\|"size":[0-9]*' + count=$(curl -fsS -H "Authorization: token $TOKEN" \ + "$SERVER/api/v1/repos/$REPOSITORY/releases/tags/$RELEASE_TAG" \ + | grep -c '"browser_download_url"') + echo "assets: $count" + test "$count" -ge 2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..11baa68 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,72 @@ +name: ci + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: -D warnings + +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + # The pipeline reproduces committed artifacts byte for byte, so the tests + # read the real corpus in the checkout. Nothing here calls a model or + # reaches the network. + - name: Toolchain + run: | + rustup toolchain install stable --profile minimal --component rustfmt,clippy + rustup default stable + rustc --version && cargo --version + + - uses: Swatinem/rust-cache@v2 + + - name: Format + run: cargo fmt --check + + - name: Lint + run: cargo clippy --locked --all-targets -- -D warnings + + - name: Test + run: cargo test --locked + + # The workbench is a static frontend over the published report; its tests + # need no toolchain beyond Node. + - name: Workbench + run: node --test tests/workbench.test.cjs + + - name: Whitespace + run: git diff --check + + # The binary must build and run where no interpreter is installed. This is the + # claim the project makes, so it is a gate rather than an assertion. + binary: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Toolchain + run: | + rustup toolchain install stable --profile minimal + rustup default stable + - uses: Swatinem/rust-cache@v2 + - name: Build + run: cargo build --locked --release -p tranche-cli + - name: The command tree opens + run: ./target/release/tranche --help + - name: A root without reports is refused, not crashed + run: | + set +e + ./target/release/tranche --root "$(mktemp -d)" cluster >/dev/null 2>err.txt + status=$? + set -e + test "$status" -ne 0 + ! grep -qi 'panic' err.txt diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3976340..1ccb69e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,17 +14,83 @@ permissions: env: RELEASE_TAG: ${{ inputs.tag || github.ref_name }} + BIN: tranche + TARGET: x86_64-unknown-linux-gnu jobs: - release: + # A tag can be pushed to a commit that never ran CI. The release is the last + # chance to refuse, so the gate runs here too rather than only on master. + verify: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: ref: ${{ inputs.tag || github.ref_name }} + - name: Toolchain + run: | + rustup toolchain install stable --profile minimal --component rustfmt,clippy + rustup default stable + - uses: Swatinem/rust-cache@v2 + - run: cargo fmt --check + - run: cargo clippy --locked --all-targets -- -D warnings + - run: cargo test --locked + + # The binary is the product, so the release carries it rather than the tag + # alone. Built and exercised before it is attached. + build: + needs: verify + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.ref_name }} + - name: Toolchain + run: | + rustup toolchain install stable --profile minimal + rustup default stable + rustup target add "$TARGET" + - uses: Swatinem/rust-cache@v2 + - name: Build + run: cargo build --locked --release --target "$TARGET" -p tranche-cli + - name: Exercise it before shipping it + run: | + "./target/$TARGET/release/$BIN" --help + version="${RELEASE_TAG#v}" + reported=$("./target/$TARGET/release/$BIN" --version | awk '{print $NF}') + test "$reported" = "$version" || { + echo "::error::the binary reports $reported but the tag is $version" >&2 + exit 1 + } + - name: Package + run: | + name="$BIN-$RELEASE_TAG-$TARGET" + mkdir -p "dist/$name" + cp "target/$TARGET/release/$BIN" "dist/$name/" + cp README.md LICENSE "dist/$name/" + tar -C dist -czf "dist/$name.tar.gz" "$name" + (cd dist && sha256sum "$name.tar.gz" > "$name.tar.gz.sha256") + ls -l dist + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/* + if-no-files-found: error - # The release notes are the tagged tag's own CHANGELOG section: the - # generator owns CHANGELOG.md, so this can never drift from it. + publish: + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.ref_name }} + + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist + + # The notes are the tagged version's own CHANGELOG section: the generator + # owns CHANGELOG.md, so the release can never drift from it. - name: Extract the tagged CHANGELOG section run: | version="${RELEASE_TAG#v}" @@ -39,8 +105,9 @@ jobs: fi printf '%s\n' "$body" > release-notes.md - # The tag already exists on the push event, so create is passed no - # target: it publishes the tag exactly as pushed. + # The tag already exists on the push event, so create is passed no target: + # it publishes the tag exactly as pushed. A rerun overwrites the attached + # assets rather than failing on them. - name: Create or update the GitHub release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -48,7 +115,26 @@ jobs: if gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then gh release edit "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ --title "$RELEASE_TAG" --notes-file release-notes.md + gh release upload "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ + --clobber dist/*.tar.gz dist/*.sha256 else gh release create "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ - --title "$RELEASE_TAG" --notes-file release-notes.md + --title "$RELEASE_TAG" --notes-file release-notes.md \ + dist/*.tar.gz dist/*.sha256 fi + + # Read back what was published instead of trusting the upload. + - name: Prove the release is complete + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ + --json tagName,isDraft,assets \ + --jq '"tag=\(.tagName) draft=\(.isDraft) assets=\(.assets|length)", + (.assets[] | " \(.name) \(.size) bytes")' + count=$(gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ + --json assets --jq '.assets|length') + test "$count" -ge 2 || { + echo "::error::expected the archive and its checksum, found $count assets" >&2 + exit 1 + } diff --git a/.gitignore b/.gitignore index 520645d..a8c7d28 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,6 @@ skills-lock.json # runtime data; fixtures and deliberately published output are a different # category and are tracked on purpose. out/evidence/ + +# Rust build artifacts; the lockfile is tracked for reproducible CLI builds. +/target/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..75b40ea --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,66 @@ +# Working rules for this repository + +These are the conventions every change here follows. They are short on purpose: +each one exists because breaking it caused a real defect, and the reason is stated +so a later reader can tell whether the rule still applies. + +## 1. No source file reaches 300 lines + +Split by responsibility into sibling modules. A module that needs three concepts is +three modules. This applies to every crate's `src/`, not to tests. + +The limit is not cosmetic. A file that has grown past it has almost always taken on +a second job, and the two jobs then have to be read together to understand either. + +## 2. `mod.rs` and `lib.rs` hold no code + +They declare modules and re-export names, and that is all. No functions, no +structs, no `impl` blocks, no `const` definitions, no helper types — not even a +small one. + +A module root is a table of contents. Code placed there is code nobody looks for: +it is invisible to a reader scanning for where a behaviour lives, and it accretes +because the file always looks empty. Behaviour belongs in a named sibling module; +`mod.rs` points at it. + +``` +src/ + evidence/ + mod.rs declarations and re-exports only + vocabulary.rs the constants + errors.rs the error types + coverage.rs the behaviour +``` + +## 3. Tests live only in `tests/` + +Never a `#[cfg(test)]` module inside a source file. Integration tests under +`tests/` are named for the outcome they protect rather than the module they +exercise: a test named after a module drifts into restating the implementation, +while one named after an outcome fails when the behaviour breaks. + +## 4. `gh` stays a subprocess + +The GitHub credential stays inside `gh`. Do not reimplement GitHub auth, and do not +read the token in this process or place it in an argv. + +## 5. The on-disk format is the contract + +Everything committed under `out/` and `docs/` is an interface every reader depends +on. A change to the pipeline is judged by whether it reproduces those bytes, not by +whether it looks correct. Four properties look like accidents and are not: + +- **Insertion order, not sorted.** Category order and `tranches.md` sections follow + first appearance. The digests cannot catch a mistake here, because they sort keys + explicitly. +- **Floats keep the shortest round-tripping form.** `0.6` stays `0.6`. +- **Stored JSON separators carry a space.** A compact serializer restyles every + artifact. +- **The workbench payload is flattened to ASCII** and escapes `&`, `<` and `>` — it + is fetched and injected, and a PR title is untrusted text from GitHub. + +## 6. Never fabricate a result + +A claim about live state comes from a fresh read of that state. A test assertion is +backed by a real run. When a step cannot be completed, name the blocker precisely +rather than producing output that looks like success. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a44fca4 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1652 @@ +# 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 = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[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 = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +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 = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[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 = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[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", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[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 = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[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 = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tranche-cli" +version = "0.8.2" +dependencies = [ + "clap", + "serde", + "serde_json", + "tempfile", + "time", + "tokio", + "tranche-core", +] + +[[package]] +name = "tranche-core" +version = "0.8.2" +dependencies = [ + "libc", + "regex", + "reqwest", + "serde", + "serde_json", + "sha2", + "tempfile", + "time", + "tokio", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[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.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[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.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed" +dependencies = [ + "rustls-pki-types", +] + +[[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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[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.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c3b72f0 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,19 @@ +[workspace] +resolver = "2" +members = ["crates/tranche-core", "crates/tranche-cli"] + +[workspace.package] +version = "0.8.2" +edition = "2024" +authors = ["Vittorio Distefano "] +repository = "https://github.com/blackopsrepl/Tranche" +license = "MIT" + +[workspace.dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tempfile = "3" + +[profile.release] +lto = true +codegen-units = 1 diff --git a/Makefile b/Makefile index f692179..8365aca 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ # Tranche Makefile -# Jev-powered triage pipeline with colorized output +# Jev-powered triage pipeline, native Rust # ============== Colors & Symbols ============== GREEN := \033[92m @@ -22,20 +22,15 @@ SCALE := ⚖️ # ============== Project Metadata ============== REPO := blackopsrepl/Tranche LIVE_URL := https://vdistefano.studio/Tranche/ -# One interpreter for every target. `PYTHON` (env or command line) wins; -# otherwise hostpython.py resolves it. -PYTHON_CMD ?= python3 -ifeq ($(strip $(PYTHON)),) -PYTHON := $(shell $(PYTHON_CMD) hostpython.py 2>/dev/null) -endif -ifeq ($(strip $(PYTHON)),) -$(error No usable Python interpreter: '$(PYTHON_CMD) hostpython.py' failed) -endif JUDGED := $(shell test -f out/judgments.jsonl && wc -l < out/judgments.jsonl || echo 0) PAIRED := $(shell test -f out/pair_verdicts.jsonl && wc -l < out/pair_verdicts.jsonl || echo 0) +# The pipeline is the native binary. `tranche` resolves from PATH; +# `make cli-install` builds and installs it from this checkout. Override with +# TRANCHE=./target/debug/tranche to run an uninstalled build. +TRANCHE ?= tranche # ============== Phony Targets ============== -.PHONY: banner help fetch refresh judge judge-full dupes cluster page gif all evidence evidence-show publish verify info clean-judgments test check mcp-check print-interpreter release-check release-dry-run release +.PHONY: banner help fetch refresh judge judge-full dupes cluster batches page all evidence evidence-show publish verify info clean-judgments test check cli-install release-check release-dry-run release # ============== Default Target ============== .DEFAULT_GOAL := help @@ -55,7 +50,7 @@ fetch: banner @printf "$(CYAN)$(BOLD)╔══════════════════════════════════════╗$(RESET)\n" @printf "$(CYAN)$(BOLD)║ Fetching Open PRs ║$(RESET)\n" @printf "$(CYAN)$(BOLD)╚══════════════════════════════════════╝$(RESET)\n\n" - @$(PYTHON) tranche.py fetch --transport gh + @$(TRANCHE) fetch --transport gh # ============== Jev Pipeline ============== @@ -64,7 +59,7 @@ judge: banner @printf "$(CYAN)$(BOLD)║ Jev Judgment Pass ║$(RESET)\n" @printf "$(CYAN)$(BOLD)╚══════════════════════════════════════╝$(RESET)\n\n" @printf "$(ARROW) $(BOLD)Judging PRs (7 typed questions, one batched call each)...$(RESET)\n" - @$(PYTHON) tranche.py judge --resume && \ + @$(TRANCHE) judge --resume && \ printf "$(GREEN)$(CHECK) Judgments saved to out/judgments.jsonl$(RESET)\n\n" || \ (printf "$(RED)$(CROSS) Judge pass failed$(RESET)\n\n" && exit 1) @@ -72,39 +67,38 @@ judge-full: banner @printf "$(RED)$(BOLD)WARNING: fresh pass over all PRs — ~5M input tokens on Jev$(RESET)\n" @printf "$(YELLOW)Press Ctrl+C to abort, or Enter to continue...$(RESET)\n" @read dummy - @$(PYTHON) tranche.py judge + @$(TRANCHE) judge dupes: banner @printf "$(ARROW) $(BOLD)Comparing candidate pairs with Jev sameness judgments...$(RESET)\n" - @$(PYTHON) tranche.py dupes && \ + @$(TRANCHE) dupes && \ printf "$(GREEN)$(CHECK) Pair verdicts in out/pair_verdicts.jsonl$(RESET)\n\n" || \ (printf "$(RED)$(CROSS) Dupe pass failed$(RESET)\n\n" && exit 1) cluster: banner @printf "$(ARROW) $(BOLD)Clustering tranches, dupes, escalation lists...$(RESET)\n" - @$(PYTHON) tranche.py cluster + @$(TRANCHE) cluster + +# Issue #4/#8: cumulative pre-release batches and the park record. +batches: banner + @printf "$(ARROW) $(BOLD)Classifying review candidates into cumulative batches...$(RESET)\n" + @$(TRANCHE) batches # ============== Output ============== page: banner @printf "$(ARROW) $(BOLD)Rendering GitHub Pages report from out/ data...$(RESET)\n" - @$(PYTHON) gen_page.py && \ + @$(TRANCHE) page && \ printf "$(GREEN)$(CHECK) docs/index.html written$(RESET)\n\n" || \ (printf "$(RED)$(CROSS) Page generation failed$(RESET)\n\n" && exit 1) -gif: banner - @printf "$(ARROW) $(BOLD)Rendering title GIF with glyphfx (capture → rasterize)...$(RESET)\n" - @$(PYTHON) tools/make_title_gif.py && \ - printf "$(GREEN)$(CHECK) docs/assets/tranche.gif written$(RESET)\n\n" || \ - (printf "$(RED)$(CROSS) GIF generation failed$(RESET)\n\n" && exit 1) - # ============== Composite Targets ============== refresh: banner @printf "$(CYAN)$(BOLD)╔══════════════════════════════════════╗$(RESET)\n" @printf "$(CYAN)$(BOLD)║ Incremental Refresh (all) ║$(RESET)\n" @printf "$(CYAN)$(BOLD)╚══════════════════════════════════════╝$(RESET)\n\n" - @$(PYTHON) tranche.py refresh --max-pairs $(if $(MAX_PAIRS),$(MAX_PAIRS),400) + @$(TRANCHE) refresh --max-pairs $(if $(MAX_PAIRS),$(MAX_PAIRS),400) # Issue #9: capture the public evidence of one native batch, locally and ignored. evidence: banner @@ -112,10 +106,10 @@ evidence: banner @printf "$(CYAN)$(BOLD)║ Evidence capture (batch) ║$(RESET)\n" @printf "$(CYAN)$(BOLD)╚══════════════════════════════════════╝$(RESET)\n\n" @test -n "$(BATCH)" || (printf "$(RED)Usage: make evidence BATCH=B001 [BUDGET=200]$(RESET)\n" && exit 2) - @$(PYTHON) tranche.py evidence capture --batch $(BATCH) --request-budget $(if $(BUDGET),$(BUDGET),200) + @$(TRANCHE) evidence capture --batch $(BATCH) --request-budget $(if $(BUDGET),$(BUDGET),200) evidence-show: banner - @$(PYTHON) tranche.py evidence show --batch $(BATCH) + @$(TRANCHE) evidence show --batch $(BATCH) all: @$(MAKE) fetch @@ -148,8 +142,7 @@ verify: banner (printf "$(RED)$(CROSS) Live check failed (HTTP $$code)$(RESET)\n\n" && exit 1) info: banner - @$(PYTHON) -c "import json; s=json.load(open('out/summary.json')); [print(f' $(CYAN){k:>22}$(RESET) {v}') for k,v in s.items()]" - @printf "\n" + @$(TRANCHE) info # ============== Danger Zone ============== @@ -161,23 +154,16 @@ clean-judgments: banner printf "$(GREEN)$(CHECK) Judgment cache cleared$(RESET)\n\n" test: - @$(PYTHON) -m unittest discover -s tests -v + @cargo test --locked check: test + @cargo fmt --check + @cargo clippy --locked --all-targets -- -D warnings @if command -v node >/dev/null 2>&1; then node --test tests/workbench.test.cjs; else printf 'Node unavailable; optional frontend tests skipped.\n'; fi - @ruff check . - @$(PYTHON) -m compileall -q tranche.py gen_page.py hostpython.py mcp_server.py report_loader.py ghread.py evidence.py tests tools @git diff --check -# Real-client subprocess check against the current local corpus, separate from -# the offline gates. MCP_PYTHON supplies the MCP client SDK; the server imports -# nothing, so it defaults to the same interpreter. -MCP_PYTHON ?= $(PYTHON) -mcp-check: - @TRANCHE_MCP_INTEGRATION=1 $(MCP_PYTHON) -m unittest tests.test_mcp_stdio -v - -print-interpreter: - @printf '%s\n' '$(PYTHON)' +cli-install: + @cargo install --path . --locked release-check: check @node --check .versionrc.js @@ -198,11 +184,12 @@ help: banner @/bin/echo -e " $(GREEN)make judge$(RESET) - Jev pass over unjudged PRs (resume-safe)" @/bin/echo -e " $(GREEN)make dupes$(RESET) - Compare candidate pairs with Jev" @/bin/echo -e " $(GREEN)make cluster$(RESET) - Build tranches, dupe groups, escalation lists" + @/bin/echo -e " $(GREEN)make batches$(RESET) - Build cumulative pre-release batches and the park record" @/bin/echo -e " $(GREEN)make refresh$(RESET) - $(BOLD)Deterministic incremental refresh of everything$(RESET)" + @/bin/echo -e " $(GRAY)Every stage runs the native frontend: tranche fetch|judge|dupes|cluster|batches|refresh|page$(RESET)" @/bin/echo -e "" @/bin/echo -e "$(CYAN)$(BOLD)Output:$(RESET)" @/bin/echo -e " $(GREEN)make page$(RESET) - Render docs/index.html from out/ data" - @/bin/echo -e " $(GREEN)make gif$(RESET) - Re-render the glyphfx title GIF" @/bin/echo -e "" @/bin/echo -e "$(CYAN)$(BOLD)Composite:$(RESET)" @/bin/echo -e " $(GREEN)make all$(RESET) - $(YELLOW)$(BOLD)fetch → judge → dupes → cluster → page$(RESET)" @@ -213,8 +200,13 @@ help: banner @/bin/echo -e " $(GREEN)make evidence BATCH=B001$(RESET) - Capture one batch's public evidence (read-only)" @/bin/echo -e " $(GREEN)make evidence-show BATCH=B001$(RESET) - Inspect the current batch's coverage" @/bin/echo -e "" + @/bin/echo -e "$(CYAN)$(BOLD)Rust toolchain:$(RESET)" + @/bin/echo -e " $(GREEN)make cli-install$(RESET) - Build and install the tranche binary from this checkout" + @/bin/echo -e " $(GRAY)Override the binary with TRANCHE=./target/debug/tranche$(RESET)" + @/bin/echo -e "" @/bin/echo -e "$(CYAN)$(BOLD)Release:$(RESET)" - @/bin/echo -e " $(GREEN)make check$(RESET) - Offline tests, Ruff, syntax and whitespace" + @/bin/echo -e " $(GREEN)make test$(RESET) - Cargo tests over the workspace" + @/bin/echo -e " $(GREEN)make check$(RESET) - Tests plus format, clippy and whitespace" @/bin/echo -e " $(GREEN)make release-dry-run$(RESET) - Preview version/changelog on clean master" @/bin/echo -e " $(GREEN)make release$(RESET) - Gate, bump VERSION, generate changelog, commit + tag" @/bin/echo -e "" diff --git a/README.md b/README.md index 43aaf2c..5618a4c 100644 --- a/README.md +++ b/README.md @@ -22,320 +22,198 @@ boundary from the follow-up reply: *"I'm not delegating the user experience."* Taste-level PRs get their own `user-experience` lane that the pipeline prepares but never pre-judges. -## What Tranche actually does +## What Tranche does -- **Fetches** the open PRs of `omacom/omarchy` into a local snapshot (via `gh`, already authenticated). +- **Fetches** the open PRs of `omacom/omarchy` into a local snapshot, through + `gh`, so the credential never touches a command line. - **Judges** each PR with one batched Jev call: what area it touches, how risky - it is, whether it's a fix, how finished it looks, how much review effort it + it is, whether it is a fix, how finished it looks, how much review effort it needs, whether it smells security-relevant, and whether it admits to duplicating something. -- **Finds likely duplicate groups** by comparing candidate pairs (title/body - similarity plus cross-references between PRs). -- **Batches** confirmed groups into merge units of up to five PRs, security - batches first — each batch ships a ready-to-paste reviewer prompt. -- **Publishes** everything: a browsable HTML workbench and a read-only MCP - server that AI agents can question directly. +- **Finds likely duplicate groups** by comparing candidate pairs — title and + body similarity plus literal cross-references between PRs. +- **Batches** those groups into merge units of up to five PRs, security first. + Each batch carries a ready-to-paste reviewer prompt. +- **Publishes** everything: `out/` for machines and agents, and a browsable HTML + workbench for people. It is a discovery and prioritization pass. It never merges, never closes, and its "duplicates" are model suggestions, not verified facts. Maintainers decide what happens to a PR — always. -## Quick start +## Install -You need Python 3.10+ and the [`gh` CLI](https://cli.github.com) signed in. -A Jev API key is only needed for the model stages (`judge`, `dupes`); -fetching, clustering, rendering and tests run offline. +You need a Rust toolchain, and the [`gh` CLI](https://cli.github.com) signed in +for the fetch stage. A Jev API key is needed only for `judge` and `dupes`. ```bash git clone https://github.com/blackopsrepl/Tranche && cd Tranche - -# one-time: give the model stages a key -echo "apikey_..." > ~/Documents/jevapi.txt # or: export TYPESAFE_API_KEY=... - -python3 tranche.py refresh # the whole pipeline, incremental +cargo install --path . --locked ``` -That single command runs `fetch → judge → dupes → cluster → batches → page` -in a fixed order and reuses everything its caches can still support. The -first run judges the whole backlog (thousands of model calls); every run -after that pays only for what actually changed. Open `docs/index.html` when -it finishes — or just browse the live report linked above. - -Check what a refresh *would* do before spending anything: +The binary is self-contained: no interpreter, no daemon, no database, no service +to start. It reads a checkout containing the captured corpus and the reports +derived from it. Run it from that checkout, or point at one from anywhere: ```bash -python3 tranche.py refresh --dry-run +tranche --root /path/to/Tranche cluster ``` -## Everyday commands +`--root` defaults to the current directory. `--help` at any level shows the +flags that exist. + +## Quick start ```bash -python3 tranche.py refresh # normal day: whole pipeline, incremental, deterministic -python3 tranche.py fetch # re-capture open-PR membership (authenticated via gh) -python3 tranche.py judge --resume # model pass; resume reuses matching judgments only -python3 tranche.py dupes # re-run the candidate-pair comparisons -python3 tranche.py cluster # rebuild out/{clusters.json,dupes.json,tranches.md,summary.json} -python3 tranche.py batches # rebuild out/batches.json and parked.json -python3 gen_page.py # render docs/index.html + workbench payload +# Give the model stages a key. Either source works; the env var wins. +echo "apikey_..." > ~/Documents/jevapi.txt +export TYPESAFE_API_KEY=apikey_... + +tranche fetch # capture open-PR membership (needs gh) +tranche judge --resume # one batched model call per unjudged PR +tranche dupes # compare candidate pairs +tranche cluster # build clusters, dupes, tranches.md, summary +tranche batches # pack batches, write the park record +tranche page # render the workbench ``` -Cost intuition: a refresh with nothing new spends **zero** model calls. A full -corpus re-judge is ~2,800 calls (~5M input tokens) and only happens when the -question policy or the model changes — which is rare and deliberate. A dupe -pass over all candidate pairs is a few hundred thousand tokens. The dry-run -tells you which situation you are in before you commit to it. +`tranche refresh` runs those stages in that fixed order and reuses whatever its +caches still support. `tranche refresh --dry-run` reports what it would do +without spending a model call. -## The MCP server +Every stage is safe to re-run. `cluster` and `batches` are pure functions of the +stored corpus — they call no model and touch no network. -Tranche can serve your local reports to AI agents over the -[Model Context Protocol](https://modelcontextprotocol.io) — the same data the -workbench shows, plus the per-batch reviewer prompts. The server is a single -self-contained Python file. No SDK, no package install, no daemon, no -database: your client launches it, it answers over stdio, done. +## Checking a report before you trust it -### Starting it +The report is bound: it records a digest of the inputs it was built from, and the +gate refuses a report whose binding no longer matches. Ask what you are looking +at rather than assuming: ```bash -python3 mcp_server.py --root /absolute/path/to/Tranche +tranche info # the counts and digests of the current report +tranche info --json # the same, for a script +tranche cluster --json # rebuild and print the summary as JSON ``` -The `--root` must be a Tranche checkout that already has reports — run -`refresh` at least once. Every MCP client config expresses the same two -fields (command + args) under its own names; the generic shape is: - -```json -{ - "mcpServers": { - "tranche": { - "command": "python3", - "args": ["/absolute/path/to/Tranche/mcp_server.py", "--root", "/absolute/path/to/Tranche"] - } - } -} -``` +`summary.json` carries `report_binding` and the digests of every output. If a +reader and a writer disagree about `report_binding`, they are looking at +different observations. -The server speaks standard JSON-RPC 2.0 over newline-delimited stdio -(`initialize`, `tools/list`, `tools/call`, `ping`), negotiating protocol -versions 2024-11-05 through 2025-11-25. Any conforming MCP client can drive -it; no client is named or required. Tools advertise JSON Schema input schemas -and standard `readOnlyHint` annotations. Invalid arguments and stale reports -come back as tool errors with `isError: true` — so an agent can read the -message and correct itself — and unknown tools get protocol error -32602. - -### The six tools - -| Tool | Answers the question | -| --- | --- | -| `surface()` | "What's in the corpus right now?" Coverage, category counts, queue sizes, batch inventory, parked state, activity counts, available filters. | -| `query(...)` | "Which PRs match this?" Filter by text, category, risk band, security, exact finished-form score, batch or queue; security-first ordering, paginated. | -| `pick(batch_id)` | "What exactly is batch B042?" Members with source bindings and the exact reviewer prompt the workbench would copy. | -| `next_prompt(after)` | "What's the next batch to review?" Walks batches in report order; stateless — no reservations, nothing is marked done. | -| `related(number)` | "What is this PR related to?" Model relationship evidence with explicit uncertain/contradictory diagnostics. | -| `digests()` | "Am I looking at the right report?" Report binding and SHA-256 digests of every input and output read. | - -Every result carries the repository, provenance digests and a disclaimer: -model suggestions from titles and shortened descriptions — never merge -approval, never verified duplication. Unknown values stay `null`, never zero. - -### Updating and maintaining it - -The server has **no state of its own**. It reads the report files under -`--root` on every call and revalidates their binding digests each time, so -"updating" means updating the reports, not the server process: - -1. **New data:** run `python3 tranche.py refresh` (or the individual stages). - The next `surface()` call reflects it. No server restart needed for data. -2. **New code:** `git pull`. This is the one case where you *must* restart the - server process — a long-running process keeps its old code in memory and - will refuse the new reports with a staleness error. Kill it; the client - respawns a fresh one on its next call. -3. **New categories or tools:** clients cache the tool list per session, so - reconnect the client (or start a new session) after a schema-changing - update even if the server itself is fresh. - -Health checks, cheapest first: call `digests()` and compare -`report_binding` against `out/summary.json`; discover the tools with -`hermes mcp test tranche` (on Hermes) or your client's equivalent; or run the -full integration check against a disposable copy of the corpus: +## Everyday commands ```bash -make mcp-check MCP_PYTHON=/path/to/python-with-mcp-sdk +tranche fetch [--transport gh|urllib|curl] # re-capture open-PR membership +tranche judge [--resume] [--limit N] # model pass; resume reuses matches +tranche dupes [--max-pairs N] # candidate-pair comparisons +tranche cluster [--allow-unbound] # offline; no model, no network +tranche batches # offline; packs batches from the report +tranche info # read the current report's numbers +tranche page # render docs/index.html +tranche refresh [--max-pairs N] [--no-page] [--dry-run] +tranche all # judge --resume, dupes, cluster, batches ``` -When something goes wrong: - -| Symptom | What it means | Fix | -| --- | --- | --- | -| every tool says "Reports are stale, unbound, foreign or modified; rerun cluster" | the report files and the code that validates them disagree | restart the server process; if the reports really are old, run `refresh` | -| a new category or tool is missing in your client | the client cached its session's tool list | reconnect the client / start a new session | -| `pick` / `next_prompt` fail, other tools work | no batch file in this report root | `python3 tranche.py batches` | -| refusal naming an argument or enum value | the call didn't match the advertised schema | fix the arguments; the message lists what is accepted | -| everything fails on a copied directory | the copy is missing snapshot, caches or matching `out/` reports | serve a complete report root, or run the pipeline there | - -Hard limits, by design: results paginate at 25 items (max 100), query text -caps at 512 characters, input files at 128 MiB (256 MiB total, 512 paths), -responses at 1 MiB. `--allow-unbound` inspection reports are refused outright. - -## FAQ - -**Does Tranche merge or close anything?** -No. The pipeline and the MCP server are read-only toward GitHub. Nothing -claims, reserves or approves work. - -**What does "duplicate" mean here?** -A Jev judgment that two PRs propose the same underlying change, with the -model-consistency checks described below. It is a merge-review lead, not a -verified duplicate — always compare sources before closing anything, and note -that PR age never selects a survivor. - -**Why is a risk score wrong?** -Because it judges `title + body + diffstat` only. It never reads patches, -test results or CI. Treat scores as sorting hints for human review, and treat -`unknown` (null) as unknown — the pipeline never fakes a zero. - -**What does a refresh cost?** -Nothing when nothing changed. Rough numbers for this backlog: full re-judge -~2,800 calls / ~5M input tokens (only after a question-policy or model -change), a full dupe pass a few hundred thousand tokens. `refresh --dry-run` -reports the situation without spending anything. - -**Why did all judgments suddenly invalidate?** -The question policy or the model changed, so every cached answer no longer -answers *today's question*. That invalidation is the point — it is how a new -category like `user-experience` becomes real instead of cosmetic. The next -`refresh` re-judges the corpus once; expect a full-corpus pass, and run the -dupe stage with a raised `--max-pairs` (e.g. `refresh --max-pairs 900`) so -the pair comparisons aren't cut off mid-pass. - -**The MCP server says "reports are stale" right after I pulled new code.** -A running server process holds its old code in memory. Restart it (see the -maintenance table above); your client will relaunch it automatically. - -**Do I need a Jev key to try this?** -Not for `fetch`, `cluster`, `page`, the MCP server, or the tests. Only -`judge` and `dupes` call the model. - -**Where do the reviewer prompts come from?** -Each batch carries one, stored in `out/batches.json` and byte-identical to -the workbench's Copy button. It is review *instruction* for an agent, not -executable authorization. - -**Can several agents share one server?** -Each client launches its own server process; the processes are stateless and -read-only, so they can't get in each other's way. The shared state is the -report directory itself. - -**How do I cut a release?** -See [Versioned releases](#versioned-releases) — one command plus a push, and -the GitHub release publishes itself. +Cost intuition: a refresh with nothing new spends **zero** model calls. A full +corpus re-judge is ~2,800 calls (~5M input tokens) and only happens when the +question policy or the model changes, which is rare and deliberate. A dupe pass +over all candidate pairs is a few hundred thousand tokens. The dry-run tells you +which situation you are in before you commit to it. ## What Jev is asked (one batched call per PR) -| Question | Type | Meaning | -|---------------|--------|-----------------------------------------------------| -| `category` | Choice | install-setup / desktop-config / user-experience / shell-cli / apps-integrations / hardware-drivers / update-release / agents-ai / docs / fix-misc / unclear | -| `risk` | Score | 0 text-only → 4 could break existing installs | -| `is_fix` | Noul | P(bug fix, not feature/taste change) | -| `dupe_signal` | Noul | P(title/body admits duplication or supersedence) | -| `finished_form` | Score | 0 no description → 3 what+why+QA evidence | -| `review_effort` | Score | 0 trivial → 3 substantial | -| `security_flag` | Noul | P(touches secrets/sudo/remote-code/network exposure) | +| Question | Type | Meaning | +|---|---|---| +| `category` | Choice | install-setup / desktop-config / user-experience / shell-cli / apps-integrations / hardware-drivers / update-release / agents-ai / docs / fix-misc / unclear | +| `risk` | Score | 0 text-only → 4 could break existing installs | +| `is_fix` | Noul | P(bug fix, not feature/taste change) | +| `dupe_signal` | Noul | P(title/body admits duplication or supersedence) | +| `finished_form` | Score | 0 no description → 3 what+why+QA evidence | +| `review_effort` | Score | 0 trivial → 3 substantial | +| `security_flag` | Noul | P(touches secrets/sudo/remote-code/network exposure) | + +A **Noul** is a probability; a **Score** is an integer band. A question the model +answers unusably becomes `null` and is listed in `normalization_errors` — it is +never coerced to zero, because an unknown and a measured low are different facts. ## How the evidence binds Judgments bind the fields they were based on — title, body, head SHA, labels, -draft state, diffstat, timestamps, the exact question set and the model — not -the whole GitHub response envelope, whose repository-wide counters change on +draft state, diffstat, timestamps, the exact question set and the model — not the +whole GitHub response envelope, whose repository-wide counters change on unrelated events. A re-fetch that changed nothing reuses everything; a changed -description re-asks. The same discipline applies to pair verdicts. Resume -reuses only matching records, and matching-but-malformed responses are -reported as unknowns, never silently dropped. A floating alias like -`jev-latest` can drift under its fixed name; pin a concrete model or re-run -`judge` when that matters. - -`fetch` commits exact observed membership atomically — a failed capture -leaves the previous snapshot untouched — and runs through `gh api` so the -credential never touches a command line. Unauthenticated GitHub allows 60 -requests/hour and one capture costs ~29. Pagination is not a point-in-time -snapshot: a captured PR may have changed by the time you read it. +description re-asks. The same discipline applies to pair verdicts. + +`fetch` commits exact observed membership atomically: a failed capture leaves the +previous snapshot untouched. Pagination is not a point-in-time snapshot, so a +captured PR may have changed by the time you read it. Published historical judgments have no bindings and cannot be retrofitted; -`judge --resume` re-evaluates them at API cost. `--limit N` (judge) and -`--max-pairs N` (dupes) bound work per pass. For offline inspection only, +`judge --resume` re-evaluates them at API cost. `--limit` (judge) and +`--max-pairs` (dupes) bound work per pass. For offline inspection only, `cluster --allow-unbound` includes legacy judgments with warnings; they never enter review candidates or batches. ## Outputs -- `out/tranches.md` — review candidates, relationship diagnostics, risk/security - escalation leads, author follow-up leads, and the batch plan. -- `out/clusters.json` — judgments grouped by category × risk band - (`low`, `core`, `danger`, `unknown`), with source digests and URLs. -- `out/dupes.json` — `confirmed_groups` (model-consistent candidates, **not - verified duplicates**), `review_groups` and `uncertain_pairs`. -- `out/batches.json` — merge batches bound to the `dupes.json` digest; - `out/parked.json` — PRs held out of batches (drafts, unfinished forms, - unjudged/stale, same-change holds) with their unblock paths. -- `out/summary.json` — counts, token usage, report binding and output digests. -- `docs/index.html` + `docs/data/workbench.json` — the rendered workbench. +Everything lands in `out/`, and all of it is tracked in this repository: + +| File | What it is | +|---|---| +| `tranches.md` | The human report: review candidates, relationship diagnostics, escalation and follow-up leads, the batch plan. | +| `clusters.json` | Judgments grouped by category × risk band (`low`, `core`, `danger`, `unknown`), with source digests and URLs. | +| `dupes.json` | `confirmed_groups` (model-consistent candidates, **not** verified duplicates), `review_groups`, `uncertain_pairs`. | +| `batches.json` | Merge batches bound to the `dupes.json` digest. | +| `parked.json` | PRs held out of batches, each with its named unblock path. | +| `summary.json` | Counts, token usage, report binding and output digests. | +| `docs/index.html`, `docs/data/workbench.json` | The rendered workbench. | Review-candidate thresholds: risk ≤ 1.5, finished_form ≥ 1.8, is_fix ≥ 0.6, -security_flag < 0.5, current judgment, not a draft, outside a candidate -group. A missing field can never qualify a PR. +security_flag < 0.5, current judgment, not a draft, outside a candidate group. A +missing field can never qualify a PR. ## Security meta-category (top priority) -Security is a cross-cutting classification over **all** PRs, not a category -slot: every PR whose `security_flag` reaches 0.5 joins a `security-review` -set that outranks every category — first section of `tranches.md`, first -queue of the workbench, top of the sidebar. Review these before any batch. -Membership never replaces a PR's own category, and an unknown probability is -never flagged. +Security is a cross-cutting classification over **all** PRs, not a category slot: +every PR whose `security_flag` reaches 0.5 joins a `security-review` set that +outranks every category — the first section of `tranches.md`, the first queue of +the workbench. Review these before any batch. Membership never replaces a PR's +own category, and an unknown probability is never flagged. ## Batches -A **batch is a Jev-determined group of PRs to merge into ONE pull request**: -exactly the model-consistent `same_change` groups, disjoint by construction. -Groups with contradictory or untested internal evidence and uncertain pairs -are excluded on purpose — being unbatched is the honest state for them, and -`out/parked.json` records why each held-out PR is there. Batches are ordered -security-first, then risk band, then activity: `updated_at` on this repo is -continuous bot churn, so the activity signal is the head SHA bound at -judgment time ("head revised" = the author pushed since). Batches are a -plan, never a verified-safe merge. +A **batch is a group of PRs to merge into ONE pull request**: exactly the +model-consistent `same_change` groups, disjoint by construction. Groups with +contradictory or untested internal evidence, and uncertain pairs, are excluded on +purpose — being unbatched is the honest state for them, and `parked.json` records +why each held-out PR is there. + +Batches are ordered security-first, then by risk band, then by activity. +`updated_at` on this repository is continuous bot churn, so the activity signal +is the head SHA bound at judgment time: a revised head means the author pushed +since. Batches are a plan, never a verified-safe merge. ## Development ```bash -make test # unit tests, synthetic inputs, no network, no credentials -make check # tests + lint + optional real-browser workbench probe -make mcp-check MCP_PYTHON=/path/to/venv-python # opt-in real-client MCP integration +make test # cargo tests over the workspace +make check # tests plus format, clippy and whitespace +make cli-install # build and install the binary from this checkout ``` -The [native evidence CLI](docs/EVIDENCE_PACKET.md) for issue #9 lets a user select -a batch, capture its public source material, inspect citations, resume a partial -capture and export a packet — all inside Tranche. The capture implementation, -native state and packet format are maintained in this repository and shipped as -Tranche, with the CLI, workbench and MCP reading the same evidence; users never -need another application, and external tools may consume exports. - -```bash -python3 tranche.py evidence capture --batch B001 --request-budget 100 -python3 tranche.py evidence show --batch B001 -python3 tranche.py evidence export --batch B001 --output review-packet.json -``` +Two conventions hold across the codebase: no source file reaches 300 lines, and +tests live only in `tests/`, named for the outcome they protect rather than the +module they exercise. [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) explains the +layout and what the on-disk formats guarantee. -Evidence is optional, read-only toward GitHub and model-free. Design: -[docs/decisions/native-evidence-cli.md](docs/decisions/native-evidence-cli.md); -implemented behaviour: [docs/EVIDENCE_CLI.md](docs/EVIDENCE_CLI.md). Publication -to the workbench and MCP retrieval are follow-up work on the same service. +CI runs the same gate on every push and pull request, on GitHub and on the local +Forgejo. A release carries the built binary, not just a tag. ## Versioned releases -One coherent iteration produces one release tag. `VERSION` and -`CHANGELOG.md` are owned by [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) -(`.versionrc.js`); never edit them by hand. Developer tooling: Node, -`commit-and-tag-version` and Ruff — no runtime Python dependencies. +One coherent iteration produces one release tag. `VERSION` and `CHANGELOG.md` are +owned by [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) +(`.versionrc.js`); never edit them by hand. ```bash git pull --ff-only origin master @@ -345,15 +223,88 @@ git push --follow-tags origin master ``` The pushed `v*` tag triggers the `release` workflow -(`.github/workflows/release.yml`), which publishes the GitHub release from -that tag's own `CHANGELOG.md` section — notes can never drift from the -changelog. A tag that predates the workflow (or any existing tag) can be -published retroactively through the same path: +(`.github/workflows/release.yml`), which re-runs the gate on the tagged commit, +builds the release binary for `x86_64-unknown-linux-gnu`, confirms the binary +reports the tagged version, packages it with a checksum, and publishes the +release from that tag's own `CHANGELOG.md` section — so notes can never drift +from the changelog. An existing tag can be published retroactively: ```bash gh workflow run release --ref master -f tag=v0.8.1 ``` -Verify afterwards with `gh release list` — the releases page, not the tag -list, is what people see. Releases version the code, not the freshness or -correctness of historical model judgments. +Verify with `gh release list` — the releases page, not the tag list, is what +people see. Releases version the code, not the freshness or correctness of +historical model judgments. + +## FAQ + +**Does Tranche merge or close anything?** +No. The pipeline is read-only toward GitHub. Nothing claims, reserves or approves +work. + +**What does "duplicate" mean here?** +A Jev judgment that two PRs propose the same underlying change, with the +model-consistency checks described above. It is a merge-review lead, not a +verified duplicate — always compare sources before closing anything, and note +that PR age never selects a survivor. + +**Why is a risk score wrong?** +Because it judges `title + body + diffstat` only. It never reads patches, test +results or CI. Treat scores as sorting hints for human review, and treat `unknown` +(null) as unknown — the pipeline never fakes a zero. + +**Do I need a Jev key to try this?** +Not for `fetch`, `cluster`, `batches`, `page`, `info` or the tests. Only `judge` +and `dupes` call the model. + +**Which commands run offline?** +`cluster`, `batches`, `info` and `page`. `fetch` needs `gh` and the network; +`judge` and `dupes` need the model. `refresh` and `all` run the whole set, so +they need both. + +**A command printed "this operation is not implemented yet". Why?** +Every command is wired except `evidence …`, whose capture, inspection and export +verbs still refuse. The commands that exist and the state of each are in +[docs/NATIVE_CLI.md](docs/NATIVE_CLI.md). + +**Can an agent query the reports?** +Yes, through the MCP server: `surface`, `query`, `pick`, `next_prompt`, `related` +and `digests` answer questions about the report over stdio, read-only. It is +being ported to a `tranche-mcp` binary; `mcp_server.py` is still in the tree as +the reference that port is verified against. The read projection the workbench +and the server share is the same port. + +**What does a refresh cost?** +Nothing when nothing changed. Rough numbers for this backlog: a full re-judge is +~2,800 calls and ~5M input tokens (only after a question-policy or model change); +a full dupe pass is a few hundred thousand tokens. `refresh --dry-run` reports +the situation without spending anything. + +**Why did all judgments suddenly invalidate?** +The question policy or the model changed, so every cached answer no longer +answers *today's question*. That invalidation is the point — it is how a new +category like `user-experience` becomes real instead of cosmetic. The next +refresh re-judges the corpus once; run the dupe stage with a raised `--max-pairs` +so pair comparisons are not cut off mid-pass. + +**Where do the reviewer prompts come from?** +Each batch carries one, stored in `out/batches.json` and byte-identical to the +workbench's Copy button. It is review *instruction* for an agent, not executable +authorization. + +**Can I trust the JSON for tooling?** +Yes, and more strongly than usual: the pipeline's tests rebuild the committed +`out/` files from the stored corpus and assert byte equality. If a change alters +those bytes, the test fails. Three format properties are load-bearing and +documented in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): objects keep +insertion order, floats keep the shortest round-tripping form, and JSON +separators carry a space. + +**How do I cut a release?** +See [Versioned releases](#versioned-releases) — one command plus a push, and the +release publishes itself with the binary attached. + +**Why is everything in `out/` committed?** +Because it is the interface. Agents, the workbench and any external tool read +those files, so their exact bytes are the contract the tests defend. diff --git a/WIREFRAME.md b/WIREFRAME.md index e4b0057..25076b6 100644 --- a/WIREFRAME.md +++ b/WIREFRAME.md @@ -11,7 +11,7 @@ disagree with each other: | Surface | File | Audience | | --- | --- | --- | | Workbench | `docs/index.html` + `docs/data/workbench.json` | a human triaging the backlog | -| Evidence CLI | `tranche.py evidence …` (`evidence.py`) | a reviewer, and the workbench/MCP later | +| CLI | `tranche` (Rust frontend over `tranche.py` / `evidence.py`) | an operator, and the workbench/MCP later | | MCP server | `mcp_server.py` | an AI agent asking bounded questions | ## 1. Workbench @@ -87,7 +87,7 @@ A capture is **not** a workbench view. Its output is a coverage report plus, on request, a byte window or a resolved citation. The shape: ``` -$ python3 tranche.py evidence capture --batch B001 --request-budget 100 +$ tranche evidence capture --batch B001 --request-budget 100 capture <32 hex> batch B001 generation … INCOMPLETE | COMPLETE observed stop request_budget|none requests 37/100 (failures 0, …) 281655 bytes stored, 40 citations @@ -99,7 +99,7 @@ capture <32 hex> batch B001 generation … INCOMPLETE | COMPLETE checks complete 4p 0c [check_runs=complete, statuses=complete, fork_check_runs=complete, fork_statuses=complete] … - resume: python3 tranche.py evidence capture --batch B001 --reuse-capture + resume: tranche evidence capture --batch B001 --reuse-capture ``` ### Required behaviour @@ -134,7 +134,7 @@ from. Tools today: `surface`, `query`, `pick`, `next_prompt`, `related`, - **Refuse stale, foreign, unbound or modified reports** before answering, using the same loader the CLI uses. - **Bounded schemas**: advertised `inputSchema` with enums, bounds and patterns; - arguments are validated against it, not by Python signature errors. + arguments are validated against it, not by an implementation's signature errors. - **Never serve historical stale cache rows** as current; the producer's projection is the only one published. - **Prompt picking stays stateless and read-only**. diff --git a/crates/tranche-cli/Cargo.lock b/crates/tranche-cli/Cargo.lock new file mode 100644 index 0000000..ea52d6b --- /dev/null +++ b/crates/tranche-cli/Cargo.lock @@ -0,0 +1,420 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[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 = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[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 = "pyo3" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "700d18fa267b73b9b521fd7e13580e2f446916f176cacee1ab63fcc8191f1655" +dependencies = [ + "libc", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", +] + +[[package]] +name = "pyo3-build-config" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b3fc0c4d08f6bb10e71fe39dfb9e2f59c6eb6854e22ec8092f50c69a4499adb" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfc0b8e19df29aad7086cf977bb0c2a2f143e30567eb113e9cf72b62ca698330" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6100e8a4b5eba53afaa5ed078364851a0b2499c553a44c31026b929049b49dc6" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6143877a16e82b5a727b7127ff4cd86858a24a28d745d72f43e6f227c7b1bdb3" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[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 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "tranche-cli" +version = "0.8.2" +dependencies = [ + "clap", + "pyo3", + "serde", + "serde_json", + "tempfile", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[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.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/tranche-cli/Cargo.toml b/crates/tranche-cli/Cargo.toml new file mode 100644 index 0000000..c5a2206 --- /dev/null +++ b/crates/tranche-cli/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "tranche-cli" +description = "Tranche command line: the review pipeline as a native binary" +version.workspace = true +edition.workspace = true +authors.workspace = true +repository.workspace = true +license.workspace = true + +[[bin]] +name = "tranche" +path = "src/main.rs" + +[dependencies] +clap = { version = "4.6.7", features = ["derive"] } +serde = { workspace = true } +serde_json = { workspace = true } +tranche-core = { path = "../tranche-core" } +time = { version = "0.3", features = ["formatting"] } +tokio = { version = "1", features = ["macros", "rt", "time"] } + +[dev-dependencies] +tempfile = { workspace = true } diff --git a/crates/tranche-cli/src/cli.rs b/crates/tranche-cli/src/cli.rs new file mode 100644 index 0000000..aead451 --- /dev/null +++ b/crates/tranche-cli/src/cli.rs @@ -0,0 +1,242 @@ +use clap::{Args, Parser, Subcommand, ValueEnum}; +use std::path::PathBuf; + +/// The Tranche command line. +/// +/// Acquisition and model calls only ever happen because a command asked for +/// them; there is no implicit work. +#[derive(Debug, Parser)] +#[command( + name = "tranche", + version, + about = "Tranche · PR review pipeline", + long_about = "Tranche · PR review pipeline\n\n\ + Reads a checkout containing the captured corpus and the derived \ + reports. `--root` selects it; the default is the current directory.", + subcommand_required = true, + arg_required_else_help = true, + propagate_version = true +)] +pub struct Cli { + /// Checkout holding the captured corpus and the derived reports. + #[arg(long, global = true, default_value = ".", value_name = "DIR")] + pub root: PathBuf, + + /// Emit machine-readable JSON instead of a formatted report. + #[arg(long, global = true)] + pub json: bool, + + #[command(subcommand)] + pub command: Command, +} + +#[derive(Debug, Subcommand)] +pub enum Command { + /// Refresh the observed open-PR membership from GitHub. + Fetch(Fetch), + /// Judge each PR with one batched model call. + Judge(Judge), + /// Compare candidate pairs for sameness. + Dupes(Dupes), + /// Build tranches, duplicate groups and escalation lists. + Cluster(Cluster), + /// Build cumulative pre-release batches and the park record. + Batches, + /// Print the numbers from the current report. + Info, + /// Run fetch, judge, dupes, cluster, batches and page in order. + Refresh(Refresh), + /// Judge, then dupes, cluster and batches. + All(All), + /// Render the workbench from the bound reports. + Page, + /// Capture, inspect and export public PR evidence. + #[command(subcommand_required = true, arg_required_else_help = true)] + Evidence { + #[command(subcommand)] + command: Evidence, + }, +} + +/// How GitHub is reached when membership is refreshed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum Transport { + /// The authenticated `gh` CLI. + Gh, + /// The standard library HTTP client. + Urllib, + /// The `curl` binary. + Curl, +} + +impl std::fmt::Display for Transport { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let name = match self { + Self::Gh => "gh", + Self::Urllib => "urllib", + Self::Curl => "curl", + }; + f.write_str(name) + } +} + +#[derive(Debug, Args)] +pub struct Fetch { + /// How to reach GitHub. + #[arg(long, value_enum, default_value_t = Transport::Gh)] + pub transport: Transport, +} + +#[derive(Debug, Args)] +pub struct Judge { + /// Judge only the N newest unjudged PRs. + #[arg(long, value_name = "N", value_parser = positive)] + pub limit: Option, + + /// Reuse judgments bound to unchanged input, questions and model. + #[arg(long)] + pub resume: bool, +} + +#[derive(Debug, Args)] +pub struct Dupes { + /// Cap the number of pair comparisons this pass. + #[arg(long, value_name = "N", default_value_t = 300)] + pub max_pairs: u64, +} + +#[derive(Debug, Args)] +pub struct Cluster { + /// Inspect legacy judgments with freshness warnings. + #[arg(long)] + pub allow_unbound: bool, +} + +#[derive(Debug, Args)] +pub struct Refresh { + /// Cap the number of pair comparisons this pass. + #[arg(long, value_name = "N", default_value_t = 400)] + pub max_pairs: u64, + + /// Skip rendering the workbench. + #[arg(long)] + pub no_page: bool, + + /// Report what would change without writing. + #[arg(long)] + pub dry_run: bool, +} + +#[derive(Debug, Args)] +pub struct All { + /// Judge only the N newest unjudged PRs. + #[arg(long, value_name = "N", value_parser = positive)] + pub limit: Option, + + /// Accepted for compatibility; `all` always resumes. + #[arg(long)] + pub resume: bool, + + /// Cap the number of pair comparisons this pass. + #[arg(long, value_name = "N", default_value_t = 300)] + pub max_pairs: u64, +} + +#[derive(Debug, Subcommand)] +pub enum Evidence { + /// Validate a batch and acquire or resume its public evidence. + Capture(Capture), + /// Inspect coverage, sources or citations offline. + Show(Show), + /// Write a self-contained packet after the public-sharing gate. + Export(Export), +} + +#[derive(Debug, Args)] +pub struct Capture { + /// Batch to capture, such as B001. + #[arg(long, value_name = "BATCH")] + pub batch: String, + + /// Requests this run may attempt; the last few are held back for the + /// completion checks. + #[arg(long, value_name = "N", default_value_t = 200)] + pub request_budget: u64, + + /// Bytes this capture may store. + #[arg(long, value_name = "N", default_value_t = 67_108_864)] + pub max_bytes: u64, + + /// Start a new capture generation even if one is stored. + #[arg(long)] + pub fresh: bool, + + /// Resume or extend one explicit capture. + #[arg(long, value_name = "ID")] + pub reuse_capture: Option, + + /// Replace a writer lock whose process is gone. + #[arg(long)] + pub break_lock: bool, +} + +#[derive(Debug, Args)] +pub struct Show { + /// Inspect the evidence associated with the current batch. + #[arg(long, value_name = "BATCH", conflicts_with = "capture")] + pub batch: Option, + + /// Inspect one capture historically, with no report consulted. + #[arg(long, value_name = "ID")] + pub capture: Option, + + /// Read a bounded window from one stored source. + #[arg(long, value_name = "ID", conflicts_with = "citation")] + pub source: Option, + + /// Resolve one citation against stored bytes. + #[arg(long, value_name = "ID")] + pub citation: Option, + + /// First byte of the window. + #[arg(long, value_name = "N", default_value_t = 0)] + pub start_byte: u64, + + /// Window length in bytes. + #[arg(long, value_name = "N", default_value_t = 16_384)] + pub length: u64, +} + +#[derive(Debug, Args)] +pub struct Export { + /// Export the evidence associated with the current batch. + #[arg(long, value_name = "BATCH", conflicts_with = "capture")] + pub batch: Option, + + /// Export one historical capture. + #[arg(long, value_name = "ID")] + pub capture: Option, + + /// Destination file, or `-` for stdout. + #[arg(long, value_name = "FILE")] + pub output: String, + + /// Confirm an export of a capture that is not the current one. + #[arg(long)] + pub allow_historical: bool, + + /// Requests the sharing gate may spend. + #[arg(long, value_name = "N", default_value_t = 8)] + pub request_budget: u64, + + /// Bytes the sharing gate may read. + #[arg(long, value_name = "N", default_value_t = 67_108_864)] + pub max_bytes: u64, +} + +fn positive(value: &str) -> Result { + match value.parse::() { + Ok(0) | Err(_) => Err("must be a positive integer".to_owned()), + Ok(number) => Ok(number), + } +} diff --git a/crates/tranche-cli/src/commands.rs b/crates/tranche-cli/src/commands.rs new file mode 100644 index 0000000..0694146 --- /dev/null +++ b/crates/tranche-cli/src/commands.rs @@ -0,0 +1,168 @@ +//! Command dispatch. +//! +//! Every operation resolves to one entry point. Dispatch itself decides nothing +//! about a report: it picks the handler and turns the result into an exit code. + +use tranche_core::report::Root; + +use crate::cli::{Cli, Command, Evidence}; +use crate::report_files::read_json; +use crate::reports::{batches as build_batches, cluster_report}; + +/// What the operator sees, and the status the process exits with. +/// +/// Exit codes are an interface — scripts branch on them — so each outcome is +/// constructed in one place rather than chosen ad hoc at the call site. +#[derive(Debug)] +pub struct Outcome { + pub code: i32, + pub stdout: String, + pub stderr: String, +} + +impl Outcome { + /// A completed operation. + pub fn success(stdout: String) -> Self { + Self { + code: 0, + stdout, + stderr: String::new(), + } + } + + /// A refusal: a message for the operator and the status that reports it. + pub fn refusal(message: impl Into, code: i32) -> Self { + Self { + code, + stdout: String::new(), + stderr: format!("{}\n", message.into()), + } + } +} + +pub fn run(cli: &Cli) -> Outcome { + let root = Root::new(&cli.root); + match &cli.command { + Command::Evidence { command } => evidence(&root, command, cli.json), + Command::Cluster(args) => cluster_report(&root, args.allow_unbound, cli.json), + Command::Batches => build_batches(&root, cli.json), + Command::Info => print_info(&root, cli.json), + Command::Fetch(args) => run_fetch(&root, args.transport), + Command::Judge(args) => run_judge(&root, args.resume, args.limit), + Command::Dupes(args) => run_dupes(&root, args.max_pairs), + Command::Refresh(args) => crate::refresh::refresh( + &root, + args.max_pairs, + args.no_page, + args.dry_run, + &mut |line: &str| println!("{line}"), + ), + Command::All(args) => run_all(&root, args.limit, args.max_pairs), + Command::Page => crate::workbench::page(&root, &mut |line: &str| println!("{line}")), + } +} + +/// Judge, then compare, then rebuild the report and the batches. +/// +/// The same steps `refresh` runs minus the fetch and the page, so it is the +/// command for a corpus that is already captured. +fn run_all(root: &Root, limit: Option, max_pairs: u64) -> Outcome { + let mut say = |line: &str| println!("{line}"); + if let Err(error) = crate::judgment::judge(root, true, limit, &mut say) { + return Outcome::refusal(format!("all stopped at judge: {error}"), 1); + } + if let Err(error) = crate::dupes::dupes(root, max_pairs, &mut say) { + return Outcome::refusal(format!("all stopped at dupes: {error}"), 1); + } + for (step, outcome) in [ + ( + "cluster", + crate::reports::cluster_report(root, false, false), + ), + ("batches", crate::reports::batches(root, false)), + ] { + if outcome.code != 0 { + return Outcome::refusal( + format!("all stopped at {step}: {}", outcome.stderr.trim()), + 1, + ); + } + } + Outcome::success(String::new()) +} + +/// Compare the outstanding candidate pairs. +fn run_dupes(root: &Root, max_pairs: u64) -> Outcome { + let mut progress = |line: &str| println!("{line}"); + match crate::dupes::dupes(root, max_pairs, &mut progress) { + Ok((written, errors)) => { + if errors > 0 { + return Outcome::refusal( + format!("{written} verdicts appended; {errors} failed; re-run to continue"), + 1, + ); + } + Outcome::success(String::new()) + } + Err(error) => Outcome::refusal(error, 1), + } +} + +/// Judge every unjudged PR, newest first. +fn run_judge(root: &Root, resume: bool, limit: Option) -> Outcome { + let mut progress = |line: &str| println!("{line}"); + match crate::judgment::judge(root, resume, limit, &mut progress) { + Ok((written, errors)) => { + if errors > 0 { + // A partial pass is not a failure, but the operator must see it, + // and re-running with `--resume` picks up where it stopped. + return Outcome::refusal( + format!("{written} judgments appended; {errors} failed; re-run with --resume"), + 1, + ); + } + Outcome::success(String::new()) + } + Err(error) => Outcome::refusal(error, 1), + } +} + +/// Refresh the observed open-PR membership. +fn run_fetch(root: &Root, transport: crate::cli::Transport) -> Outcome { + let transport = match transport { + crate::cli::Transport::Gh => tranche_core::gh::Transport::Gh, + crate::cli::Transport::Curl => tranche_core::gh::Transport::Curl, + crate::cli::Transport::Urllib => tranche_core::gh::Transport::Urllib, + }; + let mut progress = |line: &str| println!("{line}"); + match crate::pipeline::fetch(root, transport, &mut progress) { + Ok(_) => Outcome::success(String::new()), + Err(error) => Outcome::refusal(error, 1), + } +} + +/// Print the numbers from the current report. +/// +/// Read from the summary on disk rather than recomputed, so this reports what +/// was published. +fn print_info(root: &Root, json: bool) -> Outcome { + let summary = match read_json(&root.summary_path()) { + Ok(summary) => summary, + Err(error) => return Outcome::refusal(format!("summary.json: {error}"), 1), + }; + if json { + return Outcome::success(format!( + "{}\n", + tranche_core::util::indented_json(&summary).unwrap_or_default() + )); + } + let mut lines = String::new(); + for (key, value) in summary.as_object().into_iter().flatten() { + lines.push_str(&format!("{key:>22} {value}\n")); + } + Outcome::success(lines) +} + +fn evidence(root: &Root, verb: &Evidence, json: bool) -> Outcome { + crate::evidence::run(root, verb, json) +} diff --git a/crates/tranche-cli/src/dupes.rs b/crates/tranche-cli/src/dupes.rs new file mode 100644 index 0000000..36f11a4 --- /dev/null +++ b/crates/tranche-cli/src/dupes.rs @@ -0,0 +1,249 @@ +//! The duplicate pass: compare candidate pairs and append the verdicts. +//! +//! Candidate selection and the stored-verdict cache are both already decided by +//! `tranche-core`; this decides which of that work to do now, asks about it, and +//! appends what comes back. The log is append-only, so a re-run never rewrites an +//! earlier verdict. + +use std::io::Write; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use serde_json::Value; +use tranche_core::domain::dupe::{normalize_pair, pair_binding, reusable_pair}; +use tranche_core::domain::judge::usage as token_usage; +use tranche_core::domain::pr::{Pr, Prs, load_prs}; +use tranche_core::domain::questions::pair_questions; +use tranche_core::jev; +use tranche_core::report::{MODEL, REPOSITORY, Root}; + +use crate::pairing::{brief, outstanding, ref_index}; + +/// How many requests are in flight at once. +const WORKERS: usize = 6; + +/// Past this many unjudged PRs, say so before comparing. +const WARN_MISSING: usize = 100; + +/// One comparison to make. +struct Job { + a: u64, + b: u64, + similarity: f64, + state: Value, + binding: String, +} + +/// Compare the outstanding candidate pairs and append the verdicts. +/// +/// Returns how many were compared and how many failed. +pub fn dupes( + root: &Root, + max_pairs: u64, + report: &mut dyn FnMut(&str), +) -> Result<(usize, usize), String> { + let corpus: Prs = load_prs(root, REPOSITORY).map_err(|error| error.0)?; + let judgments = crate::pairing::judgments(root, &corpus)?; + + let missing = corpus.len().saturating_sub(judgments.len()); + if missing > WARN_MISSING { + report(&format!( + "warning: {missing} PRs not judged yet; the dupe pass runs on the judged subset" + )); + } + + let all = outstanding(root, &corpus, &judgments)?; + let selected: Vec<(f64, u64, u64)> = all.iter().take(max_pairs as usize).copied().collect(); + report(&format!( + "{} candidate pairs to compare ({} already current)", + all.len().min(max_pairs as usize), + cache_size(root, &corpus) + )); + if selected.is_empty() { + return Ok((0, 0)); + } + + let jobs: Vec = selected + .iter() + .filter_map(|(score, a, b)| { + // A candidate can go stale between selection and the call: a PR + // closed and was refetched out of the corpus. + let (left, right) = (corpus.get(*a)?, corpus.get(*b)?); + Some(job(left, right, *score)) + }) + .collect(); + + let questions = pair_questions(); + let outcomes = ask_all(&jobs, &questions); + + let mut errors = Vec::new(); + let mut written = 0usize; + let mut tokens = (0i64, 0i64); + let path = root.pairs_path(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .map_err(|error| format!("cannot create {}: {error}", parent.display()))?; + } + let mut stream = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .map_err(|error| format!("cannot open the verdict log: {error}"))?; + for (job, outcome) in jobs.iter().zip(outcomes) { + match outcome { + Ok(answer) => { + let record = normalize_pair(&record_for(job, &answer)); + let line = serde_json::to_string(&record) + .map_err(|error| format!("cannot encode a verdict: {error}"))?; + writeln!(stream, "{line}") + .map_err(|error| format!("cannot append to the verdict log: {error}"))?; + let (input, output) = token_usage(&record); + tokens.0 += input; + tokens.1 += output; + written += 1; + } + Err(error) => errors.push(format!("#{} ↔ #{}: {error}", job.a, job.b)), + } + } + stream + .flush() + .map_err(|error| format!("cannot flush the verdict log: {error}"))?; + + report("candidate pair comparison complete"); + report(&format!("tokens: in={} out={}", tokens.0, tokens.1)); + for error in errors.iter().take(10) { + report(error); + } + Ok((written, errors.len())) +} + +/// How many stored verdicts are still current, for the progress line. +fn cache_size(root: &Root, corpus: &Prs) -> usize { + tranche_core::domain::dupe::pair_cache(root, corpus, REPOSITORY, MODEL) + .map(|cache| { + cache + .values() + .filter(|record| { + reusable_pair(record) && record["freshness"].as_str() == Some("current") + }) + .count() + }) + .unwrap_or(0) +} + +/// One comparison, ready to ask. +fn job(left: &Pr, right: &Pr, similarity: f64) -> Job { + let (a, b) = (left.number, right.number); + Job { + a, + b, + similarity, + state: serde_json::json!({"pr_a": brief(left), "pr_b": brief(right)}), + binding: pair_binding(left, right, REPOSITORY, MODEL), + } +} + +/// The verdict a comparison is stored as. +/// +/// The field set is a compatibility surface: `normalize_pair` reads these and the +/// binding is the cache key. +fn record_for(job: &Job, answer: &Value) -> Value { + let sameness = answer + .get("answers") + .and_then(|answers| answers.get("sameness")) + .cloned() + .unwrap_or_else(|| serde_json::json!({})); + serde_json::json!({ + "a": job.a, + "b": job.b, + // Three places, as the pipeline has always rounded it. + "similarity": (job.similarity * 1000.0).round() / 1000.0, + "verdict": sameness.get("choice"), + "probabilities": sameness.get("probabilities"), + "usage": answer.get("usage").cloned().unwrap_or_else(|| serde_json::json!({})), + "binding": job.binding, + "requested_model": MODEL, + "resolved_model": answer.get("model"), + "request_id": answer.get("request_id"), + "judged_at": judged_at(), + "input": job.state, + }) +} + +/// Ask about every job, at most `WORKERS` at a time. +/// +/// Each job's outcome is kept, so one failure does not lose the others. A +/// rejected key stops the pass rather than spending it on requests that cannot +/// succeed. +fn ask_all(jobs: &[Job], questions: &Value) -> Vec> { + let outcomes: Mutex>>> = Mutex::new(vec![None; jobs.len()]); + let fatal: Mutex> = Mutex::new(None); + let next = AtomicUsize::new(0); + + std::thread::scope(|scope| { + for _ in 0..WORKERS.min(jobs.len()) { + scope.spawn(|| { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(error) => { + *fatal.lock().expect("lock") = Some(format!("no runtime: {error}")); + return; + } + }; + loop { + if fatal.lock().expect("lock").is_some() { + return; + } + let index = next.fetch_add(1, Ordering::SeqCst); + let Some(job) = jobs.get(index) else { return }; + let outcome = runtime + .block_on(jev::ask(&job.state, questions, MODEL)) + .map_err(|error| error.to_string()); + if let Err(message) = &outcome + && message.contains("401") + { + *fatal.lock().expect("lock") = Some(message.clone()); + } + outcomes.lock().expect("lock")[index] = Some(outcome); + } + }); + } + }); + + if let Some(message) = fatal.lock().expect("lock").take() { + return jobs + .iter() + .enumerate() + .map( + |(index, _)| match outcomes.lock().expect("lock")[index].take() { + Some(outcome) => outcome, + None => Err(message.clone()), + }, + ) + .collect(); + } + outcomes + .into_inner() + .expect("lock") + .into_iter() + .enumerate() + .map(|(index, outcome)| { + outcome.unwrap_or_else(|| Err(format!("job {index} never completed"))) + }) + .collect() +} + +/// The reference index the corpus contributes, so a pair can be nominated by a +/// literal mention rather than only by prose resemblance. +pub fn references(corpus: &Prs) -> std::collections::HashMap> { + ref_index(corpus) +} +/// The judgment time, in the ISO-8601 form the log records. +fn judged_at() -> String { + time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| String::new()) +} diff --git a/crates/tranche-cli/src/evidence/acquiring.rs b/crates/tranche-cli/src/evidence/acquiring.rs new file mode 100644 index 0000000..ea4025f --- /dev/null +++ b/crates/tranche-cli/src/evidence/acquiring.rs @@ -0,0 +1,154 @@ +//! `evidence capture`: validate a batch and acquire or resume its evidence. +//! +//! The only evidence command that spends a GitHub budget. It refuses an unknown batch, +//! a stored capture bound to a different selection, and a completion check it cannot +//! afford, rather than producing evidence that describes the wrong work. + +use serde_json::Value; +use tranche_core::domain::pr::load_prs; +use tranche_core::evidence::capture; +use tranche_core::evidence::report; +use tranche_core::evidence::{Plan, select}; +use tranche_core::report::{REPOSITORY, Root}; + +use crate::commands::Outcome; + +use super::reading::{print_coverage, resume_hint, resume_target}; +use crate::cli::Capture; +use serde_json::json; +use tranche_core::evidence::EXIT_INCOMPLETE; +use tranche_core::evidence::capture::Stopped; + +/// `evidence capture`: validate a batch and acquire or resume its evidence. +pub fn capture_evidence(root: &Root, args: &Capture, json_output: bool) -> Outcome { + let say = |line: &str| println!("{line}"); + let corpus = match load_prs(root, REPOSITORY) { + Ok(corpus) => corpus, + Err(error) => return Outcome::refusal(format!("corpus: {}", error.0), 1), + }; + let plan = match Plan::read(root) { + Ok(plan) => plan, + Err(error) => return Outcome::refusal(error.0, 1), + }; + let selection = match select(root, &args.batch, &corpus, &plan) { + Ok(selection) => selection, + Err(error) => return Outcome::refusal(error.0, 3), + }; + + // Resume an existing capture of this selection, or start a fresh generation. + let existing = if args.fresh { + None + } else { + match args.reuse_capture.as_deref() { + Some(id) => Some(id.to_owned()), + None => resume_target(root, &selection), + } + }; + let capture_id = existing.unwrap_or_else(capture::new_capture_id); + + // A stored capture of a different selection is refused rather than extended: + // the evidence would describe two different batches under one identity. + if let Ok(manifest) = capture::stored_manifest(root, &capture_id) + && manifest["selection"] != selection.as_json() + { + return Outcome::refusal( + format!( + "capture {capture_id} belongs to a different selection; \ + omit --reuse-capture to start a fresh one" + ), + 3, + ); + } + + let manifest = match capture::stored_manifest(root, &capture_id) { + Ok(manifest) => manifest, + Err(_) => { + capture::fresh_manifest(&selection, &capture_id, args.request_budget, args.max_bytes) + } + }; + + let mut lock = match capture::lock_for(root, &capture_id) { + Ok(lock) => lock, + Err(error) => return Outcome::refusal(error, 3), + }; + if let Err(error) = lock.acquire(args.break_lock) { + return Outcome::refusal(error.0, 3); + } + + say(&format!( + "capture {capture_id} for batch {} ({} members, {} components each, budget {})", + args.batch, + selection.members.len(), + tranche_core::evidence::COMPONENTS.len(), + args.request_budget + )); + let outcome = { + let mut run = match capture::Capture::new( + root, + selection, + capture_id.clone(), + manifest, + args.request_budget, + args.max_bytes, + ) { + Ok(run) => run, + Err(error) => { + lock.release(); + return Outcome::refusal(error, 3); + } + }; + let stopped = run.run(); + for line in &run.log { + say(&format!(" {line}")); + } + // Re-read the manifest the run wrote: the checkpoint is the record, and the + // in-memory copy is only what the run last knew. + let stored = match capture::stored_manifest(root, &capture_id) { + Ok(stored) => stored, + Err(_) => run.manifest().clone(), + }; + (stopped, report::coverage(&stored)) + }; + lock.release(); + + let (stopped, coverage) = outcome; + if json_output { + let payload = json!({ + "coverage": coverage, + "next": if coverage["complete"].as_bool() == Some(true) { + Value::Null + } else { + json!(resume_hint(&args.batch, &capture_id)) + }, + }); + println!( + "{}", + serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_owned()) + ); + } else { + print_coverage(&coverage); + if coverage["complete"].as_bool() != Some(true) { + say(&format!(" {}", resume_hint(&args.batch, &capture_id))); + } + } + // A stop reason is a fact about the run, reported in the same place the coverage + // is, so a caller reads one block rather than two. + match stopped { + Stopped::Finished => {} + Stopped::Budget => { + say(" stopped: the request budget could not cover the completion checks") + } + Stopped::Transport => say(" stopped: the transport failed"), + Stopped::RevisionDrift => say(" stopped: a member moved, so start a fresh capture"), + } + if coverage["complete"].as_bool() == Some(true) { + Outcome::success(String::new()) + } else { + // A usable but incomplete capture is its own outcome: the exit code tells a + // caller to resume rather than that something failed. + Outcome::refusal( + format!("capture {capture_id} is incomplete"), + EXIT_INCOMPLETE, + ) + } +} diff --git a/crates/tranche-cli/src/evidence/dispatch.rs b/crates/tranche-cli/src/evidence/dispatch.rs new file mode 100644 index 0000000..ad340fe --- /dev/null +++ b/crates/tranche-cli/src/evidence/dispatch.rs @@ -0,0 +1,17 @@ +//! Dispatch for the evidence verbs. + +use tranche_core::report::Root; + +use crate::cli::Evidence; +use crate::commands::Outcome; + +use super::{acquiring, inspecting}; + +/// Dispatch one evidence verb. +pub fn run(root: &Root, verb: &Evidence, json_output: bool) -> Outcome { + match verb { + Evidence::Capture(args) => acquiring::capture_evidence(root, args, json_output), + Evidence::Show(args) => inspecting::show(root, args, json_output), + Evidence::Export(args) => inspecting::export(root, args, json_output), + } +} diff --git a/crates/tranche-cli/src/evidence/inspecting.rs b/crates/tranche-cli/src/evidence/inspecting.rs new file mode 100644 index 0000000..313a793 --- /dev/null +++ b/crates/tranche-cli/src/evidence/inspecting.rs @@ -0,0 +1,176 @@ +//! `evidence show` and `evidence export`: read a stored capture offline. +//! +//! `show` answers from the recorded state and the stored bodies alone. `export` +//! writes the self-contained packet, and a historical export is explicit rather than +//! implied. + +use tranche_core::evidence::report; +use tranche_core::report::Root; + +use crate::commands::Outcome; + +use super::reading::{load_manifest, print_coverage, resume_hint}; +use crate::cli::{Export, Show}; +use serde_json::json; + +/// `evidence show`: inspect coverage, a source window or a citation, offline. +pub fn show(root: &Root, args: &Show, json_output: bool) -> Outcome { + let manifest = match load_manifest(root, args.capture.as_deref(), args.batch.as_deref()) { + Ok((manifest, note)) => { + if let Some(note) = note { + println!("{note}"); + } + manifest + } + Err(error) => return Outcome::refusal(error.0, 3), + }; + + if let Some(source_id) = args.source.as_deref() { + let window = match report::window( + root, + &manifest, + source_id, + args.start_byte as usize, + args.length as usize, + ) { + Ok(window) => window, + Err(error) => return Outcome::refusal(error, 3), + }; + if json_output { + println!( + "{}", + serde_json::to_string_pretty(&window).unwrap_or_else(|_| "{}".to_owned()) + ); + } else { + println!( + "source {source_id} #{} {}/{} page {}", + window["number"], window["component"], window["group"], window["page"] + ); + println!( + " {} {} {} bytes sha256 {}", + window["url"].as_str().unwrap_or(""), + window["media_type"].as_str().unwrap_or(""), + window["body_bytes"], + window["body_sha256"].as_str().unwrap_or("") + ); + println!( + " bytes {}..{}{}", + window["start_byte"], + window["end_byte"], + match window["next_start"].as_u64() { + Some(next) => format!(" next --start-byte {next}"), + None => " (end of source)".to_owned(), + } + ); + print!("{}", window["content"].as_str().unwrap_or("")); + if !window["content"].as_str().unwrap_or("").ends_with('\n') { + println!(); + } + } + return Outcome::success(String::new()); + } + + if let Some(citation_id) = args.citation.as_deref() { + let resolved = match report::resolve_citation(root, &manifest, citation_id) { + Ok(resolved) => resolved, + Err(error) => return Outcome::refusal(error, 3), + }; + if json_output { + println!( + "{}", + serde_json::to_string_pretty(&resolved).unwrap_or_else(|_| "{}".to_owned()) + ); + } else { + let citation = &resolved["citation"]; + println!( + "citation {citation_id} #{} {}", + citation["number"], + citation["component"].as_str().unwrap_or("") + ); + println!( + " source {} bytes {}..{} excerpt sha256 {}", + citation["source_id"].as_str().unwrap_or(""), + citation["start_byte"], + citation["end_byte"], + resolved["excerpt_sha256"].as_str().unwrap_or("") + ); + print!("{}", resolved["excerpt"].as_str().unwrap_or("")); + if !resolved["excerpt"].as_str().unwrap_or("").ends_with('\n') { + println!(); + } + } + return Outcome::success(String::new()); + } + + let coverage = report::coverage(&manifest); + if json_output { + println!( + "{}", + serde_json::to_string_pretty(&coverage).unwrap_or_else(|_| "{}".to_owned()) + ); + } else { + if args.capture.is_some() { + println!("historical capture - nothing here is checked against the current report"); + } + print_coverage(&coverage); + if coverage["complete"].as_bool() != Some(true) { + let batch = manifest["selection"]["batch"]["id"].as_str().unwrap_or(""); + let id = manifest["capture_id"].as_str().unwrap_or(""); + println!(" {}", resume_hint(batch, id)); + } + } + Outcome::success(String::new()) +} +/// `evidence export`: write the self-contained packet. +pub fn export(root: &Root, args: &Export, json_output: bool) -> Outcome { + let manifest = match load_manifest(root, args.capture.as_deref(), args.batch.as_deref()) { + Ok((manifest, _)) => manifest, + Err(error) => return Outcome::refusal(error.0, 3), + }; + // A historical export is explicit and never claims current-batch compatibility. + let historical = args.capture.is_some(); + if historical && !args.allow_historical { + return Outcome::refusal( + "exporting a stored capture that is not the current batch needs --allow-historical", + 3, + ); + } + let (packet, bytes) = + match tranche_core::evidence::packet::bytes(root, &manifest, args.max_bytes as usize) { + Ok(built) => built, + Err(error) => return Outcome::refusal(error, 3), + }; + if args.output == "-" { + use std::io::Write; + let _ = std::io::stdout().write_all(&bytes); + return Outcome::success(String::new()); + } + if let Err(error) = std::fs::write(&args.output, &bytes) { + return Outcome::refusal(format!("cannot write {}: {error}", args.output), 3); + } + let complete = packet["complete"].as_bool() == Some(true); + if json_output { + println!( + "{}", + json!({ + "capture_id": packet["capture_id"], + "packet_digest": packet["packet_digest"], + "bytes": bytes.len(), + "complete": complete, + "output": args.output, + }) + ); + } else { + println!("wrote {} ({} bytes)", args.output, bytes.len()); + println!( + " packet digest {}", + packet["packet_digest"].as_str().unwrap_or("") + ); + println!( + " capture {} {}", + packet["capture_id"].as_str().unwrap_or(""), + if complete { "COMPLETE" } else { "INCOMPLETE" } + ); + } + Outcome::success(String::new()) +} diff --git a/crates/tranche-cli/src/evidence/mod.rs b/crates/tranche-cli/src/evidence/mod.rs new file mode 100644 index 0000000..32f953e --- /dev/null +++ b/crates/tranche-cli/src/evidence/mod.rs @@ -0,0 +1,11 @@ +//! The three evidence verbs: capture, show and export. +//! +//! These are the only commands that touch the network for evidence, and the only ones +//! that write under `out/evidence/`. Every one refuses rather than guessing. + +pub mod acquiring; +pub mod dispatch; +pub mod inspecting; +pub mod reading; + +pub use dispatch::run; diff --git a/crates/tranche-cli/src/evidence/reading.rs b/crates/tranche-cli/src/evidence/reading.rs new file mode 100644 index 0000000..ce9c269 --- /dev/null +++ b/crates/tranche-cli/src/evidence/reading.rs @@ -0,0 +1,131 @@ +//! Finding a stored capture, and printing what it recorded. + +use serde_json::Value; +use tranche_core::domain::pr::load_prs; +use tranche_core::evidence::capture; +use tranche_core::evidence::{Plan, select}; +use tranche_core::report::{REPOSITORY, Root}; + +/// The capture a batch currently resolves to, if one exists. +pub fn resume_target( + root: &Root, + selection: &tranche_core::evidence::selection::Selection, +) -> Option { + let wanted = selection.as_json(); + let directory = root.evidence_dir(); + let entries = std::fs::read_dir(&directory).ok()?; + let mut found: Vec = Vec::new(); + for entry in entries.flatten() { + let id = entry.file_name().to_string_lossy().into_owned(); + if let Ok(manifest) = capture::stored_manifest(root, &id) + && manifest["selection"] == wanted + { + found.push(id); + } + } + found.sort(); + found.into_iter().next() +} +/// The manifest a show or export command reads. +pub fn load_manifest( + root: &Root, + capture_id: Option<&str>, + batch: Option<&str>, +) -> Result<(Value, Option), tranche_core::evidence::EvidenceError> { + if let Some(id) = capture_id { + // Historical inspection consults no report at all. + let manifest = + capture::stored_manifest(root, id).map_err(tranche_core::evidence::refuse)?; + return Ok((manifest, None)); + } + let Some(batch_id) = batch else { + return Err(tranche_core::evidence::refuse( + "expected --batch or --capture", + )); + }; + let corpus = + load_prs(root, REPOSITORY).map_err(|error| tranche_core::evidence::refuse(error.0))?; + let plan = Plan::read(root).map_err(|error| tranche_core::evidence::refuse(error.0))?; + let selection = select(root, batch_id, &corpus, &plan) + .map_err(|error| tranche_core::evidence::refuse(error.0))?; + match resume_target(root, &selection) { + Some(id) => { + let manifest = + capture::stored_manifest(root, &id).map_err(tranche_core::evidence::refuse)?; + Ok((manifest, None)) + } + None => Err(tranche_core::evidence::refuse(format!( + "no capture is associated with the current {batch_id}; \ + run `tranche evidence capture --batch {batch_id}`" + ))), + } +} +/// How a caller resumes an incomplete capture. +pub fn resume_hint(batch: &str, capture_id: &str) -> String { + format!("resume: tranche evidence capture --batch {batch} --reuse-capture {capture_id}") +} +/// The coverage report as the operator reads it. +pub fn print_coverage(coverage: &Value) { + let state = if coverage["complete"].as_bool() == Some(true) { + "COMPLETE" + } else { + "INCOMPLETE" + }; + let generation = coverage["generation"].as_str().unwrap_or(""); + println!( + "capture {} batch {} generation {}... {state}", + coverage["capture_id"].as_str().unwrap_or(""), + coverage["batch"].as_str().unwrap_or(""), + &generation[..generation.len().min(12)] + ); + let requests = &coverage["requests"]; + println!( + " observed {} stop {} requests {}/{} (failures {}, identity checks {})", + coverage["observed_at"].as_str().unwrap_or(""), + coverage["stop_reason"].as_str().unwrap_or("none"), + requests["requests_used"], + requests["request_limit"], + requests["failures"], + requests["identity_checks"] + ); + println!( + " {} bytes stored, {} citations", + coverage["bytes_stored"], coverage["citations"] + ); + for member in coverage["members"].as_array().into_iter().flatten() { + let head = member["head_sha"].as_str().unwrap_or(""); + let base = member["base_sha"].as_str().unwrap_or(""); + println!( + " #{} head {}... base {}...", + member["number"], + &head[..head.len().min(12)], + &base[..base.len().min(12)] + ); + for component in member["components"].as_array().into_iter().flatten() { + let detail = match (component["status"].as_str(), component["reason"].as_str()) { + (Some("complete"), _) | (_, None) => String::new(), + (_, Some(reason)) => format!(" - {reason}"), + }; + let groups = component["groups"] + .as_array() + .into_iter() + .flatten() + .map(|group| { + format!( + "{}={}", + group["group"].as_str().unwrap_or(""), + group["status"].as_str().unwrap_or("") + ) + }) + .collect::>() + .join(", "); + println!( + " {:<16} {:<9} {:>3}p {:>4}c [{groups}]{detail}", + component["component"].as_str().unwrap_or(""), + component["status"].as_str().unwrap_or(""), + component["pages"], + component["citations"] + ); + } + } +} diff --git a/crates/tranche-cli/src/judgment.rs b/crates/tranche-cli/src/judgment.rs new file mode 100644 index 0000000..e52cce1 --- /dev/null +++ b/crates/tranche-cli/src/judgment.rs @@ -0,0 +1,242 @@ +//! The judgment pass: ask the model about each unjudged PR and append the +//! answers. +//! +//! The log is append-only, so a re-run never rewrites an earlier answer and a +//! truncated tail costs only the record it truncated. Resume reuses a record only +//! when its binding still matches today's evidence, question set and model, which +//! is what stops a question-policy change from silently reusing stale answers. + +use std::collections::HashMap; +use std::io::Write; +use std::sync::Mutex; + +use serde_json::Value; +use tranche_core::domain::judge::{ + Judgment, current_judgments, judgment_binding, normalize_judgment, reusable_judgment, +}; +use tranche_core::domain::pr::{Pr, Prs, load_prs}; +use tranche_core::domain::questions::judge_questions; +use tranche_core::jev; +use tranche_core::report::{MODEL, REPOSITORY, Root}; + +/// How many requests are in flight at once. +const WORKERS: usize = 6; + +/// Record one answer for a PR. +struct Job { + number: u64, + state: Value, + binding: String, + title: String, + evidence_digest: String, + head_sha: Option, + updated: String, +} + +/// Judge every unjudged PR, newest first. +/// +/// Returns how many were asked and how many failed. +pub fn judge( + root: &Root, + resume: bool, + limit: Option, + report: &mut dyn FnMut(&str), +) -> Result<(usize, usize), String> { + let corpus: Prs = load_prs(root, REPOSITORY).map_err(|error| error.0)?; + if corpus.is_empty() { + return Err(format!( + "no captured PR membership under {}; fetch first", + root.pages_dir().display() + )); + } + + // Reusable means current, complete and bound: a record that is merely present + // is not enough, or a question change would go unnoticed. + let already: HashMap = if resume { + current_judgments(root, &corpus, REPOSITORY, MODEL, false)? + .into_iter() + .filter(|(_, judgment)| reusable_judgment(judgment)) + .collect() + } else { + HashMap::new() + }; + + let mut ordered: Vec<&Pr> = corpus.iter().collect(); + // Newest first: the backlog is read from the top. + ordered.sort_by_key(|pr| std::cmp::Reverse(pr.number)); + let mut todo: Vec<&Pr> = ordered + .into_iter() + .filter(|pr| !already.contains_key(&pr.number)) + .collect(); + if let Some(limit) = limit { + todo.truncate(limit as usize); + } + + report(&format!( + "{} PRs, {} already judged, {} to go", + corpus.len(), + already.len(), + todo.len() + )); + if todo.is_empty() { + return Ok((0, 0)); + } + + let path = root.judgments_path(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .map_err(|error| format!("cannot create {}: {error}", parent.display()))?; + } + if !resume { + // A fresh pass starts the log over. Resume appends to what is there. + std::fs::write(&path, "").map_err(|error| format!("cannot reset the log: {error}"))?; + } + + let jobs: Vec = todo + .iter() + .map(|pr| Job { + number: pr.number, + state: tranche_core::domain::pr::pr_state(pr), + binding: judgment_binding(pr, REPOSITORY, MODEL), + title: pr.title.clone(), + evidence_digest: pr.evidence_digest.clone(), + head_sha: pr.head_sha.clone(), + updated: pr.updated.clone(), + }) + .collect(); + + let questions = judge_questions(); + let outcomes = ask_all(&jobs, &questions); + + // Append in a deterministic order. The log's order is not digested, but an + // unordered append makes a resumed pass hard to read back. + let mut errors = Vec::new(); + let mut written = 0usize; + let mut stream = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .map_err(|error| format!("cannot open the log: {error}"))?; + for (job, outcome) in jobs.iter().zip(outcomes) { + match outcome { + Ok(answer) => { + let record = normalize_judgment(&record_for(job, &answer)); + let line = serde_json::to_string(&record) + .map_err(|error| format!("cannot encode a judgment: {error}"))?; + writeln!(stream, "{line}") + .map_err(|error| format!("cannot append to the log: {error}"))?; + written += 1; + } + Err(error) => errors.push(format!("#{}: {error}", job.number)), + } + } + stream + .flush() + .map_err(|error| format!("cannot flush the log: {error}"))?; + + report(&format!( + "done: {written} judgments appended; errors: {}", + errors.len() + )); + for error in errors.iter().take(10) { + report(error); + } + Ok((written, errors.len())) +} + +/// The record a judgment is stored as. +/// +/// The field set is a compatibility surface: `normalize_judgment` reads these and +/// the binding is the cache key, so a missing field makes a record unusable +/// rather than merely incomplete. +fn record_for(job: &Job, answer: &Value) -> Value { + serde_json::json!({ + "number": job.number, + "title": job.title, + "answers": answer.get("answers"), + "usage": answer.get("usage").cloned().unwrap_or_else(|| serde_json::json!({})), + "binding": job.binding, + "input": job.state, + "source_digest": job.evidence_digest, + "head_sha": job.head_sha, + "updated_at": job.updated, + "requested_model": MODEL, + "judged_at": judged_at(), + "resolved_model": answer.get("model"), + "request_id": answer.get("request_id"), + }) +} + +/// Ask about every job, at most `WORKERS` at a time. +/// +/// Each job's outcome is kept, so one failure does not lose the others. A +/// rejected key is fatal: it cannot succeed for any of the remaining jobs, so the +/// pass stops rather than spending five hundred failed requests. +fn ask_all(jobs: &[Job], questions: &Value) -> Vec> { + let outcomes: Mutex>>> = Mutex::new(vec![None; jobs.len()]); + let fatal: Mutex> = Mutex::new(None); + let next = std::sync::atomic::AtomicUsize::new(0); + + std::thread::scope(|scope| { + for _ in 0..WORKERS.min(jobs.len()) { + scope.spawn(|| { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(error) => { + *fatal.lock().expect("lock") = Some(format!("no runtime: {error}")); + return; + } + }; + loop { + if fatal.lock().expect("lock").is_some() { + return; + } + let index = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let Some(job) = jobs.get(index) else { return }; + let outcome = runtime + .block_on(jev::ask(&job.state, questions, MODEL)) + .map_err(|error| error.to_string()); + if let Err(message) = &outcome + && message.contains("401") + { + *fatal.lock().expect("lock") = Some(message.clone()); + } + outcomes.lock().expect("lock")[index] = Some(outcome); + } + }); + } + }); + + if let Some(message) = fatal.lock().expect("lock").take() { + // Every unfinished job reports the same cause rather than a silent gap. + return jobs + .iter() + .enumerate() + .map( + |(index, _)| match outcomes.lock().expect("lock")[index].take() { + Some(outcome) => outcome, + None => Err(message.clone()), + }, + ) + .collect(); + } + outcomes + .into_inner() + .expect("lock") + .into_iter() + .enumerate() + .map(|(index, outcome)| { + outcome.unwrap_or_else(|| Err(format!("job {index} never completed"))) + }) + .collect() +} + +/// The judgment time, in the ISO-8601 form the log records. +fn judged_at() -> String { + time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| String::new()) +} diff --git a/crates/tranche-cli/src/lib.rs b/crates/tranche-cli/src/lib.rs new file mode 100644 index 0000000..5670f44 --- /dev/null +++ b/crates/tranche-cli/src/lib.rs @@ -0,0 +1,14 @@ +//! Builds on Christopher’s initial CLI POC (@GreyforgeLabs), with the Rust +//! frontend and native integration developed and maintained in Tranche. + +pub mod cli; +pub mod commands; +pub mod dupes; +pub mod evidence; +pub mod judgment; +pub mod pairing; +pub mod pipeline; +pub mod refresh; +pub mod report_files; +pub mod reports; +pub mod workbench; diff --git a/crates/tranche-cli/src/main.rs b/crates/tranche-cli/src/main.rs new file mode 100644 index 0000000..a73aae9 --- /dev/null +++ b/crates/tranche-cli/src/main.rs @@ -0,0 +1,10 @@ +use clap::Parser; +use tranche_cli::{cli::Cli, commands}; + +fn main() { + let cli = Cli::parse(); + let outcome = commands::run(&cli); + eprint!("{}", outcome.stderr); + print!("{}", outcome.stdout); + std::process::exit(outcome.code); +} diff --git a/crates/tranche-cli/src/pairing.rs b/crates/tranche-cli/src/pairing.rs new file mode 100644 index 0000000..70b86e2 --- /dev/null +++ b/crates/tranche-cli/src/pairing.rs @@ -0,0 +1,73 @@ +//! The work a `dupes` pass performs, decided in one place. +//! +//! Defined once and consumed by both `dupes` and `refresh --dry-run`, so the +//! count a dry run reports can never disagree with the work actually done. +//! +//! A stored verdict that is still current is not work. Neither is a pair that has +//! stopped being a candidate — its similarity fell below the threshold, or the +//! body reference that nominated it was removed — even though its verdict is now +//! stale: nothing asks for that verdict, so re-running it would be work that +//! never converges. + +use std::collections::{HashMap, HashSet}; + +use serde_json::Value; +use tranche_core::domain::dupe::{candidate_pairs, pair_cache, reusable_pair}; +use tranche_core::domain::pr::{Pr, Prs}; +use tranche_core::report::{MODEL, REPOSITORY, Root}; + +/// PR number → the references it contributes as comparison candidates. +/// +/// The index is what lets a pair be nominated by a literal mention rather than by +/// prose resemblance, so it is built from the same projection the corpus uses. +pub fn ref_index(prs: &Prs) -> HashMap> { + prs.iter().map(|pr| (pr.number, pr.refs.clone())).collect() +} + +/// The pairs worth asking about, best candidate first. +pub fn outstanding( + root: &Root, + prs: &Prs, + judgments: &HashMap, +) -> Result, String> { + let cache = pair_cache(root, prs, REPOSITORY, MODEL)?; + let done: HashSet<(u64, u64)> = cache + .iter() + .filter(|(_, record)| { + reusable_pair(record) && record["freshness"].as_str() == Some("current") + }) + .map(|(pair, _)| *pair) + .collect(); + let candidates = candidate_pairs(prs, judgments, Some(&ref_index(prs))); + let mut work: Vec<(f64, u64, u64)> = candidates + .into_iter() + .filter(|(pair, _)| !done.contains(pair)) + .map(|((a, b), score)| (score, a, b)) + .collect(); + // Best candidate first. `total_cmp` rather than a partial comparison, so an + // equal score is still an order rather than a panic. + work.sort_by(|left, right| { + right + .0 + .total_cmp(&left.0) + .then_with(|| left.1.cmp(&right.1)) + .then_with(|| left.2.cmp(&right.2)) + }); + Ok(work) +} + +/// The state one side of a comparison is shown as. +/// +/// `brief` is the pair-comparison projection: a shortened description, because a +/// verdict is a judgement about what the authors said, not about their patches. +pub fn brief(pr: &Pr) -> Value { + tranche_core::domain::dupe::brief(pr) +} + +/// The judgments to compare under, keyed by PR number. +pub fn judgments( + root: &Root, + prs: &Prs, +) -> Result, String> { + tranche_core::domain::judge::current_judgments(root, prs, REPOSITORY, MODEL, false) +} diff --git a/crates/tranche-cli/src/pipeline.rs b/crates/tranche-cli/src/pipeline.rs new file mode 100644 index 0000000..027b639 --- /dev/null +++ b/crates/tranche-cli/src/pipeline.rs @@ -0,0 +1,102 @@ +//! The pipeline commands that reach outside the process. +//! +//! Everything here is orchestration over `tranche-core`: the core decides what a +//! page means, this decides when to ask for one and where the result lands. + +use std::collections::HashSet; +use std::time::Duration; + +use serde_json::Value; +use tranche_core::domain::pr::validate_pr; +use tranche_core::gh::{self, Transport}; +use tranche_core::report::{REPOSITORY, Root}; +use tranche_core::util::{atomic_json, digest}; + +/// The API's maximum page size. +const PER_PAGE: usize = 100; + +/// Pause between pages. GitHub's guidance is to leave a gap rather than burst. +const BETWEEN_PAGES: Duration = Duration::from_millis(400); + +/// The snapshot format the corpus is captured in. +const SNAPSHOT_VERSION: u64 = 1; + +/// Refresh the observed open-PR membership. +/// +/// One atomic commit at the end. A failed or partial capture returns an error and +/// writes nothing, so the last committed observation stays intact — a half-read +/// membership would make every report built from it quietly short. +pub fn fetch( + root: &Root, + transport: Transport, + report: &mut dyn FnMut(&str), +) -> Result { + let mut captured: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut page = 1usize; + loop { + let url = format!( + "{}/repos/{REPOSITORY}/pulls?state=open&per_page={PER_PAGE}&page={page}", + gh::API + ); + let items = gh::page(transport, &url).map_err(|error| error.to_string())?; + if items.is_empty() { + break; + } + for item in &items { + validate_pr(item).map_err(|error| error.0)?; + let number = item["number"].as_u64().unwrap_or(0); + if !seen.insert(number) { + // A repeat means pagination is not behaving; continuing would + // double-count a PR and inflate every count downstream. + return Err( + "invalid or repeated PR during pagination; the previous snapshot is retained" + .to_owned(), + ); + } + } + let count = items.len(); + captured.extend(items); + report(&format!( + "page {page}: {count} PRs (total {})", + captured.len() + )); + // A short page is the last page, including an exactly-full final one. + if count < PER_PAGE { + break; + } + page += 1; + std::thread::sleep(BETWEEN_PAGES); + } + + let snapshot = serde_json::json!({ + "version": SNAPSHOT_VERSION, + "repo": REPOSITORY, + "items": captured, + // The digest covers exactly the items, which is what `load_prs` re-checks. + "digest": digest(&Value::Array(captured.clone())), + "observed_at": observed_at(), + }); + let path = root.snapshot_path(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .map_err(|error| format!("cannot create {}: {error}", parent.display()))?; + } + atomic_json(&path, &snapshot).map_err(|error| format!("cannot write the snapshot: {error}"))?; + report(&format!( + "fetched {} observed open PRs into {}", + captured.len(), + path.display() + )); + Ok(snapshot) +} + +/// The observation time, in the ISO-8601 form the snapshot records. +/// +/// Not part of any digest: `load_prs` re-checks the version, the repository and +/// the digest over the items, and reads this only to report when it looked. +fn observed_at() -> String { + let now = time::OffsetDateTime::now_utc(); + now.format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| String::new()) +} diff --git a/crates/tranche-cli/src/refresh.rs b/crates/tranche-cli/src/refresh.rs new file mode 100644 index 0000000..27bcec4 --- /dev/null +++ b/crates/tranche-cli/src/refresh.rs @@ -0,0 +1,151 @@ +//! The documented one-command pipeline. +//! +//! Runs the same steps in the same order every time and reuses everything the +//! caches can still support, so the work is proportional to what actually changed +//! since the last pass rather than to the size of the corpus. +//! +//! `refresh` is also where a dry run reports: the plan, what is already judged, +//! how many pair comparisons are outstanding, and — because fetching is the one +//! step that touches the network — that it would re-read GitHub. A dry run writes +//! nothing. + +use serde_json::Value; +use tranche_core::domain::dupe::candidate_pairs; +use tranche_core::domain::pr::{Prs, load_prs}; +use tranche_core::report::{REPOSITORY, Root}; + +use crate::commands::Outcome; +use crate::pairing::{judgments, outstanding, ref_index}; +use crate::report_files::read_json; +use crate::reports::{batches as build_batches, cluster_report}; + +/// The steps, in the order they always run. +const STEPS: [&str; 6] = ["fetch", "judge", "dupes", "cluster", "batches", "page"]; + +/// The counts a refresh reports before and after, with the change marked. +const ACCOUNTED: [&str; 8] = [ + "prs_in_corpus", + "judged", + "dupe_groups", + "review_groups", + "uncertain_pairs", + "ready_prs", + "escalate_review", + "security_priority", +]; + +/// Run the pipeline: fetch, judge, dupes, cluster, batches and the page. +pub fn refresh( + root: &Root, + max_pairs: u64, + no_page: bool, + dry_run: bool, + report: &mut dyn FnMut(&str), +) -> Outcome { + let steps: Vec<&str> = STEPS + .iter() + .copied() + .filter(|step| !(*step == "page" && no_page)) + .collect(); + + if dry_run { + return plan(root, &steps, report); + } + + let before = read_json(&root.summary_path()).ok(); + let before_batches = read_json(&root.batches_path()).ok(); + + report(&format!("refresh: {}", steps.join(" -> "))); + for step in &steps { + let mut say = |line: &str| report(line); + let outcome = match *step { + "fetch" => { + crate::pipeline::fetch(root, tranche_core::gh::Transport::Gh, &mut say).map(|_| ()) + } + "judge" => crate::judgment::judge(root, true, None, &mut say).map(|_| ()), + "dupes" => crate::dupes::dupes(root, max_pairs, &mut say).map(|_| ()), + "cluster" => outcome_of(cluster_report(root, false, false)), + "batches" => outcome_of(build_batches(root, false)), + "page" => outcome_of(crate::workbench::page(root, &mut say)), + other => Err(format!("unknown step {other}")), + }; + if let Err(error) = outcome { + return Outcome::refusal(format!("refresh stopped at {step}: {error}"), 1); + } + } + + report(""); + report("refresh complete"); + let after = read_json(&root.summary_path()).ok(); + let after_batches = read_json(&root.batches_path()).ok(); + for key in ACCOUNTED { + report(&changed(key, before.as_ref(), after.as_ref())); + } + report(&changed( + "parked_prs", + before_batches.as_ref(), + after_batches.as_ref(), + )); + Outcome::success(String::new()) +} + +/// What a refresh would do, writing nothing. +fn plan(root: &Root, steps: &[&str], report: &mut dyn FnMut(&str)) -> Outcome { + let corpus: Prs = match load_prs(root, REPOSITORY) { + Ok(corpus) => corpus, + Err(error) => return Outcome::refusal(format!("corpus: {}", error.0), 1), + }; + let judgments = match judgments(root, &corpus) { + Ok(judgments) => judgments, + Err(error) => return Outcome::refusal(format!("judgments: {error}"), 1), + }; + let pending = match outstanding(root, &corpus, &judgments) { + Ok(pending) => pending, + Err(error) => return Outcome::refusal(format!("pairs: {error}"), 1), + }; + // The denominator is the candidate set before the current verdicts are + // discounted, so "n of m" reads as work remaining out of all candidates. + let candidates = candidate_pairs(&corpus, &judgments, Some(&ref_index(&corpus))).len(); + + report(&format!( + "refresh plan ({}), no changes written:", + steps.join(" -> ") + )); + report(&format!( + " judged now {}/{} captured PRs", + judgments.len(), + corpus.len() + )); + report(&format!( + " pair verdicts to re-run {} of {candidates} candidates", + pending.len() + )); + if steps.contains(&"fetch") { + report(" fetch would re-read open-PR membership from GitHub"); + } + Outcome::success(String::new()) +} + +/// One accounted count, with what it was when it moved. +fn changed(key: &str, before: Option<&Value>, after: Option<&Value>) -> String { + let new = after.and_then(|value| value.get(key)); + let old = before.and_then(|value| value.get(key)); + let marker = if old == new || old.is_none() { + String::new() + } else { + format!(" (was {})", old.map(Value::to_string).unwrap_or_default()) + }; + format!( + " {key:<22} {}{marker}", + new.map(Value::to_string).unwrap_or_else(|| "—".to_owned()) + ) +} + +/// A step that reports its own progress through `Outcome`. +fn outcome_of(outcome: Outcome) -> Result<(), String> { + if outcome.code == 0 { + Ok(()) + } else { + Err(outcome.stderr.trim().to_owned()) + } +} diff --git a/crates/tranche-cli/src/report_files.rs b/crates/tranche-cli/src/report_files.rs new file mode 100644 index 0000000..c460aae --- /dev/null +++ b/crates/tranche-cli/src/report_files.rs @@ -0,0 +1,27 @@ +//! Reading what is already on disk. +//! +//! `info` and the digest check `batches` performs both go through here, so a +//! malformed or absent file is reported the same way wherever it is needed. + +use serde_json::Value; + +use tranche_core::report::Root; + +/// Read one JSON file, or report that the pipeline's input is unusable. +pub fn read_json(path: &std::path::Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|error| format!("cannot read {}: {error}", path.display()))?; + serde_json::from_str(&text).map_err(|error| format!("{}: {error}", path.display())) +} + +/// The summary of the report currently on disk, if it is one this pipeline made. +/// +/// Read rather than recomputed, so a caller reports what was published instead of +/// what a fresh run would produce. +pub fn current_summary(root: &Root) -> Result { + let summary = read_json(&root.summary_path())?; + if summary["format_version"].as_u64() != Some(2) { + return Err("unrecognized cluster observation; run cluster first".to_owned()); + } + Ok(summary) +} diff --git a/crates/tranche-cli/src/reports.rs b/crates/tranche-cli/src/reports.rs new file mode 100644 index 0000000..707bc55 --- /dev/null +++ b/crates/tranche-cli/src/reports.rs @@ -0,0 +1,202 @@ +//! The commands that rebuild a report from the corpus and write it out. +//! +//! Each one is a thin shell over `tranche-core`: read the inputs, call the one +//! entry point, publish the artifacts in the order a reader can tolerate. Nothing +//! here decides what a report means. + +use std::collections::HashMap; +use std::io::Write; + +use tranche_core::domain::batch::{ + batch_plan_section, merge_batches, park_section, park_state, parked_payload, +}; +use tranche_core::domain::cluster::{cluster, render}; +use tranche_core::domain::dupe::current_pairs; +use tranche_core::domain::judge::{Judgment, current_judgments}; +use tranche_core::domain::pr::{Prs, load_prs}; +use tranche_core::report::{MODEL, REPOSITORY, Root}; +use tranche_core::util::{atomic_json, digest}; + +use crate::commands::Outcome; +use crate::report_files::read_json; + +/// Pack the review candidates into pre-release batches and write the park record. +/// +/// `batches` refuses to run against a report it did not produce: the recorded +/// digests have to describe the `clusters.json` and `dupes.json` on disk, or the +/// batches would be packed from a different observation than the one published. +pub fn batches(root: &Root, json: bool) -> Outcome { + let summary = match read_json(&root.summary_path()) { + Ok(summary) => summary, + Err(error) => return Outcome::refusal(format!("summary.json: {error}"), 1), + }; + if summary["format_version"].as_u64() != Some(2) || summary["repo"].as_str() != Some(REPOSITORY) + { + return Outcome::refusal("unrecognized cluster observation; run cluster first", 1); + } + let dupes = match read_json(&root.dupes_path()) { + Ok(dupes) => dupes, + Err(error) => return Outcome::refusal(format!("dupes.json: {error}"), 1), + }; + let clusters = match read_json(&root.clusters_path()) { + Ok(clusters) => clusters, + Err(error) => return Outcome::refusal(format!("clusters.json: {error}"), 1), + }; + let recorded = &summary["output_digests"]; + if recorded["clusters.json"].as_str() != Some(digest(&clusters).as_str()) { + return Outcome::refusal( + "clusters.json does not match the recorded digest; run cluster first", + 1, + ); + } + if recorded["dupes.json"].as_str() != Some(digest(&dupes).as_str()) { + return Outcome::refusal( + "dupes.json does not match the recorded digest; run cluster first", + 1, + ); + } + let dupes_digest = digest(&dupes); + + let corpus = match load_prs(root, REPOSITORY) { + Ok(corpus) => corpus, + Err(error) => return Outcome::refusal(format!("corpus: {}", error.0), 1), + }; + let judgments: HashMap = + match current_judgments(root, &corpus, REPOSITORY, MODEL, false) { + Ok(judgments) => judgments, + Err(error) => return Outcome::refusal(format!("judgments: {error}"), 1), + }; + let batches = match merge_batches(&dupes, &judgments, &corpus, &dupes_digest, REPOSITORY) { + Ok(batches) => batches, + Err(error) => return Outcome::refusal(error, 1), + }; + let parks = park_state(&dupes, &judgments, &corpus); + + let out = root.out_dir(); + if let Err(error) = std::fs::create_dir_all(&out) { + return Outcome::refusal(format!("cannot create {}: {error}", out.display()), 1); + } + if let Err(error) = atomic_json(&root.batches_path(), &batches) { + return Outcome::refusal(format!("cannot write batches.json: {error}"), 1); + } + if let Err(error) = atomic_json( + &root.parked_path(), + &parked_payload(&parks, &corpus, &judgments, &dupes_digest, REPOSITORY), + ) { + return Outcome::refusal(format!("cannot write parked.json: {error}"), 1); + } + // Batches append to the report; `cluster` owns the file and wrote the part + // above. A missing report is skipped rather than invented. + if let Err(error) = append_plan(root, &batches, &parks, &corpus) { + return Outcome::refusal(format!("cannot append to tranches.md: {error}"), 1); + } + + let count = |field: &str| batches[field].as_u64().unwrap_or(0); + if json { + return Outcome::success(format!( + "{}\n", + tranche_core::util::indented_json(&batches).unwrap_or_default() + )); + } + Outcome::success(format!( + "{} batches of ≤ {} PRs ({} security-first, {} same-change groups, {} review-group PRs excluded, {} parked)\n\ + wrote {}/batches.json, {}/parked.json\n", + batches["batches"].as_array().map(Vec::len).unwrap_or(0), + count("batch_size"), + count("security_batches"), + count("same_change_groups"), + count("excluded_review_prs"), + count("parked_prs"), + out.display(), + out.display(), + )) +} + +/// Append the batch plan and park record to the published report. +fn append_plan( + root: &Root, + batches: &serde_json::Value, + parks: &std::collections::BTreeMap>, + corpus: &Prs, +) -> std::io::Result<()> { + let path = root.tranches_path(); + if !path.exists() { + return Ok(()); + } + let mut section = batch_plan_section(batches); + if !parks.is_empty() { + section.push_str(&park_section(parks, corpus)); + } + let mut stream = std::fs::OpenOptions::new().append(true).open(&path)?; + stream.write_all(section.as_bytes()) +} + +/// Rebuild the report from the stored corpus and write every artifact `cluster` +/// owns. +/// +/// This stage writes four files, and the manifest last, so a reader never +/// sees a report whose binding does not yet exist. +pub fn cluster_report(root: &Root, allow_unbound: bool, json: bool) -> Outcome { + let corpus = match load_prs(root, REPOSITORY) { + Ok(corpus) => corpus, + Err(error) => return Outcome::refusal(format!("corpus: {}", error.0), 1), + }; + let judgments: HashMap = + match current_judgments(root, &corpus, REPOSITORY, MODEL, allow_unbound) { + Ok(judgments) => judgments, + Err(error) => return Outcome::refusal(format!("judgments: {error}"), 1), + }; + let verdicts = match current_pairs(root, &corpus, &judgments, REPOSITORY, MODEL, allow_unbound) + { + Ok(verdicts) => verdicts, + Err(error) => return Outcome::refusal(format!("pairs: {error}"), 1), + }; + + if corpus.is_empty() { + // Writing here would publish an empty report over whatever is already + // stored, and `summary.json` is the manifest a reader trusts. + return Outcome::refusal( + format!( + "no captured PR membership under {}; fetch first", + root.pages_dir().display() + ), + 1, + ); + } + + let built = cluster( + &corpus, + &judgments, + &verdicts, + REPOSITORY, + MODEL, + allow_unbound, + ); + let out = root.out_dir(); + if let Err(error) = std::fs::create_dir_all(&out) { + return Outcome::refusal(format!("cannot create {}: {error}", out.display()), 1); + } + for (name, value) in [ + ("clusters.json", &built.clusters), + ("dupes.json", &built.dupes), + ] { + if let Err(error) = atomic_json(&out.join(name), value) { + return Outcome::refusal(format!("cannot write {name}: {error}"), 1); + } + } + if let Err(error) = std::fs::write(root.tranches_path(), render(&built, REPOSITORY)) { + return Outcome::refusal(format!("cannot write tranches.md: {error}"), 1); + } + if let Err(error) = atomic_json(&root.summary_path(), &built.summary) { + return Outcome::refusal(format!("cannot write summary.json: {error}"), 1); + } + + if json { + let rendered = tranche_core::util::indented_json(&built.summary).unwrap_or_default(); + return Outcome::success(format!("{rendered}\n")); + } + Outcome::success(format!( + "wrote {}/clusters.json dupes.json tranches.md summary.json\n", + out.display() + )) +} diff --git a/crates/tranche-cli/src/workbench/labels.rs b/crates/tranche-cli/src/workbench/labels.rs new file mode 100644 index 0000000..0c6e187 --- /dev/null +++ b/crates/tranche-cli/src/workbench/labels.rs @@ -0,0 +1,21 @@ +//! The categories the picker shows, and the labels they carry. +//! +//! The order is the order the picker lists them, which is why they are one table +//! rather than a lookup and a separate ordering. + +/// Category keys to the labels the picker shows. +pub const CATEGORY_LABELS: [(&str, &str); 13] = [ + ("security-review", "Security (meta)"), + ("install-setup", "Install & Setup"), + ("desktop-config", "Desktop Config"), + ("user-experience", "User Experience"), + ("shell-cli", "Shell & CLI"), + ("apps-integrations", "Apps & Integrations"), + ("hardware-drivers", "Hardware & Drivers"), + ("update-release", "Update & Release"), + ("agents-ai", "Agents & AI"), + ("docs", "Docs"), + ("fix-misc", "Fixes & Misc"), + ("unclear", "Unclear"), + ("unknown", "Unknown"), +]; diff --git a/crates/tranche-cli/src/workbench/mod.rs b/crates/tranche-cli/src/workbench/mod.rs new file mode 100644 index 0000000..7871d8b --- /dev/null +++ b/crates/tranche-cli/src/workbench/mod.rs @@ -0,0 +1,18 @@ +//! The workbench: `docs/index.html` and the payload it fetches. +//! +//! The renderer refuses inconsistent inputs rather than showing them. A report +//! whose binding no longer matches, a `batches.json` from a different dupe run, a +//! park record that does not equal the one the current judgments produce — all of +//! those would put a maintainer in front of numbers nobody can vouch for, so none +//! of them render. +//! +//! Eligibility stays in the pipeline's own predicates. This never reclassifies a +//! judgment; it arranges what the report already says. + +mod labels; +mod page; +mod payload; +mod writing; + +pub use labels::CATEGORY_LABELS; +pub use page::page; diff --git a/crates/tranche-cli/src/workbench/page.rs b/crates/tranche-cli/src/workbench/page.rs new file mode 100644 index 0000000..6760cd9 --- /dev/null +++ b/crates/tranche-cli/src/workbench/page.rs @@ -0,0 +1,134 @@ +//! Rendering the workbench from the bound reports. +//! +//! Every gate that decides whether the page renders at all lives here, because a +//! reader seeing numbers is the thing they can no longer un-see. The arrangement of +//! what the report already says is in `payload`; this file decides whether to. + +use std::collections::HashMap; + +use tranche_core::domain::batch::{park_state, parked_payload}; +use tranche_core::domain::cluster::report_binding; +use tranche_core::domain::dupe::current_pairs; +use tranche_core::domain::judge::{Judgment, current_judgments}; +use tranche_core::domain::pr::{Prs, load_prs}; +use tranche_core::report::{MODEL, REPOSITORY, Root}; +use tranche_core::util::digest; + +use crate::commands::Outcome; +use crate::report_files::read_json; + +/// Render the workbench from the bound reports. +pub fn page(root: &Root, report: &mut dyn FnMut(&str)) -> Outcome { + let corpus: Prs = match load_prs(root, REPOSITORY) { + Ok(corpus) => corpus, + Err(error) => return Outcome::refusal(format!("corpus: {}", error.0), 1), + }; + let summary = match read_json(&root.summary_path()) { + Ok(summary) => summary, + Err(error) => return Outcome::refusal(format!("summary.json: {error}"), 1), + }; + let allow_unbound = summary["allow_unbound"].as_bool() == Some(true); + let judgments: HashMap = + match current_judgments(root, &corpus, REPOSITORY, MODEL, allow_unbound) { + Ok(judgments) => judgments, + Err(error) => return Outcome::refusal(format!("judgments: {error}"), 1), + }; + let verdicts = match current_pairs(root, &corpus, &judgments, REPOSITORY, MODEL, allow_unbound) + { + Ok(verdicts) => verdicts, + Err(error) => return Outcome::refusal(format!("pairs: {error}"), 1), + }; + let clusters = match read_json(&root.clusters_path()) { + Ok(clusters) => clusters, + Err(error) => return Outcome::refusal(format!("clusters.json: {error}"), 1), + }; + let dupes = match read_json(&root.dupes_path()) { + Ok(dupes) => dupes, + Err(error) => return Outcome::refusal(format!("dupes.json: {error}"), 1), + }; + + // The report has to be the one these judgments produce. + let binding = report_binding(&corpus, &judgments, &verdicts, REPOSITORY, MODEL); + let recorded = &summary["output_digests"]; + if summary["format_version"].as_u64() != Some(2) + || summary["repo"].as_str() != Some(REPOSITORY) + || summary["report_binding"].as_str() != Some(binding.as_str()) + || recorded["clusters.json"].as_str() != Some(digest(&clusters).as_str()) + || recorded["dupes.json"].as_str() != Some(digest(&dupes).as_str()) + { + return Outcome::refusal( + "report inputs changed or are legacy/mixed; rerun cluster before rendering", + 1, + ); + } + + // Batches and the park record ship with the workbench when present, and a + // stale one must never be shown against a newer dupe run. + let batches = match read_json(&root.batches_path()) { + Ok(batches) => { + if batches["format_version"].as_u64() != Some(3) + || batches["repo"].as_str() != Some(REPOSITORY) + || batches["dupes_digest"].as_str() != recorded["dupes.json"].as_str() + { + return Outcome::refusal( + "batches.json is stale or foreign; run `tranche batches` before rendering", + 1, + ); + } + Some(batches) + } + Err(_) => None, + }; + let parks = park_state(&dupes, &judgments, &corpus); + let parked = match read_json(&root.parked_path()) { + Ok(parked) => { + let expected = parked_payload( + &parks, + &corpus, + &judgments, + recorded["dupes.json"].as_str().unwrap_or(""), + REPOSITORY, + ); + if parked != expected { + return Outcome::refusal( + "parked.json is stale, foreign or modified; run `tranche batches` before rendering", + 1, + ); + } + Some(parked) + } + Err(_) => None, + }; + let parked_prs = batches + .as_ref() + .and_then(|batches| batches["parked_prs"].as_u64()) + .unwrap_or(0); + if parked_prs > 0 && parked.is_none() { + return Outcome::refusal( + "batches.json parked PRs but parked.json is missing; run `tranche batches`", + 1, + ); + } + + let built = super::payload::payload( + &corpus, + &judgments, + &dupes, + batches.as_ref(), + parked.as_ref(), + root, + ); + match super::writing::write(root, built) { + Ok((html, json_bytes)) => { + report(&format!( + "wrote {}/index.html ({} KB) and {}/data/workbench.json ({} KB)", + root.docs_dir().display(), + html / 1024, + root.docs_dir().display(), + json_bytes / 1024 + )); + Outcome::success(String::new()) + } + Err(error) => Outcome::refusal(error, 1), + } +} diff --git a/crates/tranche-cli/src/workbench/payload.rs b/crates/tranche-cli/src/workbench/payload.rs new file mode 100644 index 0000000..20d184b --- /dev/null +++ b/crates/tranche-cli/src/workbench/payload.rs @@ -0,0 +1,183 @@ +//! The payload the workbench fetches at boot. +//! +//! Every field is copied from a report rather than derived here, so the page can +//! only show what `cluster`, `dupes` and `batches` already decided. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use serde_json::{Map, Value, json}; +use tranche_core::domain::batch::pr_activity; +use tranche_core::domain::cluster::{escalated, review_candidate, security_priority}; +use tranche_core::domain::judge::{Judgment, load_done}; +use tranche_core::domain::pr::{Pr, Prs}; +use tranche_core::report::Root; + +use super::CATEGORY_LABELS; + +/// Build the payload. +pub(super) fn payload( + corpus: &Prs, + judgments: &HashMap, + dupes: &Value, + batches: Option<&Value>, + parked: Option<&Value>, + root: &Root, +) -> Value { + let grouped = grouped(dupes); + let mut related = grouped.clone(); + for pair in dupes["uncertain_pairs"].as_array().into_iter().flatten() { + for side in ["a", "b"] { + if let Some(number) = pair[side].as_u64() { + related.insert(number); + } + } + } + let parked_by_number: HashMap = (parked) + .and_then(|parked| parked["members"].as_array()) + .into_iter() + .flatten() + .filter_map(|member| member["number"].as_u64().map(|number| (number, member))) + .collect(); + let mut batch_of: BTreeMap> = BTreeMap::new(); + for batch in batches + .and_then(|batches| batches["batches"].as_array()) + .into_iter() + .flatten() + { + let tag = json!({"id": batch["id"], "count": batch["count"]}); + for number in batch["members"].as_array().into_iter().flatten() { + if let Some(number) = number.as_u64() { + batch_of.entry(number).or_default().push(tag.clone()); + } + } + } + let latest = load_done(root).unwrap_or_default(); + + // The page is ordered by number, not by the captured order. + let mut ordered: Vec<&Pr> = corpus.iter().collect(); + ordered.sort_by_key(|pr| pr.number); + let rows: Vec = ordered + .into_iter() + .map(|pr| { + row( + pr, + judgments, + &grouped, + &related, + &parked_by_number, + &batch_of, + &latest, + ) + }) + .collect(); + + let labels: Map = CATEGORY_LABELS + .iter() + .map(|(key, label)| ((*key).to_owned(), json!(label))) + .collect(); + let shipped: Vec = batches + .and_then(|batches| batches["batches"].as_array()) + .into_iter() + .flatten() + .map(|batch| { + json!({ + "id": batch["id"], "count": batch["count"], "members": batch["members"], + "security_members": batch["security_members"], + "average_risk": batch["average_risk"], "created": batch["created"], + "review_prompt": batch["review_prompt"], + }) + }) + .collect(); + + json!({ + "prs": rows, + "categories": Value::Object(labels), + "groups": dupes, + "batches": shipped, + "batches_available": batches.is_some(), + "parked": parked.cloned().unwrap_or(Value::Null), + }) +} + +/// One PR, with everything the page filters on. +fn row( + pr: &Pr, + judgments: &HashMap, + grouped: &HashSet, + related: &HashSet, + parked: &HashMap, + batch_of: &BTreeMap>, + latest: &HashMap, +) -> Value { + let judgment = judgments.get(&pr.number); + let finished = judgment.and_then(|judgment| judgment.metric("finished_form", "score")); + let security = judgment.map(security_priority).unwrap_or(false); + json!({ + "number": pr.number, + "title": pr.title, + "body": pr.body, + "body_truncated": pr.body_truncated, + "author": pr.author, + "created": pr.created, + "draft": pr.draft, + "activity": pr_activity(pr, latest.get(&pr.number)), + "category": judgment + .map(|judgment| judgment.category()) + .unwrap_or_else(|| "unknown".to_owned()), + // The `security-review` key is the meta category: a security-flagged PR + // is in both its own category and this one. + "categories": if security { json!(["security-review"]) } else { json!([]) }, + "freshness": judgment + .map(|judgment| judgment.freshness().to_owned()) + .unwrap_or_else(|| "unjudged or stale".to_owned()), + "risk": judgment.and_then(|judgment| judgment.metric("risk", "score")), + "security": judgment.and_then(|judgment| judgment.metric("security_flag", "noul")), + "security_priority": security, + "finished": finished, + "effort": judgment.and_then(|judgment| judgment.metric("review_effort", "score")), + "is_fix": judgment.and_then(|judgment| judgment.metric("is_fix", "noul")), + "diffstat": diffstat(pr), + "candidate": judgment + .is_some_and(|judgment| review_candidate(pr, judgment, grouped)), + "senior": judgment.is_some_and(escalated), + "followup": finished.is_some_and(|value| value <= 1.0) && !grouped.contains(&pr.number), + "related": related.contains(&pr.number), + "parked": parked + .get(&pr.number) + .and_then(|member| member.get("reasons").cloned()) + .unwrap_or_else(|| json!([])), + "batches": batch_of.get(&pr.number).cloned().unwrap_or_default(), + }) +} + +/// Which PRs sit in a grouping, confirmed or under review. +fn grouped(dupes: &Value) -> HashSet { + let mut grouped = HashSet::new(); + for group in dupes["confirmed_groups"].as_array().into_iter().flatten() { + for number in group.as_array().into_iter().flatten() { + if let Some(number) = number.as_u64() { + grouped.insert(number); + } + } + } + for group in dupes["review_groups"].as_array().into_iter().flatten() { + for number in group["members"].as_array().into_iter().flatten() { + if let Some(number) = number.as_u64() { + grouped.insert(number); + } + } + } + grouped +} + +/// The diffstat the captured list supplied, or that it supplied none. +fn diffstat(pr: &Pr) -> String { + match (pr.files, pr.additions, pr.deletions) { + (Some(files), Some(additions), Some(deletions)) + if files >= 0 && additions >= 0 && deletions >= 0 => + { + format!("{files} files changed, +{additions}/-{deletions}") + } + _ => "unknown (not supplied by the captured PR list)".to_owned(), + } +} diff --git a/crates/tranche-cli/src/workbench/writing.rs b/crates/tranche-cli/src/workbench/writing.rs new file mode 100644 index 0000000..9a5243b --- /dev/null +++ b/crates/tranche-cli/src/workbench/writing.rs @@ -0,0 +1,80 @@ +//! Writing the page and its payload. +//! +//! Two escapes live here and they are not the same escape. The template's is +//! HTML, for the category picker. The payload's is JSON-with-non-ASCII-flattened, +//! because the page is served without a charset guarantee: the payload is fetched +//! and injected, so a title containing markup must not survive as markup. + +use serde_json::Value; +use tranche_core::report::Root; + +use super::CATEGORY_LABELS; + +/// Write the page and its payload, and report the sizes. +pub(super) fn write(root: &Root, payload: Value) -> Result<(usize, usize), String> { + let template = std::fs::read_to_string(root.template_path()) + .map_err(|error| format!("cannot read {}: {error}", root.template_path().display()))?; + let options: String = CATEGORY_LABELS + .iter() + .map(|(key, label)| format!("", html(key), html(label))) + .collect(); + let count = payload["prs"].as_array().map(Vec::len).unwrap_or(0); + let page = template + .replace("{{options}}", &options) + .replace("{{count_commas}}", &commas(count)) + .replace("{{count}}", &count.to_string()); + + let compact = serde_json::to_string(&payload).map_err(|error| error.to_string())?; + let encoded = escape_json(&compact); + + let docs = root.docs_dir(); + let data = docs.join("data"); + std::fs::create_dir_all(&data) + .map_err(|error| format!("cannot create {}: {error}", data.display()))?; + std::fs::write(data.join("workbench.json"), &encoded) + .map_err(|error| format!("cannot write the payload: {error}"))?; + std::fs::write(docs.join("index.html"), &page) + .map_err(|error| format!("cannot write the page: {error}"))?; + Ok((page.len(), encoded.len())) +} + +/// Escape a string for an HTML attribute or text node. +fn html(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +/// Flatten the payload to ASCII, escaping markup and every non-ASCII character. +fn escape_json(compact: &str) -> String { + let mut out = String::with_capacity(compact.len()); + for character in compact.chars() { + match character { + '&' => out.push_str("\\u0026"), + '<' => out.push_str("\\u003c"), + '>' => out.push_str("\\u003e"), + character if (character as u32) < 0x20 || (character as u32) > 0x7e => { + let mut buffer = [0u16; 2]; + for unit in character.encode_utf16(&mut buffer) { + out.push_str(&format!("\\u{unit:04x}")); + } + } + character => out.push(character), + } + } + out +} + +/// Thousands separators, as the page shows them. +fn commas(value: usize) -> String { + let digits = value.to_string(); + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + for (index, digit) in digits.chars().enumerate() { + if index > 0 && (digits.len() - index).is_multiple_of(3) { + out.push(','); + } + out.push(digit); + } + out +} diff --git a/crates/tranche-cli/tests/comparing_the_corpus.rs b/crates/tranche-cli/tests/comparing_the_corpus.rs new file mode 100644 index 0000000..8585c29 --- /dev/null +++ b/crates/tranche-cli/tests/comparing_the_corpus.rs @@ -0,0 +1,192 @@ +//! `tranche dupes`, end to end, against a local model stub. +//! +//! The property worth proving is convergence: a comparison that has already been +//! made and is still current is not work, so a second pass spends nothing. The +//! opposite failure — re-running a pair whose verdict is still current — is what +//! makes a dupe pass never finish on a large backlog. + +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +const KEY: &str = "jev-test-key-not-real"; + +/// A model stub that answers every request and counts them. +fn model() -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").expect("a free port"); + let port = listener.local_addr().expect("address").port(); + let asked = Arc::new(AtomicU32::new(0)); + let counter = Arc::clone(&asked); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + counter.fetch_add(1, Ordering::SeqCst); + drain(&mut stream); + let body = r#"{"answers":{"sameness":{"choice":"related_but_different","probabilities":{"same_change":0.2}}},"usage":{"input_tokens":100,"output_tokens":20},"model":"jev-1.2.3","request_id":"req-2"}"#; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + (format!("http://127.0.0.1:{port}"), asked) +} + +fn drain(stream: &mut TcpStream) { + let Ok(handle) = stream.try_clone() else { + return; + }; + let mut reader = BufReader::new(handle); + let mut length = 0usize; + let mut line = String::new(); + while reader.read_line(&mut line).unwrap_or(0) > 0 { + if let Some(value) = line.to_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + if line == "\r\n" { + break; + } + line.clear(); + } + if length > 0 { + let mut body = vec![0u8; length]; + let _ = reader.read_exact(&mut body); + } +} + +/// A checkout with two PRs whose titles resemble each other, already judged. +/// +/// Both a snapshot and a judgment log are needed: a dupe pass compares judged +/// PRs only, so the candidate set comes from the judgments. +fn root_with_pair() -> tempfile::TempDir { + let root = tempfile::tempdir().expect("a root"); + let pages = root.path().join("data/pages"); + let out = root.path().join("out"); + fs::create_dir_all(&pages).expect("pages"); + fs::create_dir_all(&out).expect("out"); + + let items = serde_json::json!([ + {"number": 11, "title": "Fix panel crash on startup", "body": "a", "head": {"sha": "1".repeat(40)}, "user": {"login": "octo"}}, + {"number": 22, "title": "Fix panel crash on startup", "body": "b", "head": {"sha": "2".repeat(40)}, "user": {"login": "octo"}}, + ]); + let snapshot = serde_json::json!({ + "version": 1, + "repo": "omacom/omarchy", + "items": items, + "digest": tranche_core::util::digest(&items), + }); + fs::write( + pages.join("snapshot.json"), + serde_json::to_string(&snapshot).expect("encode"), + ) + .expect("snapshot"); + + // One judgment per PR, produced by the same code path the judge command uses. + let root_handle = tranche_core::report::Root::new(root.path()); + let (_, endpoint) = ((), String::new()); + let _ = endpoint; + let output = std::process::Command::new(env!("CARGO_BIN_EXE_tranche")) + .arg("--root") + .arg(root.path()) + .arg("judge") + .env("TYPESAFE_API_KEY", KEY) + .env("TRANCHE_DEV_API_URL", judge_endpoint()) + .output() + .expect("judge runs"); + assert!( + output.status.success(), + "judging the fixture failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let _ = root_handle; + root +} + +/// A stub endpoint for the judgment setup step. +fn judge_endpoint() -> String { + let (endpoint, _) = model(); + endpoint +} + +fn run(root: &Path, endpoint: &str, arguments: &[&str]) -> std::process::Output { + std::process::Command::new(env!("CARGO_BIN_EXE_tranche")) + .arg("--root") + .arg(root) + .args(arguments) + .env("TYPESAFE_API_KEY", KEY) + .env("TRANCHE_DEV_API_URL", endpoint) + .output() + .expect("the tranche binary runs") +} + +fn verdicts(root: &Path) -> Vec { + match fs::read_to_string(root.join("out/pair_verdicts.jsonl")) { + Ok(text) => text + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect(), + Err(_) => Vec::new(), + } +} + +#[test] +fn comparing_writes_one_verdict_for_the_candidate_pair() { + let root = root_with_pair(); + let (endpoint, asked) = model(); + let output = run(root.path(), &endpoint, &["dupes"]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let records = verdicts(root.path()); + assert_eq!(records.len(), 1, "one verdict for the one candidate pair"); + assert_eq!(asked.load(Ordering::SeqCst), 1); + let record = &records[0]; + assert_eq!(record["a"], 11); + assert_eq!(record["b"], 22); + assert!(record["binding"].is_string(), "a binding is a cache key"); + assert_eq!(record["verdict"], "related_but_different"); + // `normalize_pair` moves the token counts to the flat fields and drops the + // nested block, so a reader does not have to know which shape it got. + assert_eq!(record["input_tokens"], 100); + assert_eq!(record["output_tokens"], 20); + assert!(record.get("usage").is_none(), "the nested block is gone"); +} + +#[test] +fn a_second_pass_has_nothing_left_to_compare() { + // Convergence: a current verdict is not work. Without this a dupe pass never + // finishes, because every run would re-ask every pair it already knows. + let root = root_with_pair(); + let (endpoint, asked) = model(); + run(root.path(), &endpoint, &["dupes"]); + let after_first = asked.load(Ordering::SeqCst); + assert!(after_first >= 1); + + let output = run(root.path(), &endpoint, &["dupes"]); + assert!(output.status.success()); + assert_eq!( + asked.load(Ordering::SeqCst), + after_first, + "a second pass spends nothing" + ); + assert_eq!(verdicts(root.path()).len(), 1, "and appends nothing"); +} + +#[test] +fn max_pairs_bounds_the_pass() { + let root = root_with_pair(); + let (endpoint, asked) = model(); + let output = run(root.path(), &endpoint, &["dupes", "--max-pairs", "1"]); + assert!(output.status.success()); + assert!( + asked.load(Ordering::SeqCst) <= 1 + 2, + "at most the one pair, plus the judging setup" + ); + assert_eq!(verdicts(root.path()).len(), 1); +} diff --git a/crates/tranche-cli/tests/fetching_the_corpus.rs b/crates/tranche-cli/tests/fetching_the_corpus.rs new file mode 100644 index 0000000..496c2ca --- /dev/null +++ b/crates/tranche-cli/tests/fetching_the_corpus.rs @@ -0,0 +1,108 @@ +//! `tranche fetch`, end to end, with a fake `gh`. +//! +//! Fetching is the one command that reaches outside the process, so the thing +//! worth proving is what it leaves behind: a snapshot that the corpus loader +//! accepts, and nothing at all when the capture fails. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::process::{Command, Output}; + +/// A fake `gh` on a directory placed first on the child's own path. +/// +/// The path is set on the child process, never in this process: a test that +/// rewrote the test runner's `PATH` would change what every test beside it saw. +fn fake_gh(script_body: &str) -> tempfile::TempDir { + let directory = tempfile::tempdir().expect("a temporary directory"); + let binary: PathBuf = directory.path().join("gh"); + fs::write(&binary, format!("#!/bin/sh\n{script_body}\n")).expect("write the fake"); + fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)).expect("make it runnable"); + directory +} + +fn run(root: &std::path::Path, path: &tempfile::TempDir) -> Output { + let current = std::env::var("PATH").unwrap_or_default(); + Command::new(env!("CARGO_BIN_EXE_tranche")) + .arg("--root") + .arg(root) + .arg("fetch") + .env("PATH", format!("{}:{current}", path.path().display())) + .output() + .expect("the tranche binary runs") +} + +/// One page of two PRs, in the shape the API returns and `validate_pr` accepts. +const TWO_PRS: &str = r#"[{"number": 11, "title": "first", "body": "b", "head": {"sha": "a"}, "user": {"login": "octo"}}, {"number": 22, "title": "second", "body": null, "head": {"sha": "b"}, "user": {"login": "octo"}}]"#; + +#[test] +fn fetching_writes_a_snapshot_the_corpus_loader_accepts() { + let root = tempfile::tempdir().expect("a root"); + let path = fake_gh(&format!("printf '%s' '{TWO_PRS}'")); + let output = run(root.path(), &path); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + + let snapshot: serde_json::Value = serde_json::from_str( + &fs::read_to_string(root.path().join("data/pages/snapshot.json")).expect("a snapshot"), + ) + .expect("the snapshot is JSON"); + assert_eq!(snapshot["version"], 1); + assert_eq!(snapshot["repo"], "omacom/omarchy"); + assert_eq!(snapshot["items"].as_array().expect("items").len(), 2); + + // The digest covers exactly the items: the loader re-checks this and refuses + // a snapshot that does not describe itself. + let digest = tranche_core::util::digest(&snapshot["items"]); + assert_eq!(snapshot["digest"], digest, "the snapshot verifies"); + + // And the loader really reads it. + let corpus = tranche_core::domain::pr::load_prs( + &tranche_core::report::Root::new(root.path()), + "omacom/omarchy", + ) + .expect("the corpus loads from what fetch wrote"); + assert_eq!(corpus.len(), 2); +} + +#[test] +fn a_failed_capture_leaves_the_previous_snapshot_untouched() { + let root = tempfile::tempdir().expect("a root"); + let pages = root.path().join("data/pages"); + fs::create_dir_all(&pages).expect("a pages directory"); + let existing = r#"{"version":1,"repo":"omacom/omarchy","items":[],"digest":"x"}"#; + fs::write(pages.join("snapshot.json"), existing).expect("a previous snapshot"); + + let path = fake_gh("exit 1"); + let output = run(root.path(), &path); + assert!(!output.status.success(), "a failed fetch refuses"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("previous snapshot"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + + let after = fs::read_to_string(pages.join("snapshot.json")).expect("still there"); + assert_eq!(after, existing, "the previous snapshot was not touched"); +} + +#[test] +fn a_body_that_is_not_a_pr_list_refuses_rather_than_empty() { + // An error document read as "no open PRs" would publish an empty corpus. + let root = tempfile::tempdir().expect("a root"); + let path = fake_gh(r#"printf '%s' '{"message":"Not Found"}'"#); + let output = run(root.path(), &path); + assert!(!output.status.success(), "a non-array refuses"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("did not return a PR list"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + !root.path().join("data/pages/snapshot.json").exists(), + "nothing was written" + ); +} diff --git a/crates/tranche-cli/tests/judging_the_corpus.rs b/crates/tranche-cli/tests/judging_the_corpus.rs new file mode 100644 index 0000000..028c360 --- /dev/null +++ b/crates/tranche-cli/tests/judging_the_corpus.rs @@ -0,0 +1,211 @@ +//! `tranche judge`, end to end, against a local model stub. +//! +//! The cost of a mistake here is money: if resume stops recognizing an existing +//! judgment it re-asks the whole backlog, and if it recognizes a stale one it +//! reuses an answer to a question nobody asked. Both directions are tested. + +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +/// The API key the client will pick up. +const KEY: &str = "jev-test-key-not-real"; + +/// A model stub that answers every request the same way and counts them. +struct Model { + endpoint: String, + asked: Arc, +} + +fn model() -> Model { + let listener = TcpListener::bind("127.0.0.1:0").expect("a free port"); + let port = listener.local_addr().expect("address").port(); + let asked = Arc::new(AtomicU32::new(0)); + let counter = Arc::clone(&asked); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + counter.fetch_add(1, Ordering::SeqCst); + drain(&mut stream); + let body = r#"{"answers":{"category":{"choice":"fix-misc"},"risk":{"score":1},"is_fix":{"noul":0.9},"dupe_signal":{"noul":0.1},"finished_form":{"score":2},"review_effort":{"score":1},"security_flag":{"noul":0.0}},"usage":{"input_tokens":10,"output_tokens":5},"model":"jev-1.2.3","request_id":"req-1"}"#; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + Model { + endpoint: format!("http://127.0.0.1:{port}"), + asked, + } +} + +fn drain(stream: &mut TcpStream) { + let Ok(handle) = stream.try_clone() else { + return; + }; + let mut reader = BufReader::new(handle); + let mut length = 0usize; + let mut line = String::new(); + while reader.read_line(&mut line).unwrap_or(0) > 0 { + if let Some(value) = line.to_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + if line == "\r\n" { + break; + } + line.clear(); + } + if length > 0 { + let mut body = vec![0u8; length]; + let _ = reader.read_exact(&mut body); + } +} + +/// A checkout holding a snapshot of two PRs. +fn root_with_corpus() -> tempfile::TempDir { + let root = tempfile::tempdir().expect("a root"); + let pages = root.path().join("data/pages"); + fs::create_dir_all(&pages).expect("pages"); + let items = serde_json::json!([ + {"number": 11, "title": "first", "body": "b", "head": {"sha": "a"}, "user": {"login": "octo"}}, + {"number": 22, "title": "second", "body": null, "head": {"sha": "b"}, "user": {"login": "octo"}}, + ]); + let snapshot = serde_json::json!({ + "version": 1, + "repo": "omacom/omarchy", + "items": items, + "digest": tranche_core::util::digest(&items), + }); + fs::write( + pages.join("snapshot.json"), + serde_json::to_string(&snapshot).expect("encode"), + ) + .expect("snapshot"); + root +} + +fn run(root: &Path, endpoint: &str, arguments: &[&str]) -> std::process::Output { + let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_tranche")); + command + .arg("--root") + .arg(root) + .args(arguments) + .env("TYPESAFE_API_KEY", KEY) + .env("TRANCHE_DEV_API_URL", endpoint); + // The client reads the endpoint from the environment only when the tests set + // it; production always uses the fixed one. + command.output().expect("the tranche binary runs") +} + +fn log(root: &Path) -> Vec { + let path = root.join("out/judgments.jsonl"); + match fs::read_to_string(&path) { + Ok(text) => text + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect(), + Err(_) => Vec::new(), + } +} + +fn binary_path() -> PathBuf { + PathBuf::from(env!("CARGO_BIN_EXE_tranche")) +} + +#[test] +fn the_binary_exists() { + // A guard: every other test in this file depends on it. + assert!(binary_path().exists()); +} + +#[test] +fn judging_appends_one_record_per_pr() { + let root = root_with_corpus(); + let stub = model(); + let output = run(root.path(), &stub.endpoint, &["judge"]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let records = log(root.path()); + assert_eq!(records.len(), 2, "one record per PR"); + assert_eq!(stub.asked.load(Ordering::SeqCst), 2, "one call per PR"); + // The record carries what a reader downstream needs. + let first = &records[0]; + assert!(first["binding"].is_string(), "a binding is a cache key"); + assert!(first["answers"]["category"].is_object()); + assert_eq!(first["usage"]["input_tokens"], 10); +} + +#[test] +fn resume_does_not_re_ask_a_current_judgment() { + // The expensive failure: a resume that re-asks the whole backlog. + let root = root_with_corpus(); + let stub = model(); + run(root.path(), &stub.endpoint, &["judge"]); + assert_eq!(stub.asked.load(Ordering::SeqCst), 2); + + let output = run(root.path(), &stub.endpoint, &["judge", "--resume"]); + assert!(output.status.success()); + assert_eq!( + stub.asked.load(Ordering::SeqCst), + 2, + "a resume with nothing new spends nothing" + ); + assert_eq!(log(root.path()).len(), 2, "and appends nothing"); +} + +#[test] +fn a_changed_head_invalidates_the_judgment_and_re_asks() { + // The other direction: an answer bound to old evidence must not be reused. + let root = root_with_corpus(); + let stub = model(); + run(root.path(), &stub.endpoint, &["judge"]); + assert_eq!(stub.asked.load(Ordering::SeqCst), 2); + + // The author pushed: the head SHA the judgment was bound to no longer matches. + let pages = root.path().join("data/pages/snapshot.json"); + let text = fs::read_to_string(&pages).expect("snapshot"); + let mut snapshot: serde_json::Value = serde_json::from_str(&text).expect("parse"); + snapshot["items"][0]["head"]["sha"] = serde_json::json!("c".repeat(40)); + snapshot["digest"] = serde_json::json!(tranche_core::util::digest(&snapshot["items"])); + fs::write(&pages, serde_json::to_string(&snapshot).expect("encode")).expect("write"); + + run(root.path(), &stub.endpoint, &["judge", "--resume"]); + assert_eq!( + stub.asked.load(Ordering::SeqCst), + 3, + "the moved PR is asked again, and only it" + ); +} + +#[test] +fn a_fresh_pass_resets_the_log() { + let root = root_with_corpus(); + let stub = model(); + run(root.path(), &stub.endpoint, &["judge"]); + run(root.path(), &stub.endpoint, &["judge"]); + // Without --resume the pass starts over rather than appending duplicates. + assert_eq!(log(root.path()).len(), 2, "the log holds one pass"); + assert_eq!(stub.asked.load(Ordering::SeqCst), 4, "both PRs asked twice"); +} + +#[test] +fn a_root_without_a_corpus_refuses_rather_than_judging_nothing() { + let root = tempfile::tempdir().expect("a root"); + let stub = model(); + let output = run(root.path(), &stub.endpoint, &["judge"]); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("fetch first"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(stub.asked.load(Ordering::SeqCst), 0, "no request was made"); +} diff --git a/crates/tranche-cli/tests/missing_root_is_refused.rs b/crates/tranche-cli/tests/missing_root_is_refused.rs new file mode 100644 index 0000000..dc810ec --- /dev/null +++ b/crates/tranche-cli/tests/missing_root_is_refused.rs @@ -0,0 +1,39 @@ +use std::path::Path; +use std::process::{Command, Output}; + +fn run(root: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_tranche")) + .arg("--root") + .arg(root) + .args(args) + .output() + .expect("the tranche binary should be runnable") +} + +fn temp_root() -> tempfile::TempDir { + tempfile::tempdir().expect("a temporary root") +} + +#[test] +fn a_root_without_reports_is_refused_without_a_traceback() { + let root = temp_root(); + let output = run(root.path(), &["cluster"]); + assert_ne!(output.status.code(), Some(0)); + let stderr = String::from_utf8_lossy(&output.stderr); + // A refusal an operator can act on, not a panic dump. + assert!(!stderr.contains("panicked"), "{stderr}"); + assert!(!stderr.contains("Traceback"), "{stderr}"); +} + +#[test] +fn a_bare_invocation_prints_the_command_tree() { + let root = temp_root(); + for args in [vec![], vec!["evidence"]] { + let output = run(root.path(), &args); + assert_eq!(output.status.code(), Some(2), "{args:?}"); + // clap answers a bare invocation with help on stderr and a usage status. + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("Usage:"), "{args:?}: {stderr}"); + assert!(stderr.contains("evidence"), "{args:?}: {stderr}"); + } +} diff --git a/crates/tranche-cli/tests/refreshing_the_corpus.rs b/crates/tranche-cli/tests/refreshing_the_corpus.rs new file mode 100644 index 0000000..f6ecb4a --- /dev/null +++ b/crates/tranche-cli/tests/refreshing_the_corpus.rs @@ -0,0 +1,274 @@ +//! `tranche refresh`, end to end, against local stubs. +//! +//! Two properties decide whether this command is trustworthy. A dry run must +//! write nothing and count the same work the real pass performs, and a real run +//! must stop at the first step that fails rather than publishing a report built +//! from a half-finished pipeline. + +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +const KEY: &str = "jev-test-key-not-real"; + +/// A stub that answers both the model and GitHub, and counts each. +struct Stubs { + directory: tempfile::TempDir, + model: String, + asked: Arc, + judged: Arc, + compared: Arc, +} + +fn stubs() -> Stubs { + let listener = TcpListener::bind("127.0.0.1:0").expect("a free port"); + let port = listener.local_addr().expect("address").port(); + let asked = Arc::new(AtomicU32::new(0)); + let judged = Arc::new(AtomicU32::new(0)); + let judged_counter = Arc::clone(&judged); + let compared = Arc::new(AtomicU32::new(0)); + let compared_counter = Arc::clone(&compared); + let counter = Arc::clone(&asked); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + counter.fetch_add(1, Ordering::SeqCst); + let body = drain(&mut stream); + // The model endpoint answers the questions; the GitHub path answers a + // PR list. One stub, told apart by the body it received. + // One stub serves both model calls and the GitHub read. A judge + // request asks about `category`; a pair comparison asks about + // `sameness`. Counting them together made a dupe call look like a + // re-judgment. + let reply = if body.contains("\"category\"") { + judged_counter.fetch_add(1, Ordering::SeqCst); + r#"{"answers":{"category":{"choice":"fix-misc"},"risk":{"score":1},"is_fix":{"noul":0.9},"dupe_signal":{"noul":0.1},"finished_form":{"score":2},"review_effort":{"score":1},"security_flag":{"noul":0.0}},"usage":{"input_tokens":10,"output_tokens":5},"model":"jev-1.2.3"}"#.to_owned() + } else if body.contains("\"sameness\"") { + compared_counter.fetch_add(1, Ordering::SeqCst); + r#"{"answers":{"sameness":{"choice":"related_but_different","probabilities":{"same_change":0.2}}},"usage":{"input_tokens":100,"output_tokens":20},"model":"jev-1.2.3"}"#.to_owned() + } else { + format!( + "[{{\"number\": 11, \"title\": \"Fix panel crash on startup\", \"body\": \"a\", \"head\": {{\"sha\": \"{}\"}}, \"user\": {{\"login\": \"octo\"}}}}, {{\"number\": 22, \"title\": \"Fix panel crash on startup\", \"body\": \"b\", \"head\": {{\"sha\": \"{}\"}}, \"user\": {{\"login\": \"octo\"}}}}]", + "1".repeat(40), + "2".repeat(40), + ) + }; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", + reply.len() + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + + // A fake `gh` pointing at the same stub, so the fetch step reads it. + let directory = tempfile::tempdir().expect("a directory"); + let gh = directory.path().join("gh"); + fs::write( + &gh, + format!("#!/bin/sh\nexec curl --silent --fail 'http://127.0.0.1:{port}/pulls'\n"), + ) + .expect("write the fake gh"); + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&gh, fs::Permissions::from_mode(0o755)).expect("runnable"); + } + + Stubs { + directory, + model: format!("http://127.0.0.1:{port}"), + asked, + judged, + compared, + } +} + +fn drain(stream: &mut TcpStream) -> String { + let Ok(handle) = stream.try_clone() else { + return String::new(); + }; + let mut reader = BufReader::new(handle); + let mut length = 0usize; + let mut line = String::new(); + while reader.read_line(&mut line).unwrap_or(0) > 0 { + if let Some(value) = line.to_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + if line == "\r\n" { + break; + } + line.clear(); + } + let mut body = vec![0u8; length]; + let _ = reader.read_exact(&mut body); + String::from_utf8_lossy(&body).into_owned() +} + +fn root_with_corpus() -> tempfile::TempDir { + let root = tempfile::tempdir().expect("a root"); + let pages = root.path().join("data/pages"); + fs::create_dir_all(&pages).expect("pages"); + let items = serde_json::json!([ + {"number": 11, "title": "Fix panel crash on startup", "body": "a", "head": {"sha": "1".repeat(40)}, "user": {"login": "octo"}}, + {"number": 22, "title": "Fix panel crash on startup", "body": "b", "head": {"sha": "2".repeat(40)}, "user": {"login": "octo"}}, + ]); + let snapshot = serde_json::json!({ + "version": 1, + "repo": "omacom/omarchy", + "items": items, + "digest": tranche_core::util::digest(&items), + }); + fs::write( + pages.join("snapshot.json"), + serde_json::to_string(&snapshot).expect("encode"), + ) + .expect("snapshot"); + root +} + +fn run(root: &Path, stubs: &Stubs, arguments: &[&str]) -> Output { + let current = std::env::var("PATH").unwrap_or_default(); + Command::new(env!("CARGO_BIN_EXE_tranche")) + .arg("--root") + .arg(root) + .args(arguments) + .env("TYPESAFE_API_KEY", KEY) + .env("TRANCHE_DEV_API_URL", &stubs.model) + .env( + "PATH", + format!("{}:{current}", stubs.directory.path().display()), + ) + .output() + .expect("the tranche binary runs") +} + +fn snapshot_of(root: &Path) -> Option { + fs::read_to_string(root.join("out/summary.json")).ok() +} + +#[test] +fn a_dry_run_writes_nothing_and_reports_the_work() { + let root = root_with_corpus(); + let stub = stubs(); + let output = run(root.path(), &stub, &["refresh", "--dry-run"]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("no changes written"), "{stdout}"); + assert!(stdout.contains("judged now"), "{stdout}"); + assert!(stdout.contains("pair verdicts to re-run"), "{stdout}"); + assert!( + stdout.contains("would re-read open-PR membership"), + "{stdout}" + ); + + assert!(snapshot_of(root.path()).is_none(), "nothing was written"); + assert!( + !root.path().join("out/judgments.jsonl").exists(), + "no judgment was made" + ); + assert_eq!( + stub.asked.load(Ordering::SeqCst), + 0, + "a dry run spends nothing" + ); +} + +#[test] +fn refresh_runs_every_step_in_order_and_writes_the_page() { + // The page is a step like any other now, so a plain refresh completes and + // leaves the workbench behind. + let root = root_with_corpus(); + let stub = stubs(); + let template = root.path().join("page"); + fs::create_dir_all(&template).expect("page directory"); + fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(Path::parent) + .expect("nested in the repository") + .join("page/template.html"), + template.join("template.html"), + ) + .expect("the template"); + + let output = run(root.path(), &stub, &["refresh", "--max-pairs", "5"]); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("refresh:"), "{stdout}"); + assert!( + stdout.contains("fetch -> judge -> dupes -> cluster -> batches -> page"), + "{stdout}" + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + + // Every step left a real artifact, the page included. + assert!(root.path().join("out/judgments.jsonl").exists()); + assert!(root.path().join("out/clusters.json").exists()); + assert!(root.path().join("out/batches.json").exists()); + assert!(root.path().join("docs/index.html").exists()); + assert!(root.path().join("docs/data/workbench.json").exists()); +} + +#[test] +fn no_page_completes_the_pipeline() { + let root = root_with_corpus(); + let stub = stubs(); + let output = run(root.path(), &stub, &["refresh", "--no-page"]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("refresh complete"), "{stdout}"); + // The before/after accounting is the point of the summary block. + assert!(stdout.contains("prs_in_corpus"), "{stdout}"); + assert!(stdout.contains("parked_prs"), "{stdout}"); + + let summary = snapshot_of(root.path()).expect("a summary"); + let parsed: serde_json::Value = serde_json::from_str(&summary).expect("parses"); + assert_eq!(parsed["prs_in_corpus"], 2); + assert_eq!(parsed["judged"], 2); +} + +#[test] +fn a_second_refresh_judges_nothing_new() { + // The incremental promise: work is proportional to what changed, not to the + // corpus size. + let root = root_with_corpus(); + let stub = stubs(); + run(root.path(), &stub, &["refresh", "--no-page"]); + assert_eq!( + stub.judged.load(Ordering::SeqCst), + 2, + "the first pass judges both PRs" + ); + assert!( + stub.compared.load(Ordering::SeqCst) >= 1, + "and compares the candidate pair" + ); + + let output = run(root.path(), &stub, &["refresh", "--no-page"]); + assert!(output.status.success()); + assert_eq!( + stub.judged.load(Ordering::SeqCst), + 2, + "a second refresh re-judges nothing" + ); +} + +#[test] +fn the_binary_is_the_one_under_test() { + assert!(PathBuf::from(env!("CARGO_BIN_EXE_tranche")).exists()); +} diff --git a/crates/tranche-cli/tests/rendering_the_workbench.rs b/crates/tranche-cli/tests/rendering_the_workbench.rs new file mode 100644 index 0000000..a27ec4b --- /dev/null +++ b/crates/tranche-cli/tests/rendering_the_workbench.rs @@ -0,0 +1,170 @@ +//! `tranche page`, end to end, from the committed fixture. +//! +//! The renderer's job is to arrange what the report already says, and to refuse +//! when the inputs cannot vouch for each other. Both halves are tested: a page +//! renders from consistent inputs, and an input the report no longer describes +//! stops it. + +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +/// The checkout holding the fixture, copied so a render never touches it, with +/// the template added: the template is source, not report data. +fn root() -> tempfile::TempDir { + let repository = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(Path::parent) + .expect("nested in the repository"); + let root = tempfile::tempdir().expect("a root"); + copy( + &repository.join("crates/tranche-core/tests/fixture"), + root.path(), + ); + let page = root.path().join("page"); + fs::create_dir_all(&page).expect("page directory"); + fs::copy( + repository.join("page/template.html"), + page.join("template.html"), + ) + .expect("the template"); + root +} + +fn copy(source: &Path, destination: &Path) { + for entry in fs::read_dir(source).expect("the fixture reads") { + let entry = entry.expect("an entry"); + let target = destination.join(entry.file_name()); + if entry.file_type().expect("a type").is_dir() { + fs::create_dir_all(&target).expect("a directory"); + copy(&entry.path(), &target); + } else { + fs::copy(entry.path(), &target).expect("a file"); + } + } +} + +fn run(root: &Path) -> Output { + Command::new(env!("CARGO_BIN_EXE_tranche")) + .arg("--root") + .arg(root) + .arg("page") + .output() + .expect("the tranche binary runs") +} + +fn payload(root: &Path) -> String { + fs::read_to_string(root.join("docs/data/workbench.json")).expect("the payload reads") +} + +/// The first title the fixture's report holds, for asserting the page is filled. +fn a_fixture_title() -> String { + let clusters = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(Path::parent) + .expect("nested in the repository") + .join("crates/tranche-core/tests/fixture/out/clusters.json"); + let text = fs::read_to_string(clusters).expect("clusters"); + let parsed: serde_json::Value = serde_json::from_str(&text).expect("parses"); + parsed + .as_object() + .into_iter() + .flatten() + .flat_map(|(_, bands)| bands.as_object().into_iter().flatten()) + .flat_map(|(_, items)| items.as_array().into_iter().flatten()) + .find_map(|item| item["title"].as_str().map(str::to_owned)) + .expect("the fixture holds a titled PR") +} + +#[test] +fn a_page_renders_from_consistent_inputs() { + let root = root(); + let output = run(root.path()); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = payload(root.path()); + let parsed: serde_json::Value = serde_json::from_str(&text).expect("valid JSON"); + let rows = parsed["prs"].as_array().expect("a list of rows"); + assert!(!rows.is_empty(), "the payload carries PRs"); + + // The page really is filled: a PR from the report appears in it. + let title = a_fixture_title(); + let html = fs::read_to_string(root.path().join("docs/index.html")).expect("the page"); + assert!(!html.contains("{{options}}"), "the options were filled"); + assert!(!html.contains("{{count}}"), "the count was filled"); + assert!( + rows.iter().any(|row| row["title"] == title.as_str()), + "the expected PR is in the payload: {title}" + ); +} + +#[test] +fn the_payload_escapes_markup_so_a_title_cannot_break_out() { + // A title is untrusted text from GitHub. The fetch and the injection are the + // reason `&`, `<` and `>` are escaped rather than carried through. + let root = root(); + assert!(run(root.path()).status.success()); + let text = payload(root.path()); + assert!(!text.contains('<'), "no raw angle bracket survives"); + assert!(!text.contains('&'), "no raw ampersand survives"); + // And the escaping is the documented form, not a different one. + assert!(text.contains("\\u003c") || !text.contains("u003c")); +} + +#[test] +fn a_report_that_no_longer_describes_its_inputs_stops_the_render() { + // The gate that matters: `summary.json` records what the report was built + // from, and a report whose inputs have moved on must not be shown, because a + // maintainer would be reading numbers nobody can vouch for. + let root = root(); + let summary = root.path().join("out/summary.json"); + let text = fs::read_to_string(&summary).expect("summary"); + let mut parsed: serde_json::Value = serde_json::from_str(&text).expect("parses"); + parsed["report_binding"] = serde_json::json!("0000"); + fs::write(&summary, serde_json::to_string(&parsed).expect("encode")).expect("write"); + + let output = run(root.path()); + assert!(!output.status.success(), "a foreign binding refuses"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("rerun cluster"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + !root.path().join("docs/data/workbench.json").exists(), + "nothing was written" + ); +} + +#[test] +fn a_stale_batches_file_stops_the_render() { + let root = root(); + let batches = root.path().join("out/batches.json"); + let text = fs::read_to_string(&batches).expect("batches"); + let mut parsed: serde_json::Value = serde_json::from_str(&text).expect("parses"); + parsed["dupes_digest"] = serde_json::json!("0000"); + fs::write(&batches, serde_json::to_string(&parsed).expect("encode")).expect("write"); + let output = run(root.path()); + assert!(!output.status.success(), "a stale batches refuses"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("batches.json is stale"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn a_missing_template_refuses_rather_than_writing_a_broken_page() { + let root = root(); + fs::remove_file(root.path().join("page/template.html")).expect("remove the template"); + let output = run(root.path()); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("template"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} diff --git a/crates/tranche-cli/tests/the_command_tree.rs b/crates/tranche-cli/tests/the_command_tree.rs new file mode 100644 index 0000000..41e8b2e --- /dev/null +++ b/crates/tranche-cli/tests/the_command_tree.rs @@ -0,0 +1,168 @@ +use clap::{CommandFactory, Parser}; +use tranche_cli::cli::{Cli, Command, Evidence, Transport}; + +fn parse(args: &[&str]) -> Cli { + match Cli::try_parse_from(args) { + Ok(cli) => cli, + Err(error) => panic!("{args:?} should parse: {error}"), + } +} + +#[test] +fn every_documented_invocation_parses() { + Cli::command().debug_assert(); + let cases: &[&[&str]] = &[ + &["fetch", "--transport", "urllib"], + &["judge", "--limit", "2", "--resume"], + &["dupes", "--max-pairs", "0"], + &["cluster", "--allow-unbound"], + &["batches"], + &["refresh", "--max-pairs", "12", "--no-page", "--dry-run"], + &["all", "--limit", "1", "--resume", "--max-pairs", "0"], + &["page"], + &["evidence", "capture", "--batch", "B001"], + &["evidence", "show", "--capture", "C-123"], + &["evidence", "export", "--capture", "C-123", "--output", "-"], + ]; + for args in cases { + let mut argv = vec!["tranche"]; + argv.extend_from_slice(args); + argv.extend_from_slice(&["--json", "--root", "."]); + assert!(parse(&argv).json, "{args:?}"); + } +} + +#[test] +fn invalid_values_are_refused() { + for args in [ + ["tranche", "judge", "--limit", "0"], + ["tranche", "dupes", "--max-pairs", "-1"], + ["tranche", "fetch", "--transport", "nonsense"], + ] { + // A typo or an out-of-range value must be rejected at parse time rather + // than reaching an operation that cannot honour it. + assert!(Cli::try_parse_from(args).is_err(), "{args:?}"); + } +} + +#[test] +fn mutually_exclusive_selectors_are_refused() { + // `--batch` (current association) and `--capture` (historical) are + // different questions; asking both is a usage error, not a precedence rule. + for args in [ + &[ + "tranche", + "evidence", + "show", + "--batch", + "B001", + "--capture", + "C-123", + ][..], + &[ + "tranche", + "evidence", + "show", + "--capture", + "C-123", + "--source", + "S1", + "--citation", + "Q1", + ][..], + ] { + assert!(Cli::try_parse_from(args).is_err(), "{args:?}"); + } +} + +#[test] +fn evidence_capture_flags_are_typed() { + let cli = parse(&[ + "tranche", + "evidence", + "capture", + "--batch", + "B001", + "--request-budget", + "50", + "--max-bytes", + "999", + "--fresh", + "--reuse-capture", + "C-123", + "--break-lock", + ]); + let Command::Evidence { command } = cli.command else { + panic!("expected an evidence command"); + }; + let Evidence::Capture(capture) = command else { + panic!("expected an evidence capture command"); + }; + assert_eq!(capture.batch, "B001"); + assert_eq!(capture.request_budget, 50); + assert_eq!(capture.max_bytes, 999); + assert!(capture.fresh); + assert_eq!(capture.reuse_capture.as_deref(), Some("C-123")); + assert!(capture.break_lock); +} + +#[test] +fn evidence_show_flags_are_typed() { + let cli = parse(&[ + "tranche", + "evidence", + "show", + "--capture", + "C-123", + "--source", + "S1", + "--start-byte", + "4", + "--length", + "9", + ]); + let Command::Evidence { command } = cli.command else { + panic!("expected an evidence command"); + }; + let Evidence::Show(show) = command else { + panic!("expected an evidence show command"); + }; + assert_eq!(show.capture.as_deref(), Some("C-123")); + assert_eq!(show.source.as_deref(), Some("S1")); + assert_eq!(show.start_byte, 4); + assert_eq!(show.length, 9); +} + +#[test] +fn the_transport_set_is_closed() { + let cli = parse(&["tranche", "fetch", "--transport", "gh"]); + let Command::Fetch(fetch) = cli.command else { + panic!("expected a fetch command"); + }; + assert_eq!(fetch.transport, Transport::Gh); +} + +#[test] +fn a_bare_invocation_is_a_usage_error() { + // Asking for nothing is answered with help, not with an operation; clap + // reports it as a display-help error and the binary exits non-zero. + for args in [ + vec!["tranche"], + vec!["tranche", "evidence"], + vec!["tranche", "--root", "."], + ] { + let error = Cli::try_parse_from(&args).expect_err("should ask for help"); + // `arg_required_else_help` and `subcommand_required` can each produce + // the help-with-usage outcome; both exit 2. + assert!( + matches!( + error.kind(), + clap::error::ErrorKind::MissingSubcommand + | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand + ), + "{args:?} produced {:?}", + error.kind() + ); + assert_eq!(error.exit_code(), 2, "{args:?}"); + } +} diff --git a/crates/tranche-core/Cargo.toml b/crates/tranche-core/Cargo.toml new file mode 100644 index 0000000..20387ac --- /dev/null +++ b/crates/tranche-core/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "tranche-core" +description = "Tranche core: report gate, pipeline domain and the read projection" +version.workspace = true +edition.workspace = true +authors.workspace = true +repository.workspace = true +license.workspace = true + +[dependencies] +serde = { workspace = true } +# `arbitrary_precision` is required, not an optimization: without it serde_json +# parses a float literal to the nearest f64 it can represent, which for values +# like 0.9400000000000001 is a *different* double than the one the stored report +# holds. Report bindings digest those numbers, so the difference makes every +# report read as foreign. +# +# `preserve_order` is required for the same class of reason. The stored artifacts +# keep insertion order, so `clusters.json` leads with the `security-review` +# meta-category that the pipeline deliberately puts first. A `Map` backed by a +# sorted tree would instead emit `agents-ai` first: the digest still matches, +# because `digest` sorts keys explicitly, so the divergence is invisible to every +# check except reading the file. +serde_json = { workspace = true, features = ["arbitrary_precision", "preserve_order"] } +regex = "1" +sha2 = "0.10" +# The Jev client is one HTTPS POST to a fixed endpoint. `reqwest` carries the TLS +# stack; `tokio` drives the retry backoff, which is the only async here. +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "blocking"] } +tokio = { version = "1", features = ["macros", "rt", "time"] } +tempfile = { workspace = true } +time = { version = "0.3", features = ["formatting"] } + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[dev-dependencies] +tempfile = { workspace = true } +libc = "0.2" + diff --git a/crates/tranche-core/examples/slice_fixture.rs b/crates/tranche-core/examples/slice_fixture.rs new file mode 100644 index 0000000..9ccdf59 --- /dev/null +++ b/crates/tranche-core/examples/slice_fixture.rs @@ -0,0 +1,193 @@ +//! Build a small, committed fixture from the local corpus. +//! +//! The full corpus is 111 MiB and must stay local, so the tests that compare +//! against the published artifacts cannot read it in CI. This cuts a slice +//! small enough to commit: a handful of PRs, the judgments and pair verdicts +//! that name them, and the artifacts rebuilt from them. +//! +//! Run from the repository root; the output is written under `tests/fixture/` +//! and is meant to be committed. Nothing here is run by `cargo test`. +//! +//! ```text +//! cargo run --release -p tranche-core --example slice_fixture -- 12 +//! ``` + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use tranche_core::domain::batch::{merge_batches, park_state, parked_payload}; +use tranche_core::domain::cluster::{cluster, render}; +use tranche_core::domain::dupe::current_pairs; +use tranche_core::domain::judge::{Judgment, current_judgments}; +use tranche_core::domain::pr::load_prs; +use tranche_core::report::{MODEL, REPOSITORY, Root}; +use tranche_core::util::{atomic_json, digest}; + +/// How many PRs the slice keeps, and how many of those must be in a group. +const DEFAULT_SIZE: usize = 12; + +fn main() { + let size: usize = std::env::args() + .nth(1) + .and_then(|value| value.parse().ok()) + .unwrap_or(DEFAULT_SIZE); + let root = Root::new(Path::new(".")); + let out = PathBuf::from("crates/tranche-core/tests/fixture"); + std::fs::create_dir_all(out.join("data/pages")).expect("fixture directories"); + std::fs::create_dir_all(out.join("out")).expect("fixture directories"); + + let corpus = load_prs(&root, REPOSITORY).expect("the local corpus loads"); + let judgments = current_judgments(&root, &corpus, REPOSITORY, MODEL, false).expect("judgments"); + let verdicts = + current_pairs(&root, &corpus, &judgments, REPOSITORY, MODEL, false).expect("verdicts"); + let full = cluster(&corpus, &judgments, &verdicts, REPOSITORY, MODEL, false); + + // Members of confirmed groups first: a slice of unrelated PRs would leave + // the group and park paths untested. + let mut wanted: Vec = Vec::new(); + for group in full.dupes["confirmed_groups"] + .as_array() + .into_iter() + .flatten() + { + for number in group + .as_array() + .into_iter() + .flatten() + .filter_map(|v| v.as_u64()) + { + if wanted.len() < size && !wanted.contains(&number) { + wanted.push(number); + } + } + } + let mut ordered: Vec = corpus.numbers().to_vec(); + ordered.sort_unstable(); + for number in ordered { + if wanted.len() >= size { + break; + } + if !wanted.contains(&number) { + wanted.push(number); + } + } + wanted.sort_unstable(); + + // The captured pages, keeping only the chosen PRs. The snapshot is the + // single-file form of membership, so slicing it is enough. + let page = slice_membership(&root, &wanted); + atomic_json(&out.join("data/pages/snapshot.json"), &page).expect("snapshot"); + + // The judgment and verdict logs, keeping only records about chosen PRs. + write_lines( + &root.judgments_path(), + &out.join("out/judgments.jsonl"), + &wanted, + true, + ); + write_lines( + &root.pairs_path(), + &out.join("out/pair_verdicts.jsonl"), + &wanted, + false, + ); + + // Rebuild every artifact from the slice, so the fixture's `out/` is exactly + // what this code produces for its inputs rather than copied bytes. + let sliced = Root::new(&out); + let prs = load_prs(&sliced, REPOSITORY).expect("the slice loads"); + let judgments: HashMap = + current_judgments(&sliced, &prs, REPOSITORY, MODEL, false).expect("slice judgments"); + let verdicts = + current_pairs(&sliced, &prs, &judgments, REPOSITORY, MODEL, false).expect("slice verdicts"); + let built = cluster(&prs, &judgments, &verdicts, REPOSITORY, MODEL, false); + + atomic_json(&out.join("out/clusters.json"), &built.clusters).expect("clusters"); + atomic_json(&out.join("out/dupes.json"), &built.dupes).expect("dupes"); + std::fs::write(out.join("out/tranches.md"), render(&built, REPOSITORY)).expect("report"); + atomic_json(&out.join("out/summary.json"), &built.summary).expect("summary"); + + let dupes_digest = digest(&built.dupes); + let batches = merge_batches(&built.dupes, &judgments, &prs, &dupes_digest, REPOSITORY) + .expect("the slice packs"); + let parks = park_state(&built.dupes, &judgments, &prs); + atomic_json(&out.join("out/batches.json"), &batches).expect("batches"); + atomic_json( + &out.join("out/parked.json"), + &parked_payload(&parks, &prs, &judgments, &dupes_digest, REPOSITORY), + ) + .expect("parked"); + + // Batches append to the report, as the command does. + let mut report = std::fs::read_to_string(out.join("out/tranches.md")).expect("report"); + report.push_str(&tranche_core::domain::batch::batch_plan_section(&batches)); + if !parks.is_empty() { + report.push_str(&tranche_core::domain::batch::park_section(&parks, &prs)); + } + std::fs::write(out.join("out/tranches.md"), report).expect("report"); + + println!( + "slice of {} PRs: {} judgments, {} verdicts, {} clusters bytes", + prs.len(), + judgments.len(), + verdicts.len(), + digest(&built.clusters).len() + ); + println!("wrote {}", out.display()); +} + +/// The membership snapshot reduced to the chosen PRs. +fn slice_membership(root: &Root, wanted: &[u64]) -> serde_json::Value { + let path = root.snapshot_path(); + let text = std::fs::read_to_string(&path).unwrap_or_else(|error| { + panic!( + "{}: {error}. The corpus keeps its pages as shards; join them first.", + path.display() + ) + }); + let value: serde_json::Value = serde_json::from_str(&text).expect("snapshot parses"); + let items: Vec = value["items"] + .as_array() + .expect("items") + .iter() + .filter(|item| { + item["number"] + .as_u64() + .is_some_and(|number| wanted.contains(&number)) + }) + .cloned() + .collect(); + // The snapshot is self-verifying: its digest covers exactly the items. + serde_json::json!({ + "version": value["version"], + "repo": value["repo"], + "items": items, + "digest": digest(&serde_json::Value::Array(items.clone())), + }) +} + +/// Reduce a JSON Lines log to records about the chosen PRs. +fn write_lines(source: &Path, destination: &Path, wanted: &[u64], single: bool) { + let text = std::fs::read_to_string(source) + .unwrap_or_else(|error| panic!("{}: {error}", source.display())); + let mut kept = String::new(); + for line in text.lines() { + let Ok(record) = serde_json::from_str::(line) else { + continue; + }; + let numbers: Vec = if single { + record["number"].as_u64().into_iter().collect() + } else { + [record["a"].as_u64(), record["b"].as_u64()] + .into_iter() + .flatten() + .collect() + }; + if numbers.is_empty() || !numbers.iter().all(|number| wanted.contains(number)) { + continue; + } + kept.push_str(line); + kept.push('\n'); + } + std::fs::write(destination, kept).expect("write"); +} diff --git a/crates/tranche-core/src/domain/batch/mod.rs b/crates/tranche-core/src/domain/batch/mod.rs new file mode 100644 index 0000000..f6579a6 --- /dev/null +++ b/crates/tranche-core/src/domain/batch/mod.rs @@ -0,0 +1,16 @@ +//! Pre-release batches and the park record. +//! +//! A batch claims exactly one thing: these PRs merge together. That claim is why +//! a draft, a PR without finished form or a PR without a current judgment must +//! never appear in one, and why a same-change group is atomic — splitting it +//! would leave the remaining members claimed twice or held entirely. + +pub mod pack; +pub mod packing; +pub mod park; +pub mod report_section; + +pub use pack::{BATCH_SIZE, batch_review_prompt, pr_activity}; +pub use packing::merge_batches; +pub use park::{PARK_UNBLOCK, park_counts, park_set, park_state, parked_payload, unblock_for}; +pub use report_section::{batch_plan_section, park_section}; diff --git a/crates/tranche-core/src/domain/batch/pack.rs b/crates/tranche-core/src/domain/batch/pack.rs new file mode 100644 index 0000000..8af3b0e --- /dev/null +++ b/crates/tranche-core/src/domain/batch/pack.rs @@ -0,0 +1,75 @@ +//! The size of a tranche, the activity a batch is ordered by, and the reviewer +//! prompt each batch carries. + +use serde_json::{Value, json}; + +use crate::domain::pr::{Pr, Prs}; + +/// PRs merged together as one tranche. +pub const BATCH_SIZE: usize = 5; + +/// Whether a PR's head has moved since it was judged, and how long it has been quiet. +/// +/// Head evidence is distinct from GitHub thread churn, including bots. A matching +/// recorded head establishes an idle lower bound at judgment time; an unjudged PR +/// has only its creation date as an age proxy, and `updated_at` is thread +/// metadata rather than priority. +pub fn pr_activity(pr: &Pr, record: Option<&Value>) -> Value { + let bound_head = record + .and_then(|record| record.get("head_sha")) + .and_then(Value::as_str); + let head_moved = bound_head + .zip(pr.head_sha.as_deref()) + .is_some_and(|(bound, current)| bound != current); + let matched = bound_head + .zip(pr.head_sha.as_deref()) + .is_some_and(|(bound, current)| bound == current); + let judged_at = record + .and_then(|record| record.get("judged_at")) + .and_then(Value::as_str); + let idle_since = if head_moved { + None + } else if matched { + judged_at.map(str::to_owned) + } else { + Some(pr.created.clone()) + }; + let basis = if head_moved || idle_since.is_none() { + "unknown" + } else if matched && judged_at.is_some() { + "judgment" + } else { + "creation" + }; + json!({ + "head_moved": head_moved, + "idle_since": idle_since, + "idle_basis": basis, + "thread_updated": pr.updated, + }) +} + +/// The reviewer prompt for one batch. +/// +/// Deterministic, self-contained text: it points at every PR of the batch and +/// demands one unified proposal rather than per-PR verdicts. +pub fn batch_review_prompt(members: &[u64], batch_id: &str, prs: &Prs) -> String { + let listed = members + .iter() + .filter_map(|number| prs.get(*number)) + .map(|pr| format!("- #{}: {} — {}", pr.number, pr.title, pr.url)) + .collect::>() + .join("\n"); + format!( + "You are reviewing Omarchy pre-release batch {batch_id} ({} PRs to be merged together as one tranche).\n\n\ + Pull requests in this batch:\n{listed}\n\n\ + Work through the batch methodically:\n\ + 1. Read every PR fully — description, diff, and review comments. For PRs Jev flagged as the same change, verify they truly overlap and identify the strongest implementation of each.\n\ + 2. Map dependencies between the PRs (shared files, ordering constraints, conflicts) and check each PR's CI status.\n\ + 3. Produce ONE unified proposal for the batch: what merges, in which order, what gets squashed or dropped, and why — as a single coherent plan, not per-PR verdicts.\n\ + 4. Verify the plan: does the combined result still build and pass tests? Any PR that cannot be verified stays out — say so explicitly.\n\ + 5. Deliver: (a) the unified proposal, (b) a step-by-step merge plan with exact commands, (c) risks with mitigations, (d) an explicit list of anything excluded and why.\n\n\ + Facts over plausibility: base every claim on the actual diffs and CI state, never on titles alone. You are proposing — the human decides.", + members.len() + ) +} diff --git a/crates/tranche-core/src/domain/batch/packing.rs b/crates/tranche-core/src/domain/batch/packing.rs new file mode 100644 index 0000000..0847c4b --- /dev/null +++ b/crates/tranche-core/src/domain/batch/packing.rs @@ -0,0 +1,256 @@ +//! Packing PRs into security-first batches of five. +//! +//! A batch claims exactly one thing: these PRs merge together as one tranche. +//! That claim is why a parked PR never appears in one, and why a same-change +//! group is atomic — pulling out one member would leave the rest of the group +//! claimed twice or held entirely. + +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet}; + +use super::pack::{BATCH_SIZE, batch_review_prompt, pr_activity}; +use super::park::park_state; +use crate::domain::cluster::SECURITY_PRIORITY; +use crate::domain::judge::Judgment; +use crate::domain::pr::Prs; + +/// Pack PRs into security-first batches of five, model-determined. +pub fn merge_batches( + dupes: &Value, + judgments: &HashMap, + prs: &Prs, + dupes_digest: &str, + repository: &str, +) -> Result { + let parks = park_state(dupes, judgments, prs); + + let security_count = |members: &[u64]| -> u64 { + members + .iter() + .filter(|number| { + judgments + .get(number) + .and_then(|judgment| judgment.metric("security_flag", "noul")) + .unwrap_or(0.0) + >= SECURITY_PRIORITY + }) + .count() as u64 + }; + let unit_stats = |members: &[u64]| -> (u64, Option, String) { + let risks: Vec = members + .iter() + .filter_map(|number| judgments.get(number)) + .filter_map(|judgment| judgment.metric("risk", "score")) + .collect(); + let average = if risks.is_empty() { + None + } else { + let mean = risks.iter().sum::() / risks.len() as f64; + Some((mean * 100.0).round() / 100.0) + }; + let created = members + .iter() + .filter_map(|number| prs.get(*number)) + .map(|pr| pr.created.clone()) + .min() + .unwrap_or_default(); + (security_count(members), average, created) + }; + + let mut grouped: HashSet = HashSet::new(); + let mut units: Vec = Vec::new(); + for group in dupes + .get("confirmed_groups") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default() + { + let members: Vec = group + .as_array() + .map(|items| items.iter().filter_map(Value::as_u64).collect()) + .unwrap_or_default(); + grouped.extend(members.iter().copied()); + if members.iter().any(|member| parks.contains_key(member)) { + continue; // the whole atomic unit waits; it re-enters together + } + let (security, risk, created) = unit_stats(&members); + units.push(json!({ + "members": members, "same_change": true, + "security": security, "risk": risk, "created": created, + })); + } + let mut excluded: HashSet = HashSet::new(); + for group in dupes + .get("review_groups") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default() + { + if let Some(members) = group.get("members").and_then(Value::as_array) { + excluded.extend(members.iter().filter_map(Value::as_u64)); + } + } + let mut ordered: Vec = prs.numbers().to_vec(); + ordered.sort_unstable(); + for number in ordered { + if grouped.contains(&number) || excluded.contains(&number) || parks.contains_key(&number) { + continue; + } + let (security, risk, created) = unit_stats(&[number]); + units.push(json!({ + "members": [number], "same_change": false, + "security": security, "risk": risk, "created": created, + })); + } + + // Security outranks every risk band; within a band, the longest evidenced + // quiet head goes first. The newest bound in an atomic unit is its floor. + // + // Every component is ascending to match the key the ordering sorts by, so the + // first field is negated security rather than reversed comparison. + let priority = |unit: &Value| -> (i64, i64, bool, String, String, u64) { + let members: Vec = unit + .get("members") + .and_then(Value::as_array) + .map(|items| items.iter().filter_map(Value::as_u64).collect()) + .unwrap_or_default(); + let activities: Vec = members + .iter() + .filter_map(|number| prs.get(*number).map(|pr| (pr, *number))) + .map(|(pr, number)| { + pr_activity(pr, judgments.get(&number).map(|judgment| &judgment.record)) + }) + .collect(); + let moving = activities.iter().any(|activity| { + activity + .get("head_moved") + .and_then(Value::as_bool) + .unwrap_or(false) + }); + let idle = activities + .iter() + .filter_map(|activity| { + activity + .get("idle_since") + .and_then(Value::as_str) + .map(str::to_owned) + }) + .max() + .unwrap_or_else(|| "9999".to_owned()); + let risk = unit.get("risk").and_then(Value::as_f64); + let band = match risk { + None => 3, + Some(value) if value <= 1.5 => 0, + Some(value) if value <= 2.5 => 1, + Some(_) => 2, + }; + let security = unit.get("security").and_then(Value::as_i64).unwrap_or(0); + let created = unit + .get("created") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + ( + -security, + band, + moving, + idle, + created, + members.first().copied().unwrap_or(0), + ) + }; + units.sort_by_key(priority); + + let mut packed: Vec> = Vec::new(); + let mut current: Vec = Vec::new(); + for unit in &units { + let members: Vec = unit + .get("members") + .and_then(Value::as_array) + .map(|items| items.iter().filter_map(Value::as_u64).collect()) + .unwrap_or_default(); + if !current.is_empty() && current.len() + members.len() > BATCH_SIZE { + packed.push(std::mem::take(&mut current)); + } + current.extend(members); + } + if !current.is_empty() { + packed.push(current); + } + + if packed + .iter() + .flatten() + .any(|number| parks.contains_key(number)) + { + return Err( + "internal error: a parked PR entered a batch (issue #8 gate failed)".to_owned(), + ); + } + + let mut batches = Vec::new(); + for (index, members) in packed.iter().enumerate() { + let ordinal = index + 1; + let id = format!("B{ordinal:03}"); + let (security, average_risk, created) = unit_stats(members); + let member_set: HashSet = members.iter().copied().collect(); + let groups = units + .iter() + .filter(|unit| unit.get("same_change").and_then(Value::as_bool) == Some(true)) + .filter(|unit| { + unit.get("members") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(Value::as_u64) + .all(|number| member_set.contains(&number)) + }) + .unwrap_or(false) + }) + .count(); + batches.push(json!({ + "ordinal": ordinal, + "id": id, + "members": members, + "count": members.len(), + "target": "merged together as one tranche", + "same_change_groups": groups, + "security_members": security, + "average_risk": average_risk, + "created": created, + "review_prompt": batch_review_prompt(members, &format!("B{ordinal:03}"), prs), + })); + } + let security_batches = batches + .iter() + .filter(|batch| { + batch + .get("security_members") + .and_then(Value::as_u64) + .unwrap_or(0) + > 0 + }) + .count(); + let same_change_groups: u64 = batches + .iter() + .map(|batch| { + batch + .get("same_change_groups") + .and_then(Value::as_u64) + .unwrap_or(0) + }) + .sum(); + Ok(json!({ + "format_version": 3, + "repo": repository, + "dupes_digest": dupes_digest, + "batch_size": BATCH_SIZE, + "meaning": "A batch is 5 PRs merged together as one tranche (issue #4). Jev determines the composition: same_change groups are atomic and combine into ONE pull request inside their batch. Batches are disjoint: every PR belongs to at most one batch. Ordered security-first, then risk band and evidenced idle lower bound. Parked PRs are excluded before packing (issue #8). Model-suggested, not verified safe to merge.", + "batches": batches, + "security_batches": security_batches, + "same_change_groups": same_change_groups, + "excluded_review_prs": excluded.len(), + "parked_prs": parks.len(), + })) +} diff --git a/crates/tranche-core/src/domain/batch/park.rs b/crates/tranche-core/src/domain/batch/park.rs new file mode 100644 index 0000000..5c42533 --- /dev/null +++ b/crates/tranche-core/src/domain/batch/park.rs @@ -0,0 +1,171 @@ +//! Park decisions: a hold with a named unblock path, never a close. +//! +//! Parking is what keeps a batch's one claim — that these PRs merge together — +//! true. Reasons come only from facts the pipeline already holds: the draft bit, +//! the finished-form score, the judgment's freshness. One predicate serves every +//! consumer (batches, parked.json, the workbench and MCP), because a second copy +//! would let them disagree about which PRs are held. + +use serde_json::{Map, Value, json}; +use std::collections::{BTreeMap, HashMap}; + +use super::super::judge::Judgment; +use super::super::pr::{Pr, Prs}; + +/// Every park reason, with the action that clears it. +/// +/// A parked PR re-enters automatically: the author pushes, the judgment +/// re-binds, the next refresh re-packs. Closing stays a maintainer decision. +pub const PARK_UNBLOCK: [(&str, &str); 4] = [ + ( + "draft", + "Author marks the pull request ready for review; the next fetch recaptures it and the next batches run re-packs it.", + ), + ( + "finished_form", + "Author adds the missing description or QA evidence; judge --resume re-binds the judgment and the PR re-enters on the next refresh.", + ), + ( + "unjudged_or_stale", + "Run judge --resume (or refresh) to restore a current judgment; the PR re-enters on the next batches run.", + ), + ( + "same_change_hold", + "Held with its same_change group: atomic units are never split, so the group re-enters together when every member clears its own park reason.", + ), +]; + +/// The action that clears one reason, for the human report. +pub fn unblock_for(reason: &str) -> &'static str { + PARK_UNBLOCK + .iter() + .find(|(name, _)| *name == reason) + .map(|(_, text)| *text) + .unwrap_or("") +} + +/// A PR's own park reasons: the draft bit, the finished-form score, freshness. +/// +/// A finished form just above 1 is not parked; a missing judgment parks under +/// its own reason rather than being read as a low score. +pub fn park_set(prs: &Prs, judgments: &HashMap) -> BTreeMap> { + let mut parks = BTreeMap::new(); + let mut ordered: Vec<&Pr> = prs.iter().collect(); + ordered.sort_by_key(|pr| pr.number); + for pr in ordered { + let mut reasons = Vec::new(); + if pr.draft { + reasons.push("draft".to_owned()); + } + match judgments.get(&pr.number) { + None => reasons.push("unjudged_or_stale".to_owned()), + Some(judgment) => { + if judgment + .metric("finished_form", "score") + .is_some_and(|value| value <= 1.0) + { + reasons.push("finished_form".to_owned()); + } + } + } + if !reasons.is_empty() { + parks.insert(pr.number, reasons); + } + } + parks +} + +/// One park predicate for every consumer. +/// +/// A PR's own reasons plus `same_change_hold` for every member of a confirmed +/// group that waits for a parked member. Atomic units are never split: pulling +/// one member out would leave the rest of the group claimed twice or held +/// entirely. +pub fn park_state( + dupes: &Value, + judgments: &HashMap, + prs: &Prs, +) -> BTreeMap> { + let mut parks = park_set(prs, judgments); + let groups = dupes + .get("confirmed_groups") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + for group in groups { + let members: Vec = group + .as_array() + .map(|items| items.iter().filter_map(Value::as_u64).collect()) + .unwrap_or_default(); + if members.iter().any(|member| parks.contains_key(member)) { + for member in members { + let entry = parks.entry(member).or_default(); + if !entry.iter().any(|reason| reason == "same_change_hold") { + entry.push("same_change_hold".to_owned()); + } + } + } + } + parks +} + +/// The first-class park record. +/// +/// Membership never replaces the PR's own category, exactly as the security +/// meta-category does not. +pub fn parked_payload( + parks: &BTreeMap>, + prs: &Prs, + judgments: &HashMap, + dupes_digest: &str, + repository: &str, +) -> Value { + let members: Vec = parks + .iter() + .map(|(number, reasons)| { + let pr = prs.get(*number); + let unblock = reasons + .iter() + .map(|reason| unblock_for(reason)) + .collect::>() + .join(" "); + json!({ + "number": number, + "title": pr.map(|pr| pr.title.clone()).unwrap_or_default(), + "author": pr.map(|pr| pr.author.clone()).unwrap_or_default(), + "reasons": reasons, + "unblock": unblock, + "head_sha": pr.and_then(|pr| pr.head_sha.clone()), + "url": pr.map(|pr| pr.url.clone()), + "created": pr.map(|pr| pr.created.clone()).unwrap_or_default(), + "security_flag": judgments.get(number).and_then(|j| j.metric("security_flag", "noul")), + }) + }) + .collect(); + json!({ + "format_version": 1, + "repo": repository, + "dupes_digest": dupes_digest, + "parked": members.len(), + "meaning": "Parked before batching (issue #8): drafts, PRs without finished form, PRs without a current judgment, and same_change groups holding for a parked member. A hold with a named unblock path, never a close; re-entry is automatic when the reason clears.", + "members": members, + }) +} + +/// Park counts by reason, for the human report. +pub fn park_counts(parks: &BTreeMap>) -> Map { + let mut counts = Map::new(); + for reason in [ + "draft", + "finished_form", + "unjudged_or_stale", + "same_change_hold", + ] { + let total = parks + .values() + .filter(|reasons| reasons.iter().any(|value| value == reason)) + .count(); + counts.insert(reason.to_owned(), json!(total)); + } + counts +} diff --git a/crates/tranche-core/src/domain/batch/report_section.rs b/crates/tranche-core/src/domain/batch/report_section.rs new file mode 100644 index 0000000..272b65b --- /dev/null +++ b/crates/tranche-core/src/domain/batch/report_section.rs @@ -0,0 +1,190 @@ +//! The batch plan and park record as written into the published report. +//! +//! These are the human-readable half of the same facts the JSON files carry, so +//! they read the packed value rather than recomputing anything. + +use serde_json::Value; +use std::collections::BTreeMap; + +use super::super::pr::Prs; +use super::pack::BATCH_SIZE; +use super::park::unblock_for; + +/// The batch-plan section appended to the published report. +pub fn batch_plan_section(batches: &Value) -> String { + let list = batches + .get("batches") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let batch_size = batches + .get("batch_size") + .and_then(Value::as_u64) + .unwrap_or(BATCH_SIZE as u64); + let mut lines = vec![ + String::new(), + "# Suggested pre-release batches (issue #4)".to_owned(), + String::new(), + format!("A batch is **{batch_size} PRs merged together as one tranche**. Jev determines"), + "the composition: model-consistent same_change groups are atomic — their PRs combine into" + .to_owned(), + "ONE pull request inside the batch. Batches are disjoint (every PR is in at most one" + .to_owned(), + "batch); review groups are excluded on purpose. Ordered security-first, then".to_owned(), + "risk band and evidenced head idle time. Model-suggested, never verified safe to merge." + .to_owned(), + String::new(), + format!( + "Batches: {} · security-first batches: {} · same-change groups: {} · review-group PRs excluded: {}.", + list.len(), + batches + .get("security_batches") + .and_then(Value::as_u64) + .unwrap_or(0), + batches + .get("same_change_groups") + .and_then(Value::as_u64) + .unwrap_or(0), + batches + .get("excluded_review_prs") + .and_then(Value::as_u64) + .unwrap_or(0), + ), + String::new(), + ]; + if !list.is_empty() { + lines.push("| Batch | Size | Security | Avg risk | Groups | Members |".to_owned()); + lines.push("|---|---|---|---|---|---|".to_owned()); + for batch in &list { + let members = batch + .get("members") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(Value::as_u64) + .map(|number| format!("#{number}")) + .collect::>() + .join(" ") + }) + .unwrap_or_default(); + let risk = match batch.get("average_risk").and_then(Value::as_f64) { + None => "unknown".to_owned(), + Some(value) => format!("{value:.1}"), + }; + let security = batch + .get("security_members") + .and_then(Value::as_u64) + .filter(|value| *value > 0) + .map(|value| value.to_string()) + .unwrap_or_else(|| "—".to_owned()); + let groups = batch + .get("same_change_groups") + .and_then(Value::as_u64) + .filter(|value| *value > 0) + .map(|value| value.to_string()) + .unwrap_or_else(|| "—".to_owned()); + lines.push(format!( + "| {} | {} | {} | {} | {} | {} |", + batch.get("id").and_then(Value::as_str).unwrap_or("?"), + batch.get("count").and_then(Value::as_u64).unwrap_or(0), + security, + risk, + groups, + members, + )); + } + lines.push(String::new()); + lines.push("## Reviewer agent prompts".to_owned()); + lines.push(String::new()); + lines.push( + "Copy-paste a prompt into an agent to start a thorough, methodical review that" + .to_owned(), + ); + lines.push("produces one unified proposal + merge plan for the batch.".to_owned()); + lines.push(String::new()); + for batch in &list { + lines.push(format!( + "### {}", + batch.get("id").and_then(Value::as_str).unwrap_or("?") + )); + lines.push(String::new()); + lines.push("```".to_owned()); + lines.push( + batch + .get("review_prompt") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(), + ); + lines.push("```".to_owned()); + lines.push(String::new()); + } + } + trimmed(lines) +} + +/// The park-record section appended to the published report. +pub fn park_section(parks: &BTreeMap>, prs: &Prs) -> String { + let count = |reason: &str| { + parks + .values() + .filter(|r| r.iter().any(|r| r == reason)) + .count() + }; + let mut lines = vec![ + String::new(), + "# Parked before batching (issue #8)".to_owned(), + String::new(), + format!( + "{} PRs are parked: drafts, PRs without finished form, PRs without a", + parks.len() + ), + "current judgment, and same_change groups holding for a parked member. Park is a" + .to_owned(), + "**hold with a named unblock path, never a close** — re-entry is automatic when the" + .to_owned(), + "reason clears and the next refresh re-packs. No batch lists a parked PR.".to_owned(), + String::new(), + format!( + "Reasons: draft {} · finished_form {} · unjudged_or_stale {} · same_change_hold {}.", + count("draft"), + count("finished_form"), + count("unjudged_or_stale"), + count("same_change_hold"), + ), + String::new(), + "| PR | Reasons | Unblocked by |".to_owned(), + "|---|---|---|".to_owned(), + ]; + for (number, reasons) in parks { + let unblock = reasons + .iter() + .map(|reason| unblock_for(reason)) + .collect::>() + .join(" "); + lines.push(format!( + "| #{number} | {} | {} |", + reasons.join(", "), + unblock + )); + } + let _ = prs; + lines.push(String::new()); + lines.push( + "Parked does not remove a security-flagged PR from the security meta-category;".to_owned(), + ); + lines.push("it only removes it from merge batches. Full record: out/parked.json.".to_owned()); + lines.push(String::new()); + trimmed(lines) +} + +/// Join lines, trailing newline only. +fn trimmed(lines: Vec) -> String { + let mut section = lines.join("\n"); + while section.ends_with('\n') { + section.pop(); + } + section.push('\n'); + section +} diff --git a/crates/tranche-core/src/domain/cluster/binding.rs b/crates/tranche-core/src/domain/cluster/binding.rs new file mode 100644 index 0000000..9d05300 --- /dev/null +++ b/crates/tranche-core/src/domain/cluster/binding.rs @@ -0,0 +1,53 @@ +//! The binding that identifies one report. +//! +//! This is what makes a report a specific observation rather than any report: it +//! digests the sources, the judgments, the pairs and the question policy, so a +//! stored report that does not match is refused rather than served. The key +//! order is the numeric one, because this map is keyed by PR number as an +//! integer. + +use serde_json::{Map, Value, json}; +use std::collections::{BTreeMap, HashMap}; + +use crate::domain::judge::{BINDING_VERSION, Judgment}; +use crate::domain::pr::Prs; +use crate::domain::questions::{judge_questions, pair_questions}; + +/// The binding over the whole report: sources, judgments, pairs and policy. +/// +/// The maps here are keyed by PR number as an *integer*, so their key +/// order is numeric, not lexicographic. +pub fn report_binding( + prs: &Prs, + judgments: &HashMap, + verdicts: &[Value], + repository: &str, + model: &str, +) -> String { + let sources: Map = prs + .iter() + .map(|pr| { + ( + pr.number.to_string(), + json!({ + "source": pr.source_digest, + "evidence": pr.evidence_digest, + "references": pr.ref_digest, + }), + ) + }) + .collect(); + let ordered: BTreeMap = judgments + .iter() + .map(|(number, judgment)| (number.to_string(), &judgment.record)) + .collect(); + crate::util::digest_numeric_keys(&json!({ + "version": BINDING_VERSION, + "repo": repository, + "sources": sources, + "judgments": ordered, + "pairs": verdicts, + "questions": [judge_questions(), pair_questions()], + "model": model, + })) +} diff --git a/crates/tranche-core/src/domain/cluster/groups.rs b/crates/tranche-core/src/domain/cluster/groups.rs new file mode 100644 index 0000000..fb0f763 --- /dev/null +++ b/crates/tranche-core/src/domain/cluster/groups.rs @@ -0,0 +1,196 @@ +//! Pair verdicts to duplicate groups. +//! +//! Connectivity proposes a group; every internal relationship stays visible, so +//! a group with weak or contradictory internal evidence is reported for review +//! rather than presented as a confirmed duplicate set. + +use serde_json::{Value, json}; +use std::collections::{BTreeMap, HashMap}; + +use super::predicates::SECURITY_PRIORITY; +use crate::domain::dupe::p_same; + +/// The probability band the pipeline treats as a confirmed same-change pair. +const ACCEPT_THRESHOLD: f64 = 0.65; +const REJECT_THRESHOLD: f64 = 0.35; + +/// What a stored verdict means once its probability and label are read together. +/// +/// A verdict and a probability can disagree — the model can label two PRs +/// `same_change` while scoring them below the reject band — and that +/// self-contradiction is a real state, not a missing one. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Classification { + Same, + Different, + Uncertain, + Contradictory, + Malformed, +} + +impl Classification { + pub fn as_str(self) -> &'static str { + match self { + Self::Same => "same", + Self::Different => "different", + Self::Uncertain => "uncertain", + Self::Contradictory => "contradictory", + Self::Malformed => "malformed", + } + } +} + +/// Separate genuine contradictions from the human-review threshold band. +pub fn pair_classification(pair: &Value) -> Classification { + let Some(probability) = p_same(pair) else { + return Classification::Malformed; + }; + match pair.get("verdict").and_then(Value::as_str) { + Some("same_change") => { + if probability >= ACCEPT_THRESHOLD { + Classification::Same + } else if probability < REJECT_THRESHOLD { + Classification::Contradictory + } else { + Classification::Uncertain + } + } + Some("related_but_different") | Some("unrelated") => { + if probability < REJECT_THRESHOLD { + Classification::Different + } else if probability >= ACCEPT_THRESHOLD { + Classification::Contradictory + } else { + Classification::Uncertain + } + } + _ => Classification::Malformed, + } +} + +pub fn accepted_pair(pair: &Value) -> bool { + pair_classification(pair) == Classification::Same +} + +/// The pair identity a verdict belongs to, when both sides are usable. +fn pair_of(verdict: &Value) -> Option<(u64, u64)> { + let a = verdict.get("a").and_then(Value::as_u64)?; + let b = verdict.get("b").and_then(Value::as_u64)?; + Some((a.min(b), a.max(b))) +} + +/// Connectivity proposes groups; every internal relationship stays visible. +pub fn duplicate_groups(verdicts: &[Value]) -> (Vec>, Vec) { + let mut indexed: HashMap<(u64, u64), &Value> = HashMap::new(); + // The published group order follows the verdict order, not the order of a + // hash map: `dupes.json` is digested, so this is a compatibility surface. + let mut ordered: Vec<(u64, u64)> = Vec::new(); + for verdict in verdicts { + if let Some(pair) = pair_of(verdict) + && indexed.insert(pair, verdict).is_none() + { + ordered.push(pair); + } + } + let mut dsu = Dsu::default(); + for (a, b) in ordered { + if indexed + .get(&(a, b)) + .is_some_and(|verdict| accepted_pair(verdict)) + { + dsu.union(a, b); + } + } + + let mut connected: BTreeMap> = BTreeMap::new(); + let mut roots: Vec = dsu.parent_keys(); + roots.sort_unstable(); + for number in roots { + connected.entry(dsu.find(number)).or_default().push(number); + } + let mut candidates: Vec> = connected.into_values().filter(|g| g.len() >= 2).collect(); + // Largest first, then by member order, so the report is deterministic. + candidates.sort_by(|left, right| right.len().cmp(&left.len()).then_with(|| left.cmp(right))); + + let mut consistent = Vec::new(); + let mut review = Vec::new(); + for members in candidates { + let mut conflicts = Vec::new(); + let mut uncertain = Vec::new(); + let mut missing = Vec::new(); + let mut unbound = false; + for (index, a) in members.iter().enumerate() { + for b in &members[index + 1..] { + let Some(pair) = indexed.get(&(*a.min(b), *a.max(b))) else { + missing.push(json!([a, b])); + continue; + }; + if pair.get("freshness").and_then(Value::as_str) != Some("current") { + unbound = true; + } + if accepted_pair(pair) { + continue; + } + let classification = pair_classification(pair); + let diagnostic = json!({ + "a": a, "b": b, + "verdict": pair.get("verdict").cloned().unwrap_or(Value::Null), + "p_same": p_same(pair), + "classification": classification.as_str(), + }); + // Strong difference evidence conflicts with the proposed group; a + // self-contradictory model response also needs relationship review. + match classification { + Classification::Different | Classification::Contradictory => { + conflicts.push(diagnostic) + } + _ => uncertain.push(diagnostic), + } + } + } + if !conflicts.is_empty() || !uncertain.is_empty() || !missing.is_empty() || unbound { + review.push(json!({ + "members": members, + "conflicting_pairs": conflicts, + "uncertain_pairs": uncertain, + "missing_pairs": missing, + "unbound_evidence": unbound, + })); + } else { + consistent.push(members); + } + } + (consistent, review) +} + +/// Disjoint-set union over PR numbers, kept as a sorted map so a group's +/// iteration order is the member order and not a hash order. +#[derive(Default)] +struct Dsu { + parent: BTreeMap, +} + +impl Dsu { + fn find(&mut self, node: u64) -> u64 { + let entry = *self.parent.entry(node).or_insert(node); + if entry == node { + return node; + } + let root = self.find(entry); + self.parent.insert(node, root); + root + } + + fn union(&mut self, a: u64, b: u64) { + let (ra, rb) = (self.find(a), self.find(b)); + if ra != rb { + self.parent.insert(rb, ra); + } + } + + fn parent_keys(&self) -> Vec { + self.parent.keys().copied().collect() + } +} + +const _: f64 = SECURITY_PRIORITY; diff --git a/crates/tranche-core/src/domain/cluster/mod.rs b/crates/tranche-core/src/domain/cluster/mod.rs new file mode 100644 index 0000000..6cc1fed --- /dev/null +++ b/crates/tranche-core/src/domain/cluster/mod.rs @@ -0,0 +1,21 @@ +//! Clustering: duplicate groups, review candidates and the summary. +//! +//! The predicates here are the pipeline's judgement of its own output, so they +//! are written once and read by everything: `cluster` publishes them, the report +//! gate recomputes them, and the batch packer consumes them. A second copy would +//! let the workbench, the MCP server and the batches disagree. + +pub mod binding; +pub mod groups; +pub mod predicates; +pub mod render; +pub mod report; +pub mod style; + +pub use binding::report_binding; +pub use groups::{Classification, accepted_pair, duplicate_groups, pair_classification}; +pub use predicates::{ + SECURITY_PRIORITY, escalated, review_candidate, risk_band, security_priority, +}; +pub use render::render; +pub use report::{Clustered, cluster}; diff --git a/crates/tranche-core/src/domain/cluster/predicates.rs b/crates/tranche-core/src/domain/cluster/predicates.rs new file mode 100644 index 0000000..c6944e9 --- /dev/null +++ b/crates/tranche-core/src/domain/cluster/predicates.rs @@ -0,0 +1,70 @@ +//! The predicates that decide what a report recommends. +//! +//! These read model answers, never raw text, and every one of them treats an +//! unknown as unknown: a missing score is never coerced into a low one. + +use crate::domain::judge::Judgment; +use crate::domain::pr::Pr; +use std::collections::HashSet; + +/// The probability at or above which security is a top-priority meta-category. +pub const SECURITY_PRIORITY: f64 = 0.5; + +/// True when a PR belongs in the review-candidate tranches. +/// +/// Every input must be known and current: a stale judgment, an unusable answer +/// or a draft all disqualify, because a candidate that cannot be verified is not +/// a candidate. +pub fn review_candidate(pr: &Pr, judgment: &Judgment, grouped: &HashSet) -> bool { + let risk = judgment.metric("risk", "score"); + let finished = judgment.metric("finished_form", "score"); + let fix = judgment.metric("is_fix", "noul"); + let security = judgment.metric("security_flag", "noul"); + let effort = judgment.metric("review_effort", "score"); + if judgment.freshness() != "current" + || !crate::domain::judge::reusable_judgment(judgment) + || pr.draft + || grouped.contains(&pr.number) + || risk.is_none() + || finished.is_none() + || fix.is_none() + || security.is_none() + || effort.is_none() + { + return false; + } + let (risk, finished, fix, security) = ( + risk.unwrap_or_default(), + finished.unwrap_or_default(), + fix.unwrap_or_default(), + security.unwrap_or_default(), + ); + risk <= 1.5 && finished >= 1.8 && fix >= 0.6 && security < 0.5 +} + +/// True when risk or security warrants human escalation. +pub fn escalated(judgment: &Judgment) -> bool { + let risk = judgment.metric("risk", "score"); + let security = judgment.metric("security_flag", "noul"); + risk.is_some_and(|value| value >= 3.0) || security.is_some_and(|value| value >= 0.5) +} + +/// A cross-cutting meta-category ranked above every other category. +/// +/// Membership uses the same bar as senior escalation; unlike a category choice +/// it never replaces the PR's own area. Unknown stays unknown. +pub fn security_priority(judgment: &Judgment) -> bool { + judgment + .metric("security_flag", "noul") + .is_some_and(|value| value >= SECURITY_PRIORITY) +} + +/// The risk band a PR is filed under. +pub fn risk_band(risk: Option) -> &'static str { + match risk { + None => "unknown", + Some(value) if value <= 1.5 => "low", + Some(value) if value <= 2.5 => "core", + Some(_) => "danger", + } +} diff --git a/crates/tranche-core/src/domain/cluster/render.rs b/crates/tranche-core/src/domain/cluster/render.rs new file mode 100644 index 0000000..e3a7993 --- /dev/null +++ b/crates/tranche-core/src/domain/cluster/render.rs @@ -0,0 +1,196 @@ +//! The human report: `out/tranches.md`. +//! +//! Section order, wording and table layout follow the published report, because +//! the published file is what a maintainer reads and diffs. The JSON artifacts +//! are the machine contract; this is the prose that goes with them. + +use serde_json::Value; + +use super::SECURITY_PRIORITY; +use super::style::{cell, number, one_decimal, spaced_json, text, two_decimals}; + +/// The candidate table header, exactly as the published report writes it. +const CANDIDATE_TABLE: &str = "| PR | Title | Author | Model finished | Model effort | Model fix |\n\ + |---|---|---|---|---|---|"; + +/// Render the whole report. +pub fn render(built: &super::Clustered, repository: &str) -> String { + let summary = &built.summary; + let dupes = &built.dupes; + let confirmed = dupes["confirmed_groups"] + .as_array() + .cloned() + .unwrap_or_default(); + let review = dupes["review_groups"] + .as_array() + .cloned() + .unwrap_or_default(); + let uncertain = dupes["uncertain_pairs"] + .as_array() + .cloned() + .unwrap_or_default(); + + let mut lines = vec![ + "# Tranche — PR review candidates".to_owned(), + String::new(), + format!( + "Corpus: {} observed open PRs; {} matching judgments; {} unjudged/stale; {} unbound legacy judgments.", + summary["prs_in_corpus"], summary["judged"], summary["unjudged_or_stale"], + summary["unbound_judgments"], + ), + format!( + "Review candidates: {}. Model-consistent groups: {}. Groups needing relationship review: {}. Security-priority items: {} (meta-category, reviewed first).", + summary["ready_prs"], confirmed.len(), review.len(), summary["security_priority"], + ), + String::new(), + "Evidence: titles and shortened descriptions (1200 characters per PR; 400 per pair). \ + Diffstat is unknown unless captured input supplies it. Patches, CI, reproductions, \ + fix coverage and security have not been verified. Model scores are suggestions, \ + not calibrated guarantees or approval to merge/close. Pagination records an observation, not a point-in-time GitHub snapshot." + .to_owned(), + String::new(), + ]; + if summary["allow_unbound"].as_bool() == Some(true) { + lines.push( + "LEGACY INSPECTION: unbound judgments cannot establish freshness or enter review-candidate tranches." + .to_owned(), + ); + lines.push(String::new()); + } + + // Security ranks above every category. + if !built.security_review.is_empty() { + lines.push("## Security review — top priority (meta-category)".to_owned()); + lines.push(String::new()); + lines.push( + "These PRs touch credentials, remote code execution, sudo/permissions, network" + .to_owned(), + ); + lines.push( + format!( + "exposure or crypto material (model probability ≥ {SECURITY_PRIORITY}). Review before any category batch." + ), + ); + lines.push(String::new()); + lines.push(CANDIDATE_TABLE.to_owned()); + lines.extend(built.security_review.iter().map(candidate_row)); + lines.push(String::new()); + } + + for (category, items) in &built.tranches { + lines.push(format!( + "## Review candidates: {category} — {} PRs", + items.len() + )); + lines.push(String::new()); + lines.push(CANDIDATE_TABLE.to_owned()); + lines.extend(items.iter().map(candidate_row)); + lines.push(String::new()); + } + + lines.extend(group_section( + "Model-consistent candidate groups — verify fix coverage; no survivor selected", + &confirmed, + )); + lines.extend(group_section( + "Candidate groups needing relationship review", + &review, + )); + + if !uncertain.is_empty() { + lines.push("## Uncertain pairs — human comparison needed".to_owned()); + lines.push(String::new()); + for pair in &uncertain { + lines.push(format!( + "- #{} ↔ #{}: P(same)={}; verdict={}; {}", + pair["a"], + pair["b"], + number(&pair["p_same"]), + pair["verdict"].as_str().unwrap_or_default(), + pair["classification"].as_str().unwrap_or_default(), + )); + } + lines.push(String::new()); + } + + lines.extend(number_section( + "Escalate for risk/security review", + &built.escalate, + )); + lines.extend(number_section( + "Possible author follow-up — verify before requesting changes", + &built.follow_up, + )); + + let _ = repository; + // The report joins a line list whose last element is empty, so it ends + // with exactly one newline. The blank line before the appended plan comes + // from the plan section, not from here — adding one here shifts every + // subsequent line of the published file. + lines.join("\n") +} + +/// One candidate row. +fn candidate_row(item: &Value) -> String { + let title: String = text(&item["title"]).chars().take(80).collect(); + format!( + "| [#{}]({}) | {} | {} | {} | {} | {} |", + item["number"], + text(&item["url"]), + title, + text(&item["author"]), + one_decimal(item["finished_form"].as_f64()), + one_decimal(item["review_effort"].as_f64()), + two_decimals(item["is_fix"].as_f64()), + ) +} + +/// Group lists: members, then whatever evidence keeps a group out of the +/// confirmed set. +fn group_section(label: &str, groups: &[Value]) -> Vec { + if groups.is_empty() { + return Vec::new(); + } + let mut lines = vec![format!("## {label}"), String::new()]; + for group in groups { + let members: Vec = match group.get("members") { + Some(_) => group["members"].as_array().cloned().unwrap_or_default(), + None => group.as_array().cloned().unwrap_or_default(), + } + .iter() + .filter_map(Value::as_u64) + .map(|number| format!("#{number}")) + .collect(); + lines.push(format!("- {}", members.join(", "))); + if group.is_object() { + for field in ["conflicting_pairs", "uncertain_pairs", "missing_pairs"] { + if group[field] + .as_array() + .is_some_and(|items| !items.is_empty()) + { + lines.push(format!(" - {field}: {}", spaced_json(&group[field]))); + } + } + if group["unbound_evidence"].as_bool() == Some(true) { + lines.push(" - Unbound legacy evidence; revisions cannot be checked.".to_owned()); + } + } + } + lines.push(String::new()); + lines +} + +/// Escalation and follow-up lists, each entry its number and title. +fn number_section(label: &str, entries: &[(u64, String)]) -> Vec { + if entries.is_empty() { + return Vec::new(); + } + let mut lines = vec![format!("## {label}"), String::new()]; + lines.extend( + entries + .iter() + .map(|(number, title)| format!("- #{number} {}", cell(title))), + ); + lines.push(String::new()); + lines +} diff --git a/crates/tranche-core/src/domain/cluster/report.rs b/crates/tranche-core/src/domain/cluster/report.rs new file mode 100644 index 0000000..99d6ac4 --- /dev/null +++ b/crates/tranche-core/src/domain/cluster/report.rs @@ -0,0 +1,267 @@ +//! Building the report and the binding that identifies it. +//! +//! The binding is what makes a report a specific observation rather than any +//! report: it digests the sources, the judgments, the pairs and the question +//! policy, so a report that does not match it is refused rather than served. + +use serde_json::{Map, Value, json}; +use std::collections::{BTreeMap, HashMap, HashSet}; + +use super::groups::{Classification, duplicate_groups, pair_classification}; +use super::predicates::{escalated, review_candidate, risk_band, security_priority}; +use crate::domain::dupe::p_same; +use crate::domain::judge::{Judgment, usage}; +use crate::domain::pr::{Pr, Prs}; +use crate::util::digest; + +use super::binding::report_binding; + +/// The clustering output: the two published files and the summary. +pub struct Clustered { + pub clusters: Value, + pub dupes: Value, + pub summary: Value, + /// Review candidates per category, for the human report. Sorted by + /// descending candidate count, the tie broken by name. + pub tranches: Vec<(String, Vec)>, + /// The security meta-category, ranked probability-first. + pub security_review: Vec, + /// Numbers needing escalation, with the title the report prints. + pub escalate: Vec<(u64, String)>, + /// Possible author follow-ups, with the title the report prints. + pub follow_up: Vec<(u64, String)>, +} + +/// Build the report from the current judgments and verdicts. +pub fn cluster( + prs: &Prs, + judgments: &HashMap, + verdicts: &[Value], + repository: &str, + model: &str, + allow_unbound: bool, +) -> Clustered { + let (dupe_groups, review_groups) = duplicate_groups(verdicts); + let mut in_group: HashSet = HashSet::new(); + for group in &dupe_groups { + in_group.extend(group.iter().copied()); + } + for group in &review_groups { + if let Some(members) = group.get("members").and_then(Value::as_array) { + in_group.extend(members.iter().filter_map(Value::as_u64)); + } + } + + let mut uncertain_pairs: Vec = verdicts + .iter() + .filter(|verdict| { + matches!( + pair_classification(verdict), + Classification::Uncertain + | Classification::Contradictory + | Classification::Malformed + ) + }) + .map(|verdict| { + json!({ + "a": verdict.get("a").cloned().unwrap_or(Value::Null), + "b": verdict.get("b").cloned().unwrap_or(Value::Null), + "p_same": p_same(verdict), + "similarity": verdict.get("similarity").cloned().unwrap_or(Value::Null), + "verdict": verdict.get("verdict").cloned().unwrap_or(Value::Null), + "classification": pair_classification(verdict).as_str(), + }) + }) + .collect(); + // A stable sort: the input is in log order, and a stable sort preserves that + // order across ties. `dupes.json` is digested, so it is a contract. + uncertain_pairs.sort_by(|left, right| { + let score = |value: &Value| value.get("p_same").and_then(Value::as_f64).unwrap_or(-1.0); + score(right).total_cmp(&score(left)) + }); + + // Sorted maps: the published file's key order is not observable through the + // digest (which sorts keys), but determinism here keeps output stable. + let mut clusters: BTreeMap>> = BTreeMap::new(); + let mut tranches: BTreeMap> = BTreeMap::new(); + let mut security_review: Vec = Vec::new(); + let mut follow_up: Vec<(u64, String)> = Vec::new(); + let mut escalate: Vec<(u64, String)> = Vec::new(); + let mut category_order: Vec = Vec::new(); + let mut band_order: BTreeMap> = BTreeMap::new(); + let mut ordered: Vec<&Pr> = prs.iter().collect(); + ordered.sort_by_key(|pr| pr.number); + for pr in ordered { + let Some(judgment) = judgments.get(&pr.number) else { + continue; + }; + let risk = judgment.metric("risk", "score"); + let item = json!({ + "number": pr.number, + "title": pr.title, + "author": pr.author, + "risk": risk, + "finished_form": judgment.metric("finished_form", "score"), + "is_fix": judgment.metric("is_fix", "noul"), + "review_effort": judgment.metric("review_effort", "score"), + "security_flag": judgment.metric("security_flag", "noul"), + "freshness": judgment.freshness(), + "superseded_by": Value::Null, + "source_digest": pr.source_digest, + "evidence_digest": pr.evidence_digest, + "head_sha": pr.head_sha, + "url": pr.url, + }); + let category = judgment.category(); + let band = risk_band(risk); + // The report's category order breaks count ties by first appearance: + // the sort is stable over an object built in visit order. + if !category_order.iter().any(|seen| seen == &category) { + category_order.push(category.clone()); + } + let bands = band_order.entry(category.clone()).or_default(); + if !bands.iter().any(|seen| seen == band) { + bands.push(band.to_owned()); + } + clusters + .entry(category.clone()) + .or_default() + .entry(band.to_owned()) + .or_default() + .push(item.clone()); + if review_candidate(pr, judgment, &in_group) { + tranches.entry(category).or_default().push(item.clone()); + } + if security_priority(judgment) { + security_review.push(item.clone()); + } + let finished = judgment.metric("finished_form", "score"); + if finished.is_some_and(|value| value <= 1.0) && !in_group.contains(&pr.number) { + follow_up.push((pr.number, pr.title.clone())); + } + if escalated(judgment) { + escalate.push((pr.number, pr.title.clone())); + } + } + + security_review.sort_by(|left, right| { + let score = |value: &Value| { + value + .get("security_flag") + .and_then(Value::as_f64) + .unwrap_or(-1.0) + }; + score(right) + .total_cmp(&score(left)) + .then_with(|| number(left, "number").cmp(&number(right, "number"))) + }); + let mut clusters_payload: Map = Map::new(); + // The security meta-category is a first-class key, ordered before every + // category when consumers read clusters.json. + clusters_payload.insert( + "security-review".to_owned(), + Value::Array(security_review.clone()), + ); + for category in &category_order { + let Some(stored) = clusters.get(category) else { + continue; + }; + let mut bands: Map = Map::new(); + // An object keeps first-appearance order, so the bands of a category + // are not alphabetical. + for band in band_order.get(category).into_iter().flatten() { + if let Some(items) = stored.get(band) { + bands.insert(band.clone(), Value::Array(items.clone())); + } + } + clusters_payload.insert(category.clone(), Value::Object(bands)); + } + let clusters_payload = Value::Object(clusters_payload); + + let mut tokens = (0i64, 0i64); + for record in judgments + .values() + .map(|judgment| &judgment.record) + .chain(verdicts.iter()) + { + let (input, output) = usage(record); + tokens.0 += input; + tokens.1 += output; + } + + let dupes = json!({ + "confirmed_groups": dupe_groups, + "review_groups": review_groups, + "uncertain_pairs": uncertain_pairs, + "meaning": "Model-consistent candidate groups, not verified duplicates. No survivor selected.", + }); + // Categories by descending candidate count, the tie broken by name, so the + // report's section order is deterministic. + let ready_prs_list: Vec = tranches.values().flatten().cloned().collect(); + let mut tranche_sections: Vec<(String, Vec)> = tranches + .into_iter() + .filter(|(_, items)| !items.is_empty()) + .collect(); + tranche_sections.sort_by(|left, right| { + let rank = |name: &str| { + category_order + .iter() + .position(|seen| seen == name) + .unwrap_or(usize::MAX) + }; + right + .1 + .len() + .cmp(&left.1.len()) + .then_with(|| rank(&left.0).cmp(&rank(&right.0))) + }); + let unknown = judgments + .values() + .filter(|judgment| { + judgment.metric("risk", "score").is_none() + || judgment.metric("security_flag", "noul").is_none() + }) + .count(); + let summary = json!({ + "format_version": 2, + "repo": repository, + "prs_in_corpus": prs.len(), + "judged": judgments.len(), + "unjudged_or_stale": prs.len() - judgments.len(), + "unbound_judgments": judgments.values().filter(|j| j.freshness() == "unbound").count(), + "allow_unbound": allow_unbound, + "report_binding": report_binding(prs, judgments, verdicts, repository, model), + "dupe_groups": dupes["confirmed_groups"].as_array().map(Vec::len).unwrap_or(0), + "review_groups": dupes["review_groups"].as_array().map(Vec::len).unwrap_or(0), + "uncertain_pairs": dupes["uncertain_pairs"].as_array().map(Vec::len).unwrap_or(0), + "prs_in_dupe_groups": in_group.len(), + "superseded": 0, + "ready_tranches": tranche_sections.len(), + "ready_prs": ready_prs_list.len(), + "recommendation_kind": "review-candidates", + "needs_author_followup": follow_up.len(), + "escalate_review": escalate.len(), + "security_priority": security_review.len(), + "unknown_risk_or_security": unknown, + "tokens": {"input": tokens.0, "output": tokens.1}, + "output_digests": { + "clusters.json": digest(&clusters_payload), + "dupes.json": digest(&dupes), + }, + }); + + Clustered { + clusters: clusters_payload, + dupes, + summary, + tranches: tranche_sections, + security_review, + escalate, + follow_up, + } +} + +/// A numeric field of a record, absent meaning zero. +fn number(value: &Value, key: &str) -> u64 { + value.get(key).and_then(Value::as_u64).unwrap_or(0) +} diff --git a/crates/tranche-core/src/domain/cluster/style.rs b/crates/tranche-core/src/domain/cluster/style.rs new file mode 100644 index 0000000..737462f --- /dev/null +++ b/crates/tranche-core/src/domain/cluster/style.rs @@ -0,0 +1,91 @@ +//! Markdown formatting the published report depends on. +//! +//! These are not stylistic choices — the published `tranches.md` is compared +//! against the committed file, so a space in the wrong place is a failed test. + +use serde_json::Value; + +/// Escape a cell so a pipe or newline cannot break the table row. +pub fn cell(value: &str) -> String { + value.replace('|', "\\|").replace('\n', " ") +} + +/// A cell read from a JSON string, absent meaning empty. +pub fn text(value: &Value) -> String { + cell(value.as_str().unwrap_or_default()) +} + +/// One decimal place, or an em dash when the score is absent. +pub fn one_decimal(value: Option) -> String { + match value { + Some(number) => format!("{number:.1}"), + None => "—".to_owned(), + } +} + +/// Two decimal places, or an em dash when the score is absent. +pub fn two_decimals(value: Option) -> String { + match value { + Some(number) => format!("{number:.2}"), + None => "—".to_owned(), + } +} + +/// A float as the report writes it: the shortest form that round-trips. +/// +/// Both languages print the shortest decimal that round-trips, so `{}` agrees +/// with `repr()` on every value the pipeline stores. +pub fn number(value: &Value) -> String { + match value.as_f64() { + Some(number) => format!("{number}"), + None => "None".to_owned(), + } +} + +/// JSON with the report's separators: a space after each comma and colon. +/// +/// `serde_json::to_string` writes compact JSON (`{"a":1}`); the report writes +/// `{"a": 1}`, with a space after each comma and colon. The relationship +/// diagnostics are printed through this, and they are compared against the +/// committed report, so the spacing is part of the output. +pub fn spaced_json(value: &Value) -> String { + match value { + Value::Null => "null".to_owned(), + Value::Bool(true) => "true".to_owned(), + Value::Bool(false) => "false".to_owned(), + Value::Number(number) => number.to_string(), + Value::String(text) => json_string(text), + Value::Array(items) => { + let rendered: Vec = items.iter().map(spaced_json).collect(); + format!("[{}]", rendered.join(", ")) + } + Value::Object(map) => { + let rendered: Vec = map + .iter() + .map(|(key, value)| format!("{}: {}", json_string(key), spaced_json(value))) + .collect(); + format!("{{{}}}", rendered.join(", ")) + } + } +} + +/// A JSON string literal, escaped as `json.dumps` escapes it. +fn json_string(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 2); + out.push('"'); + for character in text.chars() { + match character { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + character if (character as u32) < 0x20 => { + out.push_str(&format!("\\u{:04x}", character as u32)); + } + character => out.push(character), + } + } + out.push('"'); + out +} diff --git a/crates/tranche-core/src/domain/dupe/mod.rs b/crates/tranche-core/src/domain/dupe/mod.rs new file mode 100644 index 0000000..4454797 --- /dev/null +++ b/crates/tranche-core/src/domain/dupe/mod.rs @@ -0,0 +1,17 @@ +//! Pair verdicts: what one records, which pairs are worth comparing, and the binding +//! that makes a stored verdict reusable. +//! +//! `pair_binding()` is a cache key exactly as the judgment binding is. A verdict is +//! only reusable while it still describes the same two revisions under the same +//! question policy, and the candidate set is what decides which pairs are worth a +//! paid comparison at all. + +pub mod normalizing; +pub mod similarity; +pub mod verdict; +pub mod verdicts; + +pub use normalizing::normalize_pair; +pub use similarity::{candidate_pairs, lexical_pairs}; +pub use verdict::{BINDING_VERSION, brief, p_same, pair_binding, pair_is_current, reusable_pair}; +pub use verdicts::{Verdicts, current_pairs, current_verdicts, pair_cache}; diff --git a/crates/tranche-core/src/domain/dupe/normalizing.rs b/crates/tranche-core/src/domain/dupe/normalizing.rs new file mode 100644 index 0000000..5125c41 --- /dev/null +++ b/crates/tranche-core/src/domain/dupe/normalizing.rs @@ -0,0 +1,71 @@ +use serde_json::{Value, json}; + +use super::verdict::p_same; +use crate::domain::judge::finite_json; + +/// Normalize a stored verdict to the shape the report reads. +pub fn normalize_pair(record: &Value) -> Value { + let mut record = finite_json(record); + let Some(object) = record.as_object_mut() else { + return record; + }; + let criteria = crate::domain::questions::sameness_criteria(); + let verdict = object.get("verdict").and_then(Value::as_str); + if !verdict.is_some_and(|value| criteria.contains(&value)) { + object.insert("verdict".to_owned(), Value::Null); + } + let mut probabilities = object + .get("probabilities") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + for (_, value) in probabilities.iter_mut() { + let usable = value + .as_f64() + .is_some_and(|number| number.is_finite() && (0.0..=1.0).contains(&number)); + if !usable { + *value = Value::Null; + } + } + let normalized = Value::Object(probabilities.clone()); + let same = p_same(&Value::Object({ + let mut map = serde_json::Map::new(); + map.insert("probabilities".to_owned(), normalized); + map + })); + probabilities.insert( + "same_change".to_owned(), + same.and_then(serde_json::Number::from_f64) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + let mut errors = Vec::new(); + let record_value = Value::Object(object.clone()); + if record_value.get("verdict").is_some_and(Value::is_null) { + errors.push("verdict: invalid or missing".to_owned()); + } + if same.is_none() { + errors.push("probabilities.same_change: invalid or missing".to_owned()); + } + object.insert("probabilities".to_owned(), Value::Object(probabilities)); + object.insert("normalization_errors".to_owned(), json!(errors)); + // The judgment block is what the report re-reads; per-request token usage is + // not, and keeping it out lets cluster read the multi-megabyte log without + // holding every usage block in memory. + let has_counts = ["input_tokens", "output_tokens"] + .iter() + .all(|field| record_value.get(*field).and_then(Value::as_i64).is_some()); + if !has_counts { + let nested = record_value.get("usage").and_then(Value::as_object); + for field in ["input_tokens", "output_tokens"] { + let value = nested + .and_then(|usage| usage.get(field)) + .and_then(Value::as_i64) + .filter(|value| *value >= 0) + .unwrap_or(0); + object.insert(field.to_owned(), json!(value)); + } + } + object.remove("usage"); + record +} diff --git a/crates/tranche-core/src/domain/dupe/similarity.rs b/crates/tranche-core/src/domain/dupe/similarity.rs new file mode 100644 index 0000000..c89e2a8 --- /dev/null +++ b/crates/tranche-core/src/domain/dupe/similarity.rs @@ -0,0 +1,154 @@ +//! Deciding which pairs are worth a paid model comparison. +//! +//! Candidate selection is mechanical and generous: title similarity, shared +//! content tokens and literal body references all nominate a pair. Nothing here +//! decides a duplicate — it decides what is worth asking about. + +use std::collections::{HashMap, HashSet}; + +use crate::domain::judge::Judgment; + +/// Candidate duplicate pairs: high title similarity within one judged category, +/// plus the body-reference edges that titles cannot express. +pub fn lexical_pairs( + prs: &crate::domain::pr::Prs, + judgments: &HashMap, + refs: Option<&HashMap>>, + threshold: f64, + jaccard_threshold: f64, +) -> Vec<(f64, u64, u64)> { + let mut by_category: HashMap> = HashMap::new(); + for (number, judgment) in judgments { + by_category + .entry(judgment.category()) + .or_default() + .push(*number); + } + let mut pairs: Vec<(f64, u64, u64)> = Vec::new(); + for numbers in by_category.values() { + let mut numbers = numbers.clone(); + numbers.sort_unstable(); + for (index, a) in numbers.iter().enumerate() { + let Some(pr_a) = prs.get(*a) else { continue }; + let title_a = pr_a.title.to_lowercase(); + for b in &numbers[index + 1..] { + let Some(pr_b) = prs.get(*b) else { continue }; + let title_b = pr_b.title.to_lowercase(); + let ratio = similarity(&title_a, &title_b); + if ratio >= threshold { + pairs.push((ratio, *a, *b)); + continue; + } + let a_tokens = tokens(&pr_a.title); + let b_tokens = tokens(&pr_b.title); + if !a_tokens.is_empty() && !b_tokens.is_empty() { + let intersection = a_tokens.intersection(&b_tokens).count() as f64; + let union = a_tokens.union(&b_tokens).count() as f64; + let jaccard = intersection / union; + if jaccard >= jaccard_threshold { + pairs.push((jaccard, *a, *b)); + } + } + } + } + } + pairs.sort_by(|left, right| right.0.total_cmp(&left.0)); + let mut seen: HashSet<(u64, u64)> = pairs.iter().map(|(_, a, b)| (*a, *b)).collect(); + + // Cross-referenced PRs are candidate duplicates even when titles differ. + for pr in prs.iter() { + let number = pr.number; + if !judgments.contains_key(&number) || refs.is_some_and(|refs| !refs.contains_key(&number)) + { + continue; + } + let references = refs.and_then(|refs| refs.get(&number)).unwrap_or(&pr.refs); + for reference in references { + let key = number.min(*reference); + let other = number.max(*reference); + if key != other + && prs.get(key).is_some() + && prs.get(other).is_some() + && judgments.contains_key(&key) + && judgments.contains_key(&other) + && seen.insert((key, other)) + { + pairs.push((1.0, key, other)); + } + } + } + pairs.sort_by(|left, right| right.0.total_cmp(&left.0)); + pairs +} + +/// Similarity of two lowercased titles, as the pipeline measures it. +/// +/// `difflib.SequenceMatcher.ratio()` is 2M/T over the longest common +/// subsequence; reproducing it matters because the threshold decides which pairs +/// are worth a paid comparison. +fn similarity(left: &str, right: &str) -> f64 { + let a: Vec = left.chars().collect(); + let b: Vec = right.chars().collect(); + let total = a.len() + b.len(); + if total == 0 { + return 1.0; + } + let matches = lcs_length(&a, &b); + (2.0 * matches as f64) / total as f64 +} + +fn lcs_length(a: &[char], b: &[char]) -> usize { + if a.is_empty() || b.is_empty() { + return 0; + } + let mut previous = vec![0usize; b.len() + 1]; + let mut current = vec![0usize; b.len() + 1]; + for left in a { + for (index, right) in b.iter().enumerate() { + current[index + 1] = if left == right { + previous[index] + 1 + } else { + current[index].max(previous[index + 1]) + }; + } + std::mem::swap(&mut previous, &mut current); + current.fill(0); + } + previous[b.len()] +} + +/// Content tokens of a title, with the stop words the pipeline drops. +fn tokens(title: &str) -> HashSet { + const STOP: [&str; 14] = [ + "the", "a", "an", "and", "or", "to", "of", "for", "in", "on", "with", "fix", "add", "an", + ]; + let mut found = HashSet::new(); + let mut word = String::new(); + for character in title.to_lowercase().chars() { + if character.is_ascii_alphanumeric() { + word.push(character); + } else if !word.is_empty() { + if !STOP.contains(&word.as_str()) { + found.insert(std::mem::take(&mut word)); + } else { + word.clear(); + } + } + } + if !word.is_empty() && !STOP.contains(&word.as_str()) { + found.insert(word); + } + found +} + +/// The pairs worth a model verdict, as `(a, b) -> similarity`. +pub fn candidate_pairs( + prs: &crate::domain::pr::Prs, + judgments: &HashMap, + refs: Option<&HashMap>>, +) -> HashMap<(u64, u64), f64> { + lexical_pairs(prs, judgments, refs, 0.72, 0.62) + .into_iter() + .map(|(score, a, b)| ((a, b), score)) + .collect() +} diff --git a/crates/tranche-core/src/domain/dupe/verdict.rs b/crates/tranche-core/src/domain/dupe/verdict.rs new file mode 100644 index 0000000..50fb68b --- /dev/null +++ b/crates/tranche-core/src/domain/dupe/verdict.rs @@ -0,0 +1,61 @@ +//! Pair verdicts, their binding, and the candidate set. +//! +//! `pair_binding()` is a cache key exactly as the judgment binding is, and the +//! candidate set is what decides which pairs are worth a paid comparison. + +use serde_json::{Value, json}; + +use crate::domain::pr::Pr; +use crate::domain::questions::pair_questions; +use crate::util::digest; + +/// Bumped only when the binding's meaning changes. +pub const BINDING_VERSION: u64 = 1; + +/// The short state a pair comparison is shown for one side. +pub fn brief(pr: &Pr) -> Value { + json!({ + "number": pr.number, + "title": pr.title, + "body": pr.body.chars().take(400).collect::(), + "evidence_basis": "shortened descriptions only; source equivalence not verified", + }) +} + +/// The binding digest for a pair, under today's evidence, policy and model. +/// +/// The pair is ordered by number, so a verdict recorded as (b, a) still matches. +pub fn pair_binding(a: &Pr, b: &Pr, repository: &str, model: &str) -> String { + let (first, second) = if a.number <= b.number { (a, b) } else { (b, a) }; + digest(&json!({ + "version": BINDING_VERSION, + "repo": repository, + "model": model, + "sources": [first.evidence_digest, second.evidence_digest], + "state": [brief(first), brief(second)], + "questions": pair_questions(), + })) +} + +/// The probability of the `same_change` verdict, or `None` when unusable. +pub fn p_same(record: &Value) -> Option { + let value = record + .get("probabilities") + .and_then(Value::as_object) + .and_then(|probabilities| probabilities.get("same_change")) + .and_then(Value::as_f64)?; + (value.is_finite() && (0.0..=1.0).contains(&value)).then_some(value) +} + +/// True when the record carries a verdict that can be reused. +pub fn reusable_pair(record: &Value) -> bool { + record + .get("verdict") + .is_some_and(|verdict| !verdict.is_null()) + && p_same(record).is_some() +} + +/// True when a stored verdict still answers today's question for today's evidence. +pub fn pair_is_current(record: &Value, binding: &str) -> bool { + record.get("binding").and_then(Value::as_str) == Some(binding) +} diff --git a/crates/tranche-core/src/domain/dupe/verdicts.rs b/crates/tranche-core/src/domain/dupe/verdicts.rs new file mode 100644 index 0000000..9ce4be6 --- /dev/null +++ b/crates/tranche-core/src/domain/dupe/verdicts.rs @@ -0,0 +1,164 @@ +//! Stored pair verdicts, in the order they were written. +//! +//! Order is part of `dupes.json`, which is digested, and it decides which pairs +//! a budgeted `dupes` pass reaches first. A hash map here would silently reorder +//! both. + +use serde_json::{Value, json}; +use std::collections::HashMap; + +use super::super::judge::Judgment; +use super::normalizing::normalize_pair; +use super::verdict::{pair_binding, pair_is_current}; +use crate::report::Root; + +/// Stored verdicts in the order they first appear in the log. +/// +/// Order is part of `dupes.json`, which is digested, and it decides which pairs +/// a budgeted `dupes` pass reaches first. A hash map here would silently reorder +/// both. +#[derive(Debug, Default, Clone)] +pub struct Verdicts { + pairs: Vec<((u64, u64), Value)>, + index: HashMap<(u64, u64), usize>, +} + +impl Verdicts { + pub fn len(&self) -> usize { + self.pairs.len() + } + + pub fn is_empty(&self) -> bool { + self.pairs.is_empty() + } + + /// Records in first-appearance order. + pub fn records(&self) -> impl Iterator { + self.pairs.iter().map(|(_, record)| record) + } + + pub fn iter(&self) -> impl Iterator { + self.pairs.iter().map(|(pair, record)| (pair, record)) + } + + pub fn get(&self, pair: &(u64, u64)) -> Option<&Value> { + self.index + .get(pair) + .map(|position| &self.pairs[*position].1) + } + + fn insert(&mut self, pair: (u64, u64), record: Value) { + match self.index.get(&pair) { + // The log is append-only, so a pair repeats; the newest record wins + // but keeps the position the pair first appeared at. + Some(position) => self.pairs[*position].1 = record, + None => { + self.index.insert(pair, self.pairs.len()); + self.pairs.push((pair, record)); + } + } + } +} + +/// The latest stored verdict per pair, for pairs whose members are both captured. +pub fn current_verdicts(root: &Root, prs: &crate::domain::pr::Prs) -> Result { + let path = root.pairs_path(); + if !path.exists() { + return Ok(Verdicts::default()); + } + let text = std::fs::read_to_string(&path).map_err(|error| error.to_string())?; + let mut verdicts = Verdicts::default(); + for line in text.lines() { + if !line.contains("\"a\"") { + continue; + } + let Ok(record) = serde_json::from_str::(line) else { + continue; + }; + let Some(object) = record.as_object() else { + continue; + }; + if object.contains_key("error") { + continue; + } + let read = |key: &str| object.get(key).and_then(Value::as_u64).filter(|n| *n > 0); + let (Some(a), Some(b)) = (read("a"), read("b")) else { + continue; + }; + let pair = (a.min(b), a.max(b)); + if pair.0 == pair.1 || prs.get(pair.0).is_none() || prs.get(pair.1).is_none() { + continue; + } + verdicts.insert(pair, normalize_pair(&record)); + } + Ok(verdicts) +} + +/// Pair verdicts a report may publish. +/// +/// A verdict is published when the pair's current descriptions still verify +/// against the record. A pair whose similarity has since fallen below the +/// discovery threshold is still published when the model actually judged it: the +/// threshold finds candidates, it does not get to hide a verified dupe. +pub fn current_pairs( + root: &Root, + prs: &crate::domain::pr::Prs, + judgments: &HashMap, + repository: &str, + model: &str, + allow_unbound: bool, +) -> Result, String> { + let mut published = Vec::new(); + for (pair, record) in current_verdicts(root, prs)?.iter() { + let (a, b) = *pair; + if !judgments.contains_key(&a) || !judgments.contains_key(&b) { + continue; + } + let (Some(pr_a), Some(pr_b)) = (prs.get(a), prs.get(b)) else { + continue; + }; + let matches = pair_is_current(record, &pair_binding(pr_a, pr_b, repository, model)); + let legacy = record.get("binding").is_none() && allow_unbound; + if matches || legacy { + let mut published_record = record.clone(); + if let Some(object) = published_record.as_object_mut() { + object.insert("a".to_owned(), json!(a)); + object.insert("b".to_owned(), json!(b)); + object.insert( + "freshness".to_owned(), + json!(if matches { "current" } else { "unbound" }), + ); + } + published.push(published_record); + } + } + Ok(published) +} + +/// Every captured pair with a stored verdict, stamped with its currency. +pub fn pair_cache( + root: &Root, + prs: &crate::domain::pr::Prs, + repository: &str, + model: &str, +) -> Result, String> { + let mut cache = HashMap::new(); + for (pair, record) in current_verdicts(root, prs)?.iter() { + let (a, b) = *pair; + let (Some(pr_a), Some(pr_b)) = (prs.get(a), prs.get(b)) else { + continue; + }; + let matches = pair_is_current(record, &pair_binding(pr_a, pr_b, repository, model)); + let mut stamped = record.clone(); + if let Some(object) = stamped.as_object_mut() { + object.insert("a".to_owned(), json!(a)); + object.insert("b".to_owned(), json!(b)); + object.insert( + "freshness".to_owned(), + json!(if matches { "current" } else { "stale" }), + ); + } + cache.insert((a, b), stamped); + } + Ok(cache) +} diff --git a/crates/tranche-core/src/domain/judge/judgment.rs b/crates/tranche-core/src/domain/judge/judgment.rs new file mode 100644 index 0000000..7997fc5 --- /dev/null +++ b/crates/tranche-core/src/domain/judge/judgment.rs @@ -0,0 +1,111 @@ +//! The judgment record and the binding that makes one current. +//! +//! `judgment_binding()` is a cache key. A mismatch does not merely look stale — it +//! makes every stored judgment unreusable, so a resume pass silently re-asks the +//! question for the whole corpus and re-bills it. + +use serde_json::{Map, Value, json}; + +use super::super::pr::{Pr, pr_state}; +use super::super::questions::{judge_questions, metric_ceiling}; +use crate::util::digest; + +/// The binding version every stored judgment is written under. +pub const BINDING_VERSION: u64 = 1; + +#[derive(Debug, Clone)] +pub struct Judgment { + pub number: u64, + pub record: Value, +} + +impl Judgment { + pub fn freshness(&self) -> &str { + self.record + .get("freshness") + .and_then(Value::as_str) + .unwrap_or("current") + } + + pub fn answers(&self) -> &Map { + static EMPTY: std::sync::OnceLock> = std::sync::OnceLock::new(); + self.record + .get("answers") + .and_then(Value::as_object) + .unwrap_or_else(|| EMPTY.get_or_init(Map::new)) + } + + /// The chosen category, or `unclear` when the answer is unusable. + pub fn category(&self) -> String { + let answer = self.answers().get("category").and_then(Value::as_object); + let chosen = answer + .and_then(|answer| answer.get("choice")) + .and_then(Value::as_str); + match chosen { + Some(value) + if judge_questions()["category"]["criteria"] + .get(value) + .is_some() => + { + value.to_owned() + } + _ => "unclear".to_owned(), + } + } + + /// A metric answer, or `None` when the model gave nothing usable. + /// + /// Absent, non-finite or out-of-range values are unknown, never zero. + pub fn metric(&self, name: &str, field: &str) -> Option { + let ceiling = metric_ceiling(name, field)?; + let answer = self.answers().get(name).and_then(Value::as_object)?; + let value = answer.get(field)?.as_f64()?; + if value.is_finite() && (0.0..=ceiling).contains(&value) { + Some(value) + } else { + None + } + } +} + +/// The binding digest for one PR under today's evidence, policy and model. +pub fn judgment_binding(pr: &Pr, repository: &str, model: &str) -> String { + digest(&json!({ + "version": BINDING_VERSION, + "repo": repository, + "source": pr.evidence_digest, + "state": pr_state(pr), + "questions": judge_questions(), + "model": model, + })) +} + +/// True when a stored record still answers today's question for today's evidence. +/// +/// The binding is the single currency test, and it digests the full question +/// policy — so a judgment made under an older question set is never presented as +/// current. Completeness is deliberately not tested: an answer with an unknown +/// field is still the answer that was given, and dropping it would turn a known +/// category into an unknown one. +pub fn judgment_is_current(record: &Value, binding: &str) -> bool { + record.get("binding").and_then(Value::as_str) == Some(binding) +} + +/// True when every question has a usable answer, so the record can be reused. +pub fn reusable_judgment(judgment: &Judgment) -> bool { + judgment + .answers() + .get("category") + .and_then(Value::as_object) + .and_then(|answer| answer.get("choice")) + .is_some_and(|choice| !choice.is_null()) + && [ + ("risk", "score"), + ("finished_form", "score"), + ("review_effort", "score"), + ("is_fix", "noul"), + ("security_flag", "noul"), + ] + .iter() + .all(|(name, field)| judgment.metric(name, field).is_some()) +} diff --git a/crates/tranche-core/src/domain/judge/mod.rs b/crates/tranche-core/src/domain/judge/mod.rs new file mode 100644 index 0000000..a697337 --- /dev/null +++ b/crates/tranche-core/src/domain/judge/mod.rs @@ -0,0 +1,16 @@ +//! Stored judgments: what one records, and the binding that makes it reusable. +//! +//! A judgment is bound to the PR evidence, the repository and the model that +//! produced it. The binding is verified rather than trusted, because a mismatch does +//! not merely look stale — it makes every stored judgment unreusable, so a resume +//! pass silently re-asks the question for the whole corpus and re-bills it. + +pub mod judgment; +pub mod records; +pub mod store; + +pub use judgment::{ + BINDING_VERSION, Judgment, judgment_binding, judgment_is_current, reusable_judgment, +}; +pub use records::{finite_json, normalize_judgment, read_lines, usage}; +pub use store::{current_judgments, load_done}; diff --git a/crates/tranche-core/src/domain/judge/records.rs b/crates/tranche-core/src/domain/judge/records.rs new file mode 100644 index 0000000..012e978 --- /dev/null +++ b/crates/tranche-core/src/domain/judge/records.rs @@ -0,0 +1,143 @@ +//! Normalizing a stored judgment to the shape the report reads, and the +//! per-request token usage the log carries. + +use serde_json::{Map, Value, json}; +use std::path::Path; + +use super::super::questions::{answer_field, judge_questions, metric_ceiling}; +use crate::util::parse_jsonl; + +pub fn finite_json(value: &Value) -> Value { + match value { + Value::Object(object) => Value::Object( + object + .iter() + .map(|(key, value)| (key.clone(), finite_json(value))) + .collect(), + ), + Value::Array(items) => Value::Array(items.iter().map(finite_json).collect()), + Value::Number(number) => match number.as_f64() { + Some(value) if !value.is_finite() => Value::Null, + _ => value.clone(), + }, + other => other.clone(), + } +} + +/// Normalize a stored judgment to the shape the rest of the pipeline reads. +/// +/// A field the model left unusable becomes `null` and is listed in +/// `normalization_errors`; it is never coerced to a value, because an unknown +/// category and an invented one are different facts. +pub fn normalize_judgment(record: &Value) -> Value { + let mut object = normalized_record(record); + let mut errors: Vec = Vec::new(); + let mut answers = object + .get("answers") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + + if let Some(policy) = judge_questions().as_object() { + for (name, question) in policy { + let Some(field) = question + .get("type") + .and_then(Value::as_str) + .and_then(answer_field) + else { + continue; + }; + let mut answer = answers + .get(name) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + let value = if field == "choice" { + let chosen = answer.get(field).and_then(Value::as_str); + let valid = chosen.is_some_and(|value| { + question + .get("criteria") + .and_then(|criteria| criteria.get(value)) + .is_some() + }); + match valid { + true => answer.get(field).cloned().unwrap_or(Value::Null), + false => { + errors.push(format!("answers.{name}.{field}: invalid or missing")); + Value::Null + } + } + } else { + let ceiling = metric_ceiling(name, field).unwrap_or(0.0); + let usable = answer + .get(field) + .and_then(Value::as_f64) + .filter(|value| value.is_finite() && (0.0..=ceiling).contains(value)); + match usable.and_then(serde_json::Number::from_f64) { + Some(number) => Value::Number(number), + None => { + errors.push(format!("answers.{name}.{field}: invalid or missing")); + Value::Null + } + } + }; + answer.insert(field.to_owned(), value); + answers.insert(name.clone(), Value::Object(answer)); + } + } + + object.insert("answers".to_owned(), Value::Object(answers)); + object.insert("normalization_errors".to_owned(), json!(errors)); + Value::Object(object) +} + +/// Token accounting as clustering reads it: the nested `usage` block only. +/// +/// This deliberately ignores the flat fields. `normalize_pair` moves a verdict's +/// tokens to the flat fields and drops `usage`, so clustering counts pair +/// verdicts as zero — and reproducing that is required, because the total is +/// published in `summary.json`. +pub fn usage(record: &Value) -> (i64, i64) { + let nested = record.get("usage").and_then(Value::as_object); + let read = |field: &str| -> i64 { + nested + .and_then(|usage| usage.get(field)) + .and_then(Value::as_i64) + .filter(|value| *value >= 0) + .unwrap_or(0) + }; + (read("input_tokens"), read("output_tokens")) +} + +fn normalized_record(record: &Value) -> Map { + let mut object: Map = record + .as_object() + .map(|object| { + object + .iter() + .map(|(key, value)| (key.clone(), finite_json(value))) + .collect() + }) + .unwrap_or_default(); + let usage = object.get("usage").and_then(Value::as_object); + let counts = ["input_tokens", "output_tokens"] + .iter() + .map(|field| { + let value = usage + .and_then(|usage| usage.get(*field)) + .and_then(Value::as_i64); + ( + (*field).to_owned(), + json!(value.filter(|value| *value >= 0).unwrap_or(0)), + ) + }) + .collect(); + object.insert("usage".to_owned(), Value::Object(counts)); + object +} + +/// Read a JSON Lines file into normalized records, or report why it cannot be used. +pub fn read_lines(path: &Path) -> Result, String> { + let text = std::fs::read_to_string(path).map_err(|error| error.to_string())?; + parse_jsonl(&text) +} diff --git a/crates/tranche-core/src/domain/judge/store.rs b/crates/tranche-core/src/domain/judge/store.rs new file mode 100644 index 0000000..0755cb3 --- /dev/null +++ b/crates/tranche-core/src/domain/judge/store.rs @@ -0,0 +1,78 @@ +//! The append-only judgment log, read newest-per-PR. +//! +//! A malformed tail — a truncated write — never costs the earlier records. + +use serde_json::{Value, json}; +use std::collections::HashMap; + +use super::super::judge::{Judgment, judgment_binding, judgment_is_current, normalize_judgment}; +use super::super::pr::Prs; +use crate::report::Root; + +pub fn load_done(root: &Root) -> Result, String> { + let path = root.judgments_path(); + if !path.exists() { + return Ok(HashMap::new()); + } + let text = std::fs::read_to_string(&path).map_err(|error| error.to_string())?; + let mut latest: HashMap = HashMap::new(); + for line in text.lines() { + if !line.contains("\"number\"") { + continue; + } + let Ok(record) = serde_json::from_str::(line) else { + continue; + }; + let Some(object) = record.as_object() else { + continue; + }; + if object.contains_key("error") { + continue; + } + let number = match object.get("number").and_then(Value::as_u64) { + Some(number) if number > 0 => number, + _ => continue, + }; + latest.insert(number, record); + } + Ok(latest + .into_iter() + .map(|(number, record)| (number, normalize_judgment(&record))) + .collect()) +} + +/// The judgments a report may publish, newest per PR, keyed by PR number. +pub fn current_judgments( + root: &Root, + prs: &Prs, + repository: &str, + model: &str, + allow_unbound: bool, +) -> Result, String> { + let mut current = HashMap::new(); + for (number, record) in load_done(root)? { + let Some(pr) = prs.get(number) else { + continue; + }; + let binding = judgment_binding(pr, repository, model); + let matches = judgment_is_current(&record, &binding); + let legacy = record.get("binding").is_none() && allow_unbound; + if matches || legacy { + let mut stored = record.clone(); + if let Some(object) = stored.as_object_mut() { + object.insert( + "freshness".to_owned(), + json!(if matches { "current" } else { "unbound" }), + ); + } + current.insert( + number, + Judgment { + number, + record: stored, + }, + ); + } + } + Ok(current) +} diff --git a/crates/tranche-core/src/domain/mod.rs b/crates/tranche-core/src/domain/mod.rs new file mode 100644 index 0000000..599405b --- /dev/null +++ b/crates/tranche-core/src/domain/mod.rs @@ -0,0 +1,8 @@ +//! Pipeline domain: captured membership, judgments, pairs, clusters and batches. + +pub mod batch; +pub mod cluster; +pub mod dupe; +pub mod judge; +pub mod pr; +pub mod questions; diff --git a/crates/tranche-core/src/domain/pr/error.rs b/crates/tranche-core/src/domain/pr/error.rs new file mode 100644 index 0000000..7e534f5 --- /dev/null +++ b/crates/tranche-core/src/domain/pr/error.rs @@ -0,0 +1,70 @@ +//! The refusal type for unusable captured input, and the loader that raises it. +//! +//! Validation is not decoration: a PR missing an identity would otherwise enter +//! every downstream digest as a hole, so it is refused at the boundary. + +use serde_json::Value; + +use super::invalidating::invalid; +use super::projection::project; +use super::record::Prs; +use super::validating::validate_pr; +use crate::report::Root; +use crate::util::digest; + +/// A captured PR is unusable, so nothing downstream may treat it as data. +#[derive(Debug)] +pub struct PrError(pub String); +impl std::fmt::Display for PrError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for PrError {} +/// Read the captured membership: one snapshot, or the sorted page shards. +pub fn load_prs(root: &Root, repository: &str) -> Result { + let pages = membership_pages(root, repository)?; + let mut prs = Prs::default(); + for page in pages { + let items = page + .as_array() + .ok_or_else(|| PrError("captured PR membership must be a list; fetch again".into()))?; + for item in items { + validate_pr(item)?; + let number = item["number"] + .as_u64() + .expect("validated as a positive int"); + if prs.by_number.contains_key(&number) { + return Err(PrError( + "repeated PR in captured membership; fetch again".into(), + )); + } + prs.insert(project(item, repository)); + } + } + Ok(prs) +} +pub(crate) fn membership_pages(root: &Root, repository: &str) -> Result, PrError> { + let snapshot = root.snapshot_path(); + if snapshot.exists() { + let text = std::fs::read_to_string(&snapshot).map_err(invalid)?; + let value: Value = serde_json::from_str(&text).map_err(invalid)?; + let version = value.get("version").and_then(Value::as_u64); + let repo = value.get("repo").and_then(Value::as_str); + let items = value.get("items").cloned().unwrap_or(Value::Null); + let recorded = value.get("digest").and_then(Value::as_str); + if version != Some(1) || repo != Some(repository) || recorded != Some(&digest(&items)) { + return Err(PrError( + "fetched snapshot identity or checksum differs; fetch again".into(), + )); + } + return Ok(vec![items]); + } + // Existing page caches stay readable until the next fetch. + let mut pages = Vec::new(); + for path in crate::report::read_page_paths(&root.pages_dir()) { + let text = std::fs::read_to_string(&path).map_err(invalid)?; + pages.push(serde_json::from_str(&text).map_err(invalid)?); + } + Ok(pages) +} diff --git a/crates/tranche-core/src/domain/pr/invalidating.rs b/crates/tranche-core/src/domain/pr/invalidating.rs new file mode 100644 index 0000000..afbafba --- /dev/null +++ b/crates/tranche-core/src/domain/pr/invalidating.rs @@ -0,0 +1,7 @@ +//! The invalid-input constructor the loader and the checker both use. + +use super::error::PrError; + +pub(crate) fn invalid(error: impl std::fmt::Display) -> PrError { + PrError(format!("{error}")) +} diff --git a/crates/tranche-core/src/domain/pr/mod.rs b/crates/tranche-core/src/domain/pr/mod.rs new file mode 100644 index 0000000..e56e66d --- /dev/null +++ b/crates/tranche-core/src/domain/pr/mod.rs @@ -0,0 +1,19 @@ +//! Captured pull requests: the record, the corpus, and how one is read and checked. +//! +//! Everything downstream is bound to these bytes, so the corpus is loaded and +//! validated once at the boundary rather than trusted as it flows through the +//! pipeline. + +pub mod error; +pub mod invalidating; +pub mod projection; +pub mod record; +pub mod references; +pub mod validating; + +pub use error::{PrError, load_prs}; + +pub use projection::{pr_evidence_digest, pr_state, read_json}; +pub use record::{BODY_CHARS, Pr, Prs}; +pub use references::reference_numbers; +pub use validating::validate_pr; diff --git a/crates/tranche-core/src/domain/pr/projection.rs b/crates/tranche-core/src/domain/pr/projection.rs new file mode 100644 index 0000000..d267984 --- /dev/null +++ b/crates/tranche-core/src/domain/pr/projection.rs @@ -0,0 +1,238 @@ +//! Turning a captured item into what the pipeline works with. +//! +//! The evidence digest covers only the fields a judgment depends on. Everything +//! else in a GitHub pull-list envelope churns without the PR changing: +//! repository-wide counters, URL scaffolding and nested remote objects all move +//! on unrelated events, so digesting the whole envelope made every PR look +//! changed after every fetch. + +use regex::Regex; +use serde_json::{Map, Value}; +use std::collections::HashMap; +use std::path::Path; +use std::sync::OnceLock; + +use super::error::PrError; +use super::invalidating::invalid; +use super::record::{BODY_CHARS, Pr, Prs}; +use super::references::reference_numbers; +use crate::util::digest; + +/// Digest of the captured fields a judgment actually depends on. +/// +/// The whole envelope churns without the PR changing: repository-wide counters, +/// URL scaffolding and nested remote objects all move on unrelated events. +pub fn pr_evidence_digest(item: &Value) -> String { + const FIELDS: [&str; 21] = [ + "number", + "title", + "body", + "created_at", + "updated_at", + "state", + "draft", + "labels", + "milestone", + "requested_reviewers", + "requested_teams", + "changed_files", + "additions", + "deletions", + "commits", + "comments", + "review_comments", + "merged_at", + "merge_commit_sha", + "user", + "head", + ]; + let Some(object) = item.as_object() else { + return digest(&Value::Object(Map::new())); + }; + let mut evidence = Map::new(); + for field in FIELDS { + let Some(value) = object.get(field) else { + continue; + }; + let projected = match field { + "user" => project_object(value, &["login"]), + "head" => project_object(value, &["sha", "ref", "label"]), + "labels" => project_labels(value), + _ => value.clone(), + }; + evidence.insert(field.to_owned(), projected); + } + digest(&Value::Object(evidence)) +} + +fn project_object(value: &Value, keep: &[&str]) -> Value { + match value { + Value::Object(object) => Value::Object( + keep.iter() + .filter(|key| object.contains_key(**key)) + .map(|key| ((*key).to_owned(), object[*key].clone())) + .collect(), + ), + Value::Array(items) => Value::Array( + items + .iter() + .map(|item| match item { + Value::Object(object) => Value::Object( + keep.iter() + .filter(|key| object.contains_key(**key)) + .map(|key| ((*key).to_owned(), object[*key].clone())) + .collect(), + ), + other => other.clone(), + }) + .collect(), + ), + other => other.clone(), + } +} + +fn project_labels(value: &Value) -> Value { + match value.as_array() { + Some(items) => Value::Array( + items + .iter() + .map( + |label| match label.as_object().and_then(|o| o.get("name")) { + Some(name) => name.clone(), + None => label.clone(), + }, + ) + .collect(), + ), + None => value.clone(), + } +} + +/// Project one captured item into the fields the pipeline works with. +pub(super) fn project(item: &Value, repository: &str) -> Pr { + let object = item.as_object().expect("validated before projection"); + let number = object["number"] + .as_u64() + .expect("validated as a positive int"); + let raw_body = object.get("body").and_then(Value::as_str).unwrap_or(""); + let refs = reference_numbers(raw_body, repository, Some(number)); + let body = clean_body(raw_body); + let text = |key: &str| { + object + .get(key) + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned() + }; + let nested = |key: &str, field: &str| { + object + .get(key) + .and_then(Value::as_object) + .and_then(|value| value.get(field)) + .and_then(Value::as_str) + .map(str::to_owned) + }; + let size = |key: &str| object.get(key).and_then(Value::as_i64); + let author = nested("user", "login") + .or_else(|| nested("author", "login")) + .unwrap_or_else(|| "unknown".to_owned()); + let url = text("html_url"); + Pr { + number, + title: text("title").trim().to_owned(), + body_truncated: body.chars().count() > BODY_CHARS, + body: body.chars().take(BODY_CHARS).collect(), + author, + created: text("created_at"), + updated: text("updated_at"), + draft: object + .get("draft") + .and_then(Value::as_bool) + .unwrap_or(false), + files: size("changed_files"), + additions: size("additions"), + deletions: size("deletions"), + labels: object + .get("labels") + .and_then(Value::as_array) + .map(|labels| { + labels + .iter() + .filter_map(|label| { + label + .as_object() + .and_then(|value| value.get("name")) + .and_then(Value::as_str) + .map(str::to_owned) + }) + .collect() + }) + .unwrap_or_default(), + refs: refs.clone(), + head_sha: nested("head", "sha"), + url: if url.is_empty() { + format!("https://github.com/{repository}/pull/{number}") + } else { + url + }, + source_digest: digest(item), + evidence_digest: pr_evidence_digest(item), + ref_digest: digest(&serde_json::json!({ "references": refs })), + } +} + +/// Strip comments, images and bare links, then collapse whitespace. +/// +/// The judged body is prose: markup and URLs are noise the model should not be +/// charged for. +fn clean_body(raw: &str) -> String { + static COMMENT: OnceLock = OnceLock::new(); + static IMAGE: OnceLock = OnceLock::new(); + static LINK: OnceLock = OnceLock::new(); + static SPACE: OnceLock = OnceLock::new(); + let comment = COMMENT.get_or_init(|| Regex::new(r"(?s)").expect("static pattern")); + let image = IMAGE.get_or_init(|| Regex::new(r"!\[[^\]]*\]\([^)]*\)").expect("static pattern")); + let link = LINK.get_or_init(|| Regex::new(r"https?://\S+").expect("static pattern")); + let space = SPACE.get_or_init(|| Regex::new(r"\s+").expect("static pattern")); + let text = comment.replace_all(raw, ""); + let text = image.replace_all(&text, ""); + let text = link.replace_all(&text, ""); + space.replace_all(&text, " ").trim().to_owned() +} + +/// PR number → the references it contributes as comparison candidates. +pub fn ref_index(prs: &Prs) -> HashMap> { + prs.iter().map(|pr| (pr.number, pr.refs.clone())).collect() +} + +/// The state handed to the model for one PR. +pub fn pr_state(pr: &Pr) -> Value { + let sizes = [pr.files, pr.additions, pr.deletions]; + let known = sizes + .iter() + .all(|size| size.is_some_and(|value| value >= 0)); + let diffstat = match (pr.files, pr.additions, pr.deletions) { + (Some(files), Some(additions), Some(deletions)) if known => { + format!("{files} files changed, +{additions}/-{deletions}") + } + _ => "unknown (not supplied by the captured PR list)".to_owned(), + }; + serde_json::json!({ + "pr": { + "title": pr.title, + "body": if pr.body.is_empty() { "(empty body)".to_owned() } else { pr.body.clone() }, + "author": pr.author, + "diffstat": diffstat, + "draft": pr.draft, + "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", + "diffstat_available": known, + "body_truncated": pr.body_truncated, + } + }) +} + +/// Read a JSON file, or report that the report inputs are unusable. +pub fn read_json(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(invalid)?; + serde_json::from_str(&text).map_err(invalid) +} diff --git a/crates/tranche-core/src/domain/pr/record.rs b/crates/tranche-core/src/domain/pr/record.rs new file mode 100644 index 0000000..9838ab0 --- /dev/null +++ b/crates/tranche-core/src/domain/pr/record.rs @@ -0,0 +1,73 @@ +//! A captured pull request, and the corpus they make up. +//! +//! A PR is read from captured pages, never fetched here, so the corpus is a fixed +//! statement rather than a moving target: every digest downstream is computed +//! against these bytes. + +use crate::util::digest; +use std::collections::HashMap; + +/// Characters of a cleaned description kept for judging. +pub const BODY_CHARS: usize = 1200; +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pr { + pub number: u64, + pub title: String, + pub body: String, + pub author: String, + pub created: String, + pub updated: String, + pub draft: bool, + pub files: Option, + pub additions: Option, + pub deletions: Option, + pub labels: Vec, + pub refs: Vec, + pub head_sha: Option, + pub url: String, + pub source_digest: String, + pub evidence_digest: String, + pub ref_digest: String, + pub body_truncated: bool, +} +/// The membership, in capture order. +/// +/// Order is preserved because the membership digest is over an ordered list of +/// PR numbers; a set would silently reorder it. +#[derive(Debug, Clone, Default)] +pub struct Prs { + order: Vec, + pub(crate) by_number: HashMap, +} +impl Prs { + pub fn len(&self) -> usize { + self.order.len() + } + + pub fn is_empty(&self) -> bool { + self.order.is_empty() + } + + pub fn get(&self, number: u64) -> Option<&Pr> { + self.by_number.get(&number) + } + + /// PR numbers in capture order. + pub fn numbers(&self) -> &[u64] { + &self.order + } + + pub fn iter(&self) -> impl Iterator { + self.order.iter().filter_map(|n| self.by_number.get(n)) + } + + /// SHA-256 over the ordered PR-number list, as the pipeline records it. + pub fn membership_digest(&self) -> String { + digest(&serde_json::json!(self.order)) + } + + pub(crate) fn insert(&mut self, pr: Pr) { + self.order.push(pr.number); + self.by_number.insert(pr.number, pr); + } +} diff --git a/crates/tranche-core/src/domain/pr/references.rs b/crates/tranche-core/src/domain/pr/references.rs new file mode 100644 index 0000000..2d9912c --- /dev/null +++ b/crates/tranche-core/src/domain/pr/references.rs @@ -0,0 +1,88 @@ +//! Literal body references: which PRs a description mentions. +//! +//! A mention selects a comparison candidate only when it names a pull request of +//! the repository under review: a bare `#N` can only mean this repository, while +//! a GitHub link or `owner/repo#N` names its own repository and must not be read +//! as ours. + +use regex::Regex; +use std::sync::OnceLock; + +pub fn reference_numbers(raw_body: &str, repository: &str, own_number: Option) -> Vec { + let mut spans: Vec<(usize, usize)> = Vec::new(); + let mut numbers: Vec = Vec::new(); + let add = |value: u64, numbers: &mut Vec| { + if !numbers.contains(&value) { + numbers.push(value); + } + }; + for pattern in [link_reference(), qualified_reference()] { + for capture in pattern.captures_iter(raw_body) { + let whole = capture.get(0).expect("a capture has a whole match"); + spans.push((whole.start(), whole.end())); + let repo = capture.name("repo").map(|m| m.as_str()).unwrap_or(""); + if repo.eq_ignore_ascii_case(repository) + && let Some(number) = capture + .name("number") + .and_then(|m| m.as_str().parse::().ok()) + { + add(number, &mut numbers); + } + } + } + for capture in bare_reference().captures_iter(raw_body) { + let whole = capture.get(0).expect("a capture has a whole match"); + // The intent is a negative look-behind on `[\w#]`; the `regex` crate has no + // look-around, so the preceding character is checked directly. Both + // forms reject the `#123` inside `abc#123` or `#123#456`. + if raw_body[..whole.start()] + .chars() + .next_back() + .is_some_and(|previous| { + previous.is_alphanumeric() || previous == '_' || previous == '#' + }) + { + continue; + } + if spans + .iter() + .any(|(start, end)| *start <= whole.start() && whole.start() < *end) + { + continue; + } + if let Some(number) = capture + .name("number") + .and_then(|m| m.as_str().parse::().ok()) + { + add(number, &mut numbers); + } + } + if let Some(own) = own_number { + numbers.retain(|number| *number != own); + } + numbers.sort_unstable(); + numbers +} + +fn link_reference() -> &'static Regex { + static PATTERN: OnceLock = OnceLock::new(); + PATTERN.get_or_init(|| { + Regex::new( + r"https?://(?:www\.)?github\.com/(?P[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/(?:issues|pull)/(?P\d+)", + ) + .expect("static pattern") + }) +} + +fn qualified_reference() -> &'static Regex { + static PATTERN: OnceLock = OnceLock::new(); + PATTERN.get_or_init(|| { + Regex::new(r"(?P[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)#(?P\d+)") + .expect("static pattern") + }) +} + +fn bare_reference() -> &'static Regex { + static PATTERN: OnceLock = OnceLock::new(); + PATTERN.get_or_init(|| Regex::new(r"#(?P\d+)\b").expect("static pattern")) +} diff --git a/crates/tranche-core/src/domain/pr/validating.rs b/crates/tranche-core/src/domain/pr/validating.rs new file mode 100644 index 0000000..c8e387c --- /dev/null +++ b/crates/tranche-core/src/domain/pr/validating.rs @@ -0,0 +1,46 @@ +//! The corpus-level check a captured PR must pass. + +use serde_json::Value; + +use super::error::PrError; + +/// A captured PR must carry the fields a judgment reads, or nothing may use it. +pub fn validate_pr(item: &Value) -> Result<(), PrError> { + let object = item + .as_object() + .ok_or_else(|| PrError("invalid captured PR shape; fetch again".into()))?; + match object.get("number") { + Some(Value::Number(number)) if number.as_u64().is_some_and(|n| n > 0) => {} + _ => return Err(PrError("invalid captured PR shape; fetch again".into())), + } + if !object.get("title").is_some_and(Value::is_string) { + return Err(PrError("invalid captured PR shape; fetch again".into())); + } + match object.get("body") { + None | Some(Value::Null) | Some(Value::String(_)) => {} + Some(_) => return Err(PrError("invalid captured PR shape; fetch again".into())), + } + for field in ["head", "user", "author"] { + match object.get(field) { + None | Some(Value::Null) | Some(Value::Object(_)) => {} + Some(_) => { + return Err(PrError(format!("invalid captured PR {field}; fetch again"))); + } + } + } + if let Some(labels) = object.get("labels").filter(|v| !v.is_null()) { + let items = labels + .as_array() + .ok_or_else(|| PrError("invalid captured PR labels; fetch again".into()))?; + for label in items { + let valid = label + .as_object() + .and_then(|object| object.get("name")) + .is_some_and(Value::is_string); + if !valid { + return Err(PrError("invalid captured PR labels; fetch again".into())); + } + } + } + Ok(()) +} diff --git a/crates/tranche-core/src/domain/questions.rs b/crates/tranche-core/src/domain/questions.rs new file mode 100644 index 0000000..c0f9d70 --- /dev/null +++ b/crates/tranche-core/src/domain/questions.rs @@ -0,0 +1,126 @@ +//! The question policy. +//! +//! This is a frozen contract, not configuration. `judgment_binding()` and +//! `pair_binding()` digest it, so editing a single character re-asks every +//! question in the corpus and re-bills the full backlog. It is written here as +//! data for the same reason: the shape is the API. + +use serde_json::{Value, json}; + +/// A metric's ceiling, which decides whether a model answer is usable. +/// +/// Absent, non-finite or out-of-range values are unknown, never zero. +pub fn metric_ceiling(name: &str, field: &str) -> Option { + match field { + "noul" => Some(1.0), + "score" if name == "risk" => Some(4.0), + "score" => Some(3.0), + _ => None, + } +} + +/// The seven typed questions asked of one PR in a single batched call. +pub fn judge_questions() -> Value { + json!({ + "category": { + "type": "choice", + "instructions": { + "question": "Which area of Omarchy does this pull request mainly touch? Read `pr.title` and `pr.body`; `pr.diffstat` shows the size. Pick exactly one; use `unclear` only when the text is too thin to tell." + }, + "criteria": { + "install-setup": "omarchy-setup menu, installer, first boot, ISO, dotfiles bootstrap", + "desktop-config": "Hyprland, Walker, waybar, wlogout, mako, keybinds, wallpapers, theming", + "user-experience": "a default/taste or look-and-feel proposal (themes, wallpapers, icons, fonts, bar or menu aesthetics); judge by the change's effect, not the subsystem it edits", + "shell-cli": "zsh config, aliases, starship, CLI tool defaults, terminal usage", + "apps-integrations": "default apps, mime handling, new application integrations (e.g. dropbox, spotify, 1password)", + "hardware-drivers": "NVIDIA, wifi, bluetooth, audio, power, HiDPI, laptops, ARM/Snapdragon, firmware", + "update-release": "omarchy-update, version bumps, release machinery, migration between versions, boot entries", + "agents-ai": "AI coding agents, agent hooks, MCP, integrations for Claude/Codex/Gemini-like tools", + "docs": "README, documentation, wiki, help text only", + "fix-misc": "a real change that fits none of the above", + "unclear": "cannot be placed from title and body alone" + } + }, + "risk": { + "type": "score", + "instructions": { + "question": "How risky is merging this pull request for existing Omarchy installations? Judge from `pr.title`, `pr.body` and `pr.diffstat`." + }, + "criteria": [ + "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", + "Config or script change that is scoped and revertible; no root-side effects at install/update time", + "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", + "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", + "Could break existing installs outright: data loss, boot failure, or user lockout" + ] + }, + "is_fix": { + "type": "noul", + "instructions": "Is this pull request primarily a fix for a bug or regression, rather than a new feature, a default/taste change, or a refactor? Judge from `pr.title` and `pr.body`." + }, + "dupe_signal": { + "type": "noul", + "instructions": "Do `pr.title` or `pr.body` indicate this pull request duplicates another change, or is superseded by / supersedes one (another open PR, or already-merged upstream work)?" + }, + "finished_form": { + "type": "score", + "instructions": { + "question": "Is this pull request in finished, reviewable form as described by `pr.body` (with `pr.title`)? DHH asked the triage team to ensure everything is ready for consideration in a finished form." + }, + "criteria": [ + "Empty or near-empty body; no description of what or why", + "Says what it does but not why, or shows no evidence it was tried", + "Clear what and why; states that it was tested on a real system", + "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused" + ] + }, + "review_effort": { + "type": "score", + "instructions": { + "question": "How much reviewer effort does this pull request need, judging by `pr.diffstat` and the change described?" + }, + "criteria": [ + "Trivial and mechanical: a typo, version number, or one-line constant", + "Small: one focused change a reviewer can hold in their head", + "Moderate: several related edits that must be checked together", + "Substantial: architectural or many-part change needing deep review" + ] + }, + "security_flag": { + "type": "noul", + "instructions": "Does this change touch credentials or secrets, download-and-execute remote code, sudo/permission changes, network exposure, or crypto material? Judge from `pr.title` and `pr.body`." + } + }) +} + +/// The one question asked of a candidate pair. +pub fn pair_questions() -> Value { + json!({ + "sameness": { + "type": "choice", + "instructions": { + "question": "Do `pr_a` and `pr_b` propose the same underlying change to Omarchy? Judge by what they modify and the outcome, not by wording." + }, + "criteria": { + "same_change": "two attempts at the same change; merging one makes the other redundant", + "related_but_different": "same area or theme but distinct outcomes; both could merge", + "unrelated": "different changes that merely share words" + } + } + }) +} + +/// The criterion labels for `sameness`, in policy order. +pub fn sameness_criteria() -> Vec<&'static str> { + vec!["same_change", "related_but_different", "unrelated"] +} + +/// The field a question's answer is read from. +pub fn answer_field(question_type: &str) -> Option<&'static str> { + match question_type { + "choice" => Some("choice"), + "score" => Some("score"), + "noul" => Some("noul"), + _ => None, + } +} diff --git a/crates/tranche-core/src/evidence/capture/checks.rs b/crates/tranche-core/src/evidence/capture/checks.rs new file mode 100644 index 0000000..b445f81 --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/checks.rs @@ -0,0 +1,83 @@ +//! The checks a response must pass, and the small URL helpers. + +use serde_json::Value; + +use super::super::read::Response; +use super::super::selection::Member; +use super::endpoints::{ci_repo, ci_repo_id, list_params}; + +/// A CI response must name the repository and revision that was asked about. +pub(crate) fn verify_ci_scope( + member: &Member, + group: &str, + response: &Response, +) -> Result<(), String> { + let payload = response.json().map_err(|error| error.message)?; + let expected_repo = ci_repo(member, group); + let expected_id = ci_repo_id(member, group); + if let Some(repo) = payload.get("repository").filter(|repo| repo.is_object()) { + if repo.get("full_name").and_then(Value::as_str) != Some(&expected_repo) { + return Err(format!( + "CI for #{} came from {:?}, not {:?}", + member.number, + repo.get("full_name").and_then(Value::as_str).unwrap_or(""), + expected_repo + )); + } + if let Some(id) = repo.get("id").and_then(Value::as_u64) + && id != expected_id + { + return Err(format!( + "CI for #{} came from repository id {id}, not {expected_id}", + member.number + )); + } + } + if let Some(sha) = payload.get("sha").and_then(Value::as_str) + && sha != member.head_sha + { + return Err(format!( + "CI for #{} names revision {sha}, not {}", + member.number, member.head_sha + )); + } + for run in payload + .get("check_runs") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + if !run.is_object() { + return Err(format!( + "CI for #{} returned a malformed check run", + member.number + )); + } + if let Some(sha) = run.get("head_sha").and_then(Value::as_str) + && sha != member.head_sha + { + return Err(format!( + "a check run for #{} names revision {sha}", + member.number + )); + } + } + Ok(()) +} +/// Append pagination parameters to a URL. +pub(crate) fn with_params(at: &str, component: &str, group: &str, page: u64) -> String { + let params = list_params(component, group, page); + if params.is_empty() { + return at.to_owned(); + } + let query: Vec = params + .into_iter() + .map(|(key, value)| format!("{key}={value}")) + .collect(); + let separator = if at.contains('?') { '&' } else { '?' }; + format!("{at}{separator}{}", query.join("&")) +} +/// Whether a transport message is the budget running out rather than a failure. +pub(crate) fn is_exhausted(message: &str) -> bool { + message.contains("budget exhausted") +} diff --git a/crates/tranche-core/src/evidence/capture/endpoints.rs b/crates/tranche-core/src/evidence/capture/endpoints.rs new file mode 100644 index 0000000..37f0fbe --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/endpoints.rs @@ -0,0 +1,225 @@ +//! Where each component is read from, and how its pages are addressed. +//! +//! The component map is the whole reason a capture is checkable: a reviewer asking +//! "was the CI observed?" gets an answer that names the repository the answer came +//! from, rather than an absence one source could not have seen. + +use serde_json::Value; + +use super::super::read::transport::GRAPHQL_URL; +use super::super::read::url; +use super::super::selection::Member; + +/// The media type that returns a patch rather than JSON. +pub const DIFF_ACCEPT: &str = "application/vnd.github.diff"; +/// The media type the other REST components ask for. +pub const JSON_MEDIA: &str = "application/vnd.github+json"; +/// The page size every list request asks for. +/// +/// It is always sent rather than assumed: GitHub's default is 30, and a page whose +/// size we do not control cannot be reasoned about. +pub const PER_PAGE: u64 = 100; +/// GitHub's own ceiling on a check-run collection. +pub const CHECK_RUN_CAP: u64 = 1000; +/// GitHub's own ceiling on a file list. +pub const FILE_LIST_CAP: u64 = 3000; + +/// The base repository's CI groups, which every member has. +pub const BASE_CI_GROUPS: [&str; 2] = ["check_runs", "statuses"]; +/// The fork's CI groups, present only when the head repository differs. +pub const FORK_CI_GROUPS: [&str; 2] = ["fork_check_runs", "fork_statuses"]; + +/// The groups one component is made of, for this member. +/// +/// `checks` is the one component whose groups depend on the member: a PR's own +/// checks live in its base repository, and a fork's head can carry its own. +pub fn groups_for(member: &Member, component: &str) -> Vec { + if component == "checks" { + return ci_targets(member) + .into_iter() + .map(|(group, _, _)| group) + .collect(); + } + vec![component.to_owned()] +} + +/// Every repository whose CI is worth reading for this member, and which groups +/// come from it. +pub fn ci_targets(member: &Member) -> Vec<(String, String, u64)> { + let mut targets: Vec<(String, String, u64)> = BASE_CI_GROUPS + .iter() + .map(|group| { + ( + (*group).to_owned(), + member.base_repo_name.clone(), + member.base_repo_id, + ) + }) + .collect(); + if member.head_repo_name != member.base_repo_name { + targets.extend(FORK_CI_GROUPS.iter().map(|group| { + ( + (*group).to_owned(), + member.head_repo_name.clone(), + member.head_repo_id, + ) + })); + } + targets +} + +/// The repository a CI group is read from: the PR's own, or the linked fork. +pub fn ci_repo(member: &Member, group: &str) -> String { + if FORK_CI_GROUPS.contains(&group) { + member.head_repo_name.clone() + } else { + member.base_repo_name.clone() + } +} + +/// That repository's numeric identity. +pub fn ci_repo_id(member: &Member, group: &str) -> u64 { + if FORK_CI_GROUPS.contains(&group) { + member.head_repo_id + } else { + member.base_repo_id + } +} + +/// The repository a component's URL must stay inside. +pub fn repo_prefix(member: &Member, component: &str, group: &str) -> String { + if component == "checks" { + ci_repo(member, group) + } else { + member.base_repo_name.clone() + } +} + +/// The first URL of a component's group. +pub fn source_url(member: &Member, component: &str, group: &str) -> String { + let base = &member.base_repo_name; + let number = member.number; + match component { + // Metadata and the diff are the same resource read as two + // representations: one JSON, one patch. + "metadata" | "diff" => format!("{}/repos/{base}/pulls/{number}", url::ORIGIN), + "files" => format!("{}/repos/{base}/pulls/{number}/files", url::ORIGIN), + "discussion" => format!("{}/repos/{base}/issues/{number}/comments", url::ORIGIN), + "review_comments" => format!("{}/repos/{base}/pulls/{number}/comments", url::ORIGIN), + "reviews" => format!("{}/repos/{base}/pulls/{number}/reviews", url::ORIGIN), + "checks" => { + let suffix = if group.ends_with("check_runs") { + "check-runs" + } else { + "status" + }; + // Check runs are read at the head revision, which is the revision whose + // CI the PR is claiming. + format!( + "{}/repos/{}/commits/{}/{suffix}", + url::ORIGIN, + ci_repo(member, group), + member.head_sha + ) + } + "closing_issues" => GRAPHQL_URL.to_owned(), + other => format!("{}/repos/{base}/pulls/{number}/{other}", url::ORIGIN), + } +} + +/// The representation a component is read as. +pub fn accept_for(component: &str) -> &'static str { + if component == "diff" { + DIFF_ACCEPT + } else { + JSON_MEDIA + } +} + +/// Pagination parameters for a group. Single-object groups take none. +pub fn list_params(component: &str, group: &str, page: u64) -> Vec<(String, String)> { + match component { + "metadata" | "diff" => Vec::new(), + // The combined status is one object, not a list. + "checks" if group == "statuses" || group == "fork_statuses" => Vec::new(), + _ => vec![ + ("per_page".to_owned(), PER_PAGE.to_string()), + ("page".to_owned(), page.to_string()), + ], + } +} + +/// The closing-issues query. +/// +/// It carries a `totalCount` so the observed-versus-reported gap can be checked, and +/// a cursor so pagination is explicit rather than assumed complete. +pub fn closing_query() -> &'static str { + // A single literal, not line-continuations: a swallowed space between tokens + // becomes `idpullRequest`, and GitHub refuses the whole query. + "query trancheClosingIssues($owner:String!,$name:String!,$number:Int!,$cursor:String){ repository(owner:$owner,name:$name){ nameWithOwner id pullRequest(number:$number){ number url closingIssuesReferences(first:100,after:$cursor){ totalCount pageInfo{hasNextPage endCursor} nodes{number url state title} } } } }" +} + +/// The variables for one page of the closing-issues query. +pub fn closing_variables(member: &Member, cursor: Option<&str>) -> Value { + let (owner, name) = member + .base_repo_name + .split_once('/') + .unwrap_or((member.base_repo_name.as_str(), "")); + serde_json::json!({ + "owner": owner, + "name": name, + "number": member.number, + "cursor": cursor, + }) +} + +/// Read one closing-issues page, or refuse a malformed or foreign answer. +/// +/// Returns the next cursor and the observed item count. The query can answer for +/// the wrong repository or pull request when an endpoint misbehaves, so both are +/// checked rather than trusted. +pub fn parse_closing(payload: &Value, member: &Member) -> Result<(Option, u64), String> { + if !payload.is_object() { + return Err("closing-issues query returned a non-object".to_owned()); + } + if let Some(errors) = payload.get("errors").filter(|errors| !errors.is_null()) { + return Err(format!("closing-issues query reported errors: {errors}")); + } + let repository = payload + .get("data") + .and_then(|data| data.get("repository")) + .ok_or_else(|| "closing-issues query returned no repository".to_owned())?; + if repository.get("nameWithOwner").and_then(Value::as_str) != Some(&member.base_repo_name) { + return Err(format!( + "closing-issues query answered for {:?}, not {:?}", + repository + .get("nameWithOwner") + .and_then(Value::as_str) + .unwrap_or(""), + member.base_repo_name + )); + } + let pull = repository + .get("pullRequest") + .ok_or_else(|| "closing-issues query answered about no pull request".to_owned())?; + if pull.get("number").and_then(Value::as_u64) != Some(member.number) { + return Err("closing-issues query answered about a different pull request".to_owned()); + } + let connection = pull + .get("closingIssuesReferences") + .ok_or_else(|| "closing-issues query returned no connection".to_owned())?; + let page_info = connection.get("pageInfo").cloned().unwrap_or(Value::Null); + let nodes = connection + .get("nodes") + .and_then(Value::as_array) + .ok_or_else(|| "closing-issues query returned no nodes".to_owned())?; + let next = if page_info.get("hasNextPage").and_then(Value::as_bool) == Some(true) { + page_info + .get("endCursor") + .and_then(Value::as_str) + .map(str::to_owned) + } else { + None + }; + Ok((next, nodes.len() as u64)) +} diff --git a/crates/tranche-core/src/evidence/capture/groups.rs b/crates/tranche-core/src/evidence/capture/groups.rs new file mode 100644 index 0000000..3fb8d5f --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/groups.rs @@ -0,0 +1,287 @@ +//! Reading one group: a REST list, or the closing-issues query. +//! +//! A group that cannot be read is blocked and named rather than failing the run. Half a +//! capture with an accurate gap is more useful than no capture with a silent one. + +use super::super::read::transport; +use super::super::selection::Member; +use super::checks::{is_exhausted, verify_ci_scope, with_params}; +use super::endpoints::{JSON_MEDIA, accept_for, repo_prefix, source_url}; +use super::lifecycle::Capture; +use super::outcome::{MAX_DIFF_BYTES, MAX_DIFF_LINES, Stopped}; +use super::pages::{self, Counts}; +use super::records; + +impl<'a> Capture<'a> { + pub(crate) fn acquire_group( + &mut self, + member: &Member, + component: &str, + group: &str, + ) -> Result<(), Stopped> { + if component == "closing_issues" { + return self.acquire_closing(member); + } + self.acquire_rest(member, component, group) + } + pub(crate) fn acquire_rest( + &mut self, + member: &Member, + component: &str, + group: &str, + ) -> Result<(), Stopped> { + let mut counts = Counts::default(); + let accept = accept_for(component); + let prefix = repo_prefix(member, component, group); + let mut page = self.group_pages(member.number, component, group) + 1; + let mut at = self + .group_next_url(member.number, component, group) + .unwrap_or_else(|| source_url(member, component, group)); + + loop { + self.reserve()?; + // Metadata and the diff take no pagination parameters; sending them + // would be a different request than the one the URL names. + let reserve = self.budget.reserved; + let url = with_params(&at, component, group, page); + let response = match transport::get( + &url, + Some(accept), + Some(&mut self.budget), + Some(reserve), + Some(&prefix), + ) { + Ok(response) => response, + Err(error) if error.too_large => { + self.block( + member.number, + component, + group, + &format!("response exceeds the transport bound: {}", error.message), + ); + return Ok(()); + } + Err(error) if is_exhausted(&error.message) => { + self.stopped = Stopped::Budget; + return Err(Stopped::Budget); + } + Err(error) => { + self.block( + member.number, + component, + group, + &format!("acquisition failed: {}", error.message), + ); + return Ok(()); + } + }; + + // A CI response names the repository it came from, and a + // repository-prefix check on the URL is not proof that it is the + // resource that was asked for. + if component == "checks" + && let Err(reason) = verify_ci_scope(member, group, &response) + { + self.block(member.number, component, group, &reason); + return Ok(()); + } + + let accepted = if component == "diff" { + pages::diff(&response, MAX_DIFF_BYTES, MAX_DIFF_LINES) + } else { + pages::list(member, component, group, &response, page, &mut counts) + }; + let accepted = match accepted { + Ok(accepted) => accepted, + Err(reason) => { + self.block(member.number, component, group, &reason); + return Ok(()); + } + }; + + // The media type is owned because the record borrows it. + let media_type = response.media_type(); + let page_text = page.to_string(); + let cursor = if page > 1 { + Some(page_text.as_str()) + } else { + None + }; + let recorded = records::record( + self.root, + &mut self.manifest, + records::Recorded { + number: member.number, + component, + group, + body: &response.body, + url: &response.url, + accept, + media_type: &media_type, + cursor, + next_cursor: accepted.next.as_deref(), + }, + ); + if let Err(reason) = recorded { + self.block(member.number, component, group, &reason); + return Ok(()); + } + self.fetched += 1; + records::set_counts(&mut self.manifest, member.number, component, group, &counts); + + if self.over_storage() { + records::finish( + &mut self.manifest, + member.number, + component, + group, + false, + Some("incomplete: stopped at the storage bound"), + ); + self.stopped = Stopped::Budget; + return Err(Stopped::Budget); + } + + if accepted.complete { + let reason = pages::shortfall(component, group, &counts); + records::finish( + &mut self.manifest, + member.number, + component, + group, + reason.is_none(), + reason.as_deref(), + ); + return Ok(()); + } + let Some(next) = accepted.next else { + records::finish( + &mut self.manifest, + member.number, + component, + group, + false, + Some("incomplete: no continuation"), + ); + return Ok(()); + }; + if page >= self.max_pages { + records::finish( + &mut self.manifest, + member.number, + component, + group, + false, + Some(&format!( + "incomplete: stopped at the {}-page bound", + self.max_pages + )), + ); + return Ok(()); + } + at = next; + page += 1; + } + } + pub(crate) fn acquire_closing(&mut self, member: &Member) -> Result<(), Stopped> { + let mut cursor: Option = None; + let mut page = self.group_pages(member.number, "closing_issues", "closing_issues") + 1; + loop { + self.reserve()?; + let variables = super::endpoints::closing_variables(member, cursor.as_deref()); + let reserve = self.budget.reserved; + let response = match transport::graphql( + super::endpoints::closing_query(), + &variables, + Some(&mut self.budget), + Some(reserve), + ) { + Ok(response) => response, + Err(error) if is_exhausted(&error.message) => { + self.stopped = Stopped::Budget; + return Err(Stopped::Budget); + } + Err(error) => { + self.block( + member.number, + "closing_issues", + "closing_issues", + &format!("acquisition failed: {}", error.message), + ); + return Ok(()); + } + }; + let payload = response.json().map_err(|_| Stopped::Transport)?; + let (next, observed) = match super::endpoints::parse_closing(&payload, member) { + Ok(parsed) => parsed, + Err(reason) => { + self.block(member.number, "closing_issues", "closing_issues", &reason); + return Ok(()); + } + }; + let media_type = response.media_type(); + let recorded = records::record( + self.root, + &mut self.manifest, + records::Recorded { + number: member.number, + component: "closing_issues", + group: "closing_issues", + body: &response.body, + url: &response.url, + accept: JSON_MEDIA, + media_type: &media_type, + cursor: cursor.as_deref(), + next_cursor: next.as_deref(), + }, + ); + if let Err(reason) = recorded { + self.block(member.number, "closing_issues", "closing_issues", &reason); + return Ok(()); + } + self.fetched += 1; + records::set_counts( + &mut self.manifest, + member.number, + "closing_issues", + "closing_issues", + &Counts { + observed, + reported: None, + }, + ); + + match next { + None => { + records::finish( + &mut self.manifest, + member.number, + "closing_issues", + "closing_issues", + true, + None, + ); + return Ok(()); + } + Some(_next) if page >= self.max_pages => { + records::finish( + &mut self.manifest, + member.number, + "closing_issues", + "closing_issues", + false, + Some(&format!( + "incomplete: stopped at the {}-page bound", + self.max_pages + )), + ); + return Ok(()); + } + Some(next) => { + cursor = Some(next); + page += 1; + } + } + } + } +} diff --git a/crates/tranche-core/src/evidence/capture/lifecycle.rs b/crates/tranche-core/src/evidence/capture/lifecycle.rs new file mode 100644 index 0000000..86904d1 --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/lifecycle.rs @@ -0,0 +1,142 @@ +//! Starting a run, and the order the work happens in. +//! +//! Two checks bracket the acquisition. A live revision check runs first, because it +//! decides whether recorded code evidence may be reused at all. The final identity +//! checks run last, against a budget held back for exactly that, because sources may +//! not be certified against a revision that moved while the run was working. + +use serde_json::{Value, json}; + +use super::super::read::transport; +use super::super::selection::Selection; +use super::super::{COMPONENTS, RESERVED_BUDGET}; +use super::endpoints::groups_for; +use super::outcome::{MAX_PAGES, Stopped, Verify}; +use crate::report::Root; + +/// One capture run over one manifest. +pub struct Capture<'a> { + pub(crate) root: &'a Root, + pub(crate) selection: Selection, + pub(crate) capture_id: String, + pub(crate) manifest: Value, + pub(crate) budget: transport::Budget, + pub(crate) max_bytes: u64, + pub(crate) max_pages: u64, + pub(crate) stopped: Stopped, + pub(crate) reused: u64, + pub(crate) fetched: u64, + pub log: Vec, +} +impl<'a> Capture<'a> { + pub fn new( + root: &'a Root, + selection: Selection, + capture_id: String, + manifest: Value, + request_limit: u64, + max_bytes: u64, + ) -> Result { + Ok(Self { + root, + selection, + capture_id, + manifest, + budget: transport::Budget::new(request_limit, RESERVED_BUDGET as u64) + .map_err(|error| error.message)?, + max_bytes, + max_pages: MAX_PAGES, + stopped: Stopped::Finished, + reused: 0, + fetched: 0, + log: Vec::new(), + }) + } + + /// Acquire everything missing, reusing what the live revision allows. + pub fn run(&mut self) -> Stopped { + if self.manifest["capture"]["stop_reason"].as_str() == Some("revision_drift") { + self.stopped = Stopped::RevisionDrift; + return self.stopped.clone(); + } + match self.acquire() { + Ok(()) => Stopped::Finished, + Err(stopped) => stopped, + } + } + fn acquire(&mut self) -> Result<(), Stopped> { + // The live revision check decides whether any recorded code evidence may be + // reused at all, so it runs before the work that reserved capacity protects. + let members = self.selection.members.clone(); + for member in &members { + if !self.budget.can(Some(self.budget.reserved)) { + return Err(Stopped::Budget); + } + let metadata = match self.verify_member(member, None) { + Ok(metadata) => metadata, + Err(Verify::Moved) => return Err(Stopped::RevisionDrift), + Err(Verify::Failed(reason)) => { + self.log.push(format!("#{}: {reason}", member.number)); + self.stopped = Stopped::Transport; + return Err(Stopped::Transport); + } + }; + // A thread-only update refreshes the mutable observations and leaves the + // code observation alone: the diffs still describe the same two commits. + if let Some(live) = metadata.get("updated_at").and_then(Value::as_str) { + let recorded = self.manifest["code_observation"]["thread_updated_at"] + .get(member.number.to_string()) + .and_then(Value::as_str); + if recorded != Some(live) { + self.refresh_mutable(member, live); + } + } + } + self.checkpoint(); + + for member in &members { + for component in COMPONENTS { + for group in groups_for(member, component) { + if self.group_status(member.number, component, &group) == "complete" { + self.reused += 1; + continue; + } + self.acquire_group(member, component, &group)?; + self.checkpoint(); + } + } + } + + // The held-back capacity is spent only now: sources may not be certified + // against a revision that moved while the run was working. + for member in &members { + match self.verify_member(member, Some(0)) { + Ok(_) | Err(Verify::Failed(_)) => {} + Err(Verify::Moved) => { + self.manifest["capture"]["stop_reason"] = json!("revision_drift"); + self.checkpoint(); + self.stopped = Stopped::RevisionDrift; + return Err(Stopped::RevisionDrift); + } + } + } + self.derive_citations()?; + self.checkpoint(); + Ok(()) + } + + /// Derive and record the citations, from the stored bytes. + fn derive_citations(&mut self) -> Result<(), Stopped> { + match super::super::citations::extract_citations(self.root, &self.manifest) { + Ok(citations) => { + self.manifest["citations"] = serde_json::json!(citations); + Ok(()) + } + Err(reason) => { + self.log + .push(format!("citation derivation failed: {reason}")); + Err(Stopped::Transport) + } + } + } +} diff --git a/crates/tranche-core/src/evidence/capture/mod.rs b/crates/tranche-core/src/evidence/capture/mod.rs new file mode 100644 index 0000000..2e580db --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/mod.rs @@ -0,0 +1,28 @@ +//! Acquiring a batch's public evidence: read-only, model-free, resumable. +//! +//! The capture is the one operation that spends a GitHub budget, so its structure is +//! all about being honest under partial progress. It never certifies a source it did +//! not re-check, never presents a capped collection as complete, and never treats a +//! previously public repository as ongoing permission to share. +//! +//! `lifecycle` is the orchestration; `endpoints` says where each component is read from, +//! `pages` decides what one page says about completeness, `records` moves the +//! manifest, and `groups` reads one group. `setup` holds identity, storage and the lock. + +pub mod checks; +pub mod endpoints; +pub mod groups; +pub mod lifecycle; +pub mod outcome; +pub mod pages; +pub mod records; +pub mod setup; +pub mod state; + +pub use lifecycle::Capture; +pub use outcome::{Stopped, Verify}; + +pub use setup::{ + accepted_url, fresh_manifest, generation_of, lock_for, new_capture_id, selection_of, + stored_manifest, +}; diff --git a/crates/tranche-core/src/evidence/capture/outcome.rs b/crates/tranche-core/src/evidence/capture/outcome.rs new file mode 100644 index 0000000..d46258c --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/outcome.rs @@ -0,0 +1,46 @@ +//! The capture's own shape: how it stops, and why a member could not be certified. +//! +//! Every outcome here is a named state rather than a boolean, because a stopped +//! capture is normal — a batch may be larger than one run's budget — and the reason +//! is what tells a reader whether to resume, retry or start over. + +/// The largest diff a capture will keep, in bytes. +pub const MAX_DIFF_BYTES: usize = 3 * 1024 * 1024; +/// The largest diff a capture will keep, in lines. +pub const MAX_DIFF_LINES: usize = 50_000; +/// Pages one group may hold before the group is reported as capped. +pub const MAX_PAGES: u64 = 60; + +/// What a run did and why it stopped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Stopped { + /// Everything the batch needed was acquired. + Finished, + /// The request budget could not cover both acquisition and the final checks. + Budget, + /// The transport failed in a way that was not one group's problem. + Transport, + /// A member moved, so the generation no longer describes it. + RevisionDrift, +} + +impl Stopped { + /// The stop reason recorded in the manifest, or none when the run finished. + pub fn reason(&self) -> Option<&'static str> { + match self { + Self::Finished => None, + Self::Budget => Some("request_budget"), + Self::Transport => Some("transport_error"), + Self::RevisionDrift => Some("revision_drift"), + } + } +} + +/// Why a member could not be certified. +pub enum Verify { + /// The member moved; the generation no longer describes it. + Moved, + /// The check could not be made, which is a transport problem rather than a + /// statement about the member. + Failed(String), +} diff --git a/crates/tranche-core/src/evidence/capture/pages.rs b/crates/tranche-core/src/evidence/capture/pages.rs new file mode 100644 index 0000000..f61dde4 --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/pages.rs @@ -0,0 +1,180 @@ +//! Validating one page and deciding what it says about completeness. +//! +//! Each collection has its own envelope, so each is read in its own terms: +//! check-runs answer with `{total_count, check_runs}` while the other lists are +//! bare arrays. A terminal cursor on a truncated collection is not completeness, +//! which is why the reported total is recorded and compared against what was +//! actually observed rather than assumed to match. + +use serde_json::Value; + +use super::super::read::Response; +use super::super::selection::Member; +use super::endpoints::{CHECK_RUN_CAP, FILE_LIST_CAP}; + +/// What one accepted page says: where to continue, whether the group is done, and +/// why not when it is not. +pub struct Accepted { + pub next: Option, + pub complete: bool, + pub reason: Option, +} + +impl Accepted { + fn continuing(next: String) -> Self { + Self { + next: Some(next), + complete: false, + reason: None, + } + } + + fn done() -> Self { + Self { + next: None, + complete: true, + reason: None, + } + } +} + +/// The observed and reported item counts a group accumulates across pages. +#[derive(Debug, Default, Clone)] +pub struct Counts { + pub observed: u64, + pub reported: Option, +} + +/// Validate one page of the diff representation. +/// +/// An oversized diff is blocked rather than truncated: half a patch presented as a +/// diff would be worse than a named gap, and GitHub itself omits patches for large +/// or unsupported files, which the file list reports separately. +pub fn diff(response: &Response, max_bytes: usize, max_lines: usize) -> Result { + let bytes = response.body.len(); + let lines = response.body.iter().filter(|byte| **byte == b'\n').count(); + if bytes > max_bytes || lines > max_lines { + return Err(format!( + "diff exceeds the review bound ({bytes} bytes, {lines} lines)" + )); + } + if response + .next_url() + .map_err(|error| error.message)? + .is_some() + { + // A diff is one representation, not a paginated list. + return Err("the diff answered with a continuation".to_owned()); + } + Ok(Accepted::done()) +} + +/// Validate one page of a list component, updating the group's counts. +pub fn list( + member: &Member, + component: &str, + group: &str, + response: &Response, + page: u64, + counts: &mut Counts, +) -> Result { + let payload = response.json().map_err(|error| error.message)?; + + match (component, group) { + ("metadata", _) => { + // The metadata response is what proves the capture still describes the + // revision it claims, so a mismatch is refused here as well as at the + // live check. + if !payload.is_object() { + return Err("metadata response is not this pull request".to_owned()); + } + if payload.get("number").and_then(Value::as_u64) != Some(member.number) { + return Err("metadata response is not this pull request".to_owned()); + } + if payload + .get("head") + .and_then(|head| head.get("sha")) + .and_then(Value::as_str) + != Some(&member.head_sha) + { + return Err("metadata response names a different head revision".to_owned()); + } + return Ok(Accepted::done()); + } + ("checks", "statuses" | "fork_statuses") => { + let statuses = payload + .as_object() + .and_then(|object| object.get("statuses")) + .and_then(Value::as_array) + .ok_or_else(|| "combined status response carries no status list".to_owned())?; + counts.observed += statuses.len() as u64; + if let Some(total) = payload.get("total_count").and_then(Value::as_u64) { + counts.reported = Some(total); + } + } + ("checks", _) => { + let runs = payload + .as_object() + .and_then(|object| object.get("check_runs")) + .and_then(Value::as_array) + .ok_or_else(|| "check-runs response carries no check-run list".to_owned())?; + counts.observed += runs.len() as u64; + if let Some(total) = payload.get("total_count").and_then(Value::as_u64) { + counts.reported = Some(total); + } + } + _ => { + if !payload.is_array() { + return Err(format!("{component} response is not a list")); + } + } + } + + match response.next_url().map_err(|error| error.message)? { + Some(next) => { + // A continuation that does not advance would loop forever against a + // live endpoint, so it is treated as no continuation at all. + if super::super::read::url::page_number(&next).map_err(|error| error.message)? <= page { + return Err("continuation URL does not advance the page number".to_owned()); + } + Ok(Accepted::continuing(next)) + } + None => Ok(Accepted::done()), + } +} + +/// A group that reported more items than it delivered is not complete. +/// +/// A terminal cursor says the pagination ended; it does not say the collection was +/// fully observed. Both the reported-versus-observed count and GitHub's own +/// documented ceilings are checked, and either gap is named rather than smoothed +/// over. +pub fn shortfall(component: &str, group: &str, counts: &Counts) -> Option { + match counts.reported { + None => None, + Some(reported) => { + if counts.observed < reported { + return Some(format!( + "incomplete: GitHub reports {reported} items but {} were observed; \ + the collection changed or is capped", + counts.observed + )); + } + if component == "checks" + && reported >= CHECK_RUN_CAP + && (group == "check_runs" || group == "fork_check_runs") + { + return Some(format!( + "incomplete: GitHub caps check runs at the {CHECK_RUN_CAP} most recent \ + suites; iterate the suites to see them all" + )); + } + if component == "files" && reported >= FILE_LIST_CAP { + return Some(format!( + "incomplete: GitHub caps the file list at {FILE_LIST_CAP} entries" + )); + } + None + } + } +} diff --git a/crates/tranche-core/src/evidence/capture/records.rs b/crates/tranche-core/src/evidence/capture/records.rs new file mode 100644 index 0000000..da2c180 --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/records.rs @@ -0,0 +1,157 @@ +//! Recording a page and moving a group's state. +//! +//! A source is appended and given an identity derived from the generation and its +//! own fields, so the same page recorded twice under one generation is the same +//! statement. The page number is the group's own count plus one, which is what makes +//! a resumed capture continue rather than restart. + +use serde_json::{Value, json}; + +use super::super::coverage::roll_up; +use super::super::selection::source_id; +use super::super::store::store_body; +use crate::report::Root; + +/// One page's provenance, as it arrives. +pub struct Recorded<'a> { + pub number: u64, + pub component: &'a str, + pub group: &'a str, + pub body: &'a [u8], + pub url: &'a str, + pub accept: &'a str, + pub media_type: &'a str, + pub cursor: Option<&'a str>, + pub next_cursor: Option<&'a str>, +} + +/// Append one source record and advance its group. +pub fn record(root: &Root, manifest: &mut Value, page: Recorded<'_>) -> Result<(), String> { + let sha = store_body(root, page.body).map_err(|error| error.0)?; + let generation = manifest["generation"].clone(); + let pages = group_entry(manifest, page.number, page.component, page.group)["pages"] + .as_u64() + .unwrap_or(0); + + let mut source = json!({ + "id": "", + "number": page.number, + "component": page.component, + "group": page.group, + "page": pages + 1, + "cursor": page.cursor, + "next_cursor": page.next_cursor, + "url": page.url, + "accept": page.accept, + "media_type": page.media_type, + "captured_at": super::super::now(), + "generation": generation, + "body_sha256": sha, + }); + // The identity is recomputed rather than stored, so a rewritten manifest + // cannot carry a source that names something else. + let identity = source_id(generation.as_str().unwrap_or(""), &source); + source["id"] = json!(identity); + + let sources = manifest["sources"] + .as_array_mut() + .ok_or_else(|| "the manifest has no source list".to_owned())?; + sources.push(source); + + let entry = group_entry(manifest, page.number, page.component, page.group); + entry["pages"] = json!(pages + 1); + let ids = entry["source_ids"] + .as_array_mut() + .ok_or_else(|| "the group has no source list".to_owned())?; + ids.push(json!(identity)); + entry["next_url"] = match page.next_cursor { + Some(cursor) => json!(cursor), + None => Value::Null, + }; + spend_bytes(manifest, page.body.len()) +} + +/// Mark a group complete or partial, and roll the component up. +pub fn finish( + manifest: &mut Value, + number: u64, + component: &str, + group: &str, + complete: bool, + reason: Option<&str>, +) { + let entry = group_entry(manifest, number, component, group); + entry["status"] = json!(if complete { "complete" } else { "partial" }); + entry["reason"] = match reason { + Some(reason) => json!(reason), + None => Value::Null, + }; + if complete { + entry["next_url"] = Value::Null; + } + roll_up(component_entry(manifest, number, component)); +} + +/// Mark a group blocked. A blocked group is a named gap, not a failure of the run: +/// the rest of the capture continues. +pub fn block(manifest: &mut Value, number: u64, component: &str, group: &str, reason: &str) { + let entry = group_entry(manifest, number, component, group); + entry["status"] = json!("blocked"); + entry["reason"] = json!(reason); + roll_up(component_entry(manifest, number, component)); +} + +/// Record the observed and reported counts a group finished with. +pub fn set_counts( + manifest: &mut Value, + number: u64, + component: &str, + group: &str, + counts: &super::pages::Counts, +) { + let entry = group_entry(manifest, number, component, group); + if let serde_json::Value::Object(object) = entry { + object.insert("items_observed".to_owned(), json!(counts.observed)); + if let Some(reported) = counts.reported { + object.insert("items_reported".to_owned(), json!(reported)); + } + } +} + +/// The group state inside one component entry. +pub fn group_entry<'a>( + manifest: &'a mut Value, + number: u64, + component: &str, + group: &str, +) -> &'a mut Value { + let entry = component_entry(manifest, number, component); + entry["groups"] + .as_array_mut() + .and_then(|groups| { + groups + .iter_mut() + .find(|state| state["group"].as_str() == Some(group)) + }) + .expect("the manifest declares every group the component has") +} + +/// The component entry for one member. +pub fn component_entry<'a>(manifest: &'a mut Value, number: u64, component: &str) -> &'a mut Value { + manifest["components"] + .as_array_mut() + .and_then(|components| { + components.iter_mut().find(|entry| { + entry["number"].as_u64() == Some(number) + && entry["component"].as_str() == Some(component) + }) + }) + .expect("the manifest declares every component every member has") +} + +/// Add stored bytes to the capture's running total. +fn spend_bytes(manifest: &mut Value, count: usize) -> Result<(), String> { + let stored = manifest["capture"]["bytes_stored"].as_u64().unwrap_or(0); + manifest["capture"]["bytes_stored"] = json!(stored + count as u64); + Ok(()) +} diff --git a/crates/tranche-core/src/evidence/capture/setup.rs b/crates/tranche-core/src/evidence/capture/setup.rs new file mode 100644 index 0000000..d9ec36d --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/setup.rs @@ -0,0 +1,63 @@ +//! Starting and resuming a capture: identity, files and the writer lock. +//! +//! A capture is addressed by a random identity and bound to one generation, so +//! resuming is a lookup rather than a guess. Every path here stays under the ignored +//! evidence directory. + +use serde_json::{Value, json}; + +use super::super::coverage::fresh_components; +use super::super::lock::Lock; +use super::super::manifest::{build_manifest, read_manifest}; +use super::super::read::url; +use super::super::selection::{Selection, generation_id, selection_from_json}; +use crate::report::Root; + +/// An empty manifest for a fresh capture, with its component state prepared. +pub fn fresh_manifest( + selection: &Selection, + capture_id: &str, + request_limit: u64, + max_bytes: u64, +) -> Value { + let mut manifest = build_manifest(selection, capture_id, request_limit as i64, None); + manifest["components"] = json!(fresh_components(selection)); + manifest["citations"] = json!([]); + manifest["capture"]["max_bytes"] = json!(max_bytes); + manifest +} + +/// Read a stored manifest, or refuse a malformed one. +pub fn stored_manifest(root: &Root, capture_id: &str) -> Result { + read_manifest(root, capture_id).map_err(|error| error.to_string()) +} + +/// The generation a capture id belongs to. +pub fn generation_of(selection: &Selection, capture_id: &str) -> String { + generation_id(selection, capture_id) +} + +/// Rebuild the selection a stored capture is bound to. +pub fn selection_of(manifest: &Value) -> Result { + let stored = manifest + .get("selection") + .ok_or_else(|| "the capture records no selection".to_owned())?; + selection_from_json(stored).map_err(|error| error.to_string()) +} + +/// A capture id derived from the clock and the process, as the native identity is. +pub fn new_capture_id() -> String { + let seed = format!("{}:{}", super::super::now(), std::process::id()); + let digest = crate::util::digest(&json!(seed)); + digest[..32].to_owned() +} + +/// Hold the writer lock for one capture, releasing it on drop. +pub fn lock_for(root: &Root, capture_id: &str) -> Result { + Lock::new(root, capture_id).map_err(|error| error.to_string()) +} + +/// A URL this transport will accept, for a caller checking one first. +pub fn accepted_url(at: &str, repo: &str) -> Result { + url::validate(at, Some(repo)).map_err(|error| error.message) +} diff --git a/crates/tranche-core/src/evidence/capture/state.rs b/crates/tranche-core/src/evidence/capture/state.rs new file mode 100644 index 0000000..7f51a0c --- /dev/null +++ b/crates/tranche-core/src/evidence/capture/state.rs @@ -0,0 +1,178 @@ +//! The run's bookkeeping: identity checks, refresh, the budget floor, the checkpoint +//! and the small accessors the rest reads through. +//! +//! The checkpoint is what makes a capture resumable, so it is written after every group +//! rather than only at the end. + +use serde_json::{Value, json}; + +use super::super::now; +use super::super::read::transport; +use super::super::selection::Member; +use super::checks::is_exhausted; +use super::endpoints::{JSON_MEDIA, source_url}; +use super::lifecycle::Capture; +use super::outcome::{Stopped, Verify}; +use super::records; + +impl<'a> Capture<'a> { + pub(crate) fn verify_member( + &mut self, + member: &Member, + reserve: Option, + ) -> Result { + self.budget.identity_checks += 1; + let at = source_url(member, "metadata", "metadata"); + let response = transport::get( + &at, + Some(JSON_MEDIA), + Some(&mut self.budget), + reserve, + Some(&member.base_repo_name), + ) + .map_err(|error| { + if is_exhausted(&error.message) { + Verify::Failed("the request budget is spent".to_owned()) + } else { + Verify::Failed(error.message) + } + })?; + let data = response + .json() + .map_err(|error| Verify::Failed(error.message))?; + if data.get("number").and_then(Value::as_u64) != Some(member.number) { + return Err(Verify::Failed(format!( + "live metadata for #{} reports a different pull request", + member.number + ))); + } + let live_base = data + .get("base") + .and_then(|base| base.get("sha")) + .and_then(Value::as_str); + let live_head = data + .get("head") + .and_then(|head| head.get("sha")) + .and_then(Value::as_str); + let (Some(live_base), Some(live_head)) = (live_base, live_head) else { + return Err(Verify::Failed(format!( + "#{} no longer exposes its revisions", + member.number + ))); + }; + if live_base != member.base_sha || live_head != member.head_sha { + return Err(Verify::Moved); + } + Ok(data) + } + pub(crate) fn refresh_mutable(&mut self, member: &Member, thread_updated: &str) { + for component in super::super::MUTABLE_COMPONENTS { + let entry = records::component_entry(&mut self.manifest, member.number, component); + if let Some(groups) = entry["groups"].as_array_mut() { + for state in groups { + state["status"] = json!("missing"); + state["reason"] = json!(format!( + "thread updated upstream ({thread_updated}); refresh pending" + )); + } + } + super::super::coverage::roll_up(entry); + } + self.manifest["code_observation"]["thread_updated_at"][member.number.to_string()] = + json!(thread_updated); + } + pub(crate) fn reserve(&mut self) -> Result<(), Stopped> { + if !self.budget.can(Some(self.budget.reserved)) { + self.manifest["capture"]["stop_reason"] = json!("request_budget"); + return Err(Stopped::Budget); + } + Ok(()) + } + pub(crate) fn checkpoint(&mut self) { + let used = self.budget.used; + let failures = self.budget.failures; + let reserved = self.budget.reserved; + let checks = self.budget.identity_checks; + let capture = &mut self.manifest["capture"]; + capture["requests_used"] = json!(used); + capture["failures"] = json!(failures); + capture["reserved"] = json!(reserved); + capture["identity_checks"] = json!(checks); + match self.stopped.reason() { + Some(reason) => capture["stop_reason"] = json!(reason), + // A resumed capture that got past the point where it ran out of budget + // is no longer stopped by it; a stop reason describes the last run. + None if capture["stop_reason"].as_str() == Some("request_budget") => { + capture["stop_reason"] = Value::Null; + } + None => {} + } + capture["observed_at"] = json!(now()); + let _ = + super::super::manifest::write_manifest(self.root, &self.capture_id, &mut self.manifest); + } + pub(crate) fn block(&mut self, number: u64, component: &str, group: &str, reason: &str) { + records::block(&mut self.manifest, number, component, group, reason); + } + + pub(crate) fn group_status(&self, number: u64, component: &str, group: &str) -> String { + self.group(number, component, group)["status"] + .as_str() + .unwrap_or("missing") + .to_owned() + } + + pub(crate) fn group_pages(&self, number: u64, component: &str, group: &str) -> u64 { + self.group(number, component, group)["pages"] + .as_u64() + .unwrap_or(0) + } + + pub(crate) fn group_next_url( + &self, + number: u64, + component: &str, + group: &str, + ) -> Option { + self.group(number, component, group)["next_url"] + .as_str() + .map(str::to_owned) + } + + pub(crate) fn group(&self, number: u64, component: &str, group: &str) -> &Value { + self.manifest["components"] + .as_array() + .into_iter() + .flatten() + .find(|entry| { + entry["number"].as_u64() == Some(number) + && entry["component"].as_str() == Some(component) + }) + .and_then(|entry| { + entry["groups"] + .as_array()? + .iter() + .find(|state| state["group"].as_str() == Some(group)) + }) + .unwrap_or(&Value::Null) + } + + pub(crate) fn over_storage(&self) -> bool { + self.manifest["capture"]["bytes_stored"] + .as_u64() + .unwrap_or(0) + > self.max_bytes + } + + pub fn manifest(&self) -> &Value { + &self.manifest + } + + pub fn fetched(&self) -> u64 { + self.fetched + } + + pub fn reused(&self) -> u64 { + self.reused + } +} diff --git a/crates/tranche-core/src/evidence/citations.rs b/crates/tranche-core/src/evidence/citations.rs new file mode 100644 index 0000000..00c26e8 --- /dev/null +++ b/crates/tranche-core/src/evidence/citations.rs @@ -0,0 +1,127 @@ +//! Deriving citations from what a capture recorded. +//! +//! Citations are a projection of the capture, computed once and stored, so every +//! reader — export, a windowed source read, a future adapter — resolves the same +//! offsets without reparsing anything or inventing its own eligibility rules. +//! Discussion and review bodies are JSON, so their text is quoted exactly and the +//! offsets are computed against the stored bytes of the response that carried them. + +use serde_json::Value; + +use super::store::read_body; +use crate::report::Root; + +/// The citation ceiling a capture will record. +pub const MAX_CITATIONS: usize = 5_000; +/// The most file entries one page may cite. +pub const MAX_CITATIONS_PER_PAGE: usize = 32; + +/// The components whose raw bytes are a document a person reads. +const CONTENT_COMPONENTS: [&str; 5] = ["files", "diff", "discussion", "review_comments", "reviews"]; + +/// Derive the citations for one capture's sources. +/// +/// Deliberately absent: the pull request's own description, which is the report's +/// evidence and not source evidence, and any citation into a `patch` field GitHub +/// omitted for a large or unsupported file, which the file list reports separately +/// as a gap. +pub fn extract_citations(root: &Root, manifest: &Value) -> Result, String> { + let mut citations: Vec = Vec::new(); + for source in manifest["sources"].as_array().into_iter().flatten() { + let component = source["component"].as_str().unwrap_or(""); + if !CONTENT_COMPONENTS.contains(&component) || citations.len() >= MAX_CITATIONS { + continue; + } + let Some(sha) = source["body_sha256"].as_str() else { + continue; + }; + let body = read_body(root, sha).map_err(|error| error.0)?; + let payload = parse(&body); + let Some(payload) = payload else { continue }; + let number = source["number"].as_u64().unwrap_or(0); + let Some(source_id) = source["id"].as_str() else { + continue; + }; + match component { + "files" => { + for entry in payload + .as_array() + .into_iter() + .flatten() + .take(MAX_CITATIONS_PER_PAGE) + { + for key in ["patch", "filename"] { + if let Some(text) = entry.get(key).and_then(Value::as_str) + && !text.is_empty() + { + add(&mut citations, number, "files", source_id, &body, text); + } + } + } + } + component @ ("discussion" | "review_comments" | "reviews") => { + for entry in payload.as_array().into_iter().flatten() { + if let Some(text) = entry.get("body").and_then(Value::as_str) { + add(&mut citations, number, component, source_id, &body, text); + } + } + } + _ => {} + } + } + // The identity covers everything except itself, like every other digest here. + for citation in &mut citations { + let computed = super::super::util::digest(citation); + citation["id"] = serde_json::json!(computed); + } + Ok(citations) +} + +/// One citation, appended only when the text is found byte-exactly. +fn add( + citations: &mut Vec, + number: u64, + component: &str, + source_id: &str, + body: &[u8], + text: &str, +) { + if text.is_empty() || citations.len() >= MAX_CITATIONS { + return; + } + let encoded = json_string_encoded(text); + let Some(start) = find(body, &encoded) else { + return; + }; + citations.push(serde_json::json!({ + "id": "", + "number": number, + "component": component, + "source_id": source_id, + "source_sha256": crate::util::sha256_hex(body), + "start_byte": start, + "end_byte": start + encoded.len(), + "excerpt_sha256": crate::util::sha256_hex(&encoded), + "kind": "body", + })); +} + +/// Parse the stored body as JSON, or none when it is not JSON. +fn parse(body: &[u8]) -> Option { + serde_json::from_slice(body).ok() +} + +/// The text encoded the way a JSON string would carry it, without the quotes. +fn json_string_encoded(text: &str) -> Vec { + let quoted = serde_json::to_string(text).unwrap_or_default(); + quoted.as_bytes()[1..quoted.len() - 1].to_vec() +} + +/// Find the first offset of `needle` in `haystack`. +fn find(haystack: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() || needle.len() > haystack.len() { + return None; + } + (0..=haystack.len() - needle.len()) + .find(|offset| &haystack[*offset..offset + needle.len()] == needle) +} diff --git a/crates/tranche-core/src/evidence/components.rs b/crates/tranche-core/src/evidence/components.rs new file mode 100644 index 0000000..c40d06f --- /dev/null +++ b/crates/tranche-core/src/evidence/components.rs @@ -0,0 +1,26 @@ +//! Check runs and statuses, and the groups a component acquires. +//! +//! A pull request's own checks live in its base repository while a fork's head +//! can carry its own, so `checks` is four separately recorded groups inside one +//! component rather than a flattened coverage entry. A missing group does not +//! mean "no CI" — it means the capture did not observe that repository. + +/// Check runs and statuses for the base repository, the fork's, or both. +pub const CHECKS_GROUPS: [&str; 4] = ["check_runs", "statuses", "fork_check_runs", "fork_statuses"]; + +/// The base-repository checks every member has. +pub const BASE_CI_GROUPS: [&str; 2] = ["check_runs", "statuses"]; + +/// The fork's own checks, present only when the head repository differs. +pub const FORK_CI_GROUPS: [&str; 2] = ["fork_check_runs", "fork_statuses"]; + +/// The groups a component acquires, in report order. +pub fn groups_for(component: &str) -> Vec { + match component { + "checks" => CHECKS_GROUPS + .iter() + .map(|name| (*name).to_owned()) + .collect(), + _ => vec![component.to_owned()], + } +} diff --git a/crates/tranche-core/src/evidence/coverage.rs b/crates/tranche-core/src/evidence/coverage.rs new file mode 100644 index 0000000..b7c7013 --- /dev/null +++ b/crates/tranche-core/src/evidence/coverage.rs @@ -0,0 +1,110 @@ +//! Coverage accounting for a capture. +//! +//! A terminal cursor is not completeness. A group only counts as complete when +//! it is recorded complete and carries no blocking reason, and a component rolls +//! up to its weakest group — so an unknown can never be published as an empty +//! answer. + +use serde_json::{Value, json}; + +use super::COMPONENTS; +use super::components::groups_for; +use super::selection::Selection; + +/// A fresh component list: every slot present, nothing claimed as acquired. +pub fn fresh_components(selection: &Selection) -> Vec { + let mut entries = Vec::new(); + for member in &selection.members { + for component in COMPONENTS { + let groups: Vec = groups_for(component) + .into_iter() + .map(|group| { + json!({ + "group": group, + "status": "missing", + "pages": 0, + "next_url": Value::Null, + "source_ids": [], + "reason": "not acquired", + }) + }) + .collect(); + entries.push(json!({ + "number": member.number, + "component": component, + "status": "missing", + "reason": "not acquired", + "groups": groups, + })); + } + } + entries +} + +/// Aggregate a component's groups into one honest status. +/// +/// The precedence is deliberate: a blocked group is the most specific failure +/// and outranks a partial one, and a group that was never acquired outranks a +/// partial one because nothing about it is known. +pub fn roll_up(entry: &mut Value) { + let groups = entry + .get("groups") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let statuses: Vec<&str> = groups + .iter() + .filter_map(|group| group.get("status").and_then(Value::as_str)) + .collect(); + let status = if statuses.contains(&"blocked") { + "blocked" + } else if statuses.contains(&"missing") { + "missing" + } else if !statuses.is_empty() && statuses.iter().all(|status| *status == "complete") { + "complete" + } else { + "partial" + }; + let problems: Vec = groups + .iter() + .filter(|group| group.get("status").and_then(Value::as_str) != Some("complete")) + .filter_map(|group| { + let name = group.get("group").and_then(Value::as_str).unwrap_or("?"); + let reason = group.get("reason").and_then(Value::as_str); + reason + .filter(|reason| !reason.is_empty()) + .map(|reason| format!("{name}: {reason}")) + }) + .collect(); + let reason = if status == "complete" { + Value::Null + } else if problems.is_empty() { + json!("incomplete") + } else { + json!(problems.join("; ")) + }; + if let Some(object) = entry.as_object_mut() { + object.insert("status".to_owned(), json!(status)); + object.insert("reason".to_owned(), reason); + } +} + +/// Whether every group reached a terminal page with nothing blocking. +pub fn is_complete(manifest: &Value) -> bool { + let stopped = manifest + .get("capture") + .and_then(|capture| capture.get("stop_reason")) + .is_some_and(|reason| !reason.is_null()); + if stopped { + return false; + } + manifest + .get("components") + .and_then(Value::as_array) + .is_some_and(|components| { + !components.is_empty() + && components.iter().all(|component| { + component.get("status").and_then(Value::as_str) == Some("complete") + }) + }) +} diff --git a/crates/tranche-core/src/evidence/errors.rs b/crates/tranche-core/src/evidence/errors.rs new file mode 100644 index 0000000..dbdbec5 --- /dev/null +++ b/crates/tranche-core/src/evidence/errors.rs @@ -0,0 +1,93 @@ +//! Evidence failures, kept as one type so a command can map them to the exact exit +//! codes scripts already branch on. +//! +//! The three kinds are distinct on purpose. A refusal is a request that cannot be +//! satisfied as asked; a selection failure means the bound report no longer describes +//! what is being asked of it; an incomplete capture is usable and merely unfinished, +//! which is why it is not an error to the caller who only wanted what was captured. + +use std::fmt; + +/// The evidence request cannot be satisfied as asked. +#[derive(Debug)] +pub struct EvidenceError(pub String); + +impl fmt::Display for EvidenceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for EvidenceError {} + +/// The current native selection refuses this request. +#[derive(Debug)] +pub struct SelectionError(pub String); + +impl fmt::Display for SelectionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for SelectionError {} + +/// The capture is usable but not complete; the message says how to resume. +#[derive(Debug)] +pub struct IncompleteCapture(pub String); + +impl fmt::Display for IncompleteCapture { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for IncompleteCapture {} + +/// Every evidence failure, in the one type a command dispatches on. +#[derive(Debug)] +pub enum Error { + Evidence(EvidenceError), + Selection(SelectionError), + Incomplete(IncompleteCapture), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Evidence(error) => write!(f, "{error}"), + Self::Selection(error) => write!(f, "{error}"), + Self::Incomplete(error) => write!(f, "{error}"), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(value: EvidenceError) -> Self { + Self::Evidence(value) + } +} + +impl From for Error { + fn from(value: SelectionError) -> Self { + Self::Selection(value) + } +} + +impl From for Error { + fn from(value: IncompleteCapture) -> Self { + Self::Incomplete(value) + } +} + +/// A refusal with a message, in the narrowest type that reports it. +pub fn refuse(message: impl Into) -> EvidenceError { + EvidenceError(message.into()) +} + +/// A refusal from the bound report rather than from the capture. +pub fn selection_refusal(message: impl Into) -> SelectionError { + SelectionError(message.into()) +} diff --git a/crates/tranche-core/src/evidence/lock.rs b/crates/tranche-core/src/evidence/lock.rs new file mode 100644 index 0000000..05c0b5e --- /dev/null +++ b/crates/tranche-core/src/evidence/lock.rs @@ -0,0 +1,150 @@ +//! The per-capture writer lock. +//! +//! One writer per capture, with a bounded TTL so a crash cannot strand work. The +//! lock records the owning pid: it is released by its owner, reclaimed when that +//! process is gone, and refused while a live writer holds it. `break_lock` is +//! the explicit operator override for the remaining case — a live-looking pid +//! that no longer owns the capture. + +use std::io::Write; +use std::path::PathBuf; + +use super::{EvidenceError, LOCK_TTL, now, refuse}; +use crate::evidence::paths::lock_path; +use crate::report::Root; + +/// An advisory lock held by one process for one capture. +pub struct Lock { + path: PathBuf, + held: bool, +} + +impl Lock { + pub fn new(root: &Root, capture_id: &str) -> Result { + Ok(Self { + path: lock_path(root, capture_id)?, + held: false, + }) + } + + /// Take the lock, reclaiming it only when the recorded owner is gone. + pub fn acquire(&mut self, break_lock: bool) -> Result<(), EvidenceError> { + if let Some(parent) = self.path.parent() { + std::fs::create_dir_all(parent) + .map_err(|error| refuse(format!("cannot create the lock directory: {error}")))?; + } + for attempt in 0..2 { + match std::fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(&self.path) + { + Ok(mut file) => { + let record = serde_json::json!({ + "pid": std::process::id(), + "started": now(), + "started_at": std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs_f64()) + .unwrap_or(0.0), + }); + let _ = file.write_all(record.to_string().as_bytes()); + let _ = file.sync_all(); + self.held = true; + return Ok(()); + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + let owner = self.owner(); + let owner_pid = owner + .as_ref() + .and_then(|owner| owner.get("pid")) + .and_then(serde_json::Value::as_i64); + // Age alone never grants permission to replace a live writer: + // the TTL only applies once the recorded process is gone. + let stale = match owner_pid { + Some(pid) => !process_alive(pid), + None => self.age_seconds() > LOCK_TTL, + }; + if break_lock || stale { + self.release_file(); + if attempt == 0 { + continue; + } + return Err(refuse(format!( + "could not replace the writer lock at {}", + self.path.display() + ))); + } + let described = owner_pid + .map(|pid| pid.to_string()) + .unwrap_or_else(|| "unknown".to_owned()); + return Err(refuse(format!( + "another writer holds this capture (pid {described}); \ + use --break-lock if it is gone" + ))); + } + Err(error) => { + return Err(refuse(format!("cannot take the writer lock: {error}"))); + } + } + } + Err(refuse(format!( + "could not replace the writer lock at {}", + self.path.display() + ))) + } + + fn owner(&self) -> Option { + let text = std::fs::read_to_string(&self.path).ok()?; + serde_json::from_str(&text).ok() + } + + fn age_seconds(&self) -> f64 { + std::fs::metadata(&self.path) + .and_then(|metadata| metadata.modified()) + .ok() + .and_then(|modified| modified.elapsed().ok()) + .map(|elapsed| elapsed.as_secs_f64()) + .unwrap_or(0.0) + } + + fn release_file(&self) { + let _ = std::fs::remove_file(&self.path); + } + + pub fn release(&mut self) { + if self.held { + self.release_file(); + self.held = false; + } + } + + /// Whether this handle currently holds the lock. + pub fn held(&self) -> bool { + self.held + } +} + +impl Drop for Lock { + fn drop(&mut self) { + self.release(); + } +} + +#[cfg(unix)] +fn process_alive(pid: i64) -> bool { + if pid <= 0 { + return false; + } + // Signal 0 performs the permission and existence checks without delivering + // anything, which is exactly the question being asked. + unsafe { + libc::kill(pid as libc::pid_t, 0) == 0 + || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) + } +} + +#[cfg(not(unix))] +fn process_alive(pid: i64) -> bool { + pid > 0 +} diff --git a/crates/tranche-core/src/evidence/manifest.rs b/crates/tranche-core/src/evidence/manifest.rs new file mode 100644 index 0000000..c1e8dae --- /dev/null +++ b/crates/tranche-core/src/evidence/manifest.rs @@ -0,0 +1,287 @@ +//! The manifest a capture writes, and the validation that proves a stored one +//! describes itself. +//! +//! A manifest is untrusted input: it is a file under `out/` a writer could have +//! edited. Reading one re-derives every identity it claims — the generation from +//! its own selection, each source's id from its own record — rather than +//! believing the stored value. Nothing here consults the current report, so a +//! historical capture stays readable after the report changes. + +use serde_json::{Map, Value, json}; + +use super::components::groups_for; +use super::paths::{atomic_manifest, manifest_path, validate_body_digest}; +use super::selection::{Selection, generation_id, source_id}; +use super::store::strict_json_loads; +use super::{COMPONENTS, FORMAT, PROFILE, RESERVED_BUDGET}; +use crate::report::Root; + +/// The empty manifest a fresh capture starts from. +pub fn build_manifest( + selection: &Selection, + capture_id: &str, + request_limit: i64, + observed_at: Option<&str>, +) -> Value { + let observed = observed_at.map(str::to_owned).unwrap_or_else(super::now); + let thread_updated: Map = selection + .members + .iter() + .map(|member| { + ( + member.number.to_string(), + member + .updated_at + .clone() + .map(Value::String) + .unwrap_or(Value::Null), + ) + }) + .collect(); + json!({ + "format": FORMAT, + "profile": PROFILE, + "capture_id": capture_id, + "generation": generation_id(selection, capture_id), + "created_at": observed, + "updated_at": observed, + "selection": selection.as_json(), + "code_observation": { + "observed_at": observed, + "thread_updated_at": Value::Object(thread_updated), + }, + "capture": { + "observed_at": observed, + "request_limit": request_limit, + "requests_used": 0, + "reserved": RESERVED_BUDGET, + "failures": 0, + "retries": 0, + "identity_checks": 0, + "stop_reason": Value::Null, + "bytes_stored": 0, + }, + "sources": [], + "components": super::coverage::fresh_components(selection), + "citations": [], + }) +} + +/// Publish a manifest, stamping the update time. +pub fn write_manifest( + root: &Root, + capture_id: &str, + manifest: &mut Value, +) -> Result<(), super::Error> { + if let Some(object) = manifest.as_object_mut() { + object.insert("updated_at".to_owned(), json!(super::now())); + } + let path = manifest_path(root, capture_id)?; + atomic_manifest(&path, manifest).map_err(Into::into) +} + +/// Load and structurally verify one capture checkpoint. +pub fn read_manifest(root: &Root, capture_id: &str) -> Result { + let path = manifest_path(root, capture_id)?; + if !path.exists() { + return Err(super::refuse(format!( + "no capture {capture_id} under {}", + super::evidence_root(root).display() + )) + .into()); + } + let data = std::fs::read(&path) + .map_err(|error| super::refuse(format!("cannot read capture manifest: {error}")))?; + let manifest = strict_json_loads(&data)?; + check_shape(&manifest, capture_id)?; + let selection = + super::selection::selection_from_json(manifest.get("selection").expect("checked above"))?; + let generation = manifest + .get("generation") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + if generation != generation_id(&selection, capture_id) { + return Err( + super::refuse("capture manifest generation does not match its own selection").into(), + ); + } + let ids = check_sources(&manifest, &selection, &generation)?; + check_citations(&manifest, &ids)?; + Ok(manifest) +} + +fn check_shape(manifest: &Value, capture_id: &str) -> Result<(), super::Error> { + if !manifest.is_object() { + return Err(super::refuse("capture manifest is not a JSON object").into()); + } + for field in [ + "format", + "profile", + "capture_id", + "generation", + "created_at", + "updated_at", + "selection", + "code_observation", + "capture", + "sources", + "components", + "citations", + ] { + if manifest.get(field).is_none() { + return Err(super::refuse(format!("capture manifest is missing {field:?}")).into()); + } + } + if manifest.get("format").and_then(Value::as_str) != Some(FORMAT) + || manifest.get("profile").and_then(Value::as_str) != Some(PROFILE) + { + return Err( + super::refuse("capture manifest declares a different format or profile").into(), + ); + } + if manifest.get("capture_id").and_then(Value::as_str) != Some(capture_id) { + return Err(super::refuse("capture manifest does not match its directory").into()); + } + if !manifest.get("sources").is_some_and(Value::is_array) + || !manifest.get("components").is_some_and(Value::is_array) + || !manifest.get("citations").is_some_and(Value::is_array) + { + return Err(super::refuse("capture manifest records are malformed").into()); + } + Ok(()) +} + +/// Verify each source record recomputes its own identity and belongs to this +/// generation. Returns the set of ids the citations may refer to. +fn check_sources( + manifest: &Value, + selection: &Selection, + generation: &str, +) -> Result, super::Error> { + let members = selection.numbers(); + let mut seen_ids = std::collections::HashSet::new(); + let mut seen_slots = std::collections::HashSet::new(); + for source in manifest + .get("sources") + .and_then(Value::as_array) + .expect("checked by shape") + { + let object = source + .as_object() + .ok_or_else(|| super::refuse("capture manifest source record is malformed"))?; + for field in [ + "id", + "number", + "component", + "group", + "page", + "cursor", + "next_cursor", + "url", + "accept", + "media_type", + "captured_at", + "generation", + "body_sha256", + ] { + if !object.contains_key(field) { + return Err(super::refuse(format!("source record is missing {field:?}")).into()); + } + } + let number = object.get("number").and_then(Value::as_u64).unwrap_or(0); + if !members.contains(&number) { + return Err(super::refuse("source record names a member outside the selection").into()); + } + let component = object + .get("component") + .and_then(Value::as_str) + .unwrap_or(""); + let group = object.get("group").and_then(Value::as_str).unwrap_or(""); + if !COMPONENTS.contains(&component) + || !groups_for(component).iter().any(|name| name == group) + { + return Err(super::refuse( + "source record names an unknown component or a group not belonging to it", + ) + .into()); + } + let page = object.get("page").and_then(Value::as_u64).unwrap_or(0); + if page < 1 { + return Err(super::refuse("source record page is malformed").into()); + } + let slot = (number, component.to_owned(), group.to_owned(), page); + let id = object + .get("id") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + if !seen_slots.insert(slot) || !seen_ids.insert(id.clone()) { + return Err(super::refuse("capture manifest repeats a source slot or id").into()); + } + if object.get("generation").and_then(Value::as_str) != Some(generation) { + return Err(super::refuse("source record belongs to a different generation").into()); + } + if id != source_id(generation, source) { + return Err(super::refuse("source record id does not match its own contents").into()); + } + let body = object + .get("body_sha256") + .and_then(Value::as_str) + .unwrap_or(""); + validate_body_digest(body) + .map_err(|_| super::refuse("source record has no usable body digest"))?; + } + Ok(seen_ids) +} + +fn check_citations( + manifest: &Value, + seen_ids: &std::collections::HashSet, +) -> Result<(), super::Error> { + for citation in manifest + .get("citations") + .and_then(Value::as_array) + .expect("checked by shape") + { + let Some(object) = citation.as_object() else { + return Err(super::refuse("capture manifest citation is malformed").into()); + }; + let expected: std::collections::HashSet<&str> = [ + "id", + "number", + "component", + "source_id", + "source_sha256", + "start_byte", + "end_byte", + "excerpt_sha256", + "kind", + ] + .into_iter() + .collect(); + let actual: std::collections::HashSet<&str> = object.keys().map(String::as_str).collect(); + if actual != expected { + return Err(super::refuse("capture manifest citation is malformed").into()); + } + let source_id_value = object + .get("source_id") + .and_then(Value::as_str) + .unwrap_or(""); + if !seen_ids.contains(source_id_value) { + return Err(super::refuse("citation references a source outside the capture").into()); + } + let start = object.get("start_byte").and_then(Value::as_i64); + let end = object.get("end_byte").and_then(Value::as_i64); + match (start, end) { + (Some(start), Some(end)) if start >= 0 && end > start => {} + _ => { + return Err(super::refuse( + "citation byte range is not a nonempty half-open interval", + ) + .into()); + } + } + } + Ok(()) +} diff --git a/crates/tranche-core/src/evidence/mod.rs b/crates/tranche-core/src/evidence/mod.rs new file mode 100644 index 0000000..20799e7 --- /dev/null +++ b/crates/tranche-core/src/evidence/mod.rs @@ -0,0 +1,30 @@ +//! Evidence: capture, inspection, storage and export. +//! +//! The service is deliberately narrow. It reads GitHub, writes only under +//! `out/evidence/`, and never calls a model, mutates GitHub, executes captured +//! content or prints a packet into a terminal. + +pub mod capture; +pub mod citations; +pub mod components; +pub mod coverage; +pub mod errors; +pub mod lock; +pub mod manifest; +pub mod packet; +pub mod paths; +pub mod read; +pub mod report; +pub mod selecting; +pub mod selection; +pub mod store; +pub mod vocabulary; + +pub use errors::{ + Error, EvidenceError, IncompleteCapture, SelectionError, refuse, selection_refusal, +}; +pub use selecting::{Plan, select}; +pub use vocabulary::{ + CODE_COMPONENTS, COMPONENTS, EXIT_INCOMPLETE, EXIT_OK, EXIT_REFUSED, EXIT_USABLE, EXIT_USAGE, + FORMAT, LOCK_TTL, MUTABLE_COMPONENTS, PROFILE, RESERVED_BUDGET, evidence_root, now, +}; diff --git a/crates/tranche-core/src/evidence/packet/base64.rs b/crates/tranche-core/src/evidence/packet/base64.rs new file mode 100644 index 0000000..55d63bb --- /dev/null +++ b/crates/tranche-core/src/evidence/packet/base64.rs @@ -0,0 +1,30 @@ +//! Standard base64, as the packet carries bodies. +//! +//! Written out rather than pulled in because it is thirty lines and the encoding is +//! part of the packet contract: a reader checks the carried bytes against the digest +//! they are filed under, so the encoder must be exactly standard. + +const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/// Encode bytes with standard base64 and padding. +pub fn base64(data: &[u8]) -> String { + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let packed = (chunk[0] as u32) << 16 + | (chunk.get(1).copied().unwrap_or(0) as u32) << 8 + | chunk.get(2).copied().unwrap_or(0) as u32; + for shift in [18, 12, 6, 0] { + out.push(ALPHABET[((packed >> shift) & 0x3f) as usize] as char); + } + if chunk.len() < 3 { + let padding = 3 - chunk.len(); + for _ in 0..padding { + out.pop(); + } + for _ in 0..padding { + out.push('='); + } + } + } + out +} diff --git a/crates/tranche-core/src/evidence/packet/building.rs b/crates/tranche-core/src/evidence/packet/building.rs new file mode 100644 index 0000000..a1cd311 --- /dev/null +++ b/crates/tranche-core/src/evidence/packet/building.rs @@ -0,0 +1,158 @@ +//! Building the packet: the projection, and the one place the fields are chosen. +//! +//! The packet is a projection of the manifest, not a copy of it. A reader holding +//! only the packet can resolve every citation with no state store, no network and +//! no second application: the selection is frozen in, each body is carried exactly +//! once, and every identity is recomputed from what the packet itself holds. +//! +//! What is deliberately absent matters as much. Manifest bookkeeping such as +//! `created_at`, `updated_at` and `bytes_stored` is not exported, because a reader +//! verifying evidence has no use for it. The manifest's own flattened coverage +//! projection is not exported either: the component state travels as held, with its +//! endpoint groups intact. + +use std::collections::BTreeMap; + +use crate::report::Root; +use serde_json::{Map, Value, json}; + +use super::base64; +use super::encoding::{FORMAT, NOTES, PROFILE, packet_bytes, packet_digest}; +use crate::evidence::coverage::is_complete; +use crate::evidence::selection::selection_from_json; +use crate::evidence::store::read_body; + +/// The capture accounting keys the packet exports, in this order. +const ACCOUNTED: [&str; 8] = [ + "observed_at", + "request_limit", + "requests_used", + "reserved", + "failures", + "retries", + "identity_checks", + "stop_reason", +]; + +/// The source keys the packet exports, in this order. +const SOURCE_FIELDS: [&str; 13] = [ + "id", + "number", + "component", + "group", + "page", + "cursor", + "next_cursor", + "url", + "accept", + "media_type", + "captured_at", + "generation", + "body_sha256", +]; + +/// Build the packet and its own digest. +pub fn build(root: &Root, manifest: &Value) -> Result { + let selection = selection_from_json( + manifest + .get("selection") + .ok_or_else(|| "the manifest records no selection".to_owned())?, + ) + .map_err(|error| error.to_string())?; + + // Each distinct body is read and carried once, keyed by its digest, so + // identical bytes are not repeated. + let mut bodies: BTreeMap = BTreeMap::new(); + for source in manifest["sources"].as_array().into_iter().flatten() { + let Some(sha) = source["body_sha256"].as_str() else { + continue; + }; + if bodies.contains_key(sha) { + continue; + } + let raw = read_body(root, sha).map_err(|error| error.0)?; + bodies.insert( + sha.to_owned(), + json!({ + "sha256": sha, + "bytes": raw.len(), + "base64": base64(&raw), + }), + ); + } + + let capture = ACCOUNTED + .iter() + .map(|key| { + ( + (*key).to_owned(), + manifest["capture"] + .get(*key) + .cloned() + .unwrap_or(Value::Null), + ) + }) + .collect::>(); + let sources: Vec = manifest["sources"] + .as_array() + .into_iter() + .flatten() + .map(|source| { + SOURCE_FIELDS + .iter() + .map(|key| { + ( + (*key).to_owned(), + source.get(*key).cloned().unwrap_or(Value::Null), + ) + }) + .collect::>() + .into() + }) + .collect(); + + let mut packet = Map::new(); + packet.insert("format".to_owned(), json!(FORMAT)); + packet.insert("profile".to_owned(), json!(PROFILE)); + packet.insert("capture_id".to_owned(), manifest["capture_id"].clone()); + packet.insert("generation".to_owned(), manifest["generation"].clone()); + packet.insert("selection".to_owned(), selection.as_json()); + packet.insert( + "membership_digest".to_owned(), + json!(selection.membership_digest()), + ); + packet.insert("complete".to_owned(), json!(is_complete(manifest))); + packet.insert("capture".to_owned(), Value::Object(capture)); + packet.insert( + "components".to_owned(), + manifest.get("components").cloned().unwrap_or(json!([])), + ); + packet.insert("sources".to_owned(), json!(sources)); + packet.insert( + "bodies".to_owned(), + Value::Object(bodies.into_iter().collect()), + ); + packet.insert( + "citations".to_owned(), + manifest.get("citations").cloned().unwrap_or(json!([])), + ); + packet.insert("notes".to_owned(), json!(NOTES)); + + let value = Value::Object(packet); + // The digest is taken before the field is added: it covers the packet, not + // itself. + let computed = packet_digest(&value); + let mut with_digest = match value { + Value::Object(object) => object, + _ => unreachable!("built as an object"), + }; + with_digest.insert("packet_digest".to_owned(), json!(computed)); + Ok(Value::Object(with_digest)) +} + +/// Serialize a built packet under the export bound. +pub fn bytes(root: &Root, manifest: &Value, limit: usize) -> Result<(Value, Vec), String> { + let packet = build(root, manifest)?; + let serialized = packet_bytes(&packet, limit)?; + Ok((packet, serialized)) +} diff --git a/crates/tranche-core/src/evidence/packet/encoding.rs b/crates/tranche-core/src/evidence/packet/encoding.rs new file mode 100644 index 0000000..11a0a5f --- /dev/null +++ b/crates/tranche-core/src/evidence/packet/encoding.rs @@ -0,0 +1,61 @@ +//! The packet's own encoding, which is this project's object digest rather than a +//! general canonicalization standard. +//! +//! Sorted keys, compact separators, no ASCII escaping, no trailing newline. The +//! distinction matters: `tranche.digest()` is an encoding this project defines, +//! and the packets it hashes are read back by this project's own tooling. + +use crate::util::digest; +use serde_json::{Map, Value}; + +/// The packet format this module produces. +pub const FORMAT: &str = "tranche.evidence-packet/v1"; +/// The profile whose components and sources the packet describes. +pub const PROFILE: &str = "pr-review/v1"; +/// The export bound, applied to the exact serialized bytes. Base64 expansion and +/// metadata count against it. +pub const DEFAULT_EXPORT_BYTES: usize = 64 * 1024 * 1024; + +/// The object digest of a packet before its own digest is added. +pub fn packet_digest(packet: &Value) -> String { + digest(packet) +} + +/// The exact serialized bytes, or a refusal when they exceed the bound. +/// +/// The size is checked on the bytes rather than on an estimate, because base64 +/// expansion is what makes a packet large and it is not predictable from the +/// record count. +pub fn packet_bytes(packet: &Value, limit: usize) -> Result, String> { + let Value::Object(object) = packet else { + return Err("a packet must be an object".to_owned()); + }; + let mut sorted = Map::new(); + let mut keys: Vec<&String> = object.keys().collect(); + keys.sort(); + for key in keys { + sorted.insert(key.clone(), object[key].clone()); + } + let text = serde_json::to_string(&Value::Object(sorted)) + .map_err(|error| format!("packet cannot be serialized ({error})"))?; + let bytes = text.into_bytes(); + if bytes.len() > limit { + return Err(format!( + "packet serializes to {} bytes, over the {limit} byte export bound; \ + narrow the batch or raise the bound deliberately", + bytes.len() + )); + } + Ok(bytes) +} + +/// The explanatory text every packet carries. +/// +/// It is part of the packet rather than documentation on purpose: a reader holding +/// only the file must not conclude that a digest proves authenticity, that a +/// captured CI run was a test Tranche ran, or that completeness is approval. +pub const NOTES: &str = "Captured from public GitHub by Tranche; read-only and model-free. \ +Digests prove integrity, not authenticity: they show the bytes are the bytes recorded, not \ +that GitHub served them. A captured CI run is an observation, not a test performed by \ +Tranche. Complete means every endpoint group reported a terminal page within the recorded \ +budgets; it is not a review, a test run or approval to merge."; diff --git a/crates/tranche-core/src/evidence/packet/mod.rs b/crates/tranche-core/src/evidence/packet/mod.rs new file mode 100644 index 0000000..6ea8110 --- /dev/null +++ b/crates/tranche-core/src/evidence/packet/mod.rs @@ -0,0 +1,18 @@ +//! The self-contained export packet. +//! +//! The packet is a projection of the manifest, not a copy of it: a reader holding +//! only the packet can resolve every citation with no state store, no network and no +//! second application. What is deliberately absent matters as much as what is +//! carried, so both are decided in `building`. +//! +//! `encoding` holds the packet's own digest and the exact serialization; it is this +//! project's encoding rather than a general canonicalization standard, and the +//! distinction is worth keeping visible. + +pub mod base64; +pub mod building; +pub mod encoding; + +pub use base64::base64; +pub use building::{build, bytes}; +pub use encoding::{DEFAULT_EXPORT_BYTES, FORMAT, PROFILE, packet_bytes, packet_digest}; diff --git a/crates/tranche-core/src/evidence/paths.rs b/crates/tranche-core/src/evidence/paths.rs new file mode 100644 index 0000000..ca366ad --- /dev/null +++ b/crates/tranche-core/src/evidence/paths.rs @@ -0,0 +1,207 @@ +//! Evidence paths and confinement. +//! +//! Everything the service reads or writes is derived from one root, and every +//! path that came from a stored record is refused unless it is a regular, +//! single-link file beneath that root with no symlink anywhere in it. A +//! checkpoint is untrusted input: it is a file on disk that an attacker with +//! write access to `out/` could have edited. + +use std::path::{Component, Path, PathBuf}; + +use super::refuse; +use crate::evidence::EvidenceError; +use crate::report::Root; + +/// A capture id must be exactly 32 lowercase hex characters. +pub fn validate_capture_id(capture_id: &str) -> Result<(), EvidenceError> { + let valid = capture_id.len() == 32 + && capture_id + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)); + if valid { + Ok(()) + } else { + Err(refuse("capture id must be 32 lowercase hex characters")) + } +} + +/// A body digest must be exactly 64 lowercase hex characters. +pub fn validate_body_digest(digest: &str) -> Result<(), EvidenceError> { + let valid = digest.len() == 64 + && digest + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)); + if valid { + Ok(()) + } else { + Err(refuse( + "source body digest must be 64 lowercase hex characters", + )) + } +} + +/// The directory holding one capture's manifest. +pub fn capture_dir(root: &Root, capture_id: &str) -> Result { + validate_capture_id(capture_id)?; + Ok(super::evidence_root(root).join(capture_id)) +} + +/// The checkpoint path for one capture. +pub fn manifest_path(root: &Root, capture_id: &str) -> Result { + Ok(capture_dir(root, capture_id)?.join("manifest.json")) +} + +/// The advisory writer lock for one capture. +pub fn lock_path(root: &Root, capture_id: &str) -> Result { + validate_capture_id(capture_id)?; + Ok(super::evidence_root(root).join(format!("{capture_id}.lock"))) +} + +/// One content-addressed body, shared by every capture that recorded it. +/// +/// Keying by digest rather than by capture is what lets a new association reuse +/// unchanged bytes without copying them. The manifest carries only the digest; +/// the location is derived, never recorded, so there is no second identity for +/// the same bytes. +pub fn body_path(root: &Root, body_digest: &str) -> Result { + validate_body_digest(body_digest)?; + Ok(super::evidence_root(root) + .join("bodies") + .join(format!("{body_digest}.bin"))) +} + +/// Resolve a stored relative path beneath `base`, refusing anything unsafe. +/// +/// Rejects an absolute path, a `..` or empty component, a NUL byte, any symlink +/// in the chain, a multiply-linked file and anything that resolves outside the +/// base. The path is checked as it exists, not as it is written down. +pub fn confined_file(base: &Path, relative: &str) -> Result { + if relative.is_empty() { + return Err(refuse("empty evidence path")); + } + if relative.contains('\0') { + return Err(refuse("evidence path contains a NUL byte")); + } + let candidate = Path::new(relative); + if candidate.is_absolute() { + return Err(refuse(format!("refusing unconfined path {relative:?}"))); + } + let mut parts: Vec<&std::ffi::OsStr> = Vec::new(); + for component in candidate.components() { + match component { + Component::Normal(part) => parts.push(part), + Component::CurDir => {} + _ => return Err(refuse(format!("refusing unconfined path {relative:?}"))), + } + } + if parts.is_empty() { + return Err(refuse(format!("refusing empty path {relative:?}"))); + } + + let base = base + .canonicalize() + .map_err(|error| refuse(format!("evidence root is unusable: {error}")))?; + let mut current = base.clone(); + for part in &parts { + current.push(part); + // `symlink_metadata` does not follow the link, which is the point: a + // symlinked directory must be refused rather than traversed. + match std::fs::symlink_metadata(¤t) { + Ok(metadata) if metadata.file_type().is_symlink() => { + return Err(refuse(format!( + "refusing symlink in evidence path: {relative:?}" + ))); + } + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(refuse(format!("evidence path is unusable: {error}"))), + } + } + let resolved = base.join(parts.iter().collect::().as_path()); + if resolved != base && !resolved.starts_with(&base) { + return Err(refuse(format!( + "refusing path outside the evidence root: {relative:?}" + ))); + } + let metadata = match std::fs::metadata(&resolved) { + Ok(metadata) => Some(metadata), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(refuse(format!("evidence path is unusable: {error}"))), + }; + if let Some(metadata) = metadata { + if !metadata.is_file() { + return Err(refuse(format!( + "refusing non-regular evidence file: {relative:?}" + ))); + } + if hard_link_count(&metadata) > 1 { + return Err(refuse(format!( + "refusing multiply-linked evidence file: {relative:?}" + ))); + } + } + Ok(resolved) +} + +#[cfg(unix)] +fn hard_link_count(metadata: &std::fs::Metadata) -> u64 { + use std::os::unix::fs::MetadataExt; + metadata.nlink() +} + +#[cfg(not(unix))] +fn hard_link_count(_metadata: &std::fs::Metadata) -> u64 { + 1 +} + +/// Publish bytes atomically: temporary sibling, fsync, rename, mode 0600. +/// +/// A partial checkpoint must never be observable, so every write that becomes a +/// record goes through here. +pub fn atomic_bytes(path: &Path, data: &[u8]) -> Result<(), EvidenceError> { + use std::io::Write; + let parent = path + .parent() + .ok_or_else(|| refuse("evidence path has no parent directory"))?; + std::fs::create_dir_all(parent) + .map_err(|error| refuse(format!("cannot create the evidence directory: {error}")))?; + let temporary = parent.join(format!( + ".pending-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_millis()) + .unwrap_or(0) + )); + let result = (|| -> std::io::Result<()> { + let mut file = std::fs::File::create(&temporary)?; + file.write_all(data)?; + file.sync_all()?; + set_private_mode(&temporary)?; + std::fs::rename(&temporary, path)?; + Ok(()) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + result.map_err(|error| refuse(format!("cannot publish evidence record: {error}"))) +} + +#[cfg(unix)] +fn set_private_mode(path: &Path) -> std::io::Result<()> { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) +} + +#[cfg(not(unix))] +fn set_private_mode(_path: &Path) -> std::io::Result<()> { + Ok(()) +} + +/// Publish a manifest atomically, in the encoding the format specifies. +pub fn atomic_manifest(path: &Path, value: &serde_json::Value) -> Result<(), EvidenceError> { + // Sorted keys and no whitespace, because a manifest is digested by the + // export. + let text = crate::util::canonical_json(value); + atomic_bytes(path, text.as_bytes()) +} diff --git a/crates/tranche-core/src/evidence/read/error.rs b/crates/tranche-core/src/evidence/read/error.rs new file mode 100644 index 0000000..56784c7 --- /dev/null +++ b/crates/tranche-core/src/evidence/read/error.rs @@ -0,0 +1,43 @@ +//! The transport could not produce a usable response. + +/// An oversized response is distinguished because the caller's remedy differs: the +/// bound is raised, not the request retried. +#[derive(Debug, Clone)] +pub struct ReadError { + pub message: String, + pub too_large: bool, +} + +impl ReadError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + too_large: false, + } + } + + pub fn too_large(message: impl Into) -> Self { + Self { + message: message.into(), + too_large: true, + } + } +} + +/// Read one URL, following validated redirects and charging every attempt. +pub fn read( + url: &str, + accept: Option<&str>, + budget: Option<&mut super::transport::Budget>, + repo_prefix: Option<&str>, +) -> Result { + super::transport::get(url, accept, budget, None, repo_prefix) +} + +impl std::fmt::Display for ReadError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.message) + } +} + +impl std::error::Error for ReadError {} diff --git a/crates/tranche-core/src/evidence/read/gh_call.rs b/crates/tranche-core/src/evidence/read/gh_call.rs new file mode 100644 index 0000000..aaea04d --- /dev/null +++ b/crates/tranche-core/src/evidence/read/gh_call.rs @@ -0,0 +1,230 @@ +//! The subprocess seam: one bounded `gh` invocation and its parsing. +//! +//! No shell is involved and no credential enters the argv — `gh` owns the token. +//! A redirect that `gh` follows itself appears as several header blocks in +//! `--include` output, and the last one is the response acted on. + +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use super::ReadError; +use super::transport::{GH_TIMEOUT, Raw}; + +/// Spawn `gh` with bounded output and return its final hop. +pub(super) fn invoke( + arguments: &[String], + stdin: Option<&[u8]>, + max_bytes: usize, +) -> Result { + let mut child = Command::new("gh") + .args(arguments) + .stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| ReadError::new(format!("cannot run gh: {error}")))?; + if let Some(data) = stdin + && let Some(mut handle) = child.stdin.take() + { + use std::io::Write; + let _ = handle.write_all(data); + } + + // Both pipes are drained on their own thread: a child that fills one while we + // wait on the other would deadlock, and the read is capped so an unbounded + // response cannot be buffered whole. + let out = child.stdout.take().expect("stdout is piped"); + let err = child.stderr.take().expect("stderr is piped"); + let out_reader = std::thread::spawn(move || read_capped(out, max_bytes + 1)); + let err_reader = + std::thread::spawn(move || read_capped(err, super::transport::MAX_STDERR_BYTES)); + let status = wait(&mut child)?; + let (stdout, out_truncated) = out_reader + .join() + .map_err(|_| ReadError::new("the gh stdout reader panicked"))? + .map_err(|error| ReadError::new(format!("gh output: {error}")))?; + let (stderr, _) = err_reader + .join() + .map_err(|_| ReadError::new("the gh stderr reader panicked"))? + .map_err(|error| ReadError::new(format!("gh error output: {error}")))?; + + if !status.success() && stdout.is_empty() { + return Err(ReadError::new(format!( + "gh failed ({})", + diagnostic(&stderr) + ))); + } + let (blocks, body) = split_response(&stdout)?; + let last = blocks.last().copied().unwrap_or(b""); + let headers = header_block(last); + if let Some(declared) = header_of(&headers, "content-length") + && let Ok(declared) = declared.parse::() + && declared > max_bytes + && !out_truncated + { + return Err(ReadError::too_large(format!( + "response declares {declared} bytes, over the {max_bytes} byte bound" + ))); + } + let code = status_of(last)?; + if !status.success() { + return Err(ReadError::new(format!( + "gh failed with HTTP {code} ({})", + diagnostic(&stderr) + ))); + } + if out_truncated { + return Err(ReadError::too_large(format!( + "response exceeded the {max_bytes} byte bound" + ))); + } + Ok(Raw { + status: code, + headers, + body: body.to_vec(), + truncated: out_truncated, + hops: blocks.len(), + }) +} + +/// Read a pipe to the end, keeping at most `limit` bytes. +fn read_capped(mut pipe: impl std::io::Read, limit: usize) -> std::io::Result<(Vec, bool)> { + let mut kept = Vec::new(); + let mut buffer = [0u8; 64 * 1024]; + let mut truncated = false; + loop { + let read = pipe.read(&mut buffer)?; + if read == 0 { + return Ok((kept, truncated)); + } + let room = limit.saturating_sub(kept.len()); + kept.extend_from_slice(&buffer[..read.min(room)]); + if read > room { + truncated = true; + } + } +} + +/// Wait for `gh`, killing it if it outlasts the timeout. +fn wait(child: &mut std::process::Child) -> Result { + let started = Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) => return Ok(status), + Ok(None) if started.elapsed() < GH_TIMEOUT => { + std::thread::sleep(Duration::from_millis(25)); + } + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(ReadError::new(format!( + "gh timed out after {}s", + GH_TIMEOUT.as_secs() + ))); + } + Err(error) => return Err(ReadError::new(format!("gh wait: {error}"))), + } + } +} + +/// Split `gh api --include` output into its header blocks and the body. +fn split_response(raw: &[u8]) -> Result<(Vec<&[u8]>, &[u8]), ReadError> { + let mut blocks = Vec::new(); + let mut index = 0usize; + while let Some(offset) = find_blank_line(&raw[index..]) { + let end = index + offset; + let block = &raw[index..end]; + let starts_with_status = block + .iter() + .position(|byte| !byte.is_ascii_whitespace()) + .is_some_and(|start| raw[index + start..].starts_with(b"HTTP/")); + if !starts_with_status { + break; + } + blocks.push(block); + index = index + offset + blank_line_len(&raw[end..]); + } + if blocks.is_empty() { + return Err(ReadError::new( + "gh api --include produced no HTTP status line", + )); + } + Ok((blocks, &raw[index..])) +} + +/// The offset where a header block ends, at the first blank line. +fn find_blank_line(raw: &[u8]) -> Option { + (0..raw.len()) + .find(|index| raw[*index..].starts_with(b"\r\n\r\n") || raw[*index..].starts_with(b"\n\n")) +} + +/// How long the blank line at the start of `raw` is. +fn blank_line_len(raw: &[u8]) -> usize { + if raw.starts_with(b"\r\n\r\n") { + 4 + } else if raw.starts_with(b"\n\n") { + 2 + } else { + 0 + } +} + +/// Parse a header block's lowercased key/value pairs, skipping the status line. +fn header_block(block: &[u8]) -> Vec<(String, String)> { + String::from_utf8_lossy(block) + .lines() + .skip(1) + .filter_map(|line| line.split_once(':')) + .map(|(key, value)| (key.trim().to_ascii_lowercase(), value.trim().to_owned())) + .collect() +} + +pub(super) fn header_of<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> { + headers + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value.as_str()) +} + +/// Parse a status line's code. +fn status_of(block: &[u8]) -> Result { + String::from_utf8_lossy(block) + .lines() + .next() + .unwrap_or("") + .split_whitespace() + .nth(1) + .and_then(|code| code.parse().ok()) + .ok_or_else(|| ReadError::new("unreadable HTTP status line from gh")) +} + +/// A short, credential-free diagnostic line for the operator. +fn diagnostic(stderr: &[u8]) -> String { + let detail = String::from_utf8_lossy(stderr) + .lines() + .map(str::trim) + .rfind(|line| !line.is_empty()) + .unwrap_or("no detail") + .to_owned(); + // A failure message is the likeliest place a token gets echoed back. + let redacted = detail + .split_whitespace() + .map(|word| { + let lower = word.to_ascii_lowercase(); + if ["token", "authorization", "password", "bearer"] + .iter() + .any(|key| lower.contains(key)) + { + "REDACTED" + } else { + word + } + }) + .collect::>() + .join(" "); + redacted.chars().take(200).collect() +} diff --git a/crates/tranche-core/src/evidence/read/mod.rs b/crates/tranche-core/src/evidence/read/mod.rs new file mode 100644 index 0000000..37e4efe --- /dev/null +++ b/crates/tranche-core/src/evidence/read/mod.rs @@ -0,0 +1,20 @@ +//! A bounded, GET-only read transport for evidence acquisition. +//! +//! Reading a PR list and throwing the status, headers and bytes away is enough for +//! discovery. Evidence needs all three, so this is the narrow extension: the same +//! credential ownership (`gh` holds the token, this process never reads it and +//! never puts it in an argv) while returning the exact response. +//! +//! Everything here is read-only. REST requests are explicit GET; a GraphQL +//! document is accepted only if it is a query, and the document travels on stdin +//! so it never appears in `ps` output. Redirects and continuation links are +//! validated against the allowed origin and the repository scope before they are +//! followed, and every attempt is charged to a budget. + +pub mod error; +pub mod gh_call; +pub mod transport; +pub mod url; + +pub use error::{ReadError, read}; +pub use transport::{Budget, MAX_RESPONSE_BYTES, Response}; diff --git a/crates/tranche-core/src/evidence/read/transport.rs b/crates/tranche-core/src/evidence/read/transport.rs new file mode 100644 index 0000000..c8f079d --- /dev/null +++ b/crates/tranche-core/src/evidence/read/transport.rs @@ -0,0 +1,299 @@ +//! Attempt accounting and the request loop. +//! +//! Every attempt is charged, failures included, because the budget exists to bound +//! what a capture costs rather than what it achieves. + +use super::ReadError; +use super::gh_call::{header_of, invoke}; +use super::url; + +/// The largest response body this transport will keep. +pub const MAX_RESPONSE_BYTES: usize = 4 * 1024 * 1024; +/// How long `gh` may take before it is killed. +pub const GH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); +/// The most stderr kept for a diagnostic. Overflow is dropped, never fatal. +pub const MAX_STDERR_BYTES: usize = 64 * 1024; +/// Redirects followed before the read is refused. +pub const MAX_REDIRECTS: usize = 3; + +/// Statuses this transport follows itself. +const REDIRECT_STATUSES: [u16; 5] = [301, 302, 303, 307, 308]; + +/// What one request is allowed to spend. +/// +/// `reserved` capacity is held back from ordinary requests so work that must not +/// be starved — the final identity checks a capture performs before it certifies +/// anything — can still run. A caller spending that capacity says so with +/// `reserve = Some(0)`. +#[derive(Debug, Clone)] +pub struct Budget { + pub limit: u64, + pub reserved: u64, + pub used: u64, + pub failures: u64, + pub identity_checks: u64, +} + +impl Budget { + pub fn new(limit: u64, reserved: u64) -> Result { + if reserved > limit { + return Err(ReadError::new( + "reserved budget must be within the request budget", + )); + } + Ok(Self { + limit, + reserved, + used: 0, + failures: 0, + identity_checks: 0, + }) + } + + /// Attempts left, whatever is reserved. + pub fn remaining(&self) -> u64 { + self.limit.saturating_sub(self.used) + } + + /// Whether one more request fits while keeping `reserve` (the reserved floor + /// by default). + pub fn can(&self, reserve: Option) -> bool { + let keep = reserve.unwrap_or(self.reserved); + self.used + 1 + keep <= self.limit + } + + /// Consume one attempt, keeping `reserve` requests available for later work. + pub fn charge(&mut self, reserve: Option) -> Result<(), ReadError> { + let keep = reserve.unwrap_or(self.reserved); + if !self.can(Some(keep)) { + return Err(ReadError::new(format!( + "request budget exhausted ({}/{}, {keep} held back)", + self.used, self.limit + ))); + } + self.used += 1; + Ok(()) + } + + pub fn record_failure(&mut self) { + self.failures += 1; + } +} + +/// One HTTP response: the exact bytes plus the metadata they arrived with. +#[derive(Debug, Clone)] +pub struct Response { + pub status: u16, + pub url: String, + /// Lowercased header names. + pub headers: Vec<(String, String)>, + pub body: Vec, + pub truncated: bool, +} + +impl Response { + pub fn header(&self, name: &str) -> Option<&str> { + header_of(&self.headers, name) + } + + /// The media type without its parameters. + pub fn media_type(&self) -> String { + self.header("content-type") + .unwrap_or("") + .split(';') + .next() + .unwrap_or("") + .trim() + .to_owned() + } + + /// The continuation URL the response advertises, validated. + pub fn next_url(&self) -> Result, ReadError> { + url::next_link(self.header("link")) + } + + /// Parse the body as UTF-8 JSON. A truncated body is never parsed silently. + pub fn json(&self) -> Result { + if self.truncated { + return Err(ReadError::too_large( + "truncated response body cannot be parsed as JSON", + )); + } + serde_json::from_slice(&self.body) + .map_err(|error| ReadError::new(format!("response body is not UTF-8 JSON ({error})"))) + } +} + +/// What one `gh` invocation produced, bounded and possibly incomplete. +pub struct Raw { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, + pub truncated: bool, + pub hops: usize, +} + +/// Read one URL, following validated redirects and charging every attempt. +/// +/// The redirects `gh` does not follow are followed here, and each one is validated +/// before it is requested. +pub fn get( + url: &str, + accept: Option<&str>, + mut budget: Option<&mut Budget>, + reserve: Option, + repo_prefix: Option<&str>, +) -> Result { + let mut attempt_url = url::validate(url, repo_prefix)?; + let mut hops = 0usize; + loop { + if let Some(inner) = budget.as_deref_mut() + && let Err(error) = inner.charge(reserve) + { + return Err(error); + } + let mut arguments = vec![ + "api".to_owned(), + "--include".to_owned(), + "--method".to_owned(), + "GET".to_owned(), + attempt_url.clone(), + ]; + if let Some(accept) = accept { + arguments.push("-H".to_owned()); + arguments.push(format!("accept: {accept}")); + } + let raw = match invoke(&arguments, None, MAX_RESPONSE_BYTES) { + Ok(raw) => raw, + Err(error) => { + // An oversized response is not a failed request: the remedy is a + // larger bound, so it is not charged as a failure. + if !error.too_large + && let Some(inner) = budget.as_deref_mut() + { + inner.record_failure(); + } + return Err(error); + } + }; + hops += raw.hops.saturating_sub(1); + if REDIRECT_STATUSES.contains(&raw.status) + && let Some(location) = header_of(&raw.headers, "location") + { + if hops >= MAX_REDIRECTS { + return Err(ReadError::new(format!( + "too many redirects from {attempt_url}" + ))); + } + attempt_url = url::validate(&url::absolute(location, &attempt_url)?, repo_prefix)?; + continue; + } + if raw.status >= 400 { + if let Some(inner) = budget.as_deref_mut() { + inner.record_failure(); + } + return Err(ReadError::new(format!( + "HTTP {} from {attempt_url}", + raw.status + ))); + } + if raw.truncated { + return Err(ReadError::too_large(format!( + "response from {attempt_url} exceeded the {MAX_RESPONSE_BYTES} byte bound" + ))); + } + return Ok(Response { + status: raw.status, + url: attempt_url, + headers: raw.headers, + body: raw.body, + truncated: false, + }); + } +} + +/// The GraphQL endpoint. +pub const GRAPHQL_URL: &str = "https://api.github.com/graphql"; + +/// The largest GraphQL request body this transport will send. +pub const MAX_GRAPHQL_BODY_BYTES: usize = 256 * 1024; + +/// Run one GraphQL query. Mutations and subscriptions are refused by construction. +/// +/// The document travels on stdin rather than in the argv, so the query text never +/// appears in `ps` output and no credential-shaped value can be mistaken for an +/// argument. This is a read path: a document that is not a query, or that mentions +/// a mutation or subscription anywhere, is refused before a request is made. +pub fn graphql( + query: &str, + variables: &serde_json::Value, + mut budget: Option<&mut Budget>, + reserve: Option, +) -> Result { + let trimmed = query.trim_start(); + if query.trim().is_empty() || !(trimmed.starts_with("query") || trimmed.starts_with('{')) { + return Err(ReadError::new( + "refusing a GraphQL document that is not a query", + )); + } + let lowered = query.to_ascii_lowercase(); + if lowered.contains("mutation") || lowered.contains("subscription") { + return Err(ReadError::new( + "refusing a GraphQL document mentioning mutation/subscription", + )); + } + let body = serde_json::to_vec(&serde_json::json!({ + "query": query, + "variables": variables, + })) + .map_err(|error| ReadError::new(format!("cannot encode the GraphQL request: {error}")))?; + if body.len() > MAX_GRAPHQL_BODY_BYTES { + return Err(ReadError::new("GraphQL request body exceeds the bound")); + } + if let Some(inner) = budget.as_deref_mut() + && let Err(error) = inner.charge(reserve) + { + return Err(error); + } + let arguments = vec![ + "api".to_owned(), + "--include".to_owned(), + "--method".to_owned(), + "POST".to_owned(), + GRAPHQL_URL.to_owned(), + "--input".to_owned(), + "-".to_owned(), + ]; + let raw = match invoke(&arguments, Some(&body), MAX_RESPONSE_BYTES) { + Ok(raw) => raw, + Err(error) => { + if !error.too_large + && let Some(inner) = budget.as_deref_mut() + { + inner.record_failure(); + } + return Err(error); + } + }; + if raw.status >= 400 { + if let Some(inner) = budget { + inner.record_failure(); + } + return Err(ReadError::new(format!( + "HTTP {} from {GRAPHQL_URL}", + raw.status + ))); + } + if raw.truncated { + return Err(ReadError::too_large(format!( + "GraphQL response exceeded the {MAX_RESPONSE_BYTES} byte bound" + ))); + } + Ok(Response { + status: raw.status, + url: GRAPHQL_URL.to_owned(), + headers: raw.headers, + body: raw.body, + truncated: false, + }) +} diff --git a/crates/tranche-core/src/evidence/read/url.rs b/crates/tranche-core/src/evidence/read/url.rs new file mode 100644 index 0000000..a66b23a --- /dev/null +++ b/crates/tranche-core/src/evidence/read/url.rs @@ -0,0 +1,204 @@ +//! URL policy for the read transport. +//! +//! A URL is checked before it is requested, and the checks are scope checks +//! rather than authenticity checks: staying inside the API origin and one +//! repository's namespace says nothing about whether the response is the +//! resource that was asked for. That is verified against the payload itself at +//! acquisition time. + +use super::ReadError; + +/// The only origin this transport will request. +pub const ORIGIN: &str = "https://api.github.com"; + +/// Query keys that look like a credential, refused wherever they appear. +/// +/// The credential stays inside `gh`; a URL that carries one is a bug or an +/// attempt to leak it, and either way it is not sent. +const CREDENTIAL_KEYS: [&str; 10] = [ + "token", + "access_token", + "authorization", + "api_key", + "client_secret", + "private_token", + "password", + "key", + "auth", + "credentials", +]; + +/// The pieces of a URL this policy cares about. +struct Parts<'a> { + scheme: &'a str, + netloc: &'a str, + path: &'a str, + query: &'a str, + fragment: &'a str, +} + +/// Split a URL without pulling in a URL crate. +/// +/// The inputs are GitHub's own `Link` headers, so the shapes are known; anything +/// unparseable is refused rather than repaired. +fn parts(url: &str) -> Option> { + let (scheme, rest) = url.split_once("://")?; + let (authority, rest) = match rest.find('/') { + Some(index) => (&rest[..index], &rest[index..]), + None => (rest, ""), + }; + let (rest, fragment) = match rest.split_once('#') { + Some((rest, fragment)) => (rest, fragment), + None => (rest, ""), + }; + let (path, query) = match rest.split_once('?') { + Some((path, query)) => (path, query), + None => (rest, ""), + }; + Some(Parts { + scheme, + netloc: authority, + path, + query, + fragment, + }) +} + +/// A URL this transport is willing to request. +/// +/// `repo_prefix` is `owner/repo` when the request must stay inside one +/// repository's REST namespace. +pub fn validate(url: &str, repo_prefix: Option<&str>) -> Result { + if url.is_empty() { + return Err(ReadError::new("refusing empty URL")); + } + if url + .chars() + .any(|character| character.is_whitespace() || character.is_control()) + { + return Err(ReadError::new( + "refusing URL containing whitespace or control characters", + )); + } + let parts = parts(url).ok_or_else(|| ReadError::new("refusing unparseable URL"))?; + if parts.scheme != "https" || parts.netloc != "api.github.com" { + return Err(ReadError::new(format!( + "refusing URL outside {ORIGIN}: {url}" + ))); + } + if !parts.fragment.is_empty() { + return Err(ReadError::new("refusing URL with a fragment")); + } + // A lookalike origin such as `https://api.github.com.evil.test` parses to a + // different netloc, but a prefix check catches one the parser would accept. + if !url.starts_with(ORIGIN) { + return Err(ReadError::new(format!( + "refusing URL that only resembles {ORIGIN}: {url}" + ))); + } + if query_keys(parts.query) + .iter() + .any(|key| CREDENTIAL_KEYS.contains(&key.as_str())) + { + return Err(ReadError::new( + "refusing URL carrying credential-shaped query parameters", + )); + } + if let Some(prefix) = repo_prefix { + let namespace = format!("/repos/{prefix}"); + if parts.path != namespace && !parts.path.starts_with(&format!("{namespace}/")) { + return Err(ReadError::new(format!( + "refusing URL outside repository {prefix}: {url}" + ))); + } + } + Ok(url.to_owned()) +} + +/// The lowercased query keys, for the credential check. +fn query_keys(query: &str) -> Vec { + query + .split('&') + .filter(|pair| !pair.is_empty()) + .map(|pair| pair.split('=').next().unwrap_or("").to_ascii_lowercase()) + .collect() +} + +/// The `rel="next"` continuation URL, validated. Other relations are ignored. +pub fn next_link(header: Option<&str>) -> Result, ReadError> { + let Some(header) = header else { + return Ok(None); + }; + for entry in split_entries(header) { + let Some((target, relations)) = entry.split_once('>') else { + continue; + }; + let target = target.trim_start_matches('<').trim(); + if !relations + .split(',') + .any(|relation| is_next(relation.trim())) + { + continue; + } + return validate(target, None).map(Some); + } + Ok(None) +} + +/// Split a `Link` header on the commas that separate entries, not the ones inside +/// a URL. +fn split_entries(header: &str) -> Vec<&str> { + let mut entries = Vec::new(); + let mut start = 0; + for (index, character) in header.char_indices() { + if character == ',' && header[index + 1..].trim_start().starts_with('<') { + entries.push(&header[start..index]); + start = index + 1; + } + } + entries.push(&header[start..]); + entries +} + +/// Whether one `Link` entry's parameters declare `rel="next"`. +fn is_next(relation: &str) -> bool { + // The parameter keeps its `;` separator from the entry, and GitHub sends no + // space before it. + let relation = relation.trim().trim_start_matches(';').trim(); + let Some((key, value)) = relation.split_once('=') else { + return false; + }; + key.trim().eq_ignore_ascii_case("rel") + && value.trim().trim_matches('"').eq_ignore_ascii_case("next") +} + +/// The `page` number a URL carries, defaulting to one. +pub fn page_number(url: &str) -> Result { + let parts = parts(url).ok_or_else(|| ReadError::new("refusing unparseable URL"))?; + for pair in parts.query.split('&') { + if let Some((key, value)) = pair.split_once('=') + && key == "page" + { + return value + .parse() + .map_err(|_| ReadError::new(format!("unreadable page parameter in {url}"))); + } + } + Ok(1) +} + +/// Resolve a redirect target against the URL that produced it. +pub fn absolute(location: &str, base: &str) -> Result { + if location.starts_with("https://") { + return Ok(location.to_owned()); + } + if !location.starts_with('/') { + return Err(ReadError::new(format!( + "refusing relative redirect target {location:?}" + ))); + } + if base.is_empty() { + return Err(ReadError::new("refusing redirect with no base")); + } + Ok(format!("{ORIGIN}{location}")) +} diff --git a/crates/tranche-core/src/evidence/report/coverage_state.rs b/crates/tranche-core/src/evidence/report/coverage_state.rs new file mode 100644 index 0000000..97c3614 --- /dev/null +++ b/crates/tranche-core/src/evidence/report/coverage_state.rs @@ -0,0 +1,93 @@ +//! Per-member and per-component coverage, from the recorded state alone. +//! +//! This is the view a reader checks a capture against: the counts and statuses that +//! say what was actually observed, before anything is interpreted. + +use serde_json::{Value, json}; + +use super::super::coverage::is_complete; + +/// The default window, in bytes. +pub const DEFAULT_WINDOW_BYTES: usize = 16 * 1024; + +/// The per-member and per-component coverage, from the recorded state alone. +pub fn coverage(manifest: &Value) -> Value { + let components = manifest["components"] + .as_array() + .cloned() + .unwrap_or_default(); + let citations = manifest["citations"] + .as_array() + .cloned() + .unwrap_or_default(); + let members: Vec = manifest["selection"]["members"] + .as_array() + .into_iter() + .flatten() + .map(|member| { + let number = member["number"].as_u64().unwrap_or(0); + let entries: Vec = components + .iter() + .filter(|entry| entry["number"].as_u64() == Some(number)) + .map(|entry| { + json!({ + "component": entry["component"], + "status": entry["status"], + "pages": entry["groups"] + .as_array() + .into_iter() + .flatten() + .map(|group| group["pages"].as_u64().unwrap_or(0)) + .sum::(), + "reason": entry["reason"], + "groups": entry["groups"] + .as_array() + .into_iter() + .flatten() + .map(|group| json!({ + "group": group["group"], + "status": group["status"], + "pages": group["pages"], + "reason": group["reason"], + })) + .collect::>(), + "citations": citations + .iter() + .filter(|citation| { + citation["number"].as_u64() == Some(number) + && citation["component"] == entry["component"] + }) + .count(), + }) + }) + .collect(); + json!({ + "number": number, + "base_sha": member["base_sha"], + "head_sha": member["head_sha"], + "components": entries, + }) + }) + .collect(); + + let capture = &manifest["capture"]; + json!({ + "capture_id": manifest["capture_id"], + "generation": manifest["generation"], + "batch": manifest["selection"]["batch"]["id"], + "observed_at": capture["observed_at"], + "stop_reason": capture["stop_reason"], + "complete": is_complete(manifest), + "requests": { + "request_limit": capture["request_limit"], + "requests_used": capture["requests_used"], + "reserved": capture["reserved"], + "failures": capture["failures"], + "retries": capture["retries"], + "identity_checks": capture["identity_checks"], + }, + "bytes_stored": capture["bytes_stored"], + "citations": citations.len(), + "members": members, + }) +} diff --git a/crates/tranche-core/src/evidence/report/mod.rs b/crates/tranche-core/src/evidence/report/mod.rs new file mode 100644 index 0000000..cf11c13 --- /dev/null +++ b/crates/tranche-core/src/evidence/report/mod.rs @@ -0,0 +1,16 @@ +//! Reading a capture back: coverage, windows and citations. +//! +//! Everything here answers from the recorded state and the stored bodies alone — no +//! network, no second application, no report. That independence is the property being +//! preserved: a reader holding only the capture directory can verify it. +//! +//! Stored bytes are never altered. A window renders them for a terminal, escaping what +//! a terminal must not receive. + +pub mod coverage_state; +pub mod printing; +pub mod windows; + +pub use coverage_state::{DEFAULT_WINDOW_BYTES, coverage}; +pub use printing::printable; +pub use windows::{resolve_citation, window}; diff --git a/crates/tranche-core/src/evidence/report/printing.rs b/crates/tranche-core/src/evidence/report/printing.rs new file mode 100644 index 0000000..f89032f --- /dev/null +++ b/crates/tranche-core/src/evidence/report/printing.rs @@ -0,0 +1,21 @@ +//! A terminal-safe rendering of stored bytes. +//! +//! Control characters, escape sequences and non-ASCII are shown as escapes rather +//! than emitted: a captured body is untrusted text and must not be able to drive the +//! terminal that reads it. + +pub fn printable(data: &[u8]) -> String { + let text = String::from_utf8_lossy(data); + let mut out = String::with_capacity(text.len()); + for character in text.chars() { + // A newline is the one control character a reader needs literally. + if character == '\n' || ('\u{20}'..='\u{7e}').contains(&character) { + out.push(character); + } else { + for unit in character.encode_utf16(&mut [0u16; 2]) { + out.push_str(&format!("\\u{unit:04x}")); + } + } + } + out +} diff --git a/crates/tranche-core/src/evidence/report/windows.rs b/crates/tranche-core/src/evidence/report/windows.rs new file mode 100644 index 0000000..c4e3ffc --- /dev/null +++ b/crates/tranche-core/src/evidence/report/windows.rs @@ -0,0 +1,112 @@ +//! Bounded windows and citation resolution, answered from the stored bytes. +//! +//! Both are the operations a reader must be able to perform without the state store, +//! the network or a second application. + +use serde_json::{Value, json}; + +use super::super::store::read_body; +use super::coverage_state::DEFAULT_WINDOW_BYTES; +use super::printing::printable; +use crate::report::Root; + +pub fn window( + root: &Root, + manifest: &Value, + source_id: &str, + start: usize, + length: usize, +) -> Result { + if length == 0 || length > DEFAULT_WINDOW_BYTES { + return Err(format!("length must be 1..{DEFAULT_WINDOW_BYTES} bytes")); + } + let source = source_for(manifest, source_id)?; + let sha = source["body_sha256"].as_str().unwrap_or(""); + let body = read_body(root, sha).map_err(|error| error.0)?; + if start > body.len() { + return Err(format!( + "start byte {start} is past the end of a {} byte source", + body.len() + )); + } + let end = body.len().min(start + length); + let chunk = &body[start..end]; + Ok(json!({ + "capture_id": manifest["capture_id"], + "source_id": source_id, + "number": source["number"], + "component": source["component"], + "group": source["group"], + "page": source["page"], + "url": source["url"], + "media_type": source["media_type"], + "body_sha256": sha, + "body_bytes": body.len(), + "start_byte": start, + "end_byte": end, + "next_start": if end < body.len() { json!(end) } else { Value::Null }, + "window_sha256": crate::util::sha256_hex(chunk), + "content": printable(chunk), + })) +} + +/// Resolve one citation against the stored bytes it names, offline. +/// +/// This is the operation a reader must be able to perform without the state store, +/// the network or another application: look the source up, verify its bytes, and +/// re-derive the excerpt digest that was recorded. A mismatch is reported rather +/// than shown, because a citation that no longer matches is worse than none. +pub fn resolve_citation(root: &Root, manifest: &Value, citation_id: &str) -> Result { + let citations = manifest["citations"] + .as_array() + .cloned() + .unwrap_or_default(); + let citation = citations + .iter() + .find(|citation| citation["id"].as_str() == Some(citation_id)) + .ok_or_else(|| { + format!( + "no citation {citation_id:?} in capture {}", + manifest["capture_id"].as_str().unwrap_or("") + ) + })?; + let source_sha = citation["source_sha256"].as_str().unwrap_or(""); + let body = read_body(root, source_sha).map_err(|error| error.0)?; + let start = citation["start_byte"].as_u64().unwrap_or(0) as usize; + let end = citation["end_byte"].as_u64().unwrap_or(0) as usize; + if start > end || end > body.len() { + return Err(format!( + "citation {citation_id:?} names a range outside its stored bytes" + )); + } + let excerpt = &body[start..end]; + let digest = crate::util::sha256_hex(excerpt); + if digest != citation["excerpt_sha256"].as_str().unwrap_or("") { + return Err(format!( + "citation {} no longer matches its stored bytes", + &citation_id[..citation_id.len().min(12)] + )); + } + let source = source_for(manifest, citation["source_id"].as_str().unwrap_or(""))?; + Ok(json!({ + "citation": citation, + "source": source, + "excerpt_sha256": digest, + "excerpt": printable(excerpt), + })) +} + +/// One source by its id. +fn source_for<'a>(manifest: &'a Value, source_id: &str) -> Result<&'a Value, String> { + manifest["sources"] + .as_array() + .into_iter() + .flatten() + .find(|source| source["id"].as_str() == Some(source_id)) + .ok_or_else(|| { + format!( + "no source {source_id:?} in capture {}", + manifest["capture_id"].as_str().unwrap_or("") + ) + }) +} diff --git a/crates/tranche-core/src/evidence/selecting.rs b/crates/tranche-core/src/evidence/selecting.rs new file mode 100644 index 0000000..a09cc88 --- /dev/null +++ b/crates/tranche-core/src/evidence/selecting.rs @@ -0,0 +1,286 @@ +//! Resolving a batch id into the selection a capture binds to. +//! +//! Every refusal here is a refusal to attach evidence to the wrong thing: an unknown +//! ordinal, a batch the report does not contain, a batch that lists parked PRs, a +//! member whose revisions or repository identities are unavailable, or members that +//! do not share one base repository. Attaching a capture to the wrong batch would +//! produce evidence that is internally consistent and describes the wrong work, which +//! is worse than no evidence at all. + +use serde_json::Value; + +use super::errors::SelectionError; +use super::selection::{Member, Selection, is_batch_id}; +use crate::domain::pr::Prs; +use crate::report::Root; + +/// One member's revision identity, taken from the captured item rather than inferred. +struct Revision { + member: Member, +} + +/// The batch plan and park record a selection is checked against. +/// +/// Owns its data because it is assembled from files read at the call site and then +/// used after those bindings could move. +pub struct Plan { + pub batches: Option, + pub parked: Option, + pub binding: Option, + pub clusters_digest: Option, + pub dupes_digest: Option, + pub batches_digest: Option, + pub parked_digest: Option, +} + +impl Plan { + /// Read the plan from the report on disk. + pub fn read(root: &Root) -> Result { + let read = |path: std::path::PathBuf, name: &str| -> Result { + let text = std::fs::read_to_string(&path) + .map_err(|error| SelectionError(format!("{name}: {error}")))?; + serde_json::from_str(&text).map_err(|error| SelectionError(format!("{name}: {error}"))) + }; + let summary = read(root.summary_path(), "summary.json")?; + let digests = summary["output_digests"].clone(); + let text = |name: &str| digests[name].as_str().map(str::to_owned); + Ok(Self { + batches: read(root.batches_path(), "batches.json").ok(), + parked: read(root.parked_path(), "parked.json").ok(), + binding: summary["report_binding"].as_str().map(str::to_owned), + clusters_digest: text("clusters.json"), + dupes_digest: text("dupes.json"), + batches_digest: text("batches.json"), + parked_digest: text("parked.json"), + }) + } +} + +/// Resolve one batch through the bound report, or refuse. +pub fn select( + root: &Root, + batch_id: &str, + corpus: &Prs, + plan: &Plan, +) -> Result { + if !is_batch_id(batch_id) { + return Err(SelectionError( + "expected an exact batch id such as B001".to_owned(), + )); + } + let Some(batches) = plan.batches.as_ref() else { + return Err(SelectionError( + "batches.json is unavailable; run `tranche batches`".to_owned(), + )); + }; + let all = batches["batches"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]); + let Some(batch) = all + .iter() + .find(|batch| batch["id"].as_str() == Some(batch_id)) + else { + return Err(SelectionError(format!( + "unknown batch id {batch_id}; the current report has {} batches", + all.len() + ))); + }; + let members_of_batch: Vec = batch["members"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_u64) + .collect(); + + // A batch that lists parked PRs means the plan and the park record disagree, + // and the disagreement is the report's, not something to work around here. + let parked: Vec = plan + .parked + .as_ref() + .and_then(|parked| parked["members"].as_array()) + .into_iter() + .flatten() + .filter_map(|member| member["number"].as_u64()) + .collect(); + let inconsistent: Vec = members_of_batch + .iter() + .copied() + .filter(|number| parked.contains(number)) + .collect(); + if !inconsistent.is_empty() { + let listed = inconsistent + .iter() + .map(|number| format!("#{number}")) + .collect::>() + .join(", "); + return Err(SelectionError(format!( + "batch {batch_id} lists parked PRs {listed}; the batch plan and the park \ + record disagree - rerun `tranche batches`" + ))); + } + + let items = captured_items(root)?; + let mut members: Vec = Vec::with_capacity(members_of_batch.len()); + for number in &members_of_batch { + let revision = revision(*number, &items, corpus)?; + members.push(revision.member); + } + let Some(first) = members.first() else { + return Err(SelectionError(format!("batch {batch_id} has no members"))); + }; + + let repository = serde_json::json!({ + "id": first.base_repo_id, + "full_name": first.base_repo_name, + // Visibility is checked live at export rather than assumed here, because a + // capture records what it read, not what it was permitted to share. + "visibility": "unknown", + }); + if members.iter().any(|member| { + member.base_repo_id != first.base_repo_id || member.base_repo_name != first.base_repo_name + }) { + return Err(SelectionError( + "batch members do not share one base repository".to_owned(), + )); + } + + let report = serde_json::json!({ + "report_binding": plan.binding, + "output_digests": { + "clusters.json": plan.clusters_digest, + "dupes.json": plan.dupes_digest, + "batches.json": plan.batches_digest, + "parked.json": plan.parked_digest, + }, + }); + + let ordinal = batch["ordinal"].as_u64().unwrap_or(0); + let prompt = batch["review_prompt"].as_str().unwrap_or("").to_owned(); + Ok(Selection { + repository, + report, + batch_id: batch_id.to_owned(), + batch_ordinal: ordinal, + prompt, + members, + }) +} + +/// The captured raw items, keyed by number. +/// +/// The revision identity is read from the captured item, because the projection the +/// report carries has already dropped the repository objects the identity needs. +fn captured_items(root: &Root) -> Result, SelectionError> { + let snapshot = root.snapshot_path(); + if snapshot.exists() { + let text = std::fs::read_to_string(&snapshot) + .map_err(|error| SelectionError(format!("cannot read the capture: {error}")))?; + let value: Value = serde_json::from_str(&text) + .map_err(|error| SelectionError(format!("the capture is unreadable: {error}")))?; + if let Some(items) = value.get("items").and_then(Value::as_array) { + return Ok(index(items)); + } + } + let mut items = Vec::new(); + for path in crate::report::read_page_paths(&root.pages_dir()) { + let text = std::fs::read_to_string(&path) + .map_err(|error| SelectionError(format!("cannot read {}: {error}", path.display())))?; + let value: Value = serde_json::from_str(&text).map_err(|error| { + SelectionError(format!("{} is unreadable: {error}", path.display())) + })?; + if let Some(page) = value.as_array() { + items.extend(page.iter().cloned()); + } + } + Ok(index(&items)) +} + +fn index(items: &[Value]) -> std::collections::HashMap { + items + .iter() + .filter_map(|item| { + item.get("number") + .and_then(Value::as_u64) + .map(|n| (n, item.clone())) + }) + .collect() +} + +/// Full base/head identity for one member, or refuse the selection. +/// +/// A short or missing revision is never substituted: the whole point of the code +/// observation is that it names an exact pair of commits. +fn revision( + number: u64, + items: &std::collections::HashMap, + corpus: &Prs, +) -> Result { + let item = items.get(&number).ok_or_else(|| { + SelectionError(format!( + "#{number} is not in the captured membership; fetch again" + )) + })?; + let head = item.get("head").cloned().unwrap_or(Value::Null); + let base = item.get("base").cloned().unwrap_or(Value::Null); + let (head_repo, base_repo) = ( + head.get("repo").cloned().unwrap_or(Value::Null), + base.get("repo").cloned().unwrap_or(Value::Null), + ); + if !head_repo.is_object() || !base_repo.is_object() { + return Err(SelectionError(format!( + "#{number} no longer exposes its base/head repository (a deleted fork cannot \ + be captured); the selection cannot bind this member" + ))); + } + let sha = |value: &Value, name: &str| -> Result { + let text = value.get("sha").and_then(Value::as_str).unwrap_or(""); + if text.len() == 40 && text.chars().all(|c| c.is_ascii_hexdigit()) { + Ok(text.to_owned()) + } else { + Err(SelectionError(format!( + "#{number} has no full 40-character {name}; fetch again" + ))) + } + }; + let repo_id = |value: &Value, name: &str| -> Result { + match value.get("id").and_then(Value::as_u64) { + Some(id) if id > 0 => Ok(id), + _ => Err(SelectionError(format!( + "#{number} has no usable {name}; fetch again" + ))), + } + }; + let repo_name = |value: &Value| { + value + .get("full_name") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned() + }; + + let pr = corpus.get(number).ok_or_else(|| { + SelectionError(format!("#{number} is missing from the report projection")) + })?; + Ok(Revision { + member: Member { + number, + source_digest: pr.source_digest.clone(), + evidence_digest: pr.evidence_digest.clone(), + base_sha: sha(&base, "base_sha")?, + head_sha: sha(&head, "head_sha")?, + base_repo_id: repo_id(&base_repo, "base_repo_id")?, + base_repo_name: repo_name(&base_repo), + head_repo_id: repo_id(&head_repo, "head_repo_id")?, + head_repo_name: repo_name(&head_repo), + head_fork: head_repo + .get("fork") + .and_then(Value::as_bool) + .unwrap_or(false), + updated_at: item + .get("updated_at") + .and_then(Value::as_str) + .map(str::to_owned), + }, + }) +} diff --git a/crates/tranche-core/src/evidence/selection.rs b/crates/tranche-core/src/evidence/selection.rs new file mode 100644 index 0000000..19e69fd --- /dev/null +++ b/crates/tranche-core/src/evidence/selection.rs @@ -0,0 +1,290 @@ +//! The selection a capture generation is bound to, and the manifest validation +//! that proves a stored checkpoint describes itself. +//! +//! A manifest is untrusted input. It is a file under `out/` that a writer could +//! have edited, so reading one re-derives every identity it claims — the +//! generation from its own selection, each source's digest from its own record — +//! rather than believing the stored value. + +use serde_json::{Map, Value, json}; + +use super::{Error, FORMAT, PROFILE}; +use crate::util::digest; + +/// Full 40-character commit SHA. +pub fn is_sha1(value: &str) -> bool { + value.len() == 40 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +/// A batch id such as `B001`. +pub fn is_batch_id(value: &str) -> bool { + let bytes = value.as_bytes(); + (4..=7).contains(&bytes.len()) && bytes[0] == b'B' && bytes[1..].iter().all(u8::is_ascii_digit) +} + +/// The code identity of one member: the exact commits and the repositories they +/// sit in. +#[derive(Debug, Clone)] +pub struct Member { + pub number: u64, + pub source_digest: String, + pub evidence_digest: String, + pub base_sha: String, + pub head_sha: String, + pub base_repo_id: u64, + pub base_repo_name: String, + pub head_repo_id: u64, + pub head_repo_name: String, + pub head_fork: bool, + pub updated_at: Option, +} + +impl Member { + /// What a revision move means: commits and the repositories they sit in. + /// + /// `updated_at` is deliberately excluded. It is observed upstream data, and a + /// PR update is thread activity rather than a code revision — treating it as + /// a revision marker would force re-downloading unchanged code. + pub fn revision_key(&self) -> Value { + json!({ + "base_sha": self.base_sha, + "head_sha": self.head_sha, + "base_repo_id": self.base_repo_id, + "base_repo_name": self.base_repo_name, + "head_repo_id": self.head_repo_id, + "head_repo_name": self.head_repo_name, + }) + } + + fn as_json(&self) -> Value { + json!({ + "number": self.number, + "source_digest": self.source_digest, + "evidence_digest": self.evidence_digest, + "base_sha": self.base_sha, + "head_sha": self.head_sha, + "base_repo_id": self.base_repo_id, + "base_repo_name": self.base_repo_name, + "head_repo_id": self.head_repo_id, + "head_repo_name": self.head_repo_name, + "head_fork": self.head_fork, + "updated_at": self.updated_at, + }) + } + + fn from_json(value: &Value) -> Result { + let read_str = |key: &str| -> Result { + value + .get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| super::refuse(format!("member is missing {key}")).into()) + }; + let read_int = |key: &str| -> Result { + value + .get(key) + .and_then(Value::as_u64) + .ok_or_else(|| super::refuse(format!("member is missing {key}")).into()) + }; + Ok(Self { + number: read_int("number")?, + source_digest: read_str("source_digest")?, + evidence_digest: read_str("evidence_digest")?, + base_sha: read_str("base_sha")?, + head_sha: read_str("head_sha")?, + base_repo_id: read_int("base_repo_id")?, + base_repo_name: read_str("base_repo_name")?, + head_repo_id: read_int("head_repo_id")?, + head_repo_name: read_str("head_repo_name")?, + head_fork: value + .get("head_fork") + .and_then(Value::as_bool) + .unwrap_or(false), + updated_at: value + .get("updated_at") + .and_then(Value::as_str) + .map(str::to_owned), + }) + } +} + +/// The immutable native selection one capture generation is bound to. +#[derive(Debug, Clone)] +pub struct Selection { + pub repository: Value, + pub report: Value, + pub batch_id: String, + pub batch_ordinal: u64, + pub prompt: String, + pub members: Vec, +} + +impl Selection { + pub fn numbers(&self) -> Vec { + self.members.iter().map(|member| member.number).collect() + } + + /// The frozen projection written into every manifest and export. + /// + /// The native batch is copied whole — ordinal, ordered membership and the + /// exact reviewer prompt — because the prompt is provenance a reader can + /// check, not a cache key. Freezing only these fields keeps a later + /// presentation change from invalidating recorded evidence. + pub fn as_json(&self) -> Value { + json!({ + "repository": self.repository, + "report": self.report, + "batch": { + "id": self.batch_id, + "ordinal": self.batch_ordinal, + "members": self.numbers(), + "count": self.members.len(), + "review_prompt": self.prompt, + }, + "members": self.members.iter().map(Member::as_json).collect::>(), + }) + } + + /// The order-sensitive membership digest. + pub fn membership_digest(&self) -> String { + digest(&json!(self.numbers())) + } + + /// The code identity of the whole selection, stable across thread churn. + pub fn revision(&self) -> Value { + let mut map = Map::new(); + for member in &self.members { + map.insert(member.number.to_string(), member.revision_key()); + } + Value::Object(map) + } + + /// One member by number. + pub fn member(&self, number: u64) -> Result<&Member, Error> { + self.members + .iter() + .find(|member| member.number == number) + .ok_or_else(|| { + super::refuse(format!("#{number} is not a member of this selection")).into() + }) + } +} + +/// The capture generation: what all its sources belong to and cannot escape. +/// +/// It deliberately excludes `updated_at`: a thread update must not mint a new +/// generation or force re-downloading unchanged code, where a moved base or head +/// must. +pub fn generation_id(selection: &Selection, capture_id: &str) -> String { + digest(&json!({ + "format": FORMAT, + "profile": PROFILE, + "capture_id": capture_id, + "repository": selection.repository, + "revision": selection.revision(), + "membership": selection.membership_digest(), + "batch": selection.batch_id, + "report": selection.report, + })) +} + +/// The digest one source record's identity is derived from. +pub fn source_id(generation: &str, source: &Value) -> String { + let fields: Map = source + .as_object() + .map(|object| { + object + .iter() + .filter(|(key, _)| key.as_str() != "id") + .map(|(key, value)| (key.clone(), value.clone())) + .collect() + }) + .unwrap_or_default(); + digest(&json!({"generation": generation, "source": Value::Object(fields)})) +} + +/// Rebuild a selection from its frozen JSON, refusing a malformed projection. +pub fn selection_from_json(stored: &Value) -> Result { + let object = stored + .as_object() + .ok_or_else(|| super::refuse("capture manifest selection is malformed"))?; + let keys: std::collections::HashSet<&str> = object.keys().map(String::as_str).collect(); + if keys + != ["repository", "report", "batch", "members"] + .into_iter() + .collect() + { + return Err(super::refuse("capture manifest selection is malformed").into()); + } + let batch = object.get("batch").expect("checked above"); + let batch_object = batch + .as_object() + .ok_or_else(|| super::refuse("capture manifest batch provenance is malformed"))?; + let batch_keys: std::collections::HashSet<&str> = + batch_object.keys().map(String::as_str).collect(); + if batch_keys + != ["id", "ordinal", "members", "count", "review_prompt"] + .into_iter() + .collect() + { + return Err(super::refuse("capture manifest batch provenance is malformed").into()); + } + let ordinal = batch_object + .get("ordinal") + .and_then(Value::as_u64) + .unwrap_or(0); + let id = batch_object.get("id").and_then(Value::as_str).unwrap_or(""); + let prompt = batch_object + .get("review_prompt") + .and_then(Value::as_str) + .unwrap_or(""); + let batch_members: Vec = batch_object + .get("members") + .and_then(Value::as_array) + .map(|items| items.iter().filter_map(Value::as_u64).collect()) + .unwrap_or_default(); + let count = batch_object + .get("count") + .and_then(Value::as_u64) + .unwrap_or(0); + if prompt.trim().is_empty() + || batch_members.is_empty() + || count != batch_members.len() as u64 + || id != format!("B{ordinal:03}") + { + return Err(super::refuse("capture manifest batch provenance is malformed").into()); + } + + let members_json = object + .get("members") + .and_then(Value::as_array) + .ok_or_else(|| super::refuse("capture manifest membership does not match its batch"))?; + let mut members = Vec::new(); + for entry in members_json { + let member = Member::from_json(entry)?; + if !is_sha1(&member.base_sha) || !is_sha1(&member.head_sha) { + return Err(super::refuse("capture manifest member revision is malformed").into()); + } + members.push(member); + } + if members + .iter() + .map(|member| member.number) + .collect::>() + != batch_members + { + return Err(super::refuse("capture manifest membership does not match its batch").into()); + } + + Ok(Selection { + repository: object.get("repository").cloned().unwrap_or(Value::Null), + report: object.get("report").cloned().unwrap_or(Value::Null), + batch_id: id.to_owned(), + batch_ordinal: ordinal, + prompt: prompt.to_owned(), + members, + }) +} diff --git a/crates/tranche-core/src/evidence/store.rs b/crates/tranche-core/src/evidence/store.rs new file mode 100644 index 0000000..307114f --- /dev/null +++ b/crates/tranche-core/src/evidence/store.rs @@ -0,0 +1,237 @@ +//! Content-addressed storage for captured response bytes. +//! +//! Bytes are written and fsynced before any manifest may cite them, so a crash +//! between the two leaves an unreferenced file — swept on the next completed run +//! — and never a checkpoint pointing at bytes that are not there. + +use super::{EvidenceError, refuse}; +use crate::evidence::paths::{atomic_bytes, body_path, confined_file}; +use crate::report::Root; +use crate::util::sha256_hex; + +/// Persist immutable source bytes and return their digest. +/// +/// An existing file with the right name is not proof: it is read back and +/// verified before it is trusted, because the name is derived from the digest +/// and nothing enforces that the bytes still match. +pub fn store_body(root: &Root, data: &[u8]) -> Result { + let digest = sha256_hex(data); + let path = body_path(root, &digest)?; + if path.exists() { + read_body(root, &digest)?; + return Ok(digest); + } + atomic_bytes(&path, data)?; + Ok(digest) +} + +/// Read stored bytes, verifying them against their digest before returning. +pub fn read_body(root: &Root, digest: &str) -> Result, EvidenceError> { + let path = body_path(root, digest)?; + let confined = confined_file(&super::evidence_root(root), &format!("bodies/{digest}.bin"))?; + if !confined.exists() { + return Err(refuse(format!( + "stored source {}… is missing", + &digest[..12.min(digest.len())] + ))); + } + let data = std::fs::read(&confined) + .map_err(|error| refuse(format!("cannot read stored source: {error}")))?; + let actual = sha256_hex(&data); + if actual != digest { + return Err(refuse(format!( + "stored source {}… is corrupted (computed {}…)", + &digest[..12.min(digest.len())], + &actual[..12] + ))); + } + let _ = path; + Ok(data) +} + +/// Load JSON refusing the shapes that make a record ambiguous. +/// +/// Duplicate keys and non-finite numbers are refusal cases: a checkpoint that +/// can be read two ways cannot be trusted to resume from. +pub fn strict_json_loads(data: &[u8]) -> Result { + let text = std::str::from_utf8(data) + .map_err(|error| refuse(format!("evidence record is not valid UTF-8 ({error})")))?; + // `serde_json` keeps the last of a duplicated key rather than refusing it, so + // the ambiguity is detected before parsing. + reject_duplicate_keys(text)?; + let value: serde_json::Value = serde_json::from_str(text) + .map_err(|error| refuse(format!("evidence record is not valid JSON ({error})")))?; + reject_non_finite(&value)?; + Ok(value) +} + +/// Refuse a duplicated object key anywhere in the document. +/// +/// A checkpoint that can be read two ways is not a checkpoint. This walks the +/// text structurally — tracking object and array nesting, and which position is +/// a key — because a value-level parser has already resolved the duplicate by +/// the time it returns a map. +fn reject_duplicate_keys(text: &str) -> Result<(), EvidenceError> { + struct Frame { + object: bool, + seen: std::collections::HashSet, + expect_key: bool, + } + let bytes = text.as_bytes(); + let mut stack: Vec = Vec::new(); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'{' => stack.push(Frame { + object: true, + seen: std::collections::HashSet::new(), + expect_key: true, + }), + b'[' => stack.push(Frame { + object: false, + seen: std::collections::HashSet::new(), + expect_key: false, + }), + b'}' | b']' => { + stack.pop(); + // The closed collection is a completed value for its parent. + if let Some(parent) = stack.last_mut() { + parent.expect_key = false; + } + } + b',' => { + if let Some(frame) = stack.last_mut() + && frame.object + { + frame.expect_key = true; + } + } + b'"' => { + let start = index; + index += 1; + while index < bytes.len() { + match bytes[index] { + b'\\' => index += 1, + b'"' => break, + _ => {} + } + index += 1; + } + let literal = &text[start..=index.min(bytes.len() - 1)]; + let is_key = stack + .last() + .is_some_and(|frame| frame.object && frame.expect_key); + if is_key { + let key: String = serde_json::from_str(literal).map_err(|error| { + refuse(format!("evidence record has an unreadable key ({error})")) + })?; + let frame = stack.last_mut().expect("checked above"); + if !frame.seen.insert(key.clone()) { + return Err(refuse(format!("duplicate JSON key {key:?}"))); + } + frame.expect_key = false; + } else if let Some(frame) = stack.last_mut() { + frame.expect_key = false; + } + } + byte if byte.is_ascii_whitespace() || byte == b':' => {} + _ => { + // A scalar value: skip to the end of the token. + while index < bytes.len() + && !matches!( + bytes[index], + b',' | b'}' | b']' | b' ' | b'\n' | b'\t' | b'\r' + ) + { + index += 1; + } + continue; + } + } + index += 1; + } + Ok(()) +} + +/// Refuse NaN and Infinity, which JSON cannot express and a digest cannot cover. +fn reject_non_finite(value: &serde_json::Value) -> Result<(), EvidenceError> { + match value { + serde_json::Value::Number(number) => { + if number.as_f64().is_some_and(|value| !value.is_finite()) { + return Err(refuse(format!("non-finite JSON number {number}"))); + } + Ok(()) + } + serde_json::Value::Array(items) => items.iter().try_for_each(reject_non_finite), + serde_json::Value::Object(map) => map.values().try_for_each(reject_non_finite), + _ => Ok(()), + } +} + +/// Every body digest any stored capture cites, for the orphan sweep. +pub fn referenced_bodies(root: &Root) -> Result, EvidenceError> { + let mut referenced = std::collections::HashSet::new(); + let directory = super::evidence_root(root); + let entries = match std::fs::read_dir(&directory) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(referenced), + Err(error) => return Err(refuse(format!("cannot read the evidence root: {error}"))), + }; + for entry in entries.flatten() { + let manifest_path = entry.path().join("manifest.json"); + if !manifest_path.is_file() { + continue; + } + // A manifest that cannot be read is skipped rather than fatal: the sweep + // must not delete bytes because one record is damaged. + let Ok(text) = std::fs::read(&manifest_path) else { + continue; + }; + let Ok(manifest) = strict_json_loads(&text) else { + continue; + }; + let Some(sources) = manifest + .get("sources") + .and_then(serde_json::Value::as_array) + else { + continue; + }; + for source in sources { + if let Some(digest) = source + .get("body_sha256") + .and_then(serde_json::Value::as_str) + { + referenced.insert(digest.to_owned()); + } + } + } + Ok(referenced) +} + +/// Remove stored bodies no capture cites. +/// +/// A crash can leave bytes written but not yet cited. They are harmless, but +/// they are also unreferenced state, so a completed run tidies them. +pub fn sweep_orphans(root: &Root) -> Result { + let directory = super::evidence_root(root).join("bodies"); + let entries = match std::fs::read_dir(&directory) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(error) => return Err(refuse(format!("cannot read the body store: {error}"))), + }; + let keep = referenced_bodies(root)?; + let mut removed = 0; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|value| value.to_str()) != Some("bin") { + continue; + } + let Some(stem) = path.file_stem().and_then(|value| value.to_str()) else { + continue; + }; + if !keep.contains(stem) && std::fs::remove_file(&path).is_ok() { + removed += 1; + } + } + Ok(removed) +} diff --git a/crates/tranche-core/src/evidence/vocabulary.rs b/crates/tranche-core/src/evidence/vocabulary.rs new file mode 100644 index 0000000..c308178 --- /dev/null +++ b/crates/tranche-core/src/evidence/vocabulary.rs @@ -0,0 +1,81 @@ +//! The evidence vocabulary: what a capture is made of, and what it costs. +//! +//! These constants are the shared language of the whole evidence service. They live +//! together because they only make sense against each other: the component list is +//! what the reserved budget protects, and the exit codes are what a caller branches +//! on when the budget runs out. + +use crate::report::Root; + +/// The packet envelope this capture format writes. +pub const FORMAT: &str = "tranche.evidence-packet/v1"; + +/// The component profile every capture claims to satisfy. +pub const PROFILE: &str = "pr-review/v1"; + +/// Components whose bytes name a code revision. +pub const CODE_COMPONENTS: [&str; 3] = ["metadata", "diff", "files"]; + +/// Components that are timestamped observations of a moving conversation. +pub const MUTABLE_COMPONENTS: [&str; 5] = [ + "discussion", + "review_comments", + "reviews", + "checks", + "closing_issues", +]; + +/// Every component a member must account for, in report order. +pub const COMPONENTS: [&str; 8] = [ + "metadata", + "diff", + "files", + "discussion", + "review_comments", + "reviews", + "checks", + "closing_issues", +]; + +/// Requests held back for the completion checks, so a shortfall stops the capture +/// explicitly instead of certifying an unverified batch. +pub const RESERVED_BUDGET: i64 = 3; + +/// A writer lock older than this is reclaimable once its process is gone. +pub const LOCK_TTL: f64 = 900.0; + +/// The exit code each outcome maps to, stable for scripts. +pub const EXIT_OK: i32 = 0; +/// Usable but incomplete. +pub const EXIT_USABLE: i32 = 1; +/// The command was called wrongly. +pub const EXIT_USAGE: i32 = 2; +/// The request was refused. +pub const EXIT_REFUSED: i32 = 3; +/// The capture is incomplete. +pub const EXIT_INCOMPLETE: i32 = 4; + +/// The evidence root beneath a report checkout. +/// +/// Capture writes land under an ignored directory, never in the report itself: the +/// report describes a backlog, while a capture is a local observation of public +/// content. +pub fn evidence_root(root: &Root) -> std::path::PathBuf { + root.evidence_dir() +} + +/// UTC now, in the format every manifest timestamp uses. +/// +/// Whole seconds, one trailing `Z`: a manifest is a statement about a moment, not a +/// high-resolution log, and the recorded format is part of what packets compare. +pub fn now() -> String { + let text = time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_owned()); + // Rfc3339 may carry fractional seconds or an offset; the recorded format is + // whole seconds with one trailing `Z`. + match text.split_once('.') { + Some((head, _)) => format!("{head}Z"), + None => text, + } +} diff --git a/crates/tranche-core/src/gh.rs b/crates/tranche-core/src/gh.rs new file mode 100644 index 0000000..d67c784 --- /dev/null +++ b/crates/tranche-core/src/gh.rs @@ -0,0 +1,210 @@ +//! Reading GitHub's open-PR list, with the credential staying inside `gh`. +//! +//! `gh api` is preferred because it is already authenticated: unauthenticated +//! GitHub allows 60 requests an hour and one capture of this backlog costs about +//! 29, so an unauthenticated refresh fails on its third pass. The token is never +//! read by this process and never placed in an argv, where it would be visible to +//! every user on the host. +//! +//! A failed or partial capture reports and leaves the previous snapshot alone. +//! Nothing here writes. + +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::time::Duration; + +use serde_json::Value; + +/// The GitHub REST base. +pub const API: &str = "https://api.github.com"; + +/// How one page is read. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Transport { + /// The authenticated `gh` CLI. + #[default] + Gh, + /// The `curl` binary. + Curl, + /// The standard library HTTP client. + Urllib, +} + +impl Transport { + pub fn as_str(self) -> &'static str { + match self { + Self::Gh => "gh", + Self::Curl => "curl", + Self::Urllib => "urllib", + } + } +} + +#[derive(Debug)] +pub struct GitHubError(pub String); + +impl std::fmt::Display for GitHubError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.0) + } +} + +impl std::error::Error for GitHubError {} + +impl From for GitHubError { + fn from(message: String) -> Self { + Self(message) + } +} + +/// One page of the open-PR list. +/// +/// The body must be a JSON array. Anything else is a refusal rather than an empty +/// page, because an error document read as "no more PRs" would silently truncate +/// the corpus. +pub fn page(transport: Transport, url: &str) -> Result, GitHubError> { + page_with(transport, url, None) +} + +/// One page, optionally resolving the command through one directory. +/// +/// The search path is a parameter rather than global state: a caller that wants +/// a specific `gh` says so, and a test cannot change what a test beside it sees. +pub fn page_with( + transport: Transport, + url: &str, + command_dir: Option<&std::path::Path>, +) -> Result, GitHubError> { + let body = match transport { + Transport::Gh => run( + "gh", + &["api", url], + Duration::from_secs(120), + "gh api fetch failed", + command_dir, + )?, + Transport::Curl => run( + "curl", + &[ + "--fail", + "--silent", + "--show-error", + "--max-time", + "60", + url, + ], + Duration::from_secs(90), + "curl fetch failed", + command_dir, + )?, + // The one transport with no external binary: useful for a caller that has + // no `gh` and a token in the environment, and the only one that needs no + // subprocess at all. + Transport::Urllib => return via_http(url), + }; + let parsed: Value = serde_json::from_str(&body) + .map_err(|error| GitHubError(format!("GitHub returned unreadable JSON: {error}")))?; + match parsed { + Value::Array(items) => Ok(items), + _ => Err(GitHubError( + "GitHub did not return a PR list; the previous snapshot is retained".to_owned(), + )), + } +} + +/// Run one command to completion and return its stdout. +/// +/// The last line of stderr is what the operator needs; the whole thing is usually +/// a progress line plus a cause. +fn run( + program: &str, + arguments: &[&str], + timeout: Duration, + context: &str, + command_dir: Option<&std::path::Path>, +) -> Result { + let program_path = match command_dir { + Some(directory) => directory.join(program), + None => PathBuf::from(program), + }; + let mut child = Command::new(&program_path) + .args(arguments) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| GitHubError(format!("{context}: cannot run {program}: {error}")))?; + + // A hung fetch must not hang the pipeline. `gh` and `curl` both take their + // own timeouts, so this is the backstop. + let started = std::time::Instant::now(); + loop { + match child.try_wait() { + Ok(Some(_)) => break, + Ok(None) if started.elapsed() < timeout => { + std::thread::sleep(Duration::from_millis(50)); + } + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(GitHubError(format!( + "{context}: timed out after {timeout:?}" + ))); + } + Err(error) => { + return Err(GitHubError(format!("{context}: {error}"))); + } + } + } + let output = child + .wait_with_output() + .map_err(|error| GitHubError(format!("{context}: {error}")))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let detail = stderr + .lines() + .rev() + .find(|line| !line.trim().is_empty()) + .unwrap_or("no detail"); + return Err(GitHubError(format!( + "{context} ({detail}); the previous snapshot is retained" + ))); + } + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) +} + +/// Read a page over HTTP, for a caller with no `gh`. +/// +/// A token is used only when the environment carries one; without it this is the +/// unauthenticated path the module documents as limited. +fn via_http(url: &str) -> Result, GitHubError> { + let blocking = reqwest::blocking::Client::builder() + .timeout(Duration::from_secs(60)) + .user_agent("tranche") + .build() + .map_err(|error| GitHubError(format!("cannot build the HTTP client: {error}")))?; + let mut request = blocking + .get(url) + .header("Accept", "application/vnd.github+json"); + if let Ok(token) = std::env::var("GITHUB_TOKEN") + && !token.trim().is_empty() + { + request = request.bearer_auth(token.trim()); + } + let response = request + .send() + .map_err(|error| GitHubError(format!("network: {error}")))?; + let status = response.status().as_u16(); + if status != 200 { + return Err(GitHubError(format!("HTTP {status} from GitHub"))); + } + response + .json::() + .map_err(|error| GitHubError(format!("GitHub returned unreadable JSON: {error}"))) + .and_then(|parsed| match parsed { + Value::Array(items) => Ok(items), + _ => Err(GitHubError( + "GitHub did not return a PR list; the previous snapshot is retained".to_owned(), + )), + }) +} diff --git a/crates/tranche-core/src/jev.rs b/crates/tranche-core/src/jev.rs new file mode 100644 index 0000000..be902da --- /dev/null +++ b/crates/tranche-core/src/jev.rs @@ -0,0 +1,229 @@ +//! The Jev client: one question set per request, with the retry rules the +//! pipeline has always used. +//! +//! A 401 and a 422 are fatal and never retried — they are question-shape bugs, +//! not load, so retrying a bad request would only spend the budget slower. A 429, +//! a 529 and any 5xx are load, so they back off and try again. The key is read +//! from the environment first and the key file second, and it never appears in an +//! error message. + +use std::path::PathBuf; +use std::time::Duration; + +use serde::Serialize; +use serde_json::Value; + +/// Where the model answers. +pub const API_URL: &str = "https://api.typesafe.ai/v1/systemone"; + +/// Attempts per request, including the first. +const ATTEMPTS: u32 = 6; + +/// The first backoff, doubled per attempt and capped. +const BACKOFF_START: Duration = Duration::from_secs(2); +const BACKOFF_CAP: Duration = Duration::from_secs(60); + +/// Characters of a failing response body kept for the operator. +const BODY_CHARS: usize = 300; + +/// Per-request timeout. +const TIMEOUT: Duration = Duration::from_secs(90); + +#[derive(Debug)] +pub struct JevError(pub String); + +impl std::fmt::Display for JevError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.0) + } +} + +impl std::error::Error for JevError {} + +impl From for JevError { + fn from(message: String) -> Self { + Self(message) + } +} + +/// The key file used when the environment carries no key. +pub fn key_file() -> PathBuf { + let mut path = std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_default(); + path.push("Documents"); + path.push("jevapi.txt"); + path +} + +/// The API key, from the environment first and the key file second. +/// +/// The returned value is the credential. It is never logged, never included in +/// an error and never written anywhere. +pub fn read_key() -> Result { + if let Ok(key) = std::env::var("TYPESAFE_API_KEY") { + let key = key.trim().to_owned(); + if !key.is_empty() { + return Ok(key); + } + } + let path = key_file(); + match std::fs::read_to_string(&path) { + Ok(key) if !key.trim().is_empty() => Ok(key.trim().to_owned()), + _ => Err(JevError(format!( + "no API key: set TYPESAFE_API_KEY or create {}", + path.display() + ))), + } +} + +/// One request's outcome, before retry classification. +enum Attempt { + /// The model answered. + Answered(Value), + /// Worth trying again, with what went wrong for the final report. + Retry(String), + /// Never worth trying again. + Fatal(String), +} + +/// Ask the model one question set about one state. +/// +/// The payload is `{"state", "model", "questions"}` — the shape the service +/// accepts, assembled here rather than by the caller so no request can drift. +pub async fn ask(state: &Value, questions: &Value, model: &str) -> Result { + ask_with( + &endpoint(), + state, + questions, + model, + BACKOFF_START, + BACKOFF_CAP, + ) + .await +} + +/// The endpoint a request goes to. +/// +/// The service URL is fixed, with one deliberate escape hatch: a caller with its +/// own environment can point a run at a local stub. That is how the retry and +/// resume paths are tested without a paid model call, and it is a whole-process +/// setting rather than mutable shared state — a test that points at its own stub +/// does so in the child process it spawns, so it cannot reach a test beside it. +fn endpoint() -> String { + std::env::var("TRANCHE_DEV_API_URL").unwrap_or_else(|_| API_URL.to_owned()) +} + +/// Ask a specific endpoint with a specific backoff. +/// +/// The backoff is a parameter so a test can exercise the exhaustion path without +/// waiting the real sixty seconds; production always passes the documented ones. +pub async fn ask_with( + endpoint: &str, + state: &Value, + questions: &Value, + model: &str, + backoff_start: Duration, + backoff_cap: Duration, +) -> Result { + ask_at( + endpoint, + state, + questions, + model, + backoff_start, + backoff_cap, + ) + .await +} + +/// Ask the endpoint given, for tests and for a local stub. +pub async fn ask_at( + endpoint: &str, + state: &Value, + questions: &Value, + model: &str, + backoff_start: Duration, + backoff_cap: Duration, +) -> Result { + let key = read_key()?; + let payload = serde_json::json!({ + "state": state, + "model": model, + "questions": questions, + }); + let client = reqwest::Client::builder() + .timeout(TIMEOUT) + .build() + .map_err(|error| JevError(format!("cannot build the HTTP client: {error}")))?; + + let mut backoff = backoff_start; + let mut last = String::new(); + for attempt in 0..ATTEMPTS { + match post(&client, endpoint, &payload, &key).await { + Attempt::Answered(value) => return Ok(value), + Attempt::Fatal(message) => return Err(JevError(message)), + Attempt::Retry(message) => { + last = message; + if attempt + 1 == ATTEMPTS { + break; + } + // Jittered, so a fleet of retries does not arrive together. + let jitter = Duration::from_millis((now_millis() % 50) as u64); + tokio::time::sleep(backoff + jitter).await; + backoff = (backoff * 2).min(backoff_cap); + } + } + } + Err(JevError(format!("retries exhausted; last error: {last}"))) +} + +/// One POST, classified for retry. +async fn post( + client: &reqwest::Client, + endpoint: &str, + payload: &impl Serialize, + key: &str, +) -> Attempt { + let response = match client + .post(endpoint) + .header("Authorization", format!("Bearer {key}")) + .header("Content-Type", "application/json") + .json(payload) + .send() + .await + { + Ok(response) => response, + // A transport failure is load until proven otherwise. + Err(error) => return Attempt::Retry(format!("network: {error}")), + }; + let status = response.status().as_u16(); + if status == 200 { + return match response.json::().await { + Ok(value) => Attempt::Answered(value), + // A malformed body is not a shape the caller can fix by retrying. + Err(error) => Attempt::Fatal(format!("HTTP 200 with an unreadable body: {error}")), + }; + } + let body = response.text().await.unwrap_or_default(); + let excerpt: String = body.chars().take(BODY_CHARS).collect(); + match status { + 401 => Attempt::Fatal(format!( + "auth rejected (401); check the key. HTTP 401: {excerpt}" + )), + 422 => Attempt::Fatal(format!( + "request rejected (422) — question shape bug. HTTP 422: {excerpt}" + )), + 429 | 529 => Attempt::Retry(format!("HTTP {status}: {excerpt}")), + status if status >= 500 => Attempt::Retry(format!("HTTP {status}: {excerpt}")), + status => Attempt::Fatal(format!("HTTP {status}: {excerpt}")), + } +} + +/// Milliseconds since the epoch, for jitter only. +fn now_millis() -> u128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_millis()) + .unwrap_or(0) +} diff --git a/crates/tranche-core/src/lib.rs b/crates/tranche-core/src/lib.rs new file mode 100644 index 0000000..9a74667 --- /dev/null +++ b/crates/tranche-core/src/lib.rs @@ -0,0 +1,12 @@ +//! Tranche core. +//! +//! Every module here is transport-free: no stdout, no argv, no JSON-RPC. The +//! `tranche` and `tranche-mcp` binaries are thin adapters over this crate, so a +//! rule stated once cannot drift between the surfaces that must agree. + +pub mod domain; +pub mod evidence; +pub mod gh; +pub mod jev; +pub mod report; +pub mod util; diff --git a/crates/tranche-core/src/report/inputs.rs b/crates/tranche-core/src/report/inputs.rs new file mode 100644 index 0000000..72b4139 --- /dev/null +++ b/crates/tranche-core/src/report/inputs.rs @@ -0,0 +1,69 @@ +//! Bounded byte fingerprints of the report inputs. +//! +//! Absent files are **omitted**, not recorded as null: the loader skips a path that +//! does not exist, and a client reading this map must see the same set of keys. +//! Keys are the path strings exactly as the pipeline builds them, because the +//! MCP `digests()` tool quotes this map back. + +use std::path::{Path, PathBuf}; + +use super::paths::{Limits, ReportError, Root, refuse}; + +/// Sorted `page_*.json` membership shards, when there is no snapshot. +pub fn read_page_paths(pages: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(pages) else { + return Vec::new(); + }; + let mut paths: Vec = entries + .flatten() + .map(|entry| entry.path()) + .filter(|path| { + let name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or(""); + name.starts_with("page_") && name.ends_with(".json") + }) + .collect(); + paths.sort(); + paths +} +/// Bounded byte fingerprints include optional files and corpus membership. +/// +/// Absent files are **omitted**, not recorded as null: the loader skips a path that +/// does not exist, and a client reading this map must see the same set of keys. +/// Keys are the path strings exactly as the pipeline builds them, because the +/// MCP `digests()` tool quotes this map back. +pub fn input_digests(root: &Root, limits: &Limits) -> Result { + let paths = root.source_paths(); + let unique: Vec<&PathBuf> = { + let mut seen = std::collections::HashSet::new(); + paths + .iter() + .filter(|path| path.exists()) + .filter(|path| seen.insert(*path)) + .collect() + }; + if unique.len() > limits.max_input_files { + return Err(refuse("Input file count exceeds limit")); + } + let mut result = serde_json::Map::new(); + let mut total = 0u64; + for path in unique { + match crate::util::file_digest(path, limits.max_file_bytes) { + Ok(Some((digest, size))) => { + total += size; + if total > limits.max_total_bytes { + return Err(refuse("Input bytes exceed limit")); + } + result.insert( + path.to_string_lossy().into_owned(), + serde_json::json!(digest), + ); + } + Ok(None) => {} + Err(_) => return Err(refuse("Input bytes exceed limit")), + } + } + Ok(serde_json::Value::Object(result)) +} diff --git a/crates/tranche-core/src/report/loading.rs b/crates/tranche-core/src/report/loading.rs new file mode 100644 index 0000000..7cad534 --- /dev/null +++ b/crates/tranche-core/src/report/loading.rs @@ -0,0 +1,22 @@ +//! Binding a report to the inputs it was built from. + +use super::paths::{BoundReport, Limits, ReportError, Root}; +use super::reading::read_report; + +/// Read and validate the bound report, or refuse it. +/// +/// Refuses before returning anything a caller could mistake for a usable +/// observation: a stale, unbound, foreign or modified input never leaves here. +pub fn load(root: &Root, limits: &Limits) -> Result { + read_report(root, limits, false) +} +/// Read a report for inspection only, admitting legacy judgments without a +/// binding. The result is explicitly not freshness-checked, so it must never be +/// presented as current. +pub fn load_for_inspection( + root: &Root, + limits: &Limits, + allow_unbound: bool, +) -> Result { + read_report(root, limits, allow_unbound) +} diff --git a/crates/tranche-core/src/report/mod.rs b/crates/tranche-core/src/report/mod.rs new file mode 100644 index 0000000..68a1691 --- /dev/null +++ b/crates/tranche-core/src/report/mod.rs @@ -0,0 +1,15 @@ +//! The report root, its derived paths, and the loading that binds one. +//! +//! One module decides where everything lives, so a relocated checkout (tests, +//! `--root`, a copied report directory) cannot end up with two modules +//! disagreeing about which file they are reading. + +pub mod inputs; +pub mod loading; +pub mod paths; +pub mod reading; + +pub use inputs::{input_digests, read_page_paths}; +pub use loading::{load, load_for_inspection}; +pub use paths::{BoundReport, Limits, MODEL, REPOSITORY, ReportError, Root}; +pub use reading::read_report; diff --git a/crates/tranche-core/src/report/paths.rs b/crates/tranche-core/src/report/paths.rs new file mode 100644 index 0000000..d26f921 --- /dev/null +++ b/crates/tranche-core/src/report/paths.rs @@ -0,0 +1,163 @@ +//! Where everything lives, and the values a report is bounded by. +//! +//! One place decides the path vocabulary, so a relocated checkout (tests, +//! `--root`, a copied report directory) cannot end up with two modules +//! disagreeing about which file they are reading. + +use std::path::{Path, PathBuf}; + +use super::inputs::read_page_paths; + +/// The repository this checkout reviews. A report from any other repository is +/// foreign, not merely different. +pub const REPOSITORY: &str = "omacom/omarchy"; +/// The model alias recorded in bindings and provenance. +pub const MODEL: &str = "jev-latest"; +/// Byte and file-count bounds for fingerprinting the bound inputs. +#[derive(Debug, Clone, Copy)] +pub struct Limits { + pub max_file_bytes: u64, + pub max_total_bytes: u64, + pub max_input_files: usize, +} +impl Default for Limits { + fn default() -> Self { + Self { + max_file_bytes: 128 * 1024 * 1024, + max_total_bytes: 256 * 1024 * 1024, + max_input_files: 512, + } + } +} +/// The local observation cannot safely be used. +#[derive(Debug)] +pub struct ReportError(pub String); +impl std::fmt::Display for ReportError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for ReportError {} +pub(crate) fn refuse(message: &str) -> ReportError { + ReportError(message.to_owned()) +} +/// The validated report projection: inputs, derived records and identity. +/// +/// Obtained only from [`load`], which applies every gate. Nothing else may +/// construct one, so a consumer cannot read a stale, foreign or modified report +/// by forgetting to check — the type is the check. +#[derive(Debug)] +pub struct BoundReport { + pub summary: serde_json::Value, + pub clusters: serde_json::Value, + pub dupes: serde_json::Value, + pub batches: Option, + pub parked: Option, + pub prs: crate::domain::pr::Prs, + pub judgments: std::collections::HashMap, + pub pairs: Vec, + /// Every stored judgment, current or not, for provenance questions. + pub latest_judgments: std::collections::HashMap, + /// The digests a reader quotes to prove which report it was served from. + pub identity: serde_json::Value, +} +/// The checkout holding the captured corpus and the derived reports. +#[derive(Clone, Debug)] +pub struct Root { + path: PathBuf, +} +impl Root { + pub fn new(path: impl Into) -> Self { + Self { path: path.into() } + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Captured PR membership pages. + pub fn pages_dir(&self) -> PathBuf { + self.path.join("data").join("pages") + } + + /// Every derived report and cache file. + pub fn out_dir(&self) -> PathBuf { + self.path.join("out") + } + + pub fn judgments_path(&self) -> PathBuf { + self.out_dir().join("judgments.jsonl") + } + + pub fn pairs_path(&self) -> PathBuf { + self.out_dir().join("pair_verdicts.jsonl") + } + + pub fn summary_path(&self) -> PathBuf { + self.out_dir().join("summary.json") + } + + pub fn clusters_path(&self) -> PathBuf { + self.out_dir().join("clusters.json") + } + + pub fn dupes_path(&self) -> PathBuf { + self.out_dir().join("dupes.json") + } + + pub fn batches_path(&self) -> PathBuf { + self.out_dir().join("batches.json") + } + + pub fn parked_path(&self) -> PathBuf { + self.out_dir().join("parked.json") + } + + pub fn tranches_path(&self) -> PathBuf { + self.out_dir().join("tranches.md") + } + + /// Captured evidence: manifests, content-addressed bodies and writer locks. + pub fn evidence_dir(&self) -> PathBuf { + self.out_dir().join("evidence") + } + + pub fn docs_dir(&self) -> PathBuf { + self.path.join("docs") + } + + pub fn template_path(&self) -> PathBuf { + self.path.join("page").join("template.html") + } + + /// The single-file membership snapshot, when the corpus was captured whole. + pub fn snapshot_path(&self) -> PathBuf { + self.pages_dir().join("snapshot.json") + } + + /// The ordered bound inputs, matching `report_loader.source_paths()`. + /// + /// The snapshot and the page shards are alternatives, not a pair: when the + /// corpus was captured whole, the shards are stale leftovers and are not + /// part of the observation. Fingerprinting both would report a changed input + /// set that the pipeline never reads. + pub fn source_paths(&self) -> Vec { + let snapshot = self.snapshot_path(); + let mut paths = vec![snapshot.clone()]; + if !snapshot.exists() { + paths.extend(read_page_paths(&self.pages_dir())); + } + paths.push(self.judgments_path()); + paths.push(self.pairs_path()); + for name in [ + "summary.json", + "clusters.json", + "dupes.json", + "batches.json", + "parked.json", + ] { + paths.push(self.out_dir().join(name)); + } + paths + } +} diff --git a/crates/tranche-core/src/report/reading.rs b/crates/tranche-core/src/report/reading.rs new file mode 100644 index 0000000..0892047 --- /dev/null +++ b/crates/tranche-core/src/report/reading.rs @@ -0,0 +1,210 @@ +//! Reading a published report and refusing one that does not verify. +//! +//! A report is an observation, not a file: it is accepted only when its recorded +//! binding still matches the judgments and pairs behind it. + +use std::path::Path; + +use super::paths::{BoundReport, Limits, MODEL, REPOSITORY, ReportError, Root, refuse}; + +pub fn read_report( + root: &Root, + _limits: &Limits, + allow_unbound: bool, +) -> Result { + use crate::domain::{cluster::cluster, dupe::current_pairs, judge, pr::load_prs}; + + let summary = read_json(&root.summary_path())?; + let clusters = read_json(&root.clusters_path())?; + let dupes = read_json(&root.dupes_path())?; + let prs = load_prs(root, REPOSITORY).map_err(|error| Refuse::from(error.0))?; + + // A malformed record anywhere in the log makes the whole observation unsafe, + // even though only the last record per PR is used. + if root.judgments_path().exists() { + check_records_are_objects(&root.judgments_path())?; + } + let judgments = judge::current_judgments(root, &prs, REPOSITORY, MODEL, allow_unbound) + .map_err(Refuse::from)?; + let pairs = current_pairs(root, &prs, &judgments, REPOSITORY, MODEL, allow_unbound) + .map_err(Refuse::from)?; + if root.pairs_path().exists() { + check_records_are_objects(&root.pairs_path())?; + } + + // Only the producer's current projection, which the report must bind. + let expected_clusters = crate::util::digest(&clusters); + let expected_dupes = crate::util::digest(&dupes); + let rebuilt = cluster(&prs, &judgments, &pairs, REPOSITORY, MODEL, allow_unbound); + let binding_matches = summary + .get("report_binding") + .and_then(serde_json::Value::as_str) + == Some(rebuilt.summary["report_binding"].as_str().unwrap_or("")); + let digests_match = summary.get("output_digests").is_some_and(|digests| { + digests + .get("clusters.json") + .and_then(serde_json::Value::as_str) + == Some(&expected_clusters) + && digests + .get("dupes.json") + .and_then(serde_json::Value::as_str) + == Some(&expected_dupes) + }); + if summary + .get("format_version") + .and_then(serde_json::Value::as_u64) + != Some(2) + || summary.get("repo").and_then(serde_json::Value::as_str) != Some(REPOSITORY) + || summary + .get("allow_unbound") + .and_then(serde_json::Value::as_bool) + != Some(false) + || !binding_matches + || !digests_match + { + return Err(refuse( + "Reports are stale, unbound, foreign or modified; rerun cluster", + )); + } + + let batches = read_optional(root, &root.batches_path())?; + if let Some(batches) = &batches { + let expected = crate::domain::batch::merge_batches( + &dupes, + &judgments, + &prs, + &expected_dupes, + REPOSITORY, + ) + .map_err(Refuse::from)?; + if crate::util::digest(batches) != crate::util::digest(&expected) { + return Err(refuse("batches.json is stale or modified; rerun batches")); + } + } + + // The park record is part of the same observation as the batches it gated. + let parked = read_optional(root, &root.parked_path())?; + if let Some(parked) = &parked { + let parks = crate::domain::batch::park_state(&dupes, &judgments, &prs); + let expected = crate::domain::batch::parked_payload( + &parks, + &prs, + &judgments, + &expected_dupes, + REPOSITORY, + ); + if crate::util::digest(parked) != crate::util::digest(&expected) { + return Err(refuse("parked.json is stale or modified; rerun batches")); + } + } + if batches + .as_ref() + .and_then(|batches| batches.get("parked_prs")) + .and_then(serde_json::Value::as_u64) + .is_some_and(|parked| parked > 0) + && parked.is_none() + { + return Err(refuse( + "batches.json parked PRs but parked.json is missing; rerun batches", + )); + } + + let mut identity = serde_json::Map::new(); + identity.insert( + "report_binding".to_owned(), + summary["report_binding"].clone(), + ); + identity.insert( + "batches.json".to_owned(), + batches + .as_ref() + .map(crate::util::digest) + .map(serde_json::Value::String) + .unwrap_or(serde_json::Value::Null), + ); + identity.insert( + "parked.json".to_owned(), + parked + .as_ref() + .map(crate::util::digest) + .map(serde_json::Value::String) + .unwrap_or(serde_json::Value::Null), + ); + if let Some(digests) = summary + .get("output_digests") + .and_then(serde_json::Value::as_object) + { + for (name, value) in digests { + identity.insert(name.clone(), value.clone()); + } + } + + let latest_judgments = judge::load_done(root).map_err(Refuse::from)?; + + Ok(BoundReport { + summary, + clusters, + dupes, + batches, + parked, + prs, + judgments, + pairs, + latest_judgments, + identity: serde_json::Value::Object(identity), + }) +} +/// A refusal carrying a message, converted from a lower-level error's text. +struct Refuse(String); +impl From for Refuse { + fn from(message: String) -> Self { + Self(message) + } +} +impl From for ReportError { + fn from(value: Refuse) -> Self { + // Lower-level failures are never reported as the specific gate they are + // not; an unreadable input is the same class as an unusable report. + let message = if value.0.contains("Invalid or missing") + || value.0.contains("must contain") + || value.0.contains("checksum") + { + "Invalid or missing bound reports; rerun cluster and batches".to_owned() + } else { + value.0 + }; + ReportError(message) + } +} +fn read_json(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|_| refuse("Invalid or missing bound reports; rerun cluster and batches"))?; + serde_json::from_str(&text) + .map_err(|_| refuse("Invalid or missing bound reports; rerun cluster and batches")) +} +fn read_optional(root: &Root, path: &Path) -> Result, ReportError> { + let _ = root; + if !path.exists() { + return Ok(None); + } + read_json(path).map(Some) +} +/// Every non-empty line must be a JSON object, or the log is not trustworthy. +fn check_records_are_objects(path: &Path) -> Result<(), ReportError> { + let text = std::fs::read_to_string(path) + .map_err(|_| refuse("Invalid or missing bound reports; rerun cluster and batches"))?; + for line in text.lines() { + if line.trim().is_empty() { + continue; + } + match serde_json::from_str::(line) { + Ok(serde_json::Value::Object(_)) => {} + _ => { + return Err(refuse( + "Invalid or missing bound reports; rerun cluster and batches", + )); + } + } + } + Ok(()) +} diff --git a/crates/tranche-core/src/util.rs b/crates/tranche-core/src/util.rs new file mode 100644 index 0000000..059c7a5 --- /dev/null +++ b/crates/tranche-core/src/util.rs @@ -0,0 +1,242 @@ +//! Shared primitives used across the core. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest as _, Sha256}; +use std::io::{self, Write}; +use std::path::Path; + +/// SHA-256 over the canonical JSON projection of a value. +/// +/// Compatibility is load-bearing: these digests are report bindings and cache +/// keys. `tranche.py:63` hashes `sort_keys=True, separators=(",", ":")`, and the +/// `out/` files on disk were written with it. A different encoding makes every +/// stored judgment unreusable and every existing report foreign. +pub fn digest(value: &serde_json::Value) -> String { + sha256_hex(canonical_json(value).as_bytes()) +} + +/// As [`digest`], but ordering integer-like keys numerically. +/// +/// Keys are compared as *objects*, and which order that +/// produces depends on the type the caller used. The report binding is keyed by +/// PR number as an **integer** (`dict[int, dict]`), so `3507` sorts before +/// `10002`; the capture generation's `revision` map is keyed by the **string** +/// `str(number)`, so it sorts lexicographically. JSON has only string keys, so +/// the two cases are indistinguishable from the value alone - the caller has to +/// say which one it is. +pub fn digest_numeric_keys(value: &serde_json::Value) -> String { + sha256_hex(canonical_json_with(value, KeyOrder::Numeric).as_bytes()) +} + +/// The key ordering a canonical encoding uses. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum KeyOrder { + /// Compare keys as written. This is the ordering for string keys, and + /// the default because most maps in the format are string-keyed. + Lexicographic, + /// Compare keys that are all integers numerically. Used where the map is keyed by + /// map by an integer. + Numeric, +} + +/// The exact JSON encoding `tranche.digest()` hashes: sorted keys, no +/// whitespace, non-ASCII preserved. +pub fn canonical_json(value: &serde_json::Value) -> String { + canonical_json_with(value, KeyOrder::Lexicographic) +} + +/// The canonical encoding under a chosen key order. +pub fn canonical_json_with(value: &serde_json::Value, order: KeyOrder) -> String { + let mut out = String::new(); + write_canonical(value, &mut out, order); + out +} + +/// The key comparison the report format produces for one map. +fn key_order(a: &str, b: &str, order: KeyOrder) -> std::cmp::Ordering { + match order { + KeyOrder::Lexicographic => a.cmp(b), + KeyOrder::Numeric => match (a.parse::(), b.parse::()) { + (Ok(left), Ok(right)) => left.cmp(&right), + _ => a.cmp(b), + }, + } +} + +fn write_canonical(value: &serde_json::Value, out: &mut String, order: KeyOrder) { + match value { + serde_json::Value::Null => out.push_str("null"), + serde_json::Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }), + serde_json::Value::Number(number) => out.push_str(&number.to_string()), + serde_json::Value::String(text) => { + out.push_str(&serde_json::to_string(text).expect("strings are serializable")) + } + serde_json::Value::Array(items) => { + out.push('['); + for (index, item) in items.iter().enumerate() { + if index > 0 { + out.push(','); + } + write_canonical(item, out, order); + } + out.push(']'); + } + serde_json::Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort_by(|a, b| key_order(a, b, order)); + out.push('{'); + for (index, key) in keys.into_iter().enumerate() { + if index > 0 { + out.push(','); + } + out.push_str(&serde_json::to_string(key).expect("keys are strings")); + out.push(':'); + write_canonical(&map[key], out, order); + } + out.push('}'); + } + } +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + let mut hasher = Sha256::new(); + hasher.update(bytes); + format!("{:x}", hasher.finalize()) +} + +/// SHA-256 of a file's bytes, or `None` when it is absent. +pub fn file_digest(path: &Path, limit: u64) -> io::Result> { + let mut file = match std::fs::File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + }; + let mut buffer = Vec::new(); + io::Read::read_to_end(&mut file, &mut buffer)?; + if buffer.len() as u64 > limit { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "input file exceeds the byte limit", + )); + } + let size = buffer.len() as u64; + Ok(Some((sha256_hex(&buffer), size))) +} + +/// Write a file atomically: temporary sibling, fsync, rename. +/// +/// A partial report must never be observable, so everything that publishes +/// state under `out/` goes through here. +pub fn atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> { + let parent = path.parent().unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(parent)?; + let mut file = tempfile::NamedTempFile::new_in(parent)?; + file.write_all(bytes)?; + file.as_file().sync_all()?; + file.persist(path).map_err(|error| error.error)?; + Ok(()) +} + +/// Serialize a value and publish it atomically. +/// +/// The report's writer puts a space +/// after each comma and colon. `serde_json::to_vec` writes compact JSON, so a +/// ported writer would silently rewrite every artifact in a different style — +/// the digests still match, because they sort and compact explicitly, but the +/// files a reader diffs would all churn. +pub fn atomic_json(path: &Path, value: &T) -> io::Result<()> { + publish_json(path, value, false) +} + +/// Serialize with the report's one-space indent, for stdout. +pub fn indented_json(value: &T) -> Result { + let encoded = spaced_json(value, true)?; + Ok(encoded) +} + +fn publish_json(path: &Path, value: &T, indent: bool) -> io::Result<()> { + let encoded = spaced_json(value, indent).map_err(io::Error::other)?; + atomic_write(path, encoded.as_bytes()) +} + +/// JSON with the report's separators, optionally at one-space indent. +fn spaced_json(value: &T, indent: bool) -> Result { + let compact = serde_json::to_string(value)?; + Ok(space_separators(&compact, indent)) +} + +/// Insert the report's separator spacing outside string literals. +/// +/// A byte-level pass rather than a re-serialization: the compact form is already +/// the right value in the right order, and walking it keeps number formatting +/// exactly as `serde_json` wrote it. +fn space_separators(compact: &str, indent: bool) -> String { + let mut out = String::with_capacity(compact.len() + compact.len() / 8); + let mut in_string = false; + let mut escaped = false; + let mut depth = 0usize; + for character in compact.chars() { + if in_string { + out.push(character); + if escaped { + escaped = false; + } else if character == '\\' { + escaped = true; + } else if character == '"' { + in_string = false; + } + continue; + } + match character { + '"' => { + in_string = true; + out.push(character); + } + ',' => { + out.push(','); + out.push(' '); + if indent { + out.push('\n'); + out.extend(std::iter::repeat_n(' ', depth)); + } + } + ':' => { + out.push(':'); + out.push(' '); + } + '{' | '[' => { + depth += 1; + out.push(character); + if indent { + out.push('\n'); + out.extend(std::iter::repeat_n(' ', depth)); + } + } + '}' | ']' => { + depth = depth.saturating_sub(1); + if indent { + out.push('\n'); + out.extend(std::iter::repeat_n(' ', depth)); + } + out.push(character); + } + character => out.push(character), + } + } + out +} + +/// Parse a JSON Lines file into records, refusing malformed lines. +pub fn parse_jsonl Deserialize<'de>>(text: &str) -> Result, String> { + let mut records = Vec::new(); + for (index, line) in text.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + records.push( + serde_json::from_str(line) + .map_err(|error| format!("malformed record on line {}: {error}", index + 1))?, + ); + } + Ok(records) +} diff --git a/crates/tranche-core/tests/binding_stored_judgments.rs b/crates/tranche-core/tests/binding_stored_judgments.rs new file mode 100644 index 0000000..d1bd213 --- /dev/null +++ b/crates/tranche-core/tests/binding_stored_judgments.rs @@ -0,0 +1,156 @@ +//! Judgment and pair bindings, pinned against the real corpus. +//! +//! These are cache keys. If a binding differs by one byte, resume stops matching +//! and the whole backlog is re-judged — thousands of paid model calls. The pins +//! are read from the committed corpus, so this is the check that a change did not +//! silently invalidate the cache. + +use tranche_core::domain::dupe::{current_verdicts, pair_binding}; +use tranche_core::domain::judge::{ + current_judgments, judgment_binding, load_done, reusable_judgment, +}; +use tranche_core::domain::pr::load_prs; +use tranche_core::report::{REPOSITORY, Root}; + +const MODEL: &str = "jev-latest"; + +fn corpus() -> Root { + Root::new( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(std::path::Path::parent) + .expect("nested in the repository"), + ) +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn judgment_bindings_match_the_stored_corpus() { + let root = corpus(); + let prs = load_prs(&root, REPOSITORY).expect("the capture loads"); + let expected = [ + ( + 3507, + "1be30deeecee233121b52ba1d7b7569d07f4431248891ef76bdcefc786aa53ca", + ), + ( + 4593, + "78e61a00c5582274c0971d0f137fcace684f5497b943dcc6b87106b885fbd990", + ), + ( + 10660, + "d5064af500a7c994a777bc66a2db92700f0374f9400a17d4e9e2413519a37fa4", + ), + ( + 13971, + "b1b01c132675eedce5b14a82e383d3814b973018e7d18d3fbdc7338e11b665bb", + ), + ]; + for (number, binding) in expected { + let pr = prs.get(number).unwrap_or_else(|| panic!("PR {number}")); + assert_eq!( + judgment_binding(pr, REPOSITORY, MODEL), + binding, + "judgment binding for {number}" + ); + } +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn every_stored_judgment_is_still_current() { + let root = corpus(); + let prs = load_prs(&root, REPOSITORY).expect("the capture loads"); + let stored = load_done(&root).expect("the log reads"); + assert_eq!(stored.len(), 2903, "records in the append-only log"); + + // The whole corpus is judged under the current policy; a binding drift shows + // up here as a collapse to zero, which is exactly the failure that would + // re-bill the backlog. + let current = current_judgments(&root, &prs, REPOSITORY, MODEL, false).expect("judgments"); + assert_eq!( + current.len(), + 2817, + "every captured PR still has its judgment" + ); + + let reusable = current.values().filter(|j| reusable_judgment(j)).count(); + assert_eq!(reusable, 2817, "every current judgment is reusable"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn pair_bindings_match_the_stored_corpus() { + let root = corpus(); + let prs = load_prs(&root, REPOSITORY).expect("the capture loads"); + let verdicts = current_verdicts(&root, &prs).expect("the verdict log reads"); + assert_eq!(verdicts.len(), 909, "distinct pairs with a stored verdict"); + + let expected = [ + ( + (4750, 7168), + "8a355122758ab93e09eded7e9b18c27f9fc2d9658003bdcb7ccf454d2c749904", + ), + ( + (4829, 7882), + "ee5f92ae6c87f308b076d9b78e13310471c6ccbcc0e5e733820ca562ebce493b", + ), + ( + (4928, 7700), + "3344cf1c44285120c7bab3834f1e443f321784bc28dfcec28d53bc96730cc040", + ), + ]; + for ((a, b), binding) in expected { + let pr_a = prs.get(a).unwrap_or_else(|| panic!("PR {a}")); + let pr_b = prs.get(b).unwrap_or_else(|| panic!("PR {b}")); + assert_eq!( + pair_binding(pr_a, pr_b, REPOSITORY, MODEL), + binding, + "pair binding for ({a}, {b})" + ); + // The binding orders the pair, so a verdict recorded the other way round + // still verifies. + assert_eq!(pair_binding(pr_b, pr_a, REPOSITORY, MODEL), binding); + } +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_moved_policy_would_invalidate_every_judgment() { + // The binding digests the question policy, which is why the policy is data + // here rather than scattered through the code. + let root = corpus(); + let prs = load_prs(&root, REPOSITORY).expect("the capture loads"); + let pr = prs.get(13971).expect("PR 13971"); + let baseline = judgment_binding(pr, REPOSITORY, MODEL); + assert_ne!( + judgment_binding(pr, REPOSITORY, "some-other-model"), + baseline + ); + assert_ne!(judgment_binding(pr, "other/repo", MODEL), baseline); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn normalization_keeps_unknowns_unknown() { + let root = corpus(); + let stored = load_done(&root).expect("the log reads"); + let record = stored.get(&13971).expect("PR 13971 was judged"); + let answers = record + .get("answers") + .and_then(|a| a.as_object()) + .expect("answers"); + // Seven questions, each normalized to exactly one answer field. + assert_eq!(answers.len(), 7, "one answer per question"); + for (name, answer) in answers { + let answer = answer + .as_object() + .unwrap_or_else(|| panic!("{name} answer")); + assert!( + answer.contains_key("choice") + || answer.contains_key("score") + || answer.contains_key("noul"), + "{name} carries its field" + ); + } +} diff --git a/crates/tranche-core/tests/building_the_export_packet.rs b/crates/tranche-core/tests/building_the_export_packet.rs new file mode 100644 index 0000000..132c69c --- /dev/null +++ b/crates/tranche-core/tests/building_the_export_packet.rs @@ -0,0 +1,243 @@ +//! The export packet, from a real capture manifest. +//! +//! The properties here are the ones a reader depends on when the packet is the +//! only thing they have: the digest recomputes from the packet's own bytes, a +//! citation resolves against the carried body, and the projection carries what the +//! contract says and nothing it does not. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; +use tranche_core::evidence::packet; +use tranche_core::report::Root; + +/// A checkout carrying the real capture, copied so a build never touches it. +fn root() -> Option { + let source = Path::new("/srv/lab/hack/omarchy-pr-jev-triage").join("out/evidence"); + let capture = source.join("108dbe75ccac6ea366b543791c8f168e/manifest.json"); + if !capture.exists() { + return None; + } + let root = tempfile::tempdir().expect("a root"); + copy(&source, &root.path().join("out/evidence")); + Some(root) +} + +fn copy(source: &Path, destination: &Path) { + std::fs::create_dir_all(destination).expect("a directory"); + for entry in std::fs::read_dir(source).expect("the capture reads") { + let entry = entry.expect("an entry"); + let target = destination.join(entry.file_name()); + if entry.file_type().expect("a type").is_dir() { + copy(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).expect("a file"); + } + } +} + +fn manifest(root: &Path) -> Value { + let path = root.join("out/evidence/108dbe75ccac6ea366b543791c8f168e/manifest.json"); + serde_json::from_str(&std::fs::read_to_string(path).expect("the manifest reads")) + .expect("the manifest parses") +} + +fn built(root: &Path) -> Value { + let report = Root::new(root.to_path_buf()); + packet::build(&report, &manifest(root)).expect("a packet is built") +} + +#[test] +fn the_packet_digest_covers_the_packet_but_not_itself() { + let Some(root) = root() else { + eprintln!("no local capture; nothing to build from"); + return; + }; + let packet = built(root.path()); + let recorded = packet["packet_digest"].as_str().expect("a digest"); + // Recompute from the packet with its own digest removed. + let mut without = packet.clone(); + without + .as_object_mut() + .expect("an object") + .remove("packet_digest"); + assert_eq!( + tranche_core::util::digest(&without), + recorded, + "the recorded digest recomputes from the packet" + ); +} + +#[test] +fn a_citation_resolves_against_the_body_the_packet_carries() { + // This is the operation a reader must be able to perform offline: no state + // store, no network, no second application. + let Some(root) = root() else { + return; + }; + let packet = built(root.path()); + let bodies = packet["bodies"].as_object().expect("carried bodies"); + let citations = packet["citations"].as_array().expect("citations"); + assert!(!citations.is_empty(), "the capture recorded citations"); + + for citation in citations { + let sha = citation["source_sha256"].as_str().expect("a source digest"); + let body = bodies.get(sha).expect("the cited body is carried"); + let decoded = decode(body["base64"].as_str().expect("base64 bodies")); + assert_eq!( + decoded.len() as u64, + body["bytes"].as_u64().expect("a byte count"), + "the carried length matches" + ); + assert_eq!( + tranche_core::util::sha256_hex(&decoded), + sha, + "the carried bytes match the digest they are filed under" + ); + let start = citation["start_byte"].as_u64().expect("a start") as usize; + let end = citation["end_byte"].as_u64().expect("an end") as usize; + assert_eq!( + tranche_core::util::sha256_hex(&decoded[start..end]), + citation["excerpt_sha256"] + .as_str() + .expect("an excerpt digest"), + "the excerpt recomputes" + ); + } +} + +#[test] +fn the_projection_carries_the_contract_and_nothing_else() { + let Some(root) = root() else { + return; + }; + let packet = built(root.path()); + for key in [ + "format", + "profile", + "capture_id", + "generation", + "selection", + "membership_digest", + "complete", + "capture", + "components", + "sources", + "bodies", + "citations", + "notes", + "packet_digest", + ] { + assert!(packet.get(key).is_some(), "carries {key}"); + } + assert_eq!(packet["format"], "tranche.evidence-packet/v1"); + assert_eq!(packet["profile"], "pr-review/v1"); + + // The manifest's own bookkeeping does not travel: a reader verifying evidence + // has no use for it. A member's `updated_at` is a selection field and stays. + let text = serde_json::to_string(&packet).expect("serializes"); + for absent in ["bytes_stored", "code_observation", "created_at"] { + assert!( + !text.contains(absent), + "the packet does not carry the manifest's {absent}" + ); + } + let top = packet.as_object().expect("an object"); + assert!( + !top.contains_key("updated_at"), + "the manifest's last-write time is not a packet field" + ); + // And a source carries no inline body, which is the superseded layout. + for source in packet["sources"].as_array().expect("sources") { + assert!( + source.get("body_base64").is_none(), + "sources reference bodies rather than inline them" + ); + } + // The accounting keys are exactly the documented set. + let capture = packet["capture"].as_object().expect("accounting"); + assert_eq!(capture.len(), 8, "eight accounting keys"); + for key in [ + "observed_at", + "request_limit", + "requests_used", + "reserved", + "failures", + "retries", + "identity_checks", + "stop_reason", + ] { + assert!(capture.contains_key(key), "accounting carries {key}"); + } +} + +#[test] +fn identical_bodies_are_carried_once() { + let Some(root) = root() else { + return; + }; + let packet = built(root.path()); + let sources = packet["sources"].as_array().expect("sources"); + let bodies = packet["bodies"].as_object().expect("bodies"); + let distinct: std::collections::HashSet<&str> = sources + .iter() + .filter_map(|source| source["body_sha256"].as_str()) + .collect(); + assert_eq!( + bodies.len(), + distinct.len(), + "one body per distinct digest, however many sources reference it" + ); +} + +#[test] +fn the_export_bound_is_checked_on_the_serialized_bytes() { + let Some(root) = root() else { + return; + }; + let report = Root::new(root.path().to_path_buf()); + let manifest = manifest(root.path()); + let (packet, bytes) = + packet::bytes(&report, &manifest, packet::DEFAULT_EXPORT_BYTES).expect("under the bound"); + assert_eq!( + bytes.len(), + serde_json::to_string(&packet).expect("serializes").len(), + "the bytes are the packet" + ); + assert!(!bytes.ends_with(b"\n"), "serialization adds no newline"); + + // A bound the packet cannot fit refuses rather than truncating: a truncated + // packet would resolve citations to the wrong bytes. + assert!(packet::bytes(&report, &manifest, 1_024).is_err()); +} + +/// Decode standard base64, asserting the padding as it goes. +fn decode(text: &str) -> Vec { + let mut out = Vec::with_capacity(text.len() / 4 * 3); + let mut buffer = 0u32; + let mut bits = 0u32; + for character in text.chars() { + if character == '=' { + break; + } + let value = match character { + 'A'..='Z' => character as u32 - 'A' as u32, + 'a'..='z' => character as u32 - 'a' as u32 + 26, + '0'..='9' => character as u32 - '0' as u32 + 52, + '+' => 62, + '/' => 63, + other => panic!("not base64: {other:?}"), + }; + buffer = (buffer << 6) | value; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((buffer >> bits) as u8); + } + } + out +} + +/// The unused-import guard: `PathBuf` is used in the helper signatures above. +#[allow(dead_code)] +fn _path_type(_: PathBuf) {} diff --git a/crates/tranche-core/tests/canonical_digests.rs b/crates/tranche-core/tests/canonical_digests.rs new file mode 100644 index 0000000..aae67b5 --- /dev/null +++ b/crates/tranche-core/tests/canonical_digests.rs @@ -0,0 +1,75 @@ +//! The canonical encoding and the digests over it. +//! +//! Every value here is pinned from the committed corpus. These are not +//! round-trip tests: they fix the exact bytes, because a mismatch silently +//! invalidates every stored judgment and makes every report on disk foreign. + +use serde_json::json; +use tranche_core::util::{KeyOrder, canonical_json, canonical_json_with, digest}; + +#[test] +fn canonical_encoding_matches_spaced_json_dumps() { + // sort_keys=True, separators=(",", ":"), ensure_ascii=False + assert_eq!(canonical_json(&json!({})), "{}"); + assert_eq!(canonical_json(&json!({"b": 1, "a": 2})), r#"{"a":2,"b":1}"#); + assert_eq!(canonical_json(&json!([1, 2, 3])), "[1,2,3]"); + assert_eq!(canonical_json(&json!(null)), "null"); + assert_eq!(canonical_json(&json!(true)), "true"); + assert_eq!(canonical_json(&json!("hi")), r#""hi""#); + // ensure_ascii=False keeps non-ASCII literal. + assert_eq!(canonical_json(&json!("café")), "\"café\""); + // Nested objects sort at every level, independent of insertion order. + assert_eq!( + canonical_json(&json!({"z": {"b": 1, "a": [{"d": 1, "c": 2}]}})), + r#"{"z":{"a":[{"c":2,"d":1}],"b":1}}"# + ); + // Floats keep the shortest round-tripping form for the values the corpus stores. + assert_eq!(canonical_json(&json!({"score": 1.1})), r#"{"score":1.1}"#); + assert_eq!(canonical_json(&json!({"p": 0.0})), r#"{"p":0.0}"#); + assert_eq!(canonical_json(&json!({"p": 0.95})), r#"{"p":0.95}"#); +} + +#[test] +fn digest_is_sha256_of_the_canonical_encoding() { + // sha256('{}'), sha256('{"a":2,"b":1}') + assert_eq!( + digest(&json!({})), + "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a" + ); + assert_eq!( + digest(&json!({"b": 1, "a": 2})), + "d3626ac30a87e6f7a6428233b3c68299976865fa5508e4267c5415c76af7a772" + ); + // Key order in the input must not change the digest. + assert_eq!( + digest(&json!({"a": 1, "b": 2})), + digest(&json!({"b": 2, "a": 1})) + ); +} + +#[test] +fn key_order_is_chosen_by_the_caller_because_key_types_differ() { + // Keys are compared as *objects*, so the order depends on + // the type the caller used. The report binding is keyed by PR number as an + // integer, so `3507` precedes `10002`. JSON has only string keys, so the two + // cases are indistinguishable from the value alone and the caller must say + // which one applies — getting it wrong silently changes a digest. + let value = json!({"10002": 1, "3507": 2, "999": 3}); + assert_eq!( + canonical_json_with(&value, KeyOrder::Numeric), + r#"{"999":3,"3507":2,"10002":1}"# + ); + // The capture generation's `revision` map is keyed by `str(number)`, so it + // sorts lexicographically; the default is therefore the string order. + assert_eq!(canonical_json(&value), r#"{"10002":1,"3507":2,"999":3}"#); + // Non-integer keys are unaffected either way, which is why the string-keyed + // maps in the format do not care. + assert_eq!( + canonical_json(&json!({"b": 1, "a": 2, "C": 3})), + r#"{"C":3,"a":2,"b":1}"# + ); + assert_eq!( + canonical_json_with(&json!({"b": 1, "a": 2, "C": 3}), KeyOrder::Numeric), + r#"{"C":3,"a":2,"b":1}"# + ); +} diff --git a/crates/tranche-core/tests/captured_membership.rs b/crates/tranche-core/tests/captured_membership.rs new file mode 100644 index 0000000..fb3f5f2 --- /dev/null +++ b/crates/tranche-core/tests/captured_membership.rs @@ -0,0 +1,165 @@ +//! Membership projection and digest compatibility, pinned against the real corpus. +//! +//! These are cache keys and report bindings, so equality is the contract: a +//! different projection silently invalidates every stored judgment and makes +//! every report on disk foreign. + +use serde_json::{Value, json}; +use tranche_core::domain::pr::{Prs, load_prs, pr_evidence_digest, reference_numbers}; +use tranche_core::report::Root; + +const REPOSITORY: &str = "omacom/omarchy"; + +fn corpus() -> Root { + Root::new(env!("CARGO_MANIFEST_DIR")) + .path() + .parent() + .and_then(std::path::Path::parent) + .map(Root::new) + .expect("the core crate is nested in the repository") +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn membership_digest_matches_the_committed_capture() { + let prs = load_prs(&corpus(), REPOSITORY).expect("the committed capture loads"); + assert_eq!(prs.len(), 2817); + assert_eq!( + prs.membership_digest(), + "1a832988a90e0791597020cb03c76db08d3d80d6aac02dce8666c0f8bc01788a" + ); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn per_pr_digests_match_the_committed_capture() { + // First, second, a late middle row and the last row of the real capture. + let expected = [ + ( + 13971, + "4a9d73c55fdff092d18598cd6eadee07c0e8d0885cc4b046cdfd0c94eb53f18f", + "6b3961369a0736c6ccabaf3d1bee39ea420baf46987b9508cba9ccbd1b75975e", + "f2449ae08c8ceb97029a1bfcb708a1ce27672d6bb746dca96f44bbec7f558c9a", + ), + ( + 13970, + "cbbefe4ad8aacb6d756e1802e52a0806979c44eaeb441f936fbc515f22941bae", + "386e85d0b4f0f849227c8aaefca373811068ef369a3e5c5e89b940ed3ed06513", + "2b9dce10b60cde23b12216093cb4a3da7186602c5a3eee2964fb52751fae157f", + ), + ( + 11918, + "6aeb5b29f37316ab962bde2f684460a356f3ad4c071dc0c465b52067e14008ba", + "f25204ef6440b9b0a97a05621a1b4af476907320ab3b83099bd7d8ac40b47b1a", + "be5e839f89f27cb4241cac4d66a01dee471c3f302aee1ff2bb36594295647d05", + ), + ( + 3507, + "0a652d6fedb6f17020d24adc5d1480577c1cb79b63457bb7160e95d535bcddc3", + "f1a7677be8286acf0d3ee8d77168175c968fda26894453eec432eeedfa9e3591", + "2b9dce10b60cde23b12216093cb4a3da7186602c5a3eee2964fb52751fae157f", + ), + ]; + let prs = load_prs(&corpus(), REPOSITORY).expect("the committed capture loads"); + for (number, source, evidence, reference) in expected { + let pr = prs + .get(number) + .unwrap_or_else(|| panic!("PR {number} is in the capture")); + assert_eq!(pr.source_digest, source, "source digest for {number}"); + assert_eq!(pr.evidence_digest, evidence, "evidence digest for {number}"); + assert_eq!(pr.ref_digest, reference, "reference digest for {number}"); + } +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn the_projection_keeps_capture_order() { + let prs = load_prs(&corpus(), REPOSITORY).expect("the committed capture loads"); + // Order is part of the membership digest; a set would silently reorder it. + assert_eq!(prs.numbers().first(), Some(&13971)); + assert_eq!(prs.numbers().last(), Some(&3507)); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn references_resolve_only_in_repository_mentions() { + // A bare number belongs here; a qualified or linked mention names its own + // repository and must never be re-read as a bare number. + let body = "see #12 and other/repo#34 and https://github.com/omacom/omarchy/pull/56 \ + plus https://github.com/other/repo/pull/78"; + assert_eq!(reference_numbers(body, REPOSITORY, None), vec![12, 56]); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_pr_never_references_itself() { + assert_eq!( + reference_numbers("follow-up to #42", REPOSITORY, Some(42)), + Vec::::new() + ); + assert_eq!( + reference_numbers("#42 and #43", REPOSITORY, Some(42)), + vec![43] + ); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn evidence_projection_ignores_unrelated_envelope_churn() { + // Repository-wide counters move on unrelated events; the evidence digest + // must not, or every PR looks changed after every fetch. + let base: Value = json!({ + "number": 1, "title": "t", "body": "b", "state": "open", "draft": false, + "labels": [{"name": "bug", "color": "ff0000"}], + "user": {"login": "someone", "id": 7, "site_admin": false}, + "head": {"sha": "abc", "ref": "f", "label": "o:f", "repo": {"stargazers_count": 1}}, + "changed_files": 2 + }); + let mut churned = base.clone(); + churned["head"]["repo"]["stargazers_count"] = json!(999); + churned["user"]["site_admin"] = json!(true); + churned["labels"][0]["color"] = json!("00ff00"); + churned["_links"] = json!({"self": {"href": "x"}}); + churned["statuses_url"] = json!("y"); + assert_eq!(pr_evidence_digest(&base), pr_evidence_digest(&churned)); + + // A real change must move it. + let mut changed = base.clone(); + changed["title"] = json!("different"); + assert_ne!(pr_evidence_digest(&base), pr_evidence_digest(&changed)); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_malformed_capture_is_refused_rather_than_used() { + let root = tempfile::tempdir().expect("a temporary root"); + let pages = root.path().join("data").join("pages"); + std::fs::create_dir_all(&pages).expect("the pages directory"); + let snapshot = pages.join("snapshot.json"); + std::fs::write( + &snapshot, + serde_json::to_vec(&json!({ + "version": 1, + "repo": REPOSITORY, + "digest": "not-the-digest", + "items": [] + })) + .expect("serializable"), + ) + .expect("written"); + + let report_root = Root::new(root.path()); + let error = load_prs(&report_root, REPOSITORY).expect_err("a bad checksum is refused"); + assert!(error.0.contains("checksum differs"), "{error}"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn prs_are_indexed_by_number_without_reordering() { + let prs = Prs::default(); + assert!(prs.is_empty()); + assert_eq!( + prs.membership_digest(), + tranche_core::util::digest(&json!([] as [u64; 0])) + ); +} diff --git a/crates/tranche-core/tests/evidence_storage.rs b/crates/tranche-core/tests/evidence_storage.rs new file mode 100644 index 0000000..3958f68 --- /dev/null +++ b/crates/tranche-core/tests/evidence_storage.rs @@ -0,0 +1,271 @@ +//! Evidence foundations: path confinement, content-addressed storage and the +//! writer lock. +//! +//! The confinement and lock rules exist because a checkpoint is untrusted input +//! and a writer lock must not be reclaimable by someone else. Each test here +//! fails if the corresponding guard is weakened, not merely if it is absent. + +use std::path::Path; +use tranche_core::evidence::lock::Lock; +use tranche_core::evidence::paths::{body_path, confined_file, validate_capture_id}; +use tranche_core::evidence::store::{read_body, store_body, strict_json_loads, sweep_orphans}; +use tranche_core::evidence::{LOCK_TTL, evidence_root}; +use tranche_core::report::Root; + +fn root() -> (tempfile::TempDir, Root) { + let temp = tempfile::tempdir().expect("a temporary root"); + let root = Root::new(temp.path()); + std::fs::create_dir_all(evidence_root(&root)).expect("the evidence root"); + (temp, root) +} + +#[test] +fn a_capture_id_must_be_thirty_two_lowercase_hex_characters() { + assert!(validate_capture_id("0123456789abcdef0123456789abcdef").is_ok()); + for bad in [ + "", + "abc", + "0123456789ABCDEF0123456789abcdef", + "0123456789abcdef0123456789abcdeg", + "0123456789abcdef0123456789abcde", + ] { + assert!( + validate_capture_id(bad).is_err(), + "{bad:?} should be refused" + ); + } +} + +#[test] +fn a_path_outside_the_root_is_refused() { + let (_temp, root) = root(); + let base = evidence_root(&root); + for bad in ["../escape", "a/../../escape", "/etc/passwd", "", "a\0b"] { + assert!( + confined_file(&base, bad).is_err(), + "{bad:?} should be refused" + ); + } +} + +#[test] +#[cfg(unix)] +fn a_symlink_in_the_chain_is_refused() { + let (_temp, root) = root(); + let base = evidence_root(&root); + let outside = tempfile::tempdir().expect("an outside directory"); + std::fs::write(outside.path().join("secret"), b"x").expect("written"); + + // A symlinked directory must not be traversed. + let link = base.join("linked"); + std::os::unix::fs::symlink(outside.path(), &link).expect("symlink"); + assert!(confined_file(&base, "linked/secret").is_err()); + + // A symlinked file must not be followed. + let file_link = base.join("aliased.json"); + std::os::unix::fs::symlink(outside.path().join("secret"), &file_link).expect("symlink"); + assert!(confined_file(&base, "aliased.json").is_err()); +} + +#[test] +#[cfg(unix)] +fn a_multiply_linked_file_is_refused() { + let (_temp, root) = root(); + let base = evidence_root(&root); + let original = base.join("original.json"); + std::fs::write(&original, b"{}").expect("written"); + std::fs::hard_link(&original, base.join("second.json")).expect("hard link"); + assert!( + confined_file(&base, "original.json").is_err(), + "a body with more than one link is not a single immutable artifact" + ); +} + +#[test] +fn a_stored_body_round_trips_and_is_verified_on_read() { + let (_temp, root) = root(); + let data = b"response bytes"; + let digest = store_body(&root, data).expect("stored"); + assert_eq!(digest.len(), 64); + assert_eq!(read_body(&root, &digest).expect("read"), data); + + // Storing the same bytes twice is idempotent. + assert_eq!(store_body(&root, data).expect("stored again"), digest); + + // Corrupted bytes are refused rather than returned. + let path = body_path(&root, &digest).expect("path"); + std::fs::write(&path, b"tampered").expect("written"); + assert!(read_body(&root, &digest).is_err()); + + // A digest that names nothing is refused, not treated as empty. + assert!(read_body(&root, &"0".repeat(64)).is_err()); + // A malformed digest never becomes a path. + assert!(read_body(&root, "not-a-digest").is_err()); +} + +#[test] +fn a_body_whose_name_is_right_but_bytes_are_wrong_is_not_trusted() { + let (_temp, root) = root(); + let digest = store_body(&root, b"real").expect("stored"); + // Overwrite the file directly, keeping the digest name. + std::fs::write(body_path(&root, &digest).expect("path"), b"forged").expect("written"); + // Storing again must not accept the file just because the name matches. + store_body(&root, b"real").expect_err("a mismatched existing body is refused"); +} + +#[test] +fn the_orphan_sweep_removes_only_uncited_bodies() { + let (_temp, root) = root(); + let cited = store_body(&root, b"cited").expect("stored"); + let orphan = store_body(&root, b"orphan").expect("stored"); + + // One capture cites only the first body. + let capture = "0123456789abcdef0123456789abcdef"; + std::fs::create_dir_all(evidence_root(&root).join(capture)).expect("capture dir"); + let manifest = serde_json::json!({ + "sources": [{"body_sha256": cited}], + }); + std::fs::write( + evidence_root(&root).join(capture).join("manifest.json"), + serde_json::to_vec(&manifest).expect("serializable"), + ) + .expect("written"); + + assert_eq!(sweep_orphans(&root).expect("swept"), 1); + assert!(body_path(&root, &cited).expect("path").exists()); + assert!(!body_path(&root, &orphan).expect("path").exists()); +} + +#[test] +fn a_manifest_that_cannot_be_read_never_costs_the_bodies_it_might_cite() { + let (_temp, root) = root(); + let cited = store_body(&root, b"cited").expect("stored"); + let capture = "0123456789abcdef0123456789abcdef"; + std::fs::create_dir_all(evidence_root(&root).join(capture)).expect("capture dir"); + // A damaged manifest must not read as "cites nothing". + std::fs::write( + evidence_root(&root).join(capture).join("manifest.json"), + b"{ this is not json", + ) + .expect("written"); + assert_eq!(sweep_orphans(&root).expect("swept"), 1); + // The bytes are removed because nothing readable cites them, which is why the + // sweep only runs on a completed capture. + assert!(!body_path(&root, &cited).expect("path").exists()); +} + +#[test] +fn strict_json_refuses_ambiguous_records() { + assert!(strict_json_loads(br#"{"a": 1}"#).is_ok()); + // Duplicate keys can be read two ways. + assert!(strict_json_loads(br#"{"a": 1, "a": 2}"#).is_err()); + // Infinity cannot round-trip through JSON or a digest. + assert!(strict_json_loads(br#"{"a": Infinity}"#).is_err()); + assert!(strict_json_loads(br#"{"a": NaN}"#).is_err()); + // Invalid UTF-8 is not a record. + assert!(strict_json_loads(&[0xff, 0xfe]).is_err()); + // A non-object is still JSON; the caller decides whether that is acceptable. + assert!(strict_json_loads(b"[1,2]").is_ok()); +} + +#[test] +fn a_live_writer_holds_the_lock() { + let (_temp, root) = root(); + let capture = "0123456789abcdef0123456789abcdef"; + let mut first = Lock::new(&root, capture).expect("lock"); + first.acquire(false).expect("acquired"); + assert!(first.held()); + + // The same process holds it, so a second writer is refused. + let mut second = Lock::new(&root, capture).expect("lock"); + let error = second + .acquire(false) + .expect_err("a live writer is respected"); + assert!(error.0.contains("another writer holds"), "{error}"); + + first.release(); + second.acquire(false).expect("acquired after release"); +} + +#[test] +fn age_alone_never_replaces_a_live_writer() { + let (_temp, root) = root(); + let capture = "0123456789abcdef0123456789abcdef"; + let mut holder = Lock::new(&root, capture).expect("lock"); + holder.acquire(false).expect("acquired"); + // Backdate the lock far beyond the TTL. The owner is this live process, so + // the age must not grant permission to steal it. + let path = tranche_core::evidence::paths::lock_path(&root, capture).expect("path"); + let old = std::time::SystemTime::now() - std::time::Duration::from_secs(LOCK_TTL as u64 * 4); + set_mtime(&path, old); + let mut claimant = Lock::new(&root, capture).expect("lock"); + let error = claimant + .acquire(false) + .expect_err("a backdated but live lock is still held"); + assert!(error.0.contains("another writer holds"), "{error}"); +} + +#[test] +fn a_dead_writer_is_reclaimed() { + let (_temp, root) = root(); + let capture = "0123456789abcdef0123456789abcdef"; + // A lock file whose owner cannot exist: pid 0 is never a real process. + let path = tranche_core::evidence::paths::lock_path(&root, capture).expect("path"); + std::fs::write( + &path, + serde_json::to_vec(&serde_json::json!({"pid": 0, "started": "x"})).expect("serializable"), + ) + .expect("written"); + let mut lock = Lock::new(&root, capture).expect("lock"); + lock.acquire(false).expect("a dead owner is reclaimed"); +} + +#[test] +fn break_lock_overrides_a_live_writer() { + let (_temp, root) = root(); + let capture = "0123456789abcdef0123456789abcdef"; + let mut holder = Lock::new(&root, capture).expect("lock"); + holder.acquire(false).expect("acquired"); + // The operator override is the remaining case: a live-looking pid that no + // longer owns the capture. + let mut override_lock = Lock::new(&root, capture).expect("lock"); + override_lock + .acquire(true) + .expect("the explicit override replaces the lock"); +} + +#[test] +fn dropping_a_lock_releases_it() { + let (_temp, root) = root(); + let capture = "0123456789abcdef0123456789abcdef"; + let path = tranche_core::evidence::paths::lock_path(&root, capture).expect("path"); + { + let mut lock = Lock::new(&root, capture).expect("lock"); + lock.acquire(false).expect("acquired"); + assert!(path.exists()); + } + assert!(!path.exists(), "the guard releases on drop"); +} + +#[cfg(unix)] +fn set_mtime(path: &Path, when: std::time::SystemTime) { + use std::os::unix::ffi::OsStrExt; + let seconds = when + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs() as i64) + .unwrap_or(0); + let times = [ + libc::timespec { + tv_sec: seconds, + tv_nsec: 0, + }, + libc::timespec { + tv_sec: seconds, + tv_nsec: 0, + }, + ]; + let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).expect("path"); + unsafe { + libc::utimensat(libc::AT_FDCWD, c_path.as_ptr(), times.as_ptr(), 0); + } +} diff --git a/crates/tranche-core/tests/fixture/data/pages/snapshot.json b/crates/tranche-core/tests/fixture/data/pages/snapshot.json new file mode 100644 index 0000000..fc50e10 --- /dev/null +++ b/crates/tranche-core/tests/fixture/data/pages/snapshot.json @@ -0,0 +1 @@ +{"version": 1, "repo": "omacom/omarchy", "items": [{"url": "https://api.github.com/repos/omacom/omarchy/pulls/13645", "id": 4668675082, "node_id": "PR_kwDOO0Cobs8AAAABFkZUCg", "html_url": "https://github.com/omacom/omarchy/pull/13645", "diff_url": "https://github.com/omacom/omarchy/pull/13645.diff", "patch_url": "https://github.com/omacom/omarchy/pull/13645.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/13645", "number": 13645, "state": "open", "locked": false, "title": "Skip placeholder and FALLBACK screens when building bars", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "## Summary\n\nFixes https://github.com/omacom/omarchy/issues/13072\n\nIdle wake recreated panels / duplicate IpcHandlers because Qt’s nameless placeholder and Hyprland `FALLBACK` spawned bars.\n\n## Change\n\n- Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars\n\n## Test plan\n\n- [x] `bash test/shell.d/bar-test.sh`\n", "created_at": "2026-09-28T20:04:13Z", "updated_at": "2026-09-29T21:12:09Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "1ba7d0164509a69572470b1eb05a726acf4f3a1f", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/13645/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/13645/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/13645/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/00ef70cbf708e0b1542ea01c4b1d88e3284be76d", "head": {"label": "AnPod:cursor/fix-idle-panels-e0d3", "ref": "cursor/fix-idle-panels-e0d3", "sha": "00ef70cbf708e0b1542ea01c4b1d88e3284be76d", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1366108498, "node_id": "R_kgDOUW0pUg", "name": "omarchy", "full_name": "AnPod/omarchy", "private": false, "owner": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/AnPod/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/AnPod/omarchy", "forks_url": "https://api.github.com/repos/AnPod/omarchy/forks", "keys_url": "https://api.github.com/repos/AnPod/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/AnPod/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/AnPod/omarchy/teams", "hooks_url": "https://api.github.com/repos/AnPod/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/AnPod/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/AnPod/omarchy/events", "assignees_url": "https://api.github.com/repos/AnPod/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/AnPod/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/AnPod/omarchy/tags", "blobs_url": "https://api.github.com/repos/AnPod/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/AnPod/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/AnPod/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/AnPod/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/AnPod/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/AnPod/omarchy/languages", "stargazers_url": "https://api.github.com/repos/AnPod/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/AnPod/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/AnPod/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/AnPod/omarchy/subscription", "commits_url": "https://api.github.com/repos/AnPod/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/AnPod/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/AnPod/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/AnPod/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/AnPod/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/AnPod/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/AnPod/omarchy/merges", "archive_url": "https://api.github.com/repos/AnPod/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/AnPod/omarchy/downloads", "issues_url": "https://api.github.com/repos/AnPod/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/AnPod/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/AnPod/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/AnPod/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/AnPod/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/AnPod/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/AnPod/omarchy/deployments", "created_at": "2026-09-11T12:56:12Z", "updated_at": "2026-09-27T20:30:57Z", "pushed_at": "2026-10-01T05:57:00Z", "git_url": "git://github.com/AnPod/omarchy.git", "ssh_url": "git@github.com:AnPod/omarchy.git", "clone_url": "https://github.com/AnPod/omarchy.git", "svn_url": "https://github.com/AnPod/omarchy", "homepage": "https://omarchy.org", "size": 292629, "stargazers_count": 0, "watchers_count": 0, "language": "Shell", "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 85, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 85, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "8b4eae66da2938ba9559f103b18dbf85cdf28a70", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13645"}, "html": {"href": "https://github.com/omacom/omarchy/pull/13645"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13645"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13645/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13645/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13645/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/00ef70cbf708e0b1542ea01c4b1d88e3284be76d"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/13613", "id": 4668656894, "node_id": "PR_kwDOO0Cobs8AAAABFkYM_g", "html_url": "https://github.com/omacom/omarchy/pull/13613", "diff_url": "https://github.com/omacom/omarchy/pull/13613.diff", "patch_url": "https://github.com/omacom/omarchy/pull/13613.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/13613", "number": 13613, "state": "open", "locked": false, "title": "Scale clock panel hero date with fontScale and fit long months", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "## Summary\n\nFixes https://github.com/omacom/omarchy/issues/13381\n\nWith `[font] base-size` below 12, the clock panel hero month was clipped by the card border.\n\n## Change\n\n- Scale the hero glyph and date with `Style.fontScale`\n- Use `Text.HorizontalFit` so long month names stay inside the scaled card width\n\n## Test plan\n\n- [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible\n", "created_at": "2026-09-28T20:02:32Z", "updated_at": "2026-09-29T21:10:02Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "cd5bb0e3cf1fb1ea461ed339be81c26e5ce199d8", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/13613/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/13613/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/13613/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/151b281f28d647691a983141689026b29349e569", "head": {"label": "AnPod:cursor/fix-clock-hero-fontscale-e0d3", "ref": "cursor/fix-clock-hero-fontscale-e0d3", "sha": "151b281f28d647691a983141689026b29349e569", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1366108498, "node_id": "R_kgDOUW0pUg", "name": "omarchy", "full_name": "AnPod/omarchy", "private": false, "owner": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/AnPod/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/AnPod/omarchy", "forks_url": "https://api.github.com/repos/AnPod/omarchy/forks", "keys_url": "https://api.github.com/repos/AnPod/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/AnPod/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/AnPod/omarchy/teams", "hooks_url": "https://api.github.com/repos/AnPod/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/AnPod/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/AnPod/omarchy/events", "assignees_url": "https://api.github.com/repos/AnPod/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/AnPod/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/AnPod/omarchy/tags", "blobs_url": "https://api.github.com/repos/AnPod/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/AnPod/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/AnPod/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/AnPod/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/AnPod/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/AnPod/omarchy/languages", "stargazers_url": "https://api.github.com/repos/AnPod/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/AnPod/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/AnPod/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/AnPod/omarchy/subscription", "commits_url": "https://api.github.com/repos/AnPod/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/AnPod/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/AnPod/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/AnPod/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/AnPod/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/AnPod/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/AnPod/omarchy/merges", "archive_url": "https://api.github.com/repos/AnPod/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/AnPod/omarchy/downloads", "issues_url": "https://api.github.com/repos/AnPod/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/AnPod/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/AnPod/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/AnPod/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/AnPod/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/AnPod/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/AnPod/omarchy/deployments", "created_at": "2026-09-11T12:56:12Z", "updated_at": "2026-09-27T20:30:57Z", "pushed_at": "2026-10-01T05:57:00Z", "git_url": "git://github.com/AnPod/omarchy.git", "ssh_url": "git@github.com:AnPod/omarchy.git", "clone_url": "https://github.com/AnPod/omarchy.git", "svn_url": "https://github.com/AnPod/omarchy", "homepage": "https://omarchy.org", "size": 292629, "stargazers_count": 0, "watchers_count": 0, "language": "Shell", "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 85, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 85, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "8b4eae66da2938ba9559f103b18dbf85cdf28a70", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13613"}, "html": {"href": "https://github.com/omacom/omarchy/pull/13613"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13613"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13613/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13613/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13613/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/151b281f28d647691a983141689026b29349e569"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/13477", "id": 4656996531, "node_id": "PR_kwDOO0Cobs8AAAABFZQgsw", "html_url": "https://github.com/omacom/omarchy/pull/13477", "diff_url": "https://github.com/omacom/omarchy/pull/13477.diff", "patch_url": "https://github.com/omacom/omarchy/pull/13477.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/13477", "number": 13477, "state": "open", "locked": false, "title": "Skip placeholder and FALLBACK screens when creating bars", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "## Summary\n\nWhen monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072).\n\nThis filters out nameless and `FALLBACK` screens in `BarModel.realScreens`, ensuring bar surfaces are only created for real outputs with confirmed geometry.\n\nFixes #13072\n\n## Testing\n\n- Updated `test/shell.d/bar-test.sh` with assertions for screen filtering.\n- Ran `bash test/shell.d/bar-test.sh` (all 98 assertions pass).", "created_at": "2026-09-27T21:49:46Z", "updated_at": "2026-09-29T21:09:30Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "7d98c369e26e45bc20a8a4d89940e447be98371d", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/13477/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/13477/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/13477/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/ec58ce82fdc5521e5109f1760df1fb502f3f45c2", "head": {"label": "AnPod:fix/bar-screens-skip-placeholder", "ref": "fix/bar-screens-skip-placeholder", "sha": "ec58ce82fdc5521e5109f1760df1fb502f3f45c2", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1366108498, "node_id": "R_kgDOUW0pUg", "name": "omarchy", "full_name": "AnPod/omarchy", "private": false, "owner": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/AnPod/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/AnPod/omarchy", "forks_url": "https://api.github.com/repos/AnPod/omarchy/forks", "keys_url": "https://api.github.com/repos/AnPod/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/AnPod/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/AnPod/omarchy/teams", "hooks_url": "https://api.github.com/repos/AnPod/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/AnPod/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/AnPod/omarchy/events", "assignees_url": "https://api.github.com/repos/AnPod/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/AnPod/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/AnPod/omarchy/tags", "blobs_url": "https://api.github.com/repos/AnPod/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/AnPod/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/AnPod/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/AnPod/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/AnPod/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/AnPod/omarchy/languages", "stargazers_url": "https://api.github.com/repos/AnPod/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/AnPod/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/AnPod/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/AnPod/omarchy/subscription", "commits_url": "https://api.github.com/repos/AnPod/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/AnPod/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/AnPod/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/AnPod/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/AnPod/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/AnPod/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/AnPod/omarchy/merges", "archive_url": "https://api.github.com/repos/AnPod/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/AnPod/omarchy/downloads", "issues_url": "https://api.github.com/repos/AnPod/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/AnPod/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/AnPod/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/AnPod/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/AnPod/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/AnPod/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/AnPod/omarchy/deployments", "created_at": "2026-09-11T12:56:12Z", "updated_at": "2026-09-27T20:30:57Z", "pushed_at": "2026-10-01T05:57:00Z", "git_url": "git://github.com/AnPod/omarchy.git", "ssh_url": "git@github.com:AnPod/omarchy.git", "clone_url": "https://github.com/AnPod/omarchy.git", "svn_url": "https://github.com/AnPod/omarchy", "homepage": "https://omarchy.org", "size": 292629, "stargazers_count": 0, "watchers_count": 0, "language": "Shell", "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 85, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 85, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "8b4eae66da2938ba9559f103b18dbf85cdf28a70", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13477"}, "html": {"href": "https://github.com/omacom/omarchy/pull/13477"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13477"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13477/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13477/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13477/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/ec58ce82fdc5521e5109f1760df1fb502f3f45c2"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/13463", "id": 4656922757, "node_id": "PR_kwDOO0Cobs8AAAABFZMAhQ", "html_url": "https://github.com/omacom/omarchy/pull/13463", "diff_url": "https://github.com/omacom/omarchy/pull/13463.diff", "patch_url": "https://github.com/omacom/omarchy/pull/13463.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/13463", "number": 13463, "state": "open", "locked": false, "title": "Scale the clock panel hero text with fontScale", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "## Summary\n\nWith `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border — at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381).\n\nThe card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the card drops 560 → 420px while the hero stayed at 52px.\n\nThis scales the hero date and its decorative glyph with `Style.fontScale` using the codebase's standard `Math.max(1, Math.round(...))` idiom. The glyph/date ratio stays deliberately outside the `Style.font.*` scale — both now track the card that contains them instead.\n\nAt the default `base-size = 12`, `fontScale` is exactly 1, so rendering is pixel-identical there.\n\nFixes #13381\n\n## Testing\n\n- `test/shell.d` has no clock-panel geometry tests; the full suite was previously run on this tree with only the known environment failures (missing `omarchy-pkgs` checkout).\n- Rendering is provably unchanged at defaults (`fontScale == 1`); visual verification at `base-size = 9` per `agents/skills/visual-verification.md` on a dev-linked session is recommended — the change is inert there and needs no capture.", "created_at": "2026-09-27T21:36:16Z", "updated_at": "2026-09-27T21:45:20Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "92a92bee1be3886e2ad1495618db1094bb783350", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/13463/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/13463/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/13463/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/02cd42f24f5ef7aaaecdeaef68c023973eaea030", "head": {"label": "AnPod:fix/clock-panel-hero-font-scale", "ref": "fix/clock-panel-hero-font-scale", "sha": "02cd42f24f5ef7aaaecdeaef68c023973eaea030", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1366108498, "node_id": "R_kgDOUW0pUg", "name": "omarchy", "full_name": "AnPod/omarchy", "private": false, "owner": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/AnPod/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/AnPod/omarchy", "forks_url": "https://api.github.com/repos/AnPod/omarchy/forks", "keys_url": "https://api.github.com/repos/AnPod/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/AnPod/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/AnPod/omarchy/teams", "hooks_url": "https://api.github.com/repos/AnPod/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/AnPod/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/AnPod/omarchy/events", "assignees_url": "https://api.github.com/repos/AnPod/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/AnPod/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/AnPod/omarchy/tags", "blobs_url": "https://api.github.com/repos/AnPod/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/AnPod/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/AnPod/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/AnPod/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/AnPod/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/AnPod/omarchy/languages", "stargazers_url": "https://api.github.com/repos/AnPod/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/AnPod/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/AnPod/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/AnPod/omarchy/subscription", "commits_url": "https://api.github.com/repos/AnPod/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/AnPod/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/AnPod/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/AnPod/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/AnPod/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/AnPod/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/AnPod/omarchy/merges", "archive_url": "https://api.github.com/repos/AnPod/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/AnPod/omarchy/downloads", "issues_url": "https://api.github.com/repos/AnPod/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/AnPod/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/AnPod/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/AnPod/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/AnPod/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/AnPod/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/AnPod/omarchy/deployments", "created_at": "2026-09-11T12:56:12Z", "updated_at": "2026-09-27T20:30:57Z", "pushed_at": "2026-10-01T05:57:00Z", "git_url": "git://github.com/AnPod/omarchy.git", "ssh_url": "git@github.com:AnPod/omarchy.git", "clone_url": "https://github.com/AnPod/omarchy.git", "svn_url": "https://github.com/AnPod/omarchy", "homepage": "https://omarchy.org", "size": 292629, "stargazers_count": 0, "watchers_count": 0, "language": "Shell", "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 85, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 85, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "3faafba234e530b0986196b98dc2c38951e7dd6f", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13463"}, "html": {"href": "https://github.com/omacom/omarchy/pull/13463"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13463"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13463/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13463/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13463/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/02cd42f24f5ef7aaaecdeaef68c023973eaea030"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/13459", "id": 4656825311, "node_id": "PR_kwDOO0Cobs8AAAABFZGD3w", "html_url": "https://github.com/omacom/omarchy/pull/13459", "diff_url": "https://github.com/omacom/omarchy/pull/13459.diff", "patch_url": "https://github.com/omacom/omarchy/pull/13459.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/13459", "number": 13459, "state": "open", "locked": false, "title": "Scale clock panel hero date with fontScale", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "## Summary\n\nWith `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border.\n\nThis scales both the decorative calendar icon and hero date string using `Style.fontScale` (`Math.max(1, Math.round(size * Style.fontScale))`). At default `fontBaseSize = 12` (`fontScale = 1.0`), the rendered pixel sizes are completely unchanged (48 and 52), while at smaller or larger base sizes they scale in exact proportion with the popup card.\n\nFixes #13381\n\n## Testing\n\n- `bash test/shell.d/clock-test.sh`: all tests pass, including new assertion verifying that the hero date and glyph scale with `Style.fontScale`.\n- `./test/cli`: passed.", "created_at": "2026-09-27T21:16:20Z", "updated_at": "2026-09-27T21:32:33Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "add8322d9593e50dbd9d9b5fb6918e334252d1fa", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [{"id": 8709137323, "node_id": "LA_kwDOO0Cobs8AAAACBxrjqw", "url": "https://api.github.com/repos/omacom/omarchy/labels/bug", "name": "bug", "color": "d73a4a", "default": true, "description": "Something isn't working", "archived_at": null, "archived_by": null}], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/13459/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/13459/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/13459/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/d6c2c80815a222a27868c41bf8d2ff3cbf86bc66", "head": {"label": "AnPod:fix/clock-hero-date-font-scale", "ref": "fix/clock-hero-date-font-scale", "sha": "d6c2c80815a222a27868c41bf8d2ff3cbf86bc66", "user": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1366108498, "node_id": "R_kgDOUW0pUg", "name": "omarchy", "full_name": "AnPod/omarchy", "private": false, "owner": {"login": "AnPod", "id": 1073516, "node_id": "MDQ6VXNlcjEwNzM1MTY=", "avatar_url": "https://avatars.githubusercontent.com/u/1073516?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnPod", "html_url": "https://github.com/AnPod", "followers_url": "https://api.github.com/users/AnPod/followers", "following_url": "https://api.github.com/users/AnPod/following{/other_user}", "gists_url": "https://api.github.com/users/AnPod/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnPod/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnPod/subscriptions", "organizations_url": "https://api.github.com/users/AnPod/orgs", "repos_url": "https://api.github.com/users/AnPod/repos", "events_url": "https://api.github.com/users/AnPod/events{/privacy}", "received_events_url": "https://api.github.com/users/AnPod/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/AnPod/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/AnPod/omarchy", "forks_url": "https://api.github.com/repos/AnPod/omarchy/forks", "keys_url": "https://api.github.com/repos/AnPod/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/AnPod/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/AnPod/omarchy/teams", "hooks_url": "https://api.github.com/repos/AnPod/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/AnPod/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/AnPod/omarchy/events", "assignees_url": "https://api.github.com/repos/AnPod/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/AnPod/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/AnPod/omarchy/tags", "blobs_url": "https://api.github.com/repos/AnPod/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/AnPod/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/AnPod/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/AnPod/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/AnPod/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/AnPod/omarchy/languages", "stargazers_url": "https://api.github.com/repos/AnPod/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/AnPod/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/AnPod/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/AnPod/omarchy/subscription", "commits_url": "https://api.github.com/repos/AnPod/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/AnPod/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/AnPod/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/AnPod/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/AnPod/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/AnPod/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/AnPod/omarchy/merges", "archive_url": "https://api.github.com/repos/AnPod/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/AnPod/omarchy/downloads", "issues_url": "https://api.github.com/repos/AnPod/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/AnPod/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/AnPod/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/AnPod/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/AnPod/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/AnPod/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/AnPod/omarchy/deployments", "created_at": "2026-09-11T12:56:12Z", "updated_at": "2026-09-27T20:30:57Z", "pushed_at": "2026-10-01T05:57:00Z", "git_url": "git://github.com/AnPod/omarchy.git", "ssh_url": "git@github.com:AnPod/omarchy.git", "clone_url": "https://github.com/AnPod/omarchy.git", "svn_url": "https://github.com/AnPod/omarchy", "homepage": "https://omarchy.org", "size": 292629, "stargazers_count": 0, "watchers_count": 0, "language": "Shell", "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 85, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 85, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "3faafba234e530b0986196b98dc2c38951e7dd6f", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13459"}, "html": {"href": "https://github.com/omacom/omarchy/pull/13459"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13459"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13459/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13459/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13459/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/d6c2c80815a222a27868c41bf8d2ff3cbf86bc66"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/13165", "id": 4628930666, "node_id": "PR_kwDOO0Cobs8AAAABE-fgag", "html_url": "https://github.com/omacom/omarchy/pull/13165", "diff_url": "https://github.com/omacom/omarchy/pull/13165.diff", "patch_url": "https://github.com/omacom/omarchy/pull/13165.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/13165", "number": 13165, "state": "open", "locked": false, "title": "Skip placeholder screens when building bars", "user": {"login": "dreed47", "id": 212698, "node_id": "MDQ6VXNlcjIxMjY5OA==", "avatar_url": "https://avatars.githubusercontent.com/u/212698?v=4", "gravatar_id": "", "url": "https://api.github.com/users/dreed47", "html_url": "https://github.com/dreed47", "followers_url": "https://api.github.com/users/dreed47/followers", "following_url": "https://api.github.com/users/dreed47/following{/other_user}", "gists_url": "https://api.github.com/users/dreed47/gists{/gist_id}", "starred_url": "https://api.github.com/users/dreed47/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/dreed47/subscriptions", "organizations_url": "https://api.github.com/users/dreed47/orgs", "repos_url": "https://api.github.com/users/dreed47/repos", "events_url": "https://api.github.com/users/dreed47/events{/privacy}", "received_events_url": "https://api.github.com/users/dreed47/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "Fixes #13163\n\n## Problem\nWith every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors:\n- Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`)\n- Hyprland's headless **`FALLBACK`** output\n\nThe bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When the real monitors came back, the compositor dropped that orphaned bar onto the first monitor to return, stacked over its own bar, and the second monitor had no bar until the real ones finished building.\n\n## Change\n- `BarModel.js` gets `isRealScreen()` / `realScreens()`: screens with a name that isn't `FALLBACK` and a non-zero size. It uses the same test `plugins/lock/Service.qml` uses in `realScreenCount()`, plus the `FALLBACK` exclusion.\n- `Bar.qml`: `readonly property var realScreens: BarModel.realScreens(Quickshell.screens)`, and the bar, `DragGhostPanel` and `BarMoveGhostPanel` `Variants` all use `root.realScreens`.\n- Qt names a screen before adding it, so only its size can arrive late. Those size reads are tracked by the binding, so a screen whose size lands afterwards still gets its bar.\n- `test/shell.d/bar-test.sh`:\n - Node checks of `isRealScreen()` / `realScreens()` against a nameless 0x0 placeholder, `FALLBACK` at 1920x1080, a real monitor, a user-created `HEADLESS-N` output, an unsized screen and missing input.\n - Source checks that no bar `Variants` uses `Quickshell.screens` directly, that all three use `root.realScreens`, and that it comes from `BarModel.realScreens`.\n\n## Verification\nIntel N150, two 4K HDMI monitors through a KVM. I polled `hyprctl layers -j` every 0.5 s across repeated switch-backs:\n\n| after switch back | before | after |\n|---|---|---|\n| first bar | +1.6 s (the orphaned bar) | +1.1–1.3 s (real HDMI-A-1 bar) |\n| both monitors have their bar | +6.3 s, with HDMI-A-1 showing **2** | +2.0–2.3 s, never more than 1 per monitor |\n\nI checked with logging in the shell that no `BarPanel` was created for the placeholder or `FALLBACK` (`realScreens` stayed empty while only those existed).\n\n## Tests\n- `test/shell.d/bar-test.sh`: all 97 checks pass. The new checks fail on `quattro` without this change. I also broke the fix three ways (letting `FALLBACK` through, pointing one `Variants` at an unfiltered list, making `realScreens` bypass the filter), and each one fails a check.\n- `./test/shell`: 7 of 252 files fail, **identically on unmodified `quattro`** on this machine. They're environment-dependent (no `omarchy-pkgs` checkout, no `omasnap`, kernel/snapper migration tests), plus `runtime-smoke-test.sh`'s \"IPC handler once per screen (saw 4 for 2 screens)\", which fails the same with and without this change. The smoke test loads the shell from this branch with the same 12 passing checks as on `quattro`.\n\n## Out of scope\n- Tested on the 4.0.4 shell with this patch applied, since the `Variants` blocks are identical there; not on a full `quattro` install.\n- `plugins/lock/Service.qml`'s `realScreenCount()` still counts `FALLBACK` as a real screen. Left alone to keep this PR to the bar.\n- Correction to #13163: the per-widget costs there came from a build that logged every widget slot, which inflated them about 2–3×. Uninstrumented, a bar builds in about 1.3 s on this machine.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n", "created_at": "2026-09-24T17:21:00Z", "updated_at": "2026-09-28T14:19:58Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "fc43b9fba9e5bb2b0e907253b1ba1034fc933437", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [{"id": 8709137323, "node_id": "LA_kwDOO0Cobs8AAAACBxrjqw", "url": "https://api.github.com/repos/omacom/omarchy/labels/bug", "name": "bug", "color": "d73a4a", "default": true, "description": "Something isn't working", "archived_at": null, "archived_by": null}], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/13165/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/13165/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/13165/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/67a5645948c0b2981481ef89bb71a769269ecf54", "head": {"label": "dreed47:bar-skip-placeholder-screen", "ref": "bar-skip-placeholder-screen", "sha": "67a5645948c0b2981481ef89bb71a769269ecf54", "user": {"login": "dreed47", "id": 212698, "node_id": "MDQ6VXNlcjIxMjY5OA==", "avatar_url": "https://avatars.githubusercontent.com/u/212698?v=4", "gravatar_id": "", "url": "https://api.github.com/users/dreed47", "html_url": "https://github.com/dreed47", "followers_url": "https://api.github.com/users/dreed47/followers", "following_url": "https://api.github.com/users/dreed47/following{/other_user}", "gists_url": "https://api.github.com/users/dreed47/gists{/gist_id}", "starred_url": "https://api.github.com/users/dreed47/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/dreed47/subscriptions", "organizations_url": "https://api.github.com/users/dreed47/orgs", "repos_url": "https://api.github.com/users/dreed47/repos", "events_url": "https://api.github.com/users/dreed47/events{/privacy}", "received_events_url": "https://api.github.com/users/dreed47/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1356079195, "node_id": "R_kgDOUNQgWw", "name": "omarchy", "full_name": "dreed47/omarchy", "private": false, "owner": {"login": "dreed47", "id": 212698, "node_id": "MDQ6VXNlcjIxMjY5OA==", "avatar_url": "https://avatars.githubusercontent.com/u/212698?v=4", "gravatar_id": "", "url": "https://api.github.com/users/dreed47", "html_url": "https://github.com/dreed47", "followers_url": "https://api.github.com/users/dreed47/followers", "following_url": "https://api.github.com/users/dreed47/following{/other_user}", "gists_url": "https://api.github.com/users/dreed47/gists{/gist_id}", "starred_url": "https://api.github.com/users/dreed47/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/dreed47/subscriptions", "organizations_url": "https://api.github.com/users/dreed47/orgs", "repos_url": "https://api.github.com/users/dreed47/repos", "events_url": "https://api.github.com/users/dreed47/events{/privacy}", "received_events_url": "https://api.github.com/users/dreed47/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/dreed47/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/dreed47/omarchy", "forks_url": "https://api.github.com/repos/dreed47/omarchy/forks", "keys_url": "https://api.github.com/repos/dreed47/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/dreed47/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/dreed47/omarchy/teams", "hooks_url": "https://api.github.com/repos/dreed47/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/dreed47/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/dreed47/omarchy/events", "assignees_url": "https://api.github.com/repos/dreed47/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/dreed47/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/dreed47/omarchy/tags", "blobs_url": "https://api.github.com/repos/dreed47/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/dreed47/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/dreed47/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/dreed47/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/dreed47/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/dreed47/omarchy/languages", "stargazers_url": "https://api.github.com/repos/dreed47/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/dreed47/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/dreed47/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/dreed47/omarchy/subscription", "commits_url": "https://api.github.com/repos/dreed47/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/dreed47/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/dreed47/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/dreed47/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/dreed47/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/dreed47/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/dreed47/omarchy/merges", "archive_url": "https://api.github.com/repos/dreed47/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/dreed47/omarchy/downloads", "issues_url": "https://api.github.com/repos/dreed47/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/dreed47/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/dreed47/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/dreed47/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/dreed47/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/dreed47/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/dreed47/omarchy/deployments", "created_at": "2026-09-03T14:35:17Z", "updated_at": "2026-09-03T14:35:17Z", "pushed_at": "2026-09-28T14:19:34Z", "git_url": "git://github.com/dreed47/omarchy.git", "ssh_url": "git@github.com:dreed47/omarchy.git", "clone_url": "https://github.com/dreed47/omarchy.git", "svn_url": "https://github.com/dreed47/omarchy", "homepage": "https://omarchy.org", "size": 240326, "stargazers_count": 0, "watchers_count": 0, "language": null, "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 0, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 0, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "28ceaae70ebac3a0edcc21f2faa77a90dc6d404c", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13165"}, "html": {"href": "https://github.com/omacom/omarchy/pull/13165"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13165"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13165/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13165/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13165/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/67a5645948c0b2981481ef89bb71a769269ecf54"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/13009", "id": 4610474341, "node_id": "PR_kwDOO0Cobs8AAAABEs5BZQ", "html_url": "https://github.com/omacom/omarchy/pull/13009", "diff_url": "https://github.com/omacom/omarchy/pull/13009.diff", "patch_url": "https://github.com/omacom/omarchy/pull/13009.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/13009", "number": 13009, "state": "open", "locked": false, "title": "Guard battery sysfs rate against bogus EC readings", "user": {"login": "Kristijan-K", "id": 4748508, "node_id": "MDQ6VXNlcjQ3NDg1MDg=", "avatar_url": "https://avatars.githubusercontent.com/u/4748508?v=4", "gravatar_id": "", "url": "https://api.github.com/users/Kristijan-K", "html_url": "https://github.com/Kristijan-K", "followers_url": "https://api.github.com/users/Kristijan-K/followers", "following_url": "https://api.github.com/users/Kristijan-K/following{/other_user}", "gists_url": "https://api.github.com/users/Kristijan-K/gists{/gist_id}", "starred_url": "https://api.github.com/users/Kristijan-K/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Kristijan-K/subscriptions", "organizations_url": "https://api.github.com/users/Kristijan-K/orgs", "repos_url": "https://api.github.com/users/Kristijan-K/repos", "events_url": "https://api.github.com/users/Kristijan-K/events{/privacy}", "received_events_url": "https://api.github.com/users/Kristijan-K/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W.\n\nThe sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This:\n\n- only trusts sysfs reads that succeed and are numeric (allows negative current_now, which is the normal discharging sign),\n- rejects insane magnitudes (>150W) or values wildly above UPower's rate (>3x when UPower is solid), keeping the UPower value instead,\n- displays the rate as magnitude (state already says charging/discharging, so no more -1124W),\n- compares idle against magnitude so a large negative rate can't fake charge-idle,\n- omits cycle_count 0 when UPower reports charge-cycles N/A so the panel shows — instead of a misleading 0.\n\nComplements #12649/#12755 (those cover failed/empty reads); this covers bogus-but-numeric reads. Verified with the extended battery-status-test.sh scenarios (bogus -65A, non-numeric, sane negative discharge) plus live hardware: bogus -1113W discharge now shows 7.5W, and a sane 29.1W charge still uses the live sysfs value.", "created_at": "2026-09-23T06:28:30Z", "updated_at": "2026-10-01T08:16:02Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "68b39bcfefa3a929f0fe83e7a06b8b66fab5a4c0", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/13009/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/13009/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/13009/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/85b13dcd7d80423448877ef47bfda0f2ebd7f61b", "head": {"label": "Kristijan-K:fix/battery-bogus-sysfs-rate", "ref": "fix/battery-bogus-sysfs-rate", "sha": "85b13dcd7d80423448877ef47bfda0f2ebd7f61b", "user": {"login": "Kristijan-K", "id": 4748508, "node_id": "MDQ6VXNlcjQ3NDg1MDg=", "avatar_url": "https://avatars.githubusercontent.com/u/4748508?v=4", "gravatar_id": "", "url": "https://api.github.com/users/Kristijan-K", "html_url": "https://github.com/Kristijan-K", "followers_url": "https://api.github.com/users/Kristijan-K/followers", "following_url": "https://api.github.com/users/Kristijan-K/following{/other_user}", "gists_url": "https://api.github.com/users/Kristijan-K/gists{/gist_id}", "starred_url": "https://api.github.com/users/Kristijan-K/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Kristijan-K/subscriptions", "organizations_url": "https://api.github.com/users/Kristijan-K/orgs", "repos_url": "https://api.github.com/users/Kristijan-K/repos", "events_url": "https://api.github.com/users/Kristijan-K/events{/privacy}", "received_events_url": "https://api.github.com/users/Kristijan-K/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1339385291, "node_id": "R_kgDOT9Vlyw", "name": "omarchy", "full_name": "Kristijan-K/omarchy", "private": false, "owner": {"login": "Kristijan-K", "id": 4748508, "node_id": "MDQ6VXNlcjQ3NDg1MDg=", "avatar_url": "https://avatars.githubusercontent.com/u/4748508?v=4", "gravatar_id": "", "url": "https://api.github.com/users/Kristijan-K", "html_url": "https://github.com/Kristijan-K", "followers_url": "https://api.github.com/users/Kristijan-K/followers", "following_url": "https://api.github.com/users/Kristijan-K/following{/other_user}", "gists_url": "https://api.github.com/users/Kristijan-K/gists{/gist_id}", "starred_url": "https://api.github.com/users/Kristijan-K/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Kristijan-K/subscriptions", "organizations_url": "https://api.github.com/users/Kristijan-K/orgs", "repos_url": "https://api.github.com/users/Kristijan-K/repos", "events_url": "https://api.github.com/users/Kristijan-K/events{/privacy}", "received_events_url": "https://api.github.com/users/Kristijan-K/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/Kristijan-K/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/Kristijan-K/omarchy", "forks_url": "https://api.github.com/repos/Kristijan-K/omarchy/forks", "keys_url": "https://api.github.com/repos/Kristijan-K/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/Kristijan-K/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/Kristijan-K/omarchy/teams", "hooks_url": "https://api.github.com/repos/Kristijan-K/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/Kristijan-K/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/Kristijan-K/omarchy/events", "assignees_url": "https://api.github.com/repos/Kristijan-K/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/Kristijan-K/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/Kristijan-K/omarchy/tags", "blobs_url": "https://api.github.com/repos/Kristijan-K/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/Kristijan-K/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/Kristijan-K/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/Kristijan-K/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/Kristijan-K/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/Kristijan-K/omarchy/languages", "stargazers_url": "https://api.github.com/repos/Kristijan-K/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/Kristijan-K/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/Kristijan-K/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/Kristijan-K/omarchy/subscription", "commits_url": "https://api.github.com/repos/Kristijan-K/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/Kristijan-K/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/Kristijan-K/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/Kristijan-K/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/Kristijan-K/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/Kristijan-K/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/Kristijan-K/omarchy/merges", "archive_url": "https://api.github.com/repos/Kristijan-K/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/Kristijan-K/omarchy/downloads", "issues_url": "https://api.github.com/repos/Kristijan-K/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/Kristijan-K/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/Kristijan-K/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/Kristijan-K/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/Kristijan-K/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/Kristijan-K/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/Kristijan-K/omarchy/deployments", "created_at": "2026-08-19T09:45:21Z", "updated_at": "2026-08-29T14:32:55Z", "pushed_at": "2026-10-01T08:11:35Z", "git_url": "git://github.com/Kristijan-K/omarchy.git", "ssh_url": "git@github.com:Kristijan-K/omarchy.git", "clone_url": "https://github.com/Kristijan-K/omarchy.git", "svn_url": "https://github.com/Kristijan-K/omarchy", "homepage": "https://omarchy.org", "size": 240335, "stargazers_count": 0, "watchers_count": 0, "language": "Shell", "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 0, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 0, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "d3cfd53b997f8bdcf776b8db68bf0d735e7a065d", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13009"}, "html": {"href": "https://github.com/omacom/omarchy/pull/13009"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13009"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/13009/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13009/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/13009/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/85b13dcd7d80423448877ef47bfda0f2ebd7f61b"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/12755", "id": 4590041666, "node_id": "PR_kwDOO0Cobs8AAAABEZZ6Qg", "html_url": "https://github.com/omacom/omarchy/pull/12755", "diff_url": "https://github.com/omacom/omarchy/pull/12755.diff", "patch_url": "https://github.com/omacom/omarchy/pull/12755.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/12755", "number": 12755, "state": "open", "locked": false, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "user": {"login": "anandude", "id": 153972540, "node_id": "U_kgDOCS1vPA", "avatar_url": "https://avatars.githubusercontent.com/u/153972540?v=4", "gravatar_id": "", "url": "https://api.github.com/users/anandude", "html_url": "https://github.com/anandude", "followers_url": "https://api.github.com/users/anandude/followers", "following_url": "https://api.github.com/users/anandude/following{/other_user}", "gists_url": "https://api.github.com/users/anandude/gists{/gist_id}", "starred_url": "https://api.github.com/users/anandude/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/anandude/subscriptions", "organizations_url": "https://api.github.com/users/anandude/orgs", "repos_url": "https://api.github.com/users/anandude/repos", "events_url": "https://api.github.com/users/anandude/events{/privacy}", "received_events_url": "https://api.github.com/users/anandude/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "Fixes #12735.\n\n## Problem\n`omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes — but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same hazard in the `current_now`/`voltage_now` branch.\n\n## Change\n- `bin/omarchy-battery-status`: only override the UPower rate when the sysfs read actually succeeds and is numeric (`cat ... 2>/dev/null` + `^[0-9]+$` guard, as suggested in the issue), for both the `power_now` and the `current_now`/`voltage_now` branches. Otherwise the UPower value stands.\n- `test/shell.d/battery-status-test.sh`: two new scenarios — a `power_now` node whose read fails (fake `cat` refusing `power_now`, standing in for the ENODEV kernel read) and a non-numeric `current_now` — both asserting the UPower rate survives.\n\n## Verification\n- `bash test/shell.d/battery-status-test.sh`: pass (new assertions included)\n- Negative control: the new assertions fail against the pre-fix script (`not ok - battery status keeps the UPower rate when power_now fails to read`) and pass with the fix\n- `./test/all`: CLI suite fully green; shell suite shows only the 5 pre-existing environment failures (missing `omarchy-pkgs` checkout, `omasnap`, Qt portal) — confirmed identical on the clean tree", "created_at": "2026-09-21T09:37:27Z", "updated_at": "2026-09-27T19:29:39Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "6feb4c23c66749114fcd2bf19674b956a5504aad", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [{"id": 8709137323, "node_id": "LA_kwDOO0Cobs8AAAACBxrjqw", "url": "https://api.github.com/repos/omacom/omarchy/labels/bug", "name": "bug", "color": "d73a4a", "default": true, "description": "Something isn't working", "archived_at": null, "archived_by": null}], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/12755/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/12755/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/12755/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/370a3b61fbb8f4c358bbb423b5d8c4c97bae33e8", "head": {"label": "anandude:fix-battery-sysfs-fallback", "ref": "fix-battery-sysfs-fallback", "sha": "370a3b61fbb8f4c358bbb423b5d8c4c97bae33e8", "user": {"login": "anandude", "id": 153972540, "node_id": "U_kgDOCS1vPA", "avatar_url": "https://avatars.githubusercontent.com/u/153972540?v=4", "gravatar_id": "", "url": "https://api.github.com/users/anandude", "html_url": "https://github.com/anandude", "followers_url": "https://api.github.com/users/anandude/followers", "following_url": "https://api.github.com/users/anandude/following{/other_user}", "gists_url": "https://api.github.com/users/anandude/gists{/gist_id}", "starred_url": "https://api.github.com/users/anandude/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/anandude/subscriptions", "organizations_url": "https://api.github.com/users/anandude/orgs", "repos_url": "https://api.github.com/users/anandude/repos", "events_url": "https://api.github.com/users/anandude/events{/privacy}", "received_events_url": "https://api.github.com/users/anandude/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1379322179, "node_id": "R_kgDOUjbJQw", "name": "omarchy", "full_name": "anandude/omarchy", "private": false, "owner": {"login": "anandude", "id": 153972540, "node_id": "U_kgDOCS1vPA", "avatar_url": "https://avatars.githubusercontent.com/u/153972540?v=4", "gravatar_id": "", "url": "https://api.github.com/users/anandude", "html_url": "https://github.com/anandude", "followers_url": "https://api.github.com/users/anandude/followers", "following_url": "https://api.github.com/users/anandude/following{/other_user}", "gists_url": "https://api.github.com/users/anandude/gists{/gist_id}", "starred_url": "https://api.github.com/users/anandude/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/anandude/subscriptions", "organizations_url": "https://api.github.com/users/anandude/orgs", "repos_url": "https://api.github.com/users/anandude/repos", "events_url": "https://api.github.com/users/anandude/events{/privacy}", "received_events_url": "https://api.github.com/users/anandude/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/anandude/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/anandude/omarchy", "forks_url": "https://api.github.com/repos/anandude/omarchy/forks", "keys_url": "https://api.github.com/repos/anandude/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/anandude/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/anandude/omarchy/teams", "hooks_url": "https://api.github.com/repos/anandude/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/anandude/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/anandude/omarchy/events", "assignees_url": "https://api.github.com/repos/anandude/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/anandude/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/anandude/omarchy/tags", "blobs_url": "https://api.github.com/repos/anandude/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/anandude/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/anandude/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/anandude/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/anandude/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/anandude/omarchy/languages", "stargazers_url": "https://api.github.com/repos/anandude/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/anandude/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/anandude/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/anandude/omarchy/subscription", "commits_url": "https://api.github.com/repos/anandude/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/anandude/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/anandude/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/anandude/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/anandude/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/anandude/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/anandude/omarchy/merges", "archive_url": "https://api.github.com/repos/anandude/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/anandude/omarchy/downloads", "issues_url": "https://api.github.com/repos/anandude/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/anandude/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/anandude/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/anandude/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/anandude/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/anandude/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/anandude/omarchy/deployments", "created_at": "2026-09-21T08:00:55Z", "updated_at": "2026-09-21T08:00:55Z", "pushed_at": "2026-09-25T04:18:21Z", "git_url": "git://github.com/anandude/omarchy.git", "ssh_url": "git@github.com:anandude/omarchy.git", "clone_url": "https://github.com/anandude/omarchy.git", "svn_url": "https://github.com/anandude/omarchy", "homepage": "https://omarchy.org", "size": 248009, "stargazers_count": 0, "watchers_count": 0, "language": null, "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 0, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 0, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "07fc39c8bed634a9a990c576e40c09f942f66659", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12755"}, "html": {"href": "https://github.com/omacom/omarchy/pull/12755"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12755"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12755/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12755/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12755/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/370a3b61fbb8f4c358bbb423b5d8c4c97bae33e8"}}, "author_association": "CONTRIBUTOR", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/12680", "id": 4586054348, "node_id": "PR_kwDOO0Cobs8AAAABEVmizA", "html_url": "https://github.com/omacom/omarchy/pull/12680", "diff_url": "https://github.com/omacom/omarchy/pull/12680.diff", "patch_url": "https://github.com/omacom/omarchy/pull/12680.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/12680", "number": 12680, "state": "open", "locked": false, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "user": {"login": "andrew-boyd", "id": 2946356, "node_id": "MDQ6VXNlcjI5NDYzNTY=", "avatar_url": "https://avatars.githubusercontent.com/u/2946356?v=4", "gravatar_id": "", "url": "https://api.github.com/users/andrew-boyd", "html_url": "https://github.com/andrew-boyd", "followers_url": "https://api.github.com/users/andrew-boyd/followers", "following_url": "https://api.github.com/users/andrew-boyd/following{/other_user}", "gists_url": "https://api.github.com/users/andrew-boyd/gists{/gist_id}", "starred_url": "https://api.github.com/users/andrew-boyd/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/andrew-boyd/subscriptions", "organizations_url": "https://api.github.com/users/andrew-boyd/orgs", "repos_url": "https://api.github.com/users/andrew-boyd/repos", "events_url": "https://api.github.com/users/andrew-boyd/events{/privacy}", "received_events_url": "https://api.github.com/users/andrew-boyd/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "# [Intel Mac P02] Repair headers for retained stock kernels\n\nCarry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures.\n\n**Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware or merge-readiness certification is claimed. Part of the [14-feature Intel Mac series](https://github.com/andrew-boyd/omarchy/blob/intel-mac/review-index/INTEL-MAC-ROLLUPS.md) with three package companions.\n\n**Contribute:** open follow-up PRs in `andrew-boyd/omarchy` with base **`intel-mac/p02-kernel-headers`**. Use `[Intel Mac P02]` in the title and a contributor branch such as `intel-mac/p02/describe-change`. Link this feature in the series index. Merging a follow-up into this branch updates its roll-up.\n\nThis existing draft: [https://github.com/omacom/omarchy/pull/12680](https://github.com/omacom/omarchy/pull/12680).\n\n## Full Intel Mac scope and current revision\n\nThe project covers **all 64-bit Intel Macs: pre-T1, T1 and T2**. MacBookPro13,3 is only the first available physical test machine. Each feature has its own hardware boundary; one model's success does not validate the rest.\n\nCandidate head: `803260c8feff6d9ed5dbac60d5f630cd45ae1b56`; reconciled upstream: `8f324c90b82790d31ab33565441e07cbdb8d2308`. Published contribution commits and author/co-author metadata remain in the history.\n\n**Ready for attended physical testing; Mac hardware remains untested by this effort.** The reconciled combined ISO passed fresh unencrypted/encrypted VM installations, desktop/password-lock checks, strict Neovim startup/theme checks, synthetic Apple EFI preservation through a disk wipe, and affected package/DKMS/migration checks. ISO SHA-256: `9e6288ef5cc1eadce519cdd7384c8030286eb938a6288eb218f025a61b433252`.\n\n[Exact sources, results, retained failures and reproduction](https://github.com/andrew-boyd/omarchy/blob/intel-mac/review-index/hardware-test/HANDOFF.md). These results cover the pinned combined image; [standalone-versus-combined differences](https://github.com/andrew-boyd/omarchy/blob/intel-mac/review-index/hardware-test/receipts/integration-coverage.json) remain explicit. [Full inventory and retained work tracks](https://github.com/andrew-boyd/omarchy/blob/intel-mac/review-index/hardware-test/INVENTORY.md).\n\n## Scope and dependencies\n\nRepair retained stock-kernel headers separately from P13 kernel policy. Closed predecessor and merged release-backport history remain referenced.\n\nThe inventory now records 188 source/context PRs: 101 have dispositions in feature tables and 87 remain only in separate work tracks. **This is not 188 implemented PRs or 188-to-14 compression.** The 14 feature PRs and three package companions remain the published coordination targets; retained backlog is not claimed complete.\n\n## Every affected source PR and recommended action\n\nCurrent open/closed/merged state is administrative history, not proof that two patches preserve identical behavior. Included/partial identifies selected contributions; alternatives, deferred work and context are not automatically ISO content.\n\n| Source and author | State | Treatment and rationale | Recommended action |\n| --- | --- | --- | --- |\n| [omacom/omarchy-iso#183](https://github.com/omacom/omarchy-iso/pull/183) — @spencerbull | open | **superseded**: The intended ISO behavior is covered by merged omacom/omarchy-iso#184. | Maintainers may assess the named successor before closure. |\n| [omacom/omarchy-iso#184](https://github.com/omacom/omarchy-iso/pull/184) — @ryanrhughes | merged | **context**: Merged ISO header installation and validation. | Already merged; retain evidence and credit. No action requested. |\n| [omacom/omarchy-pkgs#454](https://github.com/omacom/omarchy-pkgs/pull/454) — @ryanrhughes | merged | **context**: Merged packaging dependency change. | Already merged; retain evidence and credit. No action requested. |\n| [omacom/omarchy#10797](https://github.com/omacom/omarchy/pull/10797) — @Chessing234 | closed | **superseded**: Author folded this installed-flavor header helper into omacom/omarchy#12249. Retain that relationship and its Broadcom/T2 use case; do not install a second header-selection helper alongside the selected stock-kernel repair. | Already closed; retain evidence and credit. No action requested. |\n| [omacom/omarchy#11897](https://github.com/omacom/omarchy/pull/11897) — @ryanrhughes | merged | **context**: Merged hardware DKMS header foundation for linux-omarchy; retained as landed context, not newly implemented code in this roll-up. | Already merged; retain evidence and credit. No action requested. |\n| [omacom/omarchy#11898](https://github.com/omacom/omarchy/pull/11898) — @ryanrhughes | merged | **context**: Merged 4.0.4 backport of omacom/omarchy#11897. Preserve release-branch history separately from the current quattro candidate. | Already merged; retain evidence and credit. No action requested. |\n| [omacom/omarchy#11900](https://github.com/omacom/omarchy/pull/11900) — @ryanrhughes | merged | **context**: Merged base-header foundation. | Already merged; retain evidence and credit. No action requested. |\n| [omacom/omarchy#11901](https://github.com/omacom/omarchy/pull/11901) — @ryanrhughes | merged | **context**: Merged 4.0.4 header foundation. | Already merged; retain evidence and credit. No action requested. |\n| [omacom/omarchy#12074](https://github.com/omacom/omarchy/pull/12074) — @oliverox | open | **included**: Complete stock-kernel header repair migration; added local fixtures preserve the implementation. | Consider closure only after maintainers accept preserved behavior and hardware coverage. |\n| [omacom/omarchy#12090](https://github.com/omacom/omarchy/pull/12090) — @paulogeyer | open | **alternative**: Competing matching-header migration; retain for coverage comparison instead of applying duplicate migrations. | Retain for comparison; do not stack competing implementations automatically. |\n| [omacom/omarchy#12249](https://github.com/omacom/omarchy/pull/12249) — @Chessing234 | open | **alternative**: Boot-kernel alternative with a recorded failing pilot result; its distinct assumptions remain visible. | Retain for comparison; do not stack competing implementations automatically. |\n| [omacom/omarchy#9692](https://github.com/omacom/omarchy/pull/9692) — @peterholko | open | **superseded**: The wl-to-DKMS behavior is already on the target; this is migration history, not new code in P02. | Maintainers may assess the named successor before closure. |\n\n## Validation and attribution\n\nRequired fresh-image checks are satisfied, with qualified reruns. The full source suite passed 273 files with two disclosed skips, but repeated NetworkManager Polkit failures during that suite temporarily locked its test account. The following password/desktop/recovery checks failed there and passed separately in a clean overlay of the same ISO; the original aggregate remains failed. The first build attempt also failed one libfprint USB-emulation test; unchanged-source isolated repeats, two complete suites and normal package checks passed afterward. That intermittent build-test failure remains documented, and its cause is not established. VM fixtures and DKMS builds do not establish physical device behavior. Physical Wi-Fi, audio, camera, Touch Bar, fingerprint, graphics and suspend behavior remain unverified by this effort.\n\nOriginal source histories remain linked above. Source-authored commits already included in the roll-ups remain ancestors of this revision; additional copied contributions receive native attribution. [Original attribution mapping](https://github.com/andrew-boyd/omarchy/blob/intel-mac/review-index/AUTHORSHIP.md). No original PR is edited or closed by this effort.\n", "created_at": "2026-09-20T21:00:07Z", "updated_at": "2026-09-27T19:29:10Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "c74e4a48444ae63b9f4ff7c5ff95af855a528de0", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [{"id": 8709137323, "node_id": "LA_kwDOO0Cobs8AAAACBxrjqw", "url": "https://api.github.com/repos/omacom/omarchy/labels/bug", "name": "bug", "color": "d73a4a", "default": true, "description": "Something isn't working", "archived_at": null, "archived_by": null}, {"id": 9526480301, "node_id": "LA_kwDOO0Cobs8AAAACN9KNrQ", "url": "https://api.github.com/repos/omacom/omarchy/labels/compatibility", "name": "compatibility", "color": "ae5cfe", "default": false, "description": "Make Omarchy work better on everything!", "archived_at": null, "archived_by": null}], "milestone": null, "draft": true, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/12680/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/12680/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/12680/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/803260c8feff6d9ed5dbac60d5f630cd45ae1b56", "head": {"label": "andrew-boyd:intel-mac/p02-kernel-headers", "ref": "intel-mac/p02-kernel-headers", "sha": "803260c8feff6d9ed5dbac60d5f630cd45ae1b56", "user": {"login": "andrew-boyd", "id": 2946356, "node_id": "MDQ6VXNlcjI5NDYzNTY=", "avatar_url": "https://avatars.githubusercontent.com/u/2946356?v=4", "gravatar_id": "", "url": "https://api.github.com/users/andrew-boyd", "html_url": "https://github.com/andrew-boyd", "followers_url": "https://api.github.com/users/andrew-boyd/followers", "following_url": "https://api.github.com/users/andrew-boyd/following{/other_user}", "gists_url": "https://api.github.com/users/andrew-boyd/gists{/gist_id}", "starred_url": "https://api.github.com/users/andrew-boyd/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/andrew-boyd/subscriptions", "organizations_url": "https://api.github.com/users/andrew-boyd/orgs", "repos_url": "https://api.github.com/users/andrew-boyd/repos", "events_url": "https://api.github.com/users/andrew-boyd/events{/privacy}", "received_events_url": "https://api.github.com/users/andrew-boyd/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1360607515, "node_id": "R_kgDOURk5Gw", "name": "omarchy", "full_name": "andrew-boyd/omarchy", "private": false, "owner": {"login": "andrew-boyd", "id": 2946356, "node_id": "MDQ6VXNlcjI5NDYzNTY=", "avatar_url": "https://avatars.githubusercontent.com/u/2946356?v=4", "gravatar_id": "", "url": "https://api.github.com/users/andrew-boyd", "html_url": "https://github.com/andrew-boyd", "followers_url": "https://api.github.com/users/andrew-boyd/followers", "following_url": "https://api.github.com/users/andrew-boyd/following{/other_user}", "gists_url": "https://api.github.com/users/andrew-boyd/gists{/gist_id}", "starred_url": "https://api.github.com/users/andrew-boyd/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/andrew-boyd/subscriptions", "organizations_url": "https://api.github.com/users/andrew-boyd/orgs", "repos_url": "https://api.github.com/users/andrew-boyd/repos", "events_url": "https://api.github.com/users/andrew-boyd/events{/privacy}", "received_events_url": "https://api.github.com/users/andrew-boyd/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/andrew-boyd/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/andrew-boyd/omarchy", "forks_url": "https://api.github.com/repos/andrew-boyd/omarchy/forks", "keys_url": "https://api.github.com/repos/andrew-boyd/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/andrew-boyd/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/andrew-boyd/omarchy/teams", "hooks_url": "https://api.github.com/repos/andrew-boyd/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/andrew-boyd/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/andrew-boyd/omarchy/events", "assignees_url": "https://api.github.com/repos/andrew-boyd/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/andrew-boyd/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/andrew-boyd/omarchy/tags", "blobs_url": "https://api.github.com/repos/andrew-boyd/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/andrew-boyd/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/andrew-boyd/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/andrew-boyd/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/andrew-boyd/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/andrew-boyd/omarchy/languages", "stargazers_url": "https://api.github.com/repos/andrew-boyd/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/andrew-boyd/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/andrew-boyd/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/andrew-boyd/omarchy/subscription", "commits_url": "https://api.github.com/repos/andrew-boyd/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/andrew-boyd/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/andrew-boyd/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/andrew-boyd/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/andrew-boyd/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/andrew-boyd/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/andrew-boyd/omarchy/merges", "archive_url": "https://api.github.com/repos/andrew-boyd/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/andrew-boyd/omarchy/downloads", "issues_url": "https://api.github.com/repos/andrew-boyd/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/andrew-boyd/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/andrew-boyd/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/andrew-boyd/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/andrew-boyd/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/andrew-boyd/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/andrew-boyd/omarchy/deployments", "created_at": "2026-09-07T19:43:21Z", "updated_at": "2026-09-07T19:43:21Z", "pushed_at": "2026-09-29T17:42:06Z", "git_url": "git://github.com/andrew-boyd/omarchy.git", "ssh_url": "git@github.com:andrew-boyd/omarchy.git", "clone_url": "https://github.com/andrew-boyd/omarchy.git", "svn_url": "https://github.com/andrew-boyd/omarchy", "homepage": "https://omarchy.org", "size": 414703, "stargazers_count": 0, "watchers_count": 0, "language": null, "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 6, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 6, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "8f324c90b82790d31ab33565441e07cbdb8d2308", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12680"}, "html": {"href": "https://github.com/omacom/omarchy/pull/12680"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12680"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12680/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12680/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12680/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/803260c8feff6d9ed5dbac60d5f630cd45ae1b56"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/12649", "id": 4585008658, "node_id": "PR_kwDOO0Cobs8AAAABEUmuEg", "html_url": "https://github.com/omacom/omarchy/pull/12649", "diff_url": "https://github.com/omacom/omarchy/pull/12649.diff", "patch_url": "https://github.com/omacom/omarchy/pull/12649.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/12649", "number": 12649, "state": "open", "locked": false, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "user": {"login": "ujo4eva", "id": 92157639, "node_id": "U_kgDOBX42xw", "avatar_url": "https://avatars.githubusercontent.com/u/92157639?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ujo4eva", "html_url": "https://github.com/ujo4eva", "followers_url": "https://api.github.com/users/ujo4eva/followers", "following_url": "https://api.github.com/users/ujo4eva/following{/other_user}", "gists_url": "https://api.github.com/users/ujo4eva/gists{/gist_id}", "starred_url": "https://api.github.com/users/ujo4eva/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ujo4eva/subscriptions", "organizations_url": "https://api.github.com/users/ujo4eva/orgs", "repos_url": "https://api.github.com/users/ujo4eva/repos", "events_url": "https://api.github.com/users/ujo4eva/events{/privacy}", "received_events_url": "https://api.github.com/users/ujo4eva/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W).\n\nOnly trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole.\n\nSplit out from #6845 per @bjarneo's request — that PR grew to cover 3 failure modes and was closed as a dup of #10392, which only handles multi-battery percentage and keeps this bug. This is the minimal fix for #6895 with regression tests for both empty-read cases.\n\nFixes #6895.\nExtracted from #6845 (`3c40745`).\n\nVerified: existing `battery-status-test.sh` + 2 new ENODEV cases pass.\n", "created_at": "2026-09-20T16:46:58Z", "updated_at": "2026-09-27T19:29:00Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "4026ff9b29f85b847182b66db01bedf78a287022", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [{"id": 8709137323, "node_id": "LA_kwDOO0Cobs8AAAACBxrjqw", "url": "https://api.github.com/repos/omacom/omarchy/labels/bug", "name": "bug", "color": "d73a4a", "default": true, "description": "Something isn't working", "archived_at": null, "archived_by": null}, {"id": 9526480301, "node_id": "LA_kwDOO0Cobs8AAAACN9KNrQ", "url": "https://api.github.com/repos/omacom/omarchy/labels/compatibility", "name": "compatibility", "color": "ae5cfe", "default": false, "description": "Make Omarchy work better on everything!", "archived_at": null, "archived_by": null}], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/12649/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/12649/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/12649/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/50a935005cd82b5726ae21a19e86069b57f7ba21", "head": {"label": "ujo4eva:fix/battery-enodev-fallback", "ref": "fix/battery-enodev-fallback", "sha": "50a935005cd82b5726ae21a19e86069b57f7ba21", "user": {"login": "ujo4eva", "id": 92157639, "node_id": "U_kgDOBX42xw", "avatar_url": "https://avatars.githubusercontent.com/u/92157639?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ujo4eva", "html_url": "https://github.com/ujo4eva", "followers_url": "https://api.github.com/users/ujo4eva/followers", "following_url": "https://api.github.com/users/ujo4eva/following{/other_user}", "gists_url": "https://api.github.com/users/ujo4eva/gists{/gist_id}", "starred_url": "https://api.github.com/users/ujo4eva/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ujo4eva/subscriptions", "organizations_url": "https://api.github.com/users/ujo4eva/orgs", "repos_url": "https://api.github.com/users/ujo4eva/repos", "events_url": "https://api.github.com/users/ujo4eva/events{/privacy}", "received_events_url": "https://api.github.com/users/ujo4eva/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1335575801, "node_id": "R_kgDOT5tE-Q", "name": "omarchy", "full_name": "ujo4eva/omarchy", "private": false, "owner": {"login": "ujo4eva", "id": 92157639, "node_id": "U_kgDOBX42xw", "avatar_url": "https://avatars.githubusercontent.com/u/92157639?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ujo4eva", "html_url": "https://github.com/ujo4eva", "followers_url": "https://api.github.com/users/ujo4eva/followers", "following_url": "https://api.github.com/users/ujo4eva/following{/other_user}", "gists_url": "https://api.github.com/users/ujo4eva/gists{/gist_id}", "starred_url": "https://api.github.com/users/ujo4eva/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ujo4eva/subscriptions", "organizations_url": "https://api.github.com/users/ujo4eva/orgs", "repos_url": "https://api.github.com/users/ujo4eva/repos", "events_url": "https://api.github.com/users/ujo4eva/events{/privacy}", "received_events_url": "https://api.github.com/users/ujo4eva/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/ujo4eva/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/ujo4eva/omarchy", "forks_url": "https://api.github.com/repos/ujo4eva/omarchy/forks", "keys_url": "https://api.github.com/repos/ujo4eva/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/ujo4eva/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/ujo4eva/omarchy/teams", "hooks_url": "https://api.github.com/repos/ujo4eva/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/ujo4eva/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/ujo4eva/omarchy/events", "assignees_url": "https://api.github.com/repos/ujo4eva/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/ujo4eva/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/ujo4eva/omarchy/tags", "blobs_url": "https://api.github.com/repos/ujo4eva/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/ujo4eva/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/ujo4eva/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/ujo4eva/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/ujo4eva/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/ujo4eva/omarchy/languages", "stargazers_url": "https://api.github.com/repos/ujo4eva/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/ujo4eva/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/ujo4eva/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/ujo4eva/omarchy/subscription", "commits_url": "https://api.github.com/repos/ujo4eva/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/ujo4eva/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/ujo4eva/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/ujo4eva/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/ujo4eva/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/ujo4eva/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/ujo4eva/omarchy/merges", "archive_url": "https://api.github.com/repos/ujo4eva/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/ujo4eva/omarchy/downloads", "issues_url": "https://api.github.com/repos/ujo4eva/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/ujo4eva/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/ujo4eva/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/ujo4eva/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/ujo4eva/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/ujo4eva/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/ujo4eva/omarchy/deployments", "created_at": "2026-08-16T02:50:43Z", "updated_at": "2026-09-04T05:59:59Z", "pushed_at": "2026-09-26T01:02:36Z", "git_url": "git://github.com/ujo4eva/omarchy.git", "ssh_url": "git@github.com:ujo4eva/omarchy.git", "clone_url": "https://github.com/ujo4eva/omarchy.git", "svn_url": "https://github.com/ujo4eva/omarchy", "homepage": "https://omarchy.org", "size": 241020, "stargazers_count": 0, "watchers_count": 0, "language": "Shell", "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 0, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 0, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "e38c1d1289252d2adb96372eeac48d02e489c5b7", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12649"}, "html": {"href": "https://github.com/omacom/omarchy/pull/12649"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12649"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12649/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12649/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12649/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/50a935005cd82b5726ae21a19e86069b57f7ba21"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/12090", "id": 4546565577, "node_id": "PR_kwDOO0Cobs8AAAABDv8VyQ", "html_url": "https://github.com/omacom/omarchy/pull/12090", "diff_url": "https://github.com/omacom/omarchy/pull/12090.diff", "patch_url": "https://github.com/omacom/omarchy/pull/12090.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/12090", "number": 12090, "state": "open", "locked": false, "title": "Install matching kernel headers before broadcom-wl-dkms", "user": {"login": "paulogeyer", "id": 348933, "node_id": "MDQ6VXNlcjM0ODkzMw==", "avatar_url": "https://avatars.githubusercontent.com/u/348933?v=4", "gravatar_id": "", "url": "https://api.github.com/users/paulogeyer", "html_url": "https://github.com/paulogeyer", "followers_url": "https://api.github.com/users/paulogeyer/followers", "following_url": "https://api.github.com/users/paulogeyer/following{/other_user}", "gists_url": "https://api.github.com/users/paulogeyer/gists{/gist_id}", "starred_url": "https://api.github.com/users/paulogeyer/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/paulogeyer/subscriptions", "organizations_url": "https://api.github.com/users/paulogeyer/orgs", "repos_url": "https://api.github.com/users/paulogeyer/repos", "events_url": "https://api.github.com/users/paulogeyer/events{/privacy}", "received_events_url": "https://api.github.com/users/paulogeyer/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "Closes https://github.com/omacom/omarchy/issues/10975\n\n## Summary\n\nThe 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot.\n\nInstall matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels.\n\n## Test plan\n\n```bash\nbash test/shell.d/bcm43xx-headers-test.sh\n```", "created_at": "2026-09-16T10:28:25Z", "updated_at": "2026-10-01T04:31:40Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "dcb9afa983f13b4a816696db1343842097fa3ef3", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [{"id": 8709137323, "node_id": "LA_kwDOO0Cobs8AAAACBxrjqw", "url": "https://api.github.com/repos/omacom/omarchy/labels/bug", "name": "bug", "color": "d73a4a", "default": true, "description": "Something isn't working", "archived_at": null, "archived_by": null}, {"id": 9526480301, "node_id": "LA_kwDOO0Cobs8AAAACN9KNrQ", "url": "https://api.github.com/repos/omacom/omarchy/labels/compatibility", "name": "compatibility", "color": "ae5cfe", "default": false, "description": "Make Omarchy work better on everything!", "archived_at": null, "archived_by": null}], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/12090/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/12090/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/12090/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/40fc412e5e7fd6b9a5c883e7b4ac361b8b4544b4", "head": {"label": "paulogeyer:fix/10975-broadcom-headers", "ref": "fix/10975-broadcom-headers", "sha": "40fc412e5e7fd6b9a5c883e7b4ac361b8b4544b4", "user": {"login": "paulogeyer", "id": 348933, "node_id": "MDQ6VXNlcjM0ODkzMw==", "avatar_url": "https://avatars.githubusercontent.com/u/348933?v=4", "gravatar_id": "", "url": "https://api.github.com/users/paulogeyer", "html_url": "https://github.com/paulogeyer", "followers_url": "https://api.github.com/users/paulogeyer/followers", "following_url": "https://api.github.com/users/paulogeyer/following{/other_user}", "gists_url": "https://api.github.com/users/paulogeyer/gists{/gist_id}", "starred_url": "https://api.github.com/users/paulogeyer/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/paulogeyer/subscriptions", "organizations_url": "https://api.github.com/users/paulogeyer/orgs", "repos_url": "https://api.github.com/users/paulogeyer/repos", "events_url": "https://api.github.com/users/paulogeyer/events{/privacy}", "received_events_url": "https://api.github.com/users/paulogeyer/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1372861390, "node_id": "R_kgDOUdQzzg", "name": "omarchy", "full_name": "paulogeyer/omarchy", "private": false, "owner": {"login": "paulogeyer", "id": 348933, "node_id": "MDQ6VXNlcjM0ODkzMw==", "avatar_url": "https://avatars.githubusercontent.com/u/348933?v=4", "gravatar_id": "", "url": "https://api.github.com/users/paulogeyer", "html_url": "https://github.com/paulogeyer", "followers_url": "https://api.github.com/users/paulogeyer/followers", "following_url": "https://api.github.com/users/paulogeyer/following{/other_user}", "gists_url": "https://api.github.com/users/paulogeyer/gists{/gist_id}", "starred_url": "https://api.github.com/users/paulogeyer/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/paulogeyer/subscriptions", "organizations_url": "https://api.github.com/users/paulogeyer/orgs", "repos_url": "https://api.github.com/users/paulogeyer/repos", "events_url": "https://api.github.com/users/paulogeyer/events{/privacy}", "received_events_url": "https://api.github.com/users/paulogeyer/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/paulogeyer/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/paulogeyer/omarchy", "forks_url": "https://api.github.com/repos/paulogeyer/omarchy/forks", "keys_url": "https://api.github.com/repos/paulogeyer/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/paulogeyer/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/paulogeyer/omarchy/teams", "hooks_url": "https://api.github.com/repos/paulogeyer/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/paulogeyer/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/paulogeyer/omarchy/events", "assignees_url": "https://api.github.com/repos/paulogeyer/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/paulogeyer/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/paulogeyer/omarchy/tags", "blobs_url": "https://api.github.com/repos/paulogeyer/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/paulogeyer/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/paulogeyer/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/paulogeyer/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/paulogeyer/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/paulogeyer/omarchy/languages", "stargazers_url": "https://api.github.com/repos/paulogeyer/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/paulogeyer/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/paulogeyer/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/paulogeyer/omarchy/subscription", "commits_url": "https://api.github.com/repos/paulogeyer/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/paulogeyer/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/paulogeyer/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/paulogeyer/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/paulogeyer/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/paulogeyer/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/paulogeyer/omarchy/merges", "archive_url": "https://api.github.com/repos/paulogeyer/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/paulogeyer/omarchy/downloads", "issues_url": "https://api.github.com/repos/paulogeyer/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/paulogeyer/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/paulogeyer/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/paulogeyer/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/paulogeyer/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/paulogeyer/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/paulogeyer/omarchy/deployments", "created_at": "2026-09-16T10:19:54Z", "updated_at": "2026-09-16T10:19:54Z", "pushed_at": "2026-10-01T10:30:52Z", "git_url": "git://github.com/paulogeyer/omarchy.git", "ssh_url": "git@github.com:paulogeyer/omarchy.git", "clone_url": "https://github.com/paulogeyer/omarchy.git", "svn_url": "https://github.com/paulogeyer/omarchy", "homepage": "https://omarchy.org", "size": 248843, "stargazers_count": 0, "watchers_count": 0, "language": null, "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 0, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 0, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "2fbac0c8e88eca704af1650ce721a494bd11a3d0", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12090"}, "html": {"href": "https://github.com/omacom/omarchy/pull/12090"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12090"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12090/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12090/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12090/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/40fc412e5e7fd6b9a5c883e7b4ac361b8b4544b4"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}, {"url": "https://api.github.com/repos/omacom/omarchy/pulls/12074", "id": 4545496916, "node_id": "PR_kwDOO0Cobs8AAAABDu7HVA", "html_url": "https://github.com/omacom/omarchy/pull/12074", "diff_url": "https://github.com/omacom/omarchy/pull/12074.diff", "patch_url": "https://github.com/omacom/omarchy/pull/12074.patch", "issue_url": "https://api.github.com/repos/omacom/omarchy/issues/12074", "number": 12074, "state": "open", "locked": false, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "user": {"login": "oliverox", "id": 874858, "node_id": "MDQ6VXNlcjg3NDg1OA==", "avatar_url": "https://avatars.githubusercontent.com/u/874858?v=4", "gravatar_id": "", "url": "https://api.github.com/users/oliverox", "html_url": "https://github.com/oliverox", "followers_url": "https://api.github.com/users/oliverox/followers", "following_url": "https://api.github.com/users/oliverox/following{/other_user}", "gists_url": "https://api.github.com/users/oliverox/gists{/gist_id}", "starred_url": "https://api.github.com/users/oliverox/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/oliverox/subscriptions", "organizations_url": "https://api.github.com/users/oliverox/orgs", "repos_url": "https://api.github.com/users/oliverox/repos", "events_url": "https://api.github.com/users/oliverox/events{/privacy}", "received_events_url": "https://api.github.com/users/oliverox/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds:\n\n```\nrunning '70-dkms-install.hook'...\n==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271.\n```\n\n2012-2015 MacBooks with a BCM4360 or BCM4331 then come back from the Quattro upgrade with no driver bound and no Wi-Fi device at all. The installer's `fix-bcm43xx.sh` never runs on those machines, and `1789444024` only covers `linux-omarchy` and `linux-t2`.\n\n`1789325478` will give `linux-omarchy` its headers, but it deliberately leaves the stock kernel installed as the boot fallback. On these Macs that fallback still has no Wi-Fi, which is usually the way back to a working system.\n\nThis migration installs headers for any installed Arch kernel (`linux`, `linux-lts`, `linux-zen`, `linux-hardened`) when `broadcom-wl-dkms` is present. The dkms pacman hook triggers on `usr/lib/modules/*/build/include/`, so installing the headers builds the module.\n\n## Testing\n\n- `test/shell.d/broadcom-wl-headers-migration-test.sh` covers the repair, idempotency, leaving `linux-omarchy` to its own migration, skipping machines without `broadcom-wl-dkms`, and propagating a failed install. It fails when the install line is removed.\n- `test/shell.d/kernel-headers-migration-test.sh` and the other migration tests still pass.\n- Verified on a MacBook (BCM4360, `14e4:43a0`) upgraded to 4.0.3 on stock `linux` 7.2.3. Installing `linux-headers` built `wl` through the hook, `modprobe wl` brought up `wlp3s0`, and NetworkManager connected.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nFixes #10975", "created_at": "2026-09-16T08:20:51Z", "updated_at": "2026-10-01T04:29:47Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "c5b6cab364c2d43d2e547d135dc11c68fcbf5b7f", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [{"id": 8709137323, "node_id": "LA_kwDOO0Cobs8AAAACBxrjqw", "url": "https://api.github.com/repos/omacom/omarchy/labels/bug", "name": "bug", "color": "d73a4a", "default": true, "description": "Something isn't working", "archived_at": null, "archived_by": null}, {"id": 9526480301, "node_id": "LA_kwDOO0Cobs8AAAACN9KNrQ", "url": "https://api.github.com/repos/omacom/omarchy/labels/compatibility", "name": "compatibility", "color": "ae5cfe", "default": false, "description": "Make Omarchy work better on everything!", "archived_at": null, "archived_by": null}, {"id": 12176849619, "node_id": "LA_kwDOO0Cobs8AAAAC1cv60w", "url": "https://api.github.com/repos/omacom/omarchy/labels/verified", "name": "verified", "color": "159c84", "default": false, "description": "Omarchy Triage has verified that this issue is ready for final review", "archived_at": null, "archived_by": null}, {"id": 12385305356, "node_id": "LA_kwDOO0Cobs8AAAAC4jjDDA", "url": "https://api.github.com/repos/omacom/omarchy/labels/ready", "name": "ready", "color": "E244C0", "default": false, "description": "Good to merge", "archived_at": null, "archived_by": null}], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/omacom/omarchy/pulls/12074/commits", "review_comments_url": "https://api.github.com/repos/omacom/omarchy/pulls/12074/comments", "review_comment_url": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/omacom/omarchy/issues/12074/comments", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/18378142c12b85565c460ddfb1279226d42c977e", "head": {"label": "oliverox:fix-broadcom-wl-fallback-kernel-headers", "ref": "fix-broadcom-wl-fallback-kernel-headers", "sha": "18378142c12b85565c460ddfb1279226d42c977e", "user": {"login": "oliverox", "id": 874858, "node_id": "MDQ6VXNlcjg3NDg1OA==", "avatar_url": "https://avatars.githubusercontent.com/u/874858?v=4", "gravatar_id": "", "url": "https://api.github.com/users/oliverox", "html_url": "https://github.com/oliverox", "followers_url": "https://api.github.com/users/oliverox/followers", "following_url": "https://api.github.com/users/oliverox/following{/other_user}", "gists_url": "https://api.github.com/users/oliverox/gists{/gist_id}", "starred_url": "https://api.github.com/users/oliverox/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/oliverox/subscriptions", "organizations_url": "https://api.github.com/users/oliverox/orgs", "repos_url": "https://api.github.com/users/oliverox/repos", "events_url": "https://api.github.com/users/oliverox/events{/privacy}", "received_events_url": "https://api.github.com/users/oliverox/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "repo": {"id": 1372734374, "node_id": "R_kgDOUdJDpg", "name": "omarchy", "full_name": "oliverox/omarchy", "private": false, "owner": {"login": "oliverox", "id": 874858, "node_id": "MDQ6VXNlcjg3NDg1OA==", "avatar_url": "https://avatars.githubusercontent.com/u/874858?v=4", "gravatar_id": "", "url": "https://api.github.com/users/oliverox", "html_url": "https://github.com/oliverox", "followers_url": "https://api.github.com/users/oliverox/followers", "following_url": "https://api.github.com/users/oliverox/following{/other_user}", "gists_url": "https://api.github.com/users/oliverox/gists{/gist_id}", "starred_url": "https://api.github.com/users/oliverox/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/oliverox/subscriptions", "organizations_url": "https://api.github.com/users/oliverox/orgs", "repos_url": "https://api.github.com/users/oliverox/repos", "events_url": "https://api.github.com/users/oliverox/events{/privacy}", "received_events_url": "https://api.github.com/users/oliverox/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/oliverox/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": true, "url": "https://api.github.com/repos/oliverox/omarchy", "forks_url": "https://api.github.com/repos/oliverox/omarchy/forks", "keys_url": "https://api.github.com/repos/oliverox/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/oliverox/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/oliverox/omarchy/teams", "hooks_url": "https://api.github.com/repos/oliverox/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/oliverox/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/oliverox/omarchy/events", "assignees_url": "https://api.github.com/repos/oliverox/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/oliverox/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/oliverox/omarchy/tags", "blobs_url": "https://api.github.com/repos/oliverox/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/oliverox/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/oliverox/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/oliverox/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/oliverox/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/oliverox/omarchy/languages", "stargazers_url": "https://api.github.com/repos/oliverox/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/oliverox/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/oliverox/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/oliverox/omarchy/subscription", "commits_url": "https://api.github.com/repos/oliverox/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/oliverox/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/oliverox/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/oliverox/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/oliverox/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/oliverox/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/oliverox/omarchy/merges", "archive_url": "https://api.github.com/repos/oliverox/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/oliverox/omarchy/downloads", "issues_url": "https://api.github.com/repos/oliverox/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/oliverox/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/oliverox/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/oliverox/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/oliverox/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/oliverox/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/oliverox/omarchy/deployments", "created_at": "2026-09-16T08:19:30Z", "updated_at": "2026-09-16T08:19:30Z", "pushed_at": "2026-10-01T04:40:04Z", "git_url": "git://github.com/oliverox/omarchy.git", "ssh_url": "git@github.com:oliverox/omarchy.git", "clone_url": "https://github.com/oliverox/omarchy.git", "svn_url": "https://github.com/oliverox/omarchy", "homepage": "https://omarchy.org", "size": 247621, "stargazers_count": 0, "watchers_count": 0, "language": null, "has_issues": false, "has_projects": true, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 0, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 0, "open_issues": 0, "watchers": 0, "default_branch": "quattro"}}, "base": {"label": "omacom:quattro", "ref": "quattro", "sha": "2fbac0c8e88eca704af1650ce721a494bd11a3d0", "user": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 994093166, "node_id": "R_kgDOO0Cobg", "name": "omarchy", "full_name": "omacom/omarchy", "private": false, "owner": {"login": "omacom", "id": 219015873, "node_id": "O_kgDODQ3qwQ", "avatar_url": "https://avatars.githubusercontent.com/u/219015873?v=4", "gravatar_id": "", "url": "https://api.github.com/users/omacom", "html_url": "https://github.com/omacom", "followers_url": "https://api.github.com/users/omacom/followers", "following_url": "https://api.github.com/users/omacom/following{/other_user}", "gists_url": "https://api.github.com/users/omacom/gists{/gist_id}", "starred_url": "https://api.github.com/users/omacom/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/omacom/subscriptions", "organizations_url": "https://api.github.com/users/omacom/orgs", "repos_url": "https://api.github.com/users/omacom/repos", "events_url": "https://api.github.com/users/omacom/events{/privacy}", "received_events_url": "https://api.github.com/users/omacom/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/omacom/omarchy", "description": "Beautiful, Modern & Opinionated Linux", "fork": false, "url": "https://api.github.com/repos/omacom/omarchy", "forks_url": "https://api.github.com/repos/omacom/omarchy/forks", "keys_url": "https://api.github.com/repos/omacom/omarchy/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/omacom/omarchy/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/omacom/omarchy/teams", "hooks_url": "https://api.github.com/repos/omacom/omarchy/hooks", "issue_events_url": "https://api.github.com/repos/omacom/omarchy/issues/events{/number}", "events_url": "https://api.github.com/repos/omacom/omarchy/events", "assignees_url": "https://api.github.com/repos/omacom/omarchy/assignees{/user}", "branches_url": "https://api.github.com/repos/omacom/omarchy/branches{/branch}", "tags_url": "https://api.github.com/repos/omacom/omarchy/tags", "blobs_url": "https://api.github.com/repos/omacom/omarchy/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/omacom/omarchy/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/omacom/omarchy/git/refs{/sha}", "trees_url": "https://api.github.com/repos/omacom/omarchy/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/omacom/omarchy/statuses/{sha}", "languages_url": "https://api.github.com/repos/omacom/omarchy/languages", "stargazers_url": "https://api.github.com/repos/omacom/omarchy/stargazers", "contributors_url": "https://api.github.com/repos/omacom/omarchy/contributors", "subscribers_url": "https://api.github.com/repos/omacom/omarchy/subscribers", "subscription_url": "https://api.github.com/repos/omacom/omarchy/subscription", "commits_url": "https://api.github.com/repos/omacom/omarchy/commits{/sha}", "git_commits_url": "https://api.github.com/repos/omacom/omarchy/git/commits{/sha}", "comments_url": "https://api.github.com/repos/omacom/omarchy/comments{/number}", "issue_comment_url": "https://api.github.com/repos/omacom/omarchy/issues/comments{/number}", "contents_url": "https://api.github.com/repos/omacom/omarchy/contents/{+path}", "compare_url": "https://api.github.com/repos/omacom/omarchy/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/omacom/omarchy/merges", "archive_url": "https://api.github.com/repos/omacom/omarchy/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/omacom/omarchy/downloads", "issues_url": "https://api.github.com/repos/omacom/omarchy/issues{/number}", "pulls_url": "https://api.github.com/repos/omacom/omarchy/pulls{/number}", "milestones_url": "https://api.github.com/repos/omacom/omarchy/milestones{/number}", "notifications_url": "https://api.github.com/repos/omacom/omarchy/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/omacom/omarchy/labels{/name}", "releases_url": "https://api.github.com/repos/omacom/omarchy/releases{/id}", "deployments_url": "https://api.github.com/repos/omacom/omarchy/deployments", "created_at": "2025-06-01T07:26:22Z", "updated_at": "2026-10-01T18:13:49Z", "pushed_at": "2026-10-01T11:36:26Z", "git_url": "git://github.com/omacom/omarchy.git", "ssh_url": "git@github.com:omacom/omarchy.git", "clone_url": "https://github.com/omacom/omarchy.git", "svn_url": "https://github.com/omacom/omarchy", "homepage": "https://omarchy.org", "size": 249132, "stargazers_count": 43746, "watchers_count": 43746, "language": "Shell", "has_issues": true, "has_projects": false, "has_downloads": false, "has_wiki": false, "has_pages": false, "has_discussions": true, "forks_count": 5148, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 4955, "license": {"key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz"}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 5148, "open_issues": 4955, "watchers": 43746, "default_branch": "quattro"}}, "_links": {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12074"}, "html": {"href": "https://github.com/omacom/omarchy/pull/12074"}, "issue": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12074"}, "comments": {"href": "https://api.github.com/repos/omacom/omarchy/issues/12074/comments"}, "review_comments": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12074/comments"}, "review_comment": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/12074/commits"}, "statuses": {"href": "https://api.github.com/repos/omacom/omarchy/statuses/18378142c12b85565c460ddfb1279226d42c977e"}}, "author_association": "NONE", "auto_merge": null, "assignee": null, "active_lock_reason": null}], "digest": "790661f9cc866a9afe24cb74fb800049964aab0d37c734c96ea1df2066f70426"} \ No newline at end of file diff --git a/crates/tranche-core/tests/fixture/out/batches.json b/crates/tranche-core/tests/fixture/out/batches.json new file mode 100644 index 0000000..2522dab --- /dev/null +++ b/crates/tranche-core/tests/fixture/out/batches.json @@ -0,0 +1 @@ +{"format_version": 3, "repo": "omacom/omarchy", "dupes_digest": "9134de30ccfb58390e5e9c73ca7218810c9c970846a9cbb4824526312c5170b5", "batch_size": 5, "meaning": "A batch is 5 PRs merged together as one tranche (issue #4). Jev determines the composition: same_change groups are atomic and combine into ONE pull request inside their batch. Batches are disjoint: every PR belongs to at most one batch. Ordered security-first, then risk band and evidenced idle lower bound. Parked PRs are excluded before packing (issue #8). Model-suggested, not verified safe to merge.", "batches": [{"ordinal": 1, "id": "B001", "members": [13459, 13463, 13613], "count": 3, "target": "merged together as one tranche", "same_change_groups": 1, "security_members": 0, "average_risk": 0.86, "created": "2026-09-27T21:16:20Z", "review_prompt": "You are reviewing Omarchy pre-release batch B001 (3 PRs to be merged together as one tranche).\n\nPull requests in this batch:\n- #13459: Scale clock panel hero date with fontScale — https://github.com/omacom/omarchy/pull/13459\n- #13463: Scale the clock panel hero text with fontScale — https://github.com/omacom/omarchy/pull/13463\n- #13613: Scale clock panel hero date with fontScale and fit long months — https://github.com/omacom/omarchy/pull/13613\n\nWork through the batch methodically:\n1. Read every PR fully — description, diff, and review comments. For PRs Jev flagged as the same change, verify they truly overlap and identify the strongest implementation of each.\n2. Map dependencies between the PRs (shared files, ordering constraints, conflicts) and check each PR's CI status.\n3. Produce ONE unified proposal for the batch: what merges, in which order, what gets squashed or dropped, and why — as a single coherent plan, not per-PR verdicts.\n4. Verify the plan: does the combined result still build and pass tests? Any PR that cannot be verified stays out — say so explicitly.\n5. Deliver: (a) the unified proposal, (b) a step-by-step merge plan with exact commands, (c) risks with mitigations, (d) an explicit list of anything excluded and why.\n\nFacts over plausibility: base every claim on the actual diffs and CI state, never on titles alone. You are proposing — the human decides."}, {"ordinal": 2, "id": "B002", "members": [13165, 13477, 13645], "count": 3, "target": "merged together as one tranche", "same_change_groups": 1, "security_members": 0, "average_risk": 1.04, "created": "2026-09-24T17:21:00Z", "review_prompt": "You are reviewing Omarchy pre-release batch B002 (3 PRs to be merged together as one tranche).\n\nPull requests in this batch:\n- #13165: Skip placeholder screens when building bars — https://github.com/omacom/omarchy/pull/13165\n- #13477: Skip placeholder and FALLBACK screens when creating bars — https://github.com/omacom/omarchy/pull/13477\n- #13645: Skip placeholder and FALLBACK screens when building bars — https://github.com/omacom/omarchy/pull/13645\n\nWork through the batch methodically:\n1. Read every PR fully — description, diff, and review comments. For PRs Jev flagged as the same change, verify they truly overlap and identify the strongest implementation of each.\n2. Map dependencies between the PRs (shared files, ordering constraints, conflicts) and check each PR's CI status.\n3. Produce ONE unified proposal for the batch: what merges, in which order, what gets squashed or dropped, and why — as a single coherent plan, not per-PR verdicts.\n4. Verify the plan: does the combined result still build and pass tests? Any PR that cannot be verified stays out — say so explicitly.\n5. Deliver: (a) the unified proposal, (b) a step-by-step merge plan with exact commands, (c) risks with mitigations, (d) an explicit list of anything excluded and why.\n\nFacts over plausibility: base every claim on the actual diffs and CI state, never on titles alone. You are proposing — the human decides."}, {"ordinal": 3, "id": "B003", "members": [12649, 12755, 13009], "count": 3, "target": "merged together as one tranche", "same_change_groups": 1, "security_members": 0, "average_risk": 0.99, "created": "2026-09-20T16:46:58Z", "review_prompt": "You are reviewing Omarchy pre-release batch B003 (3 PRs to be merged together as one tranche).\n\nPull requests in this batch:\n- #12649: Keep UPower rate when sysfs power read fails with ENODEV — https://github.com/omacom/omarchy/pull/12649\n- #12755: Keep UPower rate when sysfs power reads fail or are non-numeric — https://github.com/omacom/omarchy/pull/12755\n- #13009: Guard battery sysfs rate against bogus EC readings — https://github.com/omacom/omarchy/pull/13009\n\nWork through the batch methodically:\n1. Read every PR fully — description, diff, and review comments. For PRs Jev flagged as the same change, verify they truly overlap and identify the strongest implementation of each.\n2. Map dependencies between the PRs (shared files, ordering constraints, conflicts) and check each PR's CI status.\n3. Produce ONE unified proposal for the batch: what merges, in which order, what gets squashed or dropped, and why — as a single coherent plan, not per-PR verdicts.\n4. Verify the plan: does the combined result still build and pass tests? Any PR that cannot be verified stays out — say so explicitly.\n5. Deliver: (a) the unified proposal, (b) a step-by-step merge plan with exact commands, (c) risks with mitigations, (d) an explicit list of anything excluded and why.\n\nFacts over plausibility: base every claim on the actual diffs and CI state, never on titles alone. You are proposing — the human decides."}], "security_batches": 0, "same_change_groups": 3, "excluded_review_prs": 0, "parked_prs": 3} \ No newline at end of file diff --git a/crates/tranche-core/tests/fixture/out/clusters.json b/crates/tranche-core/tests/fixture/out/clusters.json new file mode 100644 index 0000000..b090aaf --- /dev/null +++ b/crates/tranche-core/tests/fixture/out/clusters.json @@ -0,0 +1 @@ +{"security-review": [], "hardware-drivers": {"danger": [{"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "author": "oliverox", "risk": 2.82, "finished_form": 1.47, "is_fix": 0.91, "review_effort": 1.75, "security_flag": 0.09, "freshness": "current", "superseded_by": null, "source_digest": "c32cda86fa96924b7725469fbe5847695827876033f38b9d586a5f44a7c4308c", "evidence_digest": "9c764310ee6e05b6fff8c3cf3ae71f45c240cc08ed18c8822d94ffb70d71a837", "head_sha": "18378142c12b85565c460ddfb1279226d42c977e", "url": "https://github.com/omacom/omarchy/pull/12074"}, {"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "author": "paulogeyer", "risk": 3.0, "finished_form": 1.44, "is_fix": 0.96, "review_effort": 2.0, "security_flag": 0.18, "freshness": "current", "superseded_by": null, "source_digest": "95f26920f269f31f593cb53deab475f007a62fd8855a3b80af2f1d2f950f6651", "evidence_digest": "ad25fbf97d81dcbfb377fdf85af0e335c727e20eed5fc9d8ba42c27c5a220091", "head_sha": "40fc412e5e7fd6b9a5c883e7b4ac361b8b4544b4", "url": "https://github.com/omacom/omarchy/pull/12090"}, {"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "author": "andrew-boyd", "risk": 2.8, "finished_form": 0.99, "is_fix": 0.76, "review_effort": 2.65, "security_flag": 0.09, "freshness": "current", "superseded_by": null, "source_digest": "a8c51c7bdb488b23fca665a2fea413d169a8f7181d1d0ead91bb0552e6d98223", "evidence_digest": "c83eb4adb2ecaeb0e085f1ecd7ce80eb2f03c04bfb368dbf4addaf817ea22514", "head_sha": "803260c8feff6d9ed5dbac60d5f630cd45ae1b56", "url": "https://github.com/omacom/omarchy/pull/12680"}], "low": [{"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "author": "ujo4eva", "risk": 1.0, "finished_form": 2.27, "is_fix": 0.97, "review_effort": 1.4, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "36e5a1010498cb1b87696cd5cca52d2b32ab5ec70358e25210f874c71cb28e18", "evidence_digest": "f78454ca5db5b065576c3e5f93486154aeef2bd3c38a71424b211deadd8f9b93", "head_sha": "50a935005cd82b5726ae21a19e86069b57f7ba21", "url": "https://github.com/omacom/omarchy/pull/12649"}, {"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "author": "anandude", "risk": 1.0, "finished_form": 2.48, "is_fix": 0.97, "review_effort": 1.31, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "bfd4502d9e33f1325c7a8dea99787a27aadaeceecc291c079bfa4dea07fa8ca8", "evidence_digest": "781de83ac5183236cd4eab66f7d52dd3be5179d65a077a96ff575631c1cccba5", "head_sha": "370a3b61fbb8f4c358bbb423b5d8c4c97bae33e8", "url": "https://github.com/omacom/omarchy/pull/12755"}, {"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "author": "Kristijan-K", "risk": 0.97, "finished_form": 2.78, "is_fix": 0.95, "review_effort": 1.71, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "c05fda9de7e16cab35b5355be6bdfbe805f072ad135a80ac3f800952abc31593", "evidence_digest": "7a85df8e90c6002d9be1790c6236612b8c041f6032cedd1280e99ce95858ccac", "head_sha": "85b13dcd7d80423448877ef47bfda0f2ebd7f61b", "url": "https://github.com/omacom/omarchy/pull/13009"}]}, "desktop-config": {"low": [{"number": 13165, "title": "Skip placeholder screens when building bars", "author": "dreed47", "risk": 1.01, "finished_form": 1.15, "is_fix": 0.96, "review_effort": 1.85, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "754cd24b36741c61cd3c5e2861ae47f0c7af0a40b97ece426ef135f2ac7d00ab", "evidence_digest": "638cb3e72efed9055911cee03a8ee91cfec17a2d16acd6d5db0432b944c53aa0", "head_sha": "67a5645948c0b2981481ef89bb71a769269ecf54", "url": "https://github.com/omacom/omarchy/pull/13165"}, {"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "author": "AnPod", "risk": 1.08, "finished_form": 2.37, "is_fix": 0.96, "review_effort": 1.12, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "f9630dcf560058b13b68f76395cf58ef8dcdbdf67e906516b418cb234fde68cc", "evidence_digest": "dfd6b9b48d36332717d20cd87c0092a3f353c7a76f10616c9e707bee5f1c2f04", "head_sha": "ec58ce82fdc5521e5109f1760df1fb502f3f45c2", "url": "https://github.com/omacom/omarchy/pull/13477"}, {"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "author": "AnPod", "risk": 1.04, "finished_form": 1.65, "is_fix": 0.93, "review_effort": 1.06, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "200d24c8cbeb01ad4d1093d5bfa60724b1810dbcc840f954f9d211f482233c5f", "evidence_digest": "3ed7bb42a4d99748a46df06890fe0f1980dc14b1c8c661c3ba5561830a8f31f7", "head_sha": "00ef70cbf708e0b1542ea01c4b1d88e3284be76d", "url": "https://github.com/omacom/omarchy/pull/13645"}]}, "user-experience": {"low": [{"number": 13459, "title": "Scale clock panel hero date with fontScale", "author": "AnPod", "risk": 0.93, "finished_form": 2.15, "is_fix": 0.93, "review_effort": 1.01, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "a2e3b06d247af8c7a4a617abecdbf997e9f70e0ac8934c04cf4313fd209106d9", "evidence_digest": "228db4dadf12518446ad7c8f9bcb8fb1cc69a7a61fb3df56df8b68d255de3df1", "head_sha": "d6c2c80815a222a27868c41bf8d2ff3cbf86bc66", "url": "https://github.com/omacom/omarchy/pull/13459"}, {"number": 13463, "title": "Scale the clock panel hero text with fontScale", "author": "AnPod", "risk": 0.87, "finished_form": 1.73, "is_fix": 0.94, "review_effort": 1.03, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "0cffb8d06b6ce02226f74a3f97db90071840e3cff86018239f36d19051301c12", "evidence_digest": "bf696bf0cc001e0fbdbdafea7300d747e1752484dd71ba8c440c309ee069507d", "head_sha": "02cd42f24f5ef7aaaecdeaef68c023973eaea030", "url": "https://github.com/omacom/omarchy/pull/13463"}, {"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "author": "AnPod", "risk": 0.77, "finished_form": 1.33, "is_fix": 0.93, "review_effort": 1.05, "security_flag": 0.02, "freshness": "current", "superseded_by": null, "source_digest": "168553e351ba06424f122b88f0114218b4acff6ffbf7fc05f3ea55c02527275a", "evidence_digest": "9e0036efdb167f48533c9e32ac2502dc3186bf0c42b08dd449af6d7b654dd575", "head_sha": "151b281f28d647691a983141689026b29349e569", "url": "https://github.com/omacom/omarchy/pull/13613"}]}} \ No newline at end of file diff --git a/crates/tranche-core/tests/fixture/out/dupes.json b/crates/tranche-core/tests/fixture/out/dupes.json new file mode 100644 index 0000000..38a5566 --- /dev/null +++ b/crates/tranche-core/tests/fixture/out/dupes.json @@ -0,0 +1 @@ +{"confirmed_groups": [[12074, 12090, 12680], [12649, 12755, 13009], [13165, 13477, 13645], [13459, 13463, 13613]], "review_groups": [], "uncertain_pairs": [], "meaning": "Model-consistent candidate groups, not verified duplicates. No survivor selected."} \ No newline at end of file diff --git a/crates/tranche-core/tests/fixture/out/judgments.jsonl b/crates/tranche-core/tests/fixture/out/judgments.jsonl new file mode 100644 index 0000000..ec4904b --- /dev/null +++ b/crates/tranche-core/tests/fixture/out/judgments.jsonl @@ -0,0 +1,48 @@ +{"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.98, "probabilities": {"install-setup": 0.0, "update-release": 0.0, "fix-misc": 0.01, "docs": 0.0, "desktop-config": 0.98, "hardware-drivers": 0.0, "shell-cli": 0.0, "agents-ai": 0.0, "unclear": 0.01, "apps-integrations": 0.0}}, "risk": {"type": "score", "score": 1.05, "confidence": 0.89, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.04, "1": 0.92, "2": 0.01, "3": 0.0, "4": 0.03}}, "is_fix": {"type": "noul", "noul": 0.95}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 1.94, "confidence": 0.65, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.2, "2": 0.66, "3": 0.14}}, "review_effort": {"type": "score", "score": 1.02, "confidence": 0.81, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.08, "1": 0.85, "2": 0.04, "3": 0.03}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1331, "output_tokens": 197}} +{"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.48, "probabilities": {"agents-ai": 0.0, "update-release": 0.0, "desktop-config": 0.54, "apps-integrations": 0.02, "install-setup": 0.0, "unclear": 0.18, "shell-cli": 0.0, "fix-misc": 0.26, "hardware-drivers": 0.0, "docs": 0.0}}, "risk": {"type": "score", "score": 0.67, "confidence": 0.69, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.35, "1": 0.65, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.95}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 1.53, "confidence": 0.46, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.66, "2": 0.14, "3": 0.2}}, "review_effort": {"type": "score", "score": 1.04, "confidence": 0.86, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.05, "1": 0.87, "2": 0.07, "3": 0.01}}, "security_flag": {"type": "noul", "noul": 0.01}}, "usage": {"input_tokens": 1347, "output_tokens": 197}} +{"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.96, "probabilities": {"hardware-drivers": 0.0, "apps-integrations": 0.0, "docs": 0.0, "install-setup": 0.0, "shell-cli": 0.0, "unclear": 0.01, "fix-misc": 0.03, "update-release": 0.0, "desktop-config": 0.96, "agents-ai": 0.0}}, "risk": {"type": "score", "score": 1.06, "confidence": 0.89, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.03, "1": 0.93, "2": 0.01, "3": 0.01, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.97}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 2.62, "confidence": 0.62, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.04, "2": 0.31, "3": 0.65}}, "review_effort": {"type": "score", "score": 1.17, "confidence": 0.76, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.04, "1": 0.78, "2": 0.15, "3": 0.03}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1423, "output_tokens": 197}} +{"number": 13463, "title": "Scale the clock panel hero text with fontScale", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.54, "probabilities": {"update-release": 0.0, "shell-cli": 0.02, "fix-misc": 0.28, "unclear": 0.1, "apps-integrations": 0.01, "docs": 0.0, "agents-ai": 0.01, "desktop-config": 0.58, "hardware-drivers": 0.0, "install-setup": 0.0}}, "risk": {"type": "score", "score": 0.82, "confidence": 0.82, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.2, "1": 0.79, "2": 0.01, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 1.91, "confidence": 0.68, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.01, "1": 0.19, "2": 0.6799999999999999, "3": 0.12}}, "review_effort": {"type": "score", "score": 1.0, "confidence": 0.88, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.06, "1": 0.89, "2": 0.04, "3": 0.01}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1592, "output_tokens": 197}} +{"number": 13459, "title": "Scale clock panel hero date with fontScale", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.5, "probabilities": {"install-setup": 0.0, "apps-integrations": 0.03, "fix-misc": 0.29, "hardware-drivers": 0.0, "unclear": 0.1, "update-release": 0.0, "docs": 0.0, "desktop-config": 0.56, "agents-ai": 0.0, "shell-cli": 0.02}}, "risk": {"type": "score", "score": 0.88, "confidence": 0.88, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.13, "1": 0.86, "2": 0.01, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.95}, "dupe_signal": {"type": "noul", "noul": 0.04}, "finished_form": {"type": "score", "score": 2.53, "confidence": 0.53, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.02, "2": 0.43, "3": 0.55}}, "review_effort": {"type": "score", "score": 1.0, "confidence": 0.91, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.04, "1": 0.92, "2": 0.03, "3": 0.01}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1493, "output_tokens": 197}} +{"number": 13165, "title": "Skip placeholder screens when building bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.84, "probabilities": {"update-release": 0.0, "agents-ai": 0.0, "shell-cli": 0.0, "unclear": 0.03, "hardware-drivers": 0.0, "docs": 0.0, "install-setup": 0.0, "apps-integrations": 0.0, "desktop-config": 0.86, "fix-misc": 0.11}}, "risk": {"type": "score", "score": 1.01, "confidence": 0.95, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.02, "1": 0.97, "2": 0.0, "3": 0.0, "4": 0.01}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 1.42, "confidence": 0.57, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.59, "2": 0.39, "3": 0.02}}, "review_effort": {"type": "score", "score": 1.8, "confidence": 0.78, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.2, "2": 0.79, "3": 0.01}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1581, "output_tokens": 197}} +{"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.75, "probabilities": {"fix-misc": 0.05, "agents-ai": 0.0, "hardware-drivers": 0.78, "docs": 0.0, "install-setup": 0.0, "update-release": 0.0, "unclear": 0.05, "apps-integrations": 0.0, "shell-cli": 0.0, "desktop-config": 0.12}}, "risk": {"type": "score", "score": 0.89, "confidence": 0.85, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.15, "1": 0.83, "2": 0.01, "3": 0.01, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.95}, "dupe_signal": {"type": "noul", "noul": 0.17}, "finished_form": {"type": "score", "score": 2.87, "confidence": 0.87, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.0, "2": 0.12, "3": 0.88}}, "review_effort": {"type": "score", "score": 1.67, "confidence": 0.54, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.05, "1": 0.28, "2": 0.6, "3": 0.07}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1575, "output_tokens": 198}} +{"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.51, "probabilities": {"fix-misc": 0.14, "agents-ai": 0.0, "hardware-drivers": 0.5700000000000001, "install-setup": 0.0, "docs": 0.0, "update-release": 0.0, "unclear": 0.0, "apps-integrations": 0.0, "shell-cli": 0.29, "desktop-config": 0.0}}, "risk": {"type": "score", "score": 1.0, "confidence": 1.0, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 1.0, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.98}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 2.82, "confidence": 0.82, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.03, "2": 0.11, "3": 0.86}}, "review_effort": {"type": "score", "score": 1.28, "confidence": 0.71, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.72, "2": 0.28, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1580, "output_tokens": 198}} +{"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.8, "probabilities": {"hardware-drivers": 0.83, "unclear": 0.0, "update-release": 0.16, "fix-misc": 0.0, "docs": 0.01, "apps-integrations": 0.0, "shell-cli": 0.0, "desktop-config": 0.0, "agents-ai": 0.0, "install-setup": 0.0}}, "risk": {"type": "score", "score": 1.1, "confidence": 0.08, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.54, "1": 0.11, "2": 0.06, "3": 0.28, "4": 0.01}}, "is_fix": {"type": "noul", "noul": 0.73}, "dupe_signal": {"type": "noul", "noul": 0.68}, "finished_form": {"type": "score", "score": 1.01, "confidence": 0.84, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.08, "1": 0.84, "2": 0.08, "3": 0.0}}, "review_effort": {"type": "score", "score": 1.73, "confidence": 0.0, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.31, "1": 0.11, "2": 0.12, "3": 0.46}}, "security_flag": {"type": "noul", "noul": 0.06}}, "usage": {"input_tokens": 1574, "output_tokens": 198}} +{"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "answers": {"review_effort": {"type": "score", "score": 1.38, "confidence": 0.55, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.03, "1": 0.56, "2": 0.4, "3": 0.01}}, "security_flag": {"type": "noul", "noul": 0.02}, "category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.92, "probabilities": {"unclear": 0.04, "hardware-drivers": 0.92, "update-release": 0.0, "fix-misc": 0.03, "docs": 0.0, "shell-cli": 0.01, "apps-integrations": 0.0, "desktop-config": 0.0, "agents-ai": 0.0, "install-setup": 0.0}}, "risk": {"type": "score", "score": 0.99, "confidence": 0.97, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.02, "1": 0.98, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.98}, "dupe_signal": {"type": "noul", "noul": 0.42}, "finished_form": {"type": "score", "score": 2.55, "confidence": 0.55, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.02, "2": 0.41, "3": 0.57}}}, "usage": {"input_tokens": 1487, "output_tokens": 198}} +{"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 1.0, "probabilities": {"install-setup": 0.0, "desktop-config": 0.0, "fix-misc": 0.0, "docs": 0.0, "unclear": 0.0, "agents-ai": 0.0, "hardware-drivers": 1.0, "shell-cli": 0.0, "update-release": 0.0, "apps-integrations": 0.0}}, "risk": {"type": "score", "score": 2.94, "confidence": 0.92, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.02, "2": 0.03, "3": 0.93, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.07}, "finished_form": {"type": "score", "score": 1.76, "confidence": 0.23, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.45, "2": 0.33, "3": 0.22}}, "review_effort": {"type": "score", "score": 1.99, "confidence": 0.7, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.02, "1": 0.11, "2": 0.72, "3": 0.15}}, "security_flag": {"type": "noul", "noul": 0.16}}, "usage": {"input_tokens": 1372, "output_tokens": 198}} +{"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.85, "probabilities": {"apps-integrations": 0.0, "unclear": 0.0, "hardware-drivers": 0.86, "update-release": 0.13, "fix-misc": 0.0, "agents-ai": 0.0, "shell-cli": 0.0, "install-setup": 0.01, "docs": 0.0, "desktop-config": 0.0}}, "risk": {"type": "score", "score": 2.74, "confidence": 0.71, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.02, "1": 0.07, "2": 0.12, "3": 0.74, "4": 0.05}}, "is_fix": {"type": "noul", "noul": 0.92}, "dupe_signal": {"type": "noul", "noul": 0.25}, "finished_form": {"type": "score", "score": 1.83, "confidence": 0.52, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.32, "2": 0.53, "3": 0.15}}, "review_effort": {"type": "score", "score": 1.7, "confidence": 0.26, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.02, "1": 0.41, "2": 0.42, "3": 0.15}}, "security_flag": {"type": "noul", "noul": 0.08}}, "usage": {"input_tokens": 1632, "output_tokens": 198}} +{"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.99, "probabilities": {"hardware-drivers": 0.0, "shell-cli": 0.0, "fix-misc": 0.0, "unclear": 0.0, "update-release": 0.0, "apps-integrations": 0.0, "desktop-config": 1.0, "agents-ai": 0.0, "docs": 0.0, "install-setup": 0.0}}, "risk": {"type": "score", "score": 1.04, "confidence": 0.96, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.98, "2": 0.01, "3": 0.0, "4": 0.01}}, "is_fix": {"type": "noul", "noul": 0.93}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 1.64, "confidence": 0.57, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.39, "2": 0.58, "3": 0.03}}, "review_effort": {"type": "score", "score": 1.05, "confidence": 0.94, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.95, "2": 0.05, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1373, "output_tokens": 197}, "binding": "16db06ea4aca98b40fcc2bc8a25245e6a3acb50bb74c762b61023eb60adc1bf5", "input": {"pr": {"title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "f842d0428b981cc87066c56a9965e4b28004585279f034db7d3838c0b2e4824e", "head_sha": "00ef70cbf708e0b1542ea01c4b1d88e3284be76d", "updated_at": "2026-09-29T21:12:09Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:29:50.443466+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.59, "probabilities": {"apps-integrations": 0.01, "hardware-drivers": 0.0, "docs": 0.0, "unclear": 0.13, "update-release": 0.0, "install-setup": 0.0, "desktop-config": 0.64, "fix-misc": 0.22, "agents-ai": 0.0, "shell-cli": 0.0}}, "risk": {"type": "score", "score": 0.77, "confidence": 0.79, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.24, "1": 0.76, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.93}, "dupe_signal": {"type": "noul", "noul": 0.04}, "finished_form": {"type": "score", "score": 1.37, "confidence": 0.62, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.74, "2": 0.15, "3": 0.11}}, "review_effort": {"type": "score", "score": 1.05, "confidence": 0.95, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.95, "2": 0.05, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1389, "output_tokens": 197}, "binding": "ac1856036dbbb350a9009a5780ddc6d8811851b2e197590f41b164a7fbe4cd80", "input": {"pr": {"title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "433298244162e91ec6390f33aa4801aaef0fa6014d565ec94ffd4426d3df9c24", "head_sha": "151b281f28d647691a983141689026b29349e569", "updated_at": "2026-09-29T21:10:02Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:29:52.383065+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.98, "probabilities": {"docs": 0.0, "hardware-drivers": 0.0, "desktop-config": 0.99, "unclear": 0.0, "shell-cli": 0.0, "fix-misc": 0.01, "apps-integrations": 0.0, "agents-ai": 0.0, "install-setup": 0.0, "update-release": 0.0}}, "risk": {"type": "score", "score": 1.09, "confidence": 0.91, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.94, "2": 0.02, "3": 0.01, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 2.41, "confidence": 0.49, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.05, "2": 0.49, "3": 0.46}}, "review_effort": {"type": "score", "score": 1.11, "confidence": 0.88, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.89, "2": 0.11, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1465, "output_tokens": 197}, "binding": "d7829ee240b9d9f006a77e6e25f3622b7aa5acf0fbfee37bd2f64600780ad97c", "input": {"pr": {"title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out nameless and `FALLBACK` screens in `BarModel.realScreens`, ensuring bar surfaces are only created for real outputs with confirmed geometry. Fixes #13072 ## Testing - Updated `test/shell.d/bar-test.sh` with assertions for screen filtering. - Ran `bash test/shell.d/bar-test.sh` (all 98 assertions pass).", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "983e79291c13c523bc17989c7ea91d424bb533f8d00d5955d629c7608d631cf1", "head_sha": "ec58ce82fdc5521e5109f1760df1fb502f3f45c2", "updated_at": "2026-09-29T21:09:30Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:29:58.032323+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13463, "title": "Scale the clock panel hero text with fontScale", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.68, "probabilities": {"apps-integrations": 0.01, "docs": 0.0, "shell-cli": 0.01, "update-release": 0.0, "install-setup": 0.0, "fix-misc": 0.21, "hardware-drivers": 0.0, "desktop-config": 0.72, "agents-ai": 0.0, "unclear": 0.05}}, "risk": {"type": "score", "score": 0.87, "confidence": 0.88, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.14, "1": 0.86, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.95}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 1.76, "confidence": 0.65, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.29, "2": 0.65, "3": 0.06}}, "review_effort": {"type": "score", "score": 1.04, "confidence": 0.94, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.01, "1": 0.94, "2": 0.05, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1634, "output_tokens": 197}, "binding": "c04ea4c452bdd0f4d7d85510cd98b1be48f18ed2e534d96273bcfde0fcba0d9e", "input": {"pr": {"title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the card drops 560 \u2192 420px while the hero stayed at 52px. This scales the hero date and its decorative glyph with `Style.fontScale` using the codebase's standard `Math.max(1, Math.round(...))` idiom. The glyph/date ratio stays deliberately outside the `Style.font.*` scale \u2014 both now track the card that contains them instead. At the default `base-size = 12`, `fontScale` is exactly 1, so rendering is pixel-identical there. Fixes #13381 ## Testing - `test/shell.d` has no clock-panel geometry tests; the full suite was previously run on this tree with only the known environment failures (missing `omarchy-pkgs` checkout). - Rendering is provably unchanged at defaults (`fontScale == 1`); visual verification at `base-size = 9` per `agents/skills/visual-verification.md` on a dev-linked session is recom", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "4d3c8883438af4eaedf2168b48180669cc425f1957d86cdc1a30aba4904c6080", "head_sha": "02cd42f24f5ef7aaaecdeaef68c023973eaea030", "updated_at": "2026-09-27T21:45:20Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:29:58.723385+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13459, "title": "Scale clock panel hero date with fontScale", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.49, "probabilities": {"update-release": 0.0, "agents-ai": 0.0, "docs": 0.0, "unclear": 0.07, "hardware-drivers": 0.0, "shell-cli": 0.03, "desktop-config": 0.54, "apps-integrations": 0.04, "install-setup": 0.0, "fix-misc": 0.32}}, "risk": {"type": "score", "score": 0.9, "confidence": 0.91, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.1, "1": 0.9, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.94}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 2.13, "confidence": 0.69, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.08, "2": 0.7, "3": 0.22}}, "review_effort": {"type": "score", "score": 1.01, "confidence": 0.98, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.98, "2": 0.02, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1535, "output_tokens": 197}, "binding": "a075fb80d8a23ee71299dae45b25b6847392226635f3356863d1017e112c57eb", "input": {"pr": {"title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales both the decorative calendar icon and hero date string using `Style.fontScale` (`Math.max(1, Math.round(size * Style.fontScale))`). At default `fontBaseSize = 12` (`fontScale = 1.0`), the rendered pixel sizes are completely unchanged (48 and 52), while at smaller or larger base sizes they scale in exact proportion with the popup card. Fixes #13381 ## Testing - `bash test/shell.d/clock-test.sh`: all tests pass, including new assertion verifying that the hero date and glyph scale with `Style.fontScale`. - `./test/cli`: passed.", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "43119d909ac249aaf3a6ef272835d8a02827806c8586f4376c4be7a52531c315", "head_sha": "d6c2c80815a222a27868c41bf8d2ff3cbf86bc66", "updated_at": "2026-09-27T21:32:33Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:29:59.074915+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13165, "title": "Skip placeholder screens when building bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.84, "probabilities": {"update-release": 0.0, "hardware-drivers": 0.0, "docs": 0.0, "desktop-config": 0.86, "shell-cli": 0.0, "unclear": 0.04, "apps-integrations": 0.0, "agents-ai": 0.0, "fix-misc": 0.1, "install-setup": 0.0}}, "risk": {"type": "score", "score": 1.01, "confidence": 0.98, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.98, "2": 0.0, "3": 0.0, "4": 0.01}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 1.17, "confidence": 0.83, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.83, "2": 0.16, "3": 0.01}}, "review_effort": {"type": "score", "score": 1.84, "confidence": 0.83, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.16, "2": 0.84, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1623, "output_tokens": 197}, "binding": "9956fe4a6cc3c17f4d9b02231e8964c9cb247f7f56d86c492ba2f777f4e0a632", "input": {"pr": {"title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When the real monitors came back, the compositor dropped that orphaned bar onto the first monitor to return, stacked over its own bar, and the second monitor had no bar until the real ones finished building. ## Change - `BarModel.js` gets `isRealScreen()` / `realScreens()`: screens with a name that isn't `FALLBACK` and a non-zero size. It uses the same test `plugins/lock/Service.qml` uses in `realScreenCount()`, plus the `FALLBACK` exclusion. - `Bar.qml`: `readonly property var realScreens: BarModel.realScreens(Quickshell.screens)`, and the bar, `DragGhostPanel` and `BarMoveGhostPanel` `Variants` all use `root.realScreens`. - Qt names a screen before adding it, so only its size can arrive late. Those size reads are tracked by the binding, so a screen whose size lands afterwards still gets its ", "author": "dreed47", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "8e19810c00adf0f1a2f291da1a0cf2c143ad8b344af97d865bd75f571c1faa4e", "head_sha": "67a5645948c0b2981481ef89bb71a769269ecf54", "updated_at": "2026-09-28T14:19:58Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:30:06.368131+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "answers": {"finished_form": {"type": "score", "score": 2.8, "confidence": 0.8, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.0, "2": 0.19, "3": 0.81}}, "review_effort": {"type": "score", "score": 1.73, "confidence": 0.72, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.27, "2": 0.73, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}, "category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.68, "probabilities": {"hardware-drivers": 0.72, "update-release": 0.0, "agents-ai": 0.0, "unclear": 0.02, "fix-misc": 0.07, "apps-integrations": 0.0, "shell-cli": 0.0, "docs": 0.0, "install-setup": 0.0, "desktop-config": 0.19}}, "risk": {"type": "score", "score": 0.97, "confidence": 0.95, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.04, "1": 0.95, "2": 0.01, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.95}, "dupe_signal": {"type": "noul", "noul": 0.16}}, "usage": {"input_tokens": 1617, "output_tokens": 198}, "binding": "8bd60c4fc4cced15eb3b2958bf6f08496a4585f1bb8b2a3f98ae662c1a3ea28a", "input": {"pr": {"title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negative current_now, which is the normal discharging sign), - rejects insane magnitudes (>150W) or values wildly above UPower's rate (>3x when UPower is solid), keeping the UPower value instead, - displays the rate as magnitude (state already says charging/discharging, so no more -1124W), - compares idle against magnitude so a large negative rate can't fake charge-idle, - omits cycle_count 0 when UPower reports charge-cycles N/A so the panel shows \u2014 instead of a misleading 0. Complements #12649/#12755 (those cover failed/empty reads); this covers bogus-but-numeric reads. Verified with the extended battery-status-test.sh scenarios (bogus -65A, non-numeric, sane negative discharge) plus live hardware: bogus -1113W discharge now shows 7.5W, and a sane 29.1W charge still uses the live sysfs value.", "author": "Kristijan-K", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "fa745c5a00344dcc007f0f5d20942d3fdaaff50a4c3436557d544b27fc3e3d2e", "head_sha": "cd81d771454f9c4349fb59d72ea5e6b7c7367c75", "updated_at": "2026-09-28T09:16:09Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:30:12.368211+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.45, "probabilities": {"update-release": 0.0, "apps-integrations": 0.0, "hardware-drivers": 0.52, "install-setup": 0.0, "shell-cli": 0.33, "docs": 0.0, "desktop-config": 0.01, "fix-misc": 0.14, "agents-ai": 0.0, "unclear": 0.0}}, "risk": {"type": "score", "score": 1.0, "confidence": 1.0, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 1.0, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.97}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 2.53, "confidence": 0.53, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.12, "2": 0.22, "3": 0.66}}, "review_effort": {"type": "score", "score": 1.3, "confidence": 0.7, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.7, "2": 0.3, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1622, "output_tokens": 198}, "binding": "6795128c00850557a60782199a3fd9b7b208e0954793563361516f8a425cca0d", "input": {"pr": {"title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same hazard in the `current_now`/`voltage_now` branch. ## Change - `bin/omarchy-battery-status`: only override the UPower rate when the sysfs read actually succeeds and is numeric (`cat ... 2>/dev/null` + `^[0-9]+$` guard, as suggested in the issue), for both the `power_now` and the `current_now`/`voltage_now` branches. Otherwise the UPower value stands. - `test/shell.d/battery-status-test.sh`: two new scenarios \u2014 a `power_now` node whose read fails (fake `cat` refusing `power_now`, standing in for the ENODEV kernel read) and a non-numeric `current_now` \u2014 both asserting the UPower rate survives. ## Verification - `bash test/shell.d/battery-status-test.sh`: pass (new assertions included) - Negative control: the new assertions fail against the pre-fix script (`not ok - battery status keeps the UPo", "author": "anandude", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "181ff87f75e50c817af0957c7201fd095fe6331cd90b4bf8789b25b4ed382b11", "head_sha": "370a3b61fbb8f4c358bbb423b5d8c4c97bae33e8", "updated_at": "2026-09-27T19:29:39Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:30:20.165919+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.87, "probabilities": {"hardware-drivers": 0.88, "unclear": 0.0, "update-release": 0.11, "fix-misc": 0.01, "docs": 0.0, "apps-integrations": 0.0, "shell-cli": 0.0, "desktop-config": 0.0, "install-setup": 0.0, "agents-ai": 0.0}}, "risk": {"type": "score", "score": 2.76, "confidence": 0.76, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.07, "2": 0.09, "3": 0.81, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.75}, "dupe_signal": {"type": "noul", "noul": 0.64}, "finished_form": {"type": "score", "score": 0.99, "confidence": 0.94, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.03, "1": 0.95, "2": 0.02, "3": 0.0}}, "review_effort": {"type": "score", "score": 2.67, "confidence": 0.67, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.02, "2": 0.28, "3": 0.7}}, "security_flag": {"type": "noul", "noul": 0.09}}, "usage": {"input_tokens": 1616, "output_tokens": 198}, "binding": "1f57c8338c081c35c51bf5f16d90b2c427c30fb6f03b365a85bbf6b5c92c6604", "input": {"pr": {"title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware or merge-readiness certification is claimed. Part of the [14-feature Intel Mac series]( with three package companions. **Contribute:** open follow-up PRs in `andrew-boyd/omarchy` with base **`intel-mac/p02-kernel-headers`**. Use `[Intel Mac P02]` in the title and a contributor branch such as `intel-mac/p02/describe-change`. Link this feature in the series index. Merging a follow-up into this branch updates its roll-up. This existing draft: [ ## Full Intel Mac scope and current revision The project covers **all 64-bit Intel Macs: pre-T1, T1 and T2**. MacBookPro13,3 is only the first available physical test machine. Each feature has its own hardware boundary; one model's success does not validate the rest. Candidate head: `803260c8feff6d9ed5dbac60d5f630cd45ae1b56`; reconciled upstream: `8f324", "author": "andrew-boyd", "diffstat": "unknown (not supplied by the captured PR list)", "draft": true, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "1a33aee45fac3606b799794ddf8ffec5519990d23facfe53b1fe9fcdcf42c8ed", "head_sha": "803260c8feff6d9ed5dbac60d5f630cd45ae1b56", "updated_at": "2026-09-27T19:29:10Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:30:22.204020+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.96, "probabilities": {"docs": 0.0, "fix-misc": 0.02, "unclear": 0.01, "hardware-drivers": 0.96, "apps-integrations": 0.0, "install-setup": 0.0, "desktop-config": 0.0, "update-release": 0.0, "agents-ai": 0.0, "shell-cli": 0.01}}, "risk": {"type": "score", "score": 1.01, "confidence": 0.99, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.99, "2": 0.01, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.97}, "dupe_signal": {"type": "noul", "noul": 0.39}, "finished_form": {"type": "score", "score": 2.24, "confidence": 0.65, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.06, "2": 0.64, "3": 0.3}}, "review_effort": {"type": "score", "score": 1.4, "confidence": 0.6, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.6, "2": 0.4, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1529, "output_tokens": 198}, "binding": "820d2ab18b85a3a85220e8edfe8505795b5968be652b134f699a4b1c0de579bb", "input": {"pr": {"title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split out from #6845 per @bjarneo's request \u2014 that PR grew to cover 3 failure modes and was closed as a dup of #10392, which only handles multi-battery percentage and keeps this bug. This is the minimal fix for #6895 with regression tests for both empty-read cases. Fixes #6895. Extracted from #6845 (`3c40745`). Verified: existing `battery-status-test.sh` + 2 new ENODEV cases pass.", "author": "ujo4eva", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "1dac96366bcb9d9f05cd3ef31669b067fb528fafd0311d12a5f963c0bdf999ad", "head_sha": "50a935005cd82b5726ae21a19e86069b57f7ba21", "updated_at": "2026-09-27T19:29:00Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:30:23.228108+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 1.0, "probabilities": {"apps-integrations": 0.0, "desktop-config": 0.0, "unclear": 0.0, "fix-misc": 0.0, "agents-ai": 0.0, "hardware-drivers": 1.0, "update-release": 0.0, "shell-cli": 0.0, "docs": 0.0, "install-setup": 0.0}}, "risk": {"type": "score", "score": 3.0, "confidence": 0.96, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.0, "2": 0.02, "3": 0.96, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.07}, "finished_form": {"type": "score", "score": 1.47, "confidence": 0.53, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.64, "2": 0.26, "3": 0.1}}, "review_effort": {"type": "score", "score": 2.0, "confidence": 0.91, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.05, "2": 0.9, "3": 0.05}}, "security_flag": {"type": "noul", "noul": 0.18}}, "usage": {"input_tokens": 1414, "output_tokens": 198}, "binding": "1cb7cf3514d54b8b4dde8d84c5566101df955045b9507fa9680a0343d9f218b2", "input": {"pr": {"title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers-test.sh ```", "author": "paulogeyer", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "1c2d4c56e24699acf743ae77812cfdb61bb7f5fa75720293a44e381d71609f11", "head_sha": "40fc412e5e7fd6b9a5c883e7b4ac361b8b4544b4", "updated_at": "2026-09-27T19:25:48Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:30:38.319393+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "answers": {"review_effort": {"type": "score", "score": 1.75, "confidence": 0.65, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.3, "2": 0.65, "3": 0.05}}, "security_flag": {"type": "noul", "noul": 0.1}, "category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.87, "probabilities": {"install-setup": 0.01, "hardware-drivers": 0.89, "apps-integrations": 0.0, "unclear": 0.0, "agents-ai": 0.0, "docs": 0.0, "fix-misc": 0.0, "shell-cli": 0.0, "desktop-config": 0.0, "update-release": 0.1}}, "risk": {"type": "score", "score": 2.89, "confidence": 0.84, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.03, "2": 0.09, "3": 0.84, "4": 0.04}}, "is_fix": {"type": "noul", "noul": 0.91}, "dupe_signal": {"type": "noul", "noul": 0.2}, "finished_form": {"type": "score", "score": 1.5, "confidence": 0.5, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.54, "2": 0.41, "3": 0.05}}}, "usage": {"input_tokens": 1674, "output_tokens": 198}, "binding": "49854c5f6b021f21a458c015a22fc7383e817fddb54aff6e54ea8afe0b3daaff", "input": {"pr": {"title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or BCM4331 then come back from the Quattro upgrade with no driver bound and no Wi-Fi device at all. The installer's `fix-bcm43xx.sh` never runs on those machines, and `1789444024` only covers `linux-omarchy` and `linux-t2`. `1789325478` will give `linux-omarchy` its headers, but it deliberately leaves the stock kernel installed as the boot fallback. On these Macs that fallback still has no Wi-Fi, which is usually the way back to a working system. This migration installs headers for any installed Arch kernel (`linux`, `linux-lts`, `linux-zen`, `linux-hardened`) when `broadcom-wl-dkms` is present. The dkms pacman hook triggers on `usr/lib/modules/*/build/include/`, so installing the headers builds the module. ## Testing - `test/shell.d/broadcom-wl-headers-migration-test.sh` covers the repair, i", "author": "oliverox", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "193f3c9f2b4e4aebc0a9faa16232e905fac923eb4e4e41849d6393b98ff5083c", "head_sha": "6d9986a1704f166ea3134e0ade2148f8291ce3d8", "updated_at": "2026-09-27T19:25:50Z", "requested_model": "jev-latest", "judged_at": "2026-09-30T14:30:38.711047+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.99, "probabilities": {"install-setup": 0.0, "unclear": 0.0, "apps-integrations": 0.0, "agents-ai": 0.0, "shell-cli": 0.0, "docs": 0.0, "hardware-drivers": 0.0, "fix-misc": 0.01, "update-release": 0.0, "desktop-config": 0.99}}, "risk": {"type": "score", "score": 1.04, "confidence": 0.96, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.98, "2": 0.01, "3": 0.0, "4": 0.01}}, "is_fix": {"type": "noul", "noul": 0.93}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 1.67, "confidence": 0.59, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.37, "2": 0.59, "3": 0.04}}, "review_effort": {"type": "score", "score": 1.04, "confidence": 0.96, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.96, "2": 0.04, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1373, "output_tokens": 197}, "binding": "9cf7021aace38ba3a3f104a90864c4e711a06ed5f8030f82a0925c69e09af58d", "input": {"pr": {"title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "362523f1c6fa2e7060ed64e285b8dca8d5dfb6757d4497890b9f403f3cbbab82", "head_sha": "00ef70cbf708e0b1542ea01c4b1d88e3284be76d", "updated_at": "2026-09-29T21:12:09Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:19:27.718980+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.51, "probabilities": {"agents-ai": 0.0, "hardware-drivers": 0.0, "shell-cli": 0.0, "desktop-config": 0.56, "fix-misc": 0.25, "install-setup": 0.0, "docs": 0.0, "unclear": 0.16, "update-release": 0.0, "apps-integrations": 0.02}}, "risk": {"type": "score", "score": 0.72, "confidence": 0.76, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.28, "1": 0.72, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.93}, "dupe_signal": {"type": "noul", "noul": 0.04}, "finished_form": {"type": "score", "score": 1.34, "confidence": 0.66, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.75, "2": 0.15, "3": 0.1}}, "review_effort": {"type": "score", "score": 1.04, "confidence": 0.95, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.95, "2": 0.05, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1389, "output_tokens": 197}, "binding": "5ed3fdcef90193c6ecfe6484269fd3d8cc35cdbba886817ff8ced3f080d605d6", "input": {"pr": {"title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "5e5bbc0d363e454620810d2b72e341c9d34d458e659ffeaa715d516eca96d3f6", "head_sha": "151b281f28d647691a983141689026b29349e569", "updated_at": "2026-09-29T21:10:02Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:19:29.499786+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.97, "probabilities": {"unclear": 0.0, "fix-misc": 0.02, "desktop-config": 0.98, "shell-cli": 0.0, "agents-ai": 0.0, "install-setup": 0.0, "hardware-drivers": 0.0, "apps-integrations": 0.0, "update-release": 0.0, "docs": 0.0}}, "risk": {"type": "score", "score": 1.09, "confidence": 0.92, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.95, "2": 0.01, "3": 0.01, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 2.39, "confidence": 0.5, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.05, "2": 0.5, "3": 0.45}}, "review_effort": {"type": "score", "score": 1.11, "confidence": 0.89, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.89, "2": 0.11, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1465, "output_tokens": 197}, "binding": "211d6e09a3523273758d74e5f89a50c633ad741ff740d2d1adaa229f680b15fa", "input": {"pr": {"title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out nameless and `FALLBACK` screens in `BarModel.realScreens`, ensuring bar surfaces are only created for real outputs with confirmed geometry. Fixes #13072 ## Testing - Updated `test/shell.d/bar-test.sh` with assertions for screen filtering. - Ran `bash test/shell.d/bar-test.sh` (all 98 assertions pass).", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "765139c4479e219b0677b3c6a6b28ec1281fec5f8e2222f259a9adc9634aa051", "head_sha": "ec58ce82fdc5521e5109f1760df1fb502f3f45c2", "updated_at": "2026-09-29T21:09:30Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:19:35.475145+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13463, "title": "Scale the clock panel hero text with fontScale", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.61, "probabilities": {"docs": 0.0, "agents-ai": 0.0, "shell-cli": 0.02, "unclear": 0.07, "update-release": 0.0, "install-setup": 0.0, "hardware-drivers": 0.0, "desktop-config": 0.64, "fix-misc": 0.26, "apps-integrations": 0.01}}, "risk": {"type": "score", "score": 0.87, "confidence": 0.88, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.14, "1": 0.86, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.94}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 1.8, "confidence": 0.68, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.25, "2": 0.6900000000000001, "3": 0.06}}, "review_effort": {"type": "score", "score": 1.02, "confidence": 0.96, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.01, "1": 0.96, "2": 0.03, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1634, "output_tokens": 197}, "binding": "75ac5d77084bf1ce4077a01eb21d5630888b01352c2d7010e8d1dd58dc1f8fcb", "input": {"pr": {"title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the card drops 560 \u2192 420px while the hero stayed at 52px. This scales the hero date and its decorative glyph with `Style.fontScale` using the codebase's standard `Math.max(1, Math.round(...))` idiom. The glyph/date ratio stays deliberately outside the `Style.font.*` scale \u2014 both now track the card that contains them instead. At the default `base-size = 12`, `fontScale` is exactly 1, so rendering is pixel-identical there. Fixes #13381 ## Testing - `test/shell.d` has no clock-panel geometry tests; the full suite was previously run on this tree with only the known environment failures (missing `omarchy-pkgs` checkout). - Rendering is provably unchanged at defaults (`fontScale == 1`); visual verification at `base-size = 9` per `agents/skills/visual-verification.md` on a dev-linked session is recom", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "003ae91d0bb8a8d0f13b844d46f5f0d496b6aa4aae37a2eee97c3a0370f3760c", "head_sha": "02cd42f24f5ef7aaaecdeaef68c023973eaea030", "updated_at": "2026-09-27T21:45:20Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:19:36.275946+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13459, "title": "Scale clock panel hero date with fontScale", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.51, "probabilities": {"shell-cli": 0.03, "agents-ai": 0.0, "hardware-drivers": 0.0, "apps-integrations": 0.03, "unclear": 0.08, "desktop-config": 0.56, "docs": 0.0, "fix-misc": 0.3, "install-setup": 0.0, "update-release": 0.0}}, "risk": {"type": "score", "score": 0.9, "confidence": 0.91, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.11, "1": 0.89, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.94}, "dupe_signal": {"type": "noul", "noul": 0.04}, "finished_form": {"type": "score", "score": 2.15, "confidence": 0.69, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.08, "2": 0.69, "3": 0.23}}, "review_effort": {"type": "score", "score": 1.01, "confidence": 0.98, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.98, "2": 0.02, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1535, "output_tokens": 197}, "binding": "6adefb7067495f488f97e62706a67d3303b7be08ee9e72d6bf1405692843dab9", "input": {"pr": {"title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales both the decorative calendar icon and hero date string using `Style.fontScale` (`Math.max(1, Math.round(size * Style.fontScale))`). At default `fontBaseSize = 12` (`fontScale = 1.0`), the rendered pixel sizes are completely unchanged (48 and 52), while at smaller or larger base sizes they scale in exact proportion with the popup card. Fixes #13381 ## Testing - `bash test/shell.d/clock-test.sh`: all tests pass, including new assertion verifying that the hero date and glyph scale with `Style.fontScale`. - `./test/cli`: passed.", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "f3d45d9a952872ed4d7efd82a91ff6ca0032f30f7f7952d9f70a4d396ff71e1d", "head_sha": "d6c2c80815a222a27868c41bf8d2ff3cbf86bc66", "updated_at": "2026-09-27T21:32:33Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:19:36.531151+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13165, "title": "Skip placeholder screens when building bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.85, "probabilities": {"desktop-config": 0.87, "shell-cli": 0.0, "update-release": 0.0, "docs": 0.0, "agents-ai": 0.0, "apps-integrations": 0.0, "unclear": 0.04, "fix-misc": 0.09, "hardware-drivers": 0.0, "install-setup": 0.0}}, "risk": {"type": "score", "score": 1.01, "confidence": 0.98, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.99, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 1.18, "confidence": 0.81, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.83, "2": 0.17, "3": 0.0}}, "review_effort": {"type": "score", "score": 1.84, "confidence": 0.83, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.16, "2": 0.84, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1623, "output_tokens": 197}, "binding": "42412483f7e6d0b6ef15fbf966d73a0e67f0755a32f80a64a516559d0abd12e2", "input": {"pr": {"title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When the real monitors came back, the compositor dropped that orphaned bar onto the first monitor to return, stacked over its own bar, and the second monitor had no bar until the real ones finished building. ## Change - `BarModel.js` gets `isRealScreen()` / `realScreens()`: screens with a name that isn't `FALLBACK` and a non-zero size. It uses the same test `plugins/lock/Service.qml` uses in `realScreenCount()`, plus the `FALLBACK` exclusion. - `Bar.qml`: `readonly property var realScreens: BarModel.realScreens(Quickshell.screens)`, and the bar, `DragGhostPanel` and `BarMoveGhostPanel` `Variants` all use `root.realScreens`. - Qt names a screen before adding it, so only its size can arrive late. Those size reads are tracked by the binding, so a screen whose size lands afterwards still gets its ", "author": "dreed47", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "383ec718cc907b4456adf3c8e11112ac45eb1bcc176ef0e8512a77753d87bb48", "head_sha": "67a5645948c0b2981481ef89bb71a769269ecf54", "updated_at": "2026-09-28T14:19:58Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:19:43.856768+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.73, "probabilities": {"update-release": 0.0, "fix-misc": 0.05, "agents-ai": 0.0, "apps-integrations": 0.0, "docs": 0.0, "install-setup": 0.0, "unclear": 0.01, "shell-cli": 0.0, "hardware-drivers": 0.77, "desktop-config": 0.17}}, "risk": {"type": "score", "score": 0.98, "confidence": 0.95, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.04, "1": 0.94, "2": 0.01, "3": 0.01, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.95}, "dupe_signal": {"type": "noul", "noul": 0.17}, "finished_form": {"type": "score", "score": 2.78, "confidence": 0.78, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.0, "2": 0.22, "3": 0.78}}, "review_effort": {"type": "score", "score": 1.75, "confidence": 0.74, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.26, "2": 0.73, "3": 0.01}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1617, "output_tokens": 198}, "binding": "36aad1be43ab87d175cf5042d993dede938e63b0352e2a8d4c4ac5145407b1a7", "input": {"pr": {"title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negative current_now, which is the normal discharging sign), - rejects insane magnitudes (>150W) or values wildly above UPower's rate (>3x when UPower is solid), keeping the UPower value instead, - displays the rate as magnitude (state already says charging/discharging, so no more -1124W), - compares idle against magnitude so a large negative rate can't fake charge-idle, - omits cycle_count 0 when UPower reports charge-cycles N/A so the panel shows \u2014 instead of a misleading 0. Complements #12649/#12755 (those cover failed/empty reads); this covers bogus-but-numeric reads. Verified with the extended battery-status-test.sh scenarios (bogus -65A, non-numeric, sane negative discharge) plus live hardware: bogus -1113W discharge now shows 7.5W, and a sane 29.1W charge still uses the live sysfs value.", "author": "Kristijan-K", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "9da88c5155aabbf117690797af596147cd77aa0822c9e9e9095e90bb01550975", "head_sha": "85b13dcd7d80423448877ef47bfda0f2ebd7f61b", "updated_at": "2026-10-01T08:16:02Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:19:49.767682+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.46, "probabilities": {"agents-ai": 0.0, "update-release": 0.0, "install-setup": 0.0, "shell-cli": 0.35000000000000003, "unclear": 0.0, "hardware-drivers": 0.52, "apps-integrations": 0.0, "fix-misc": 0.13, "desktop-config": 0.0, "docs": 0.0}}, "risk": {"type": "score", "score": 1.0, "confidence": 1.0, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 1.0, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.97}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 2.44, "confidence": 0.44, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.15, "2": 0.25, "3": 0.6}}, "review_effort": {"type": "score", "score": 1.27, "confidence": 0.73, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.73, "2": 0.27, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1622, "output_tokens": 198}, "binding": "1fc573ef33e205cd80661b54ee9afa5d841ead2849ca939d3d3410b29fdb170d", "input": {"pr": {"title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same hazard in the `current_now`/`voltage_now` branch. ## Change - `bin/omarchy-battery-status`: only override the UPower rate when the sysfs read actually succeeds and is numeric (`cat ... 2>/dev/null` + `^[0-9]+$` guard, as suggested in the issue), for both the `power_now` and the `current_now`/`voltage_now` branches. Otherwise the UPower value stands. - `test/shell.d/battery-status-test.sh`: two new scenarios \u2014 a `power_now` node whose read fails (fake `cat` refusing `power_now`, standing in for the ENODEV kernel read) and a non-numeric `current_now` \u2014 both asserting the UPower rate survives. ## Verification - `bash test/shell.d/battery-status-test.sh`: pass (new assertions included) - Negative control: the new assertions fail against the pre-fix script (`not ok - battery status keeps the UPo", "author": "anandude", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "08cd688dde6399d11ba9025f400bc4e050082e16da0994ad78837bdc3c516b35", "head_sha": "370a3b61fbb8f4c358bbb423b5d8c4c97bae33e8", "updated_at": "2026-09-27T19:29:39Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:19:58.108644+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.88, "probabilities": {"fix-misc": 0.0, "agents-ai": 0.0, "update-release": 0.1, "install-setup": 0.0, "desktop-config": 0.0, "docs": 0.0, "shell-cli": 0.0, "hardware-drivers": 0.9, "apps-integrations": 0.0, "unclear": 0.0}}, "risk": {"type": "score", "score": 2.8, "confidence": 0.8, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.06, "2": 0.08, "3": 0.83, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.75}, "dupe_signal": {"type": "noul", "noul": 0.66}, "finished_form": {"type": "score", "score": 1.0, "confidence": 0.95, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.03, "1": 0.95, "2": 0.02, "3": 0.0}}, "review_effort": {"type": "score", "score": 2.65, "confidence": 0.65, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.02, "2": 0.3, "3": 0.68}}, "security_flag": {"type": "noul", "noul": 0.09}}, "usage": {"input_tokens": 1616, "output_tokens": 198}, "binding": "a3354c821f4cca269cfbf80ddf9301aa8e5ef96d55a261e915961ffaa5248ac6", "input": {"pr": {"title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware or merge-readiness certification is claimed. Part of the [14-feature Intel Mac series]( with three package companions. **Contribute:** open follow-up PRs in `andrew-boyd/omarchy` with base **`intel-mac/p02-kernel-headers`**. Use `[Intel Mac P02]` in the title and a contributor branch such as `intel-mac/p02/describe-change`. Link this feature in the series index. Merging a follow-up into this branch updates its roll-up. This existing draft: [ ## Full Intel Mac scope and current revision The project covers **all 64-bit Intel Macs: pre-T1, T1 and T2**. MacBookPro13,3 is only the first available physical test machine. Each feature has its own hardware boundary; one model's success does not validate the rest. Candidate head: `803260c8feff6d9ed5dbac60d5f630cd45ae1b56`; reconciled upstream: `8f324", "author": "andrew-boyd", "diffstat": "unknown (not supplied by the captured PR list)", "draft": true, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "e7766e58defa100b6b22222dab54e94a11010ad7741d97860dd1fe0b30ec2f13", "head_sha": "803260c8feff6d9ed5dbac60d5f630cd45ae1b56", "updated_at": "2026-09-27T19:29:10Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:20:00.231552+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.95, "probabilities": {"fix-misc": 0.03, "apps-integrations": 0.0, "shell-cli": 0.01, "install-setup": 0.0, "agents-ai": 0.0, "update-release": 0.0, "docs": 0.0, "unclear": 0.01, "desktop-config": 0.0, "hardware-drivers": 0.95}}, "risk": {"type": "score", "score": 1.0, "confidence": 0.99, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 1.0, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.97}, "dupe_signal": {"type": "noul", "noul": 0.43}, "finished_form": {"type": "score", "score": 2.29, "confidence": 0.61, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.05, "2": 0.61, "3": 0.34}}, "review_effort": {"type": "score", "score": 1.43, "confidence": 0.56, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.57, "2": 0.43, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1529, "output_tokens": 198}, "binding": "9564e6ba5531d44e7d649650c48047c7f23e1b3044a73593ef14a73b8424f249", "input": {"pr": {"title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split out from #6845 per @bjarneo's request \u2014 that PR grew to cover 3 failure modes and was closed as a dup of #10392, which only handles multi-battery percentage and keeps this bug. This is the minimal fix for #6895 with regression tests for both empty-read cases. Fixes #6895. Extracted from #6845 (`3c40745`). Verified: existing `battery-status-test.sh` + 2 new ENODEV cases pass.", "author": "ujo4eva", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "e065d8a737dada9c08845b54bc35f3ac92e018838e2d297cdd6c33836179570e", "head_sha": "50a935005cd82b5726ae21a19e86069b57f7ba21", "updated_at": "2026-09-27T19:29:00Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:20:01.032941+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 1.0, "probabilities": {"update-release": 0.0, "unclear": 0.0, "hardware-drivers": 1.0, "apps-integrations": 0.0, "install-setup": 0.0, "fix-misc": 0.0, "agents-ai": 0.0, "desktop-config": 0.0, "docs": 0.0, "shell-cli": 0.0}}, "risk": {"type": "score", "score": 2.99, "confidence": 0.97, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.0, "2": 0.01, "3": 0.97, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.07}, "finished_form": {"type": "score", "score": 1.43, "confidence": 0.56, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.66, "2": 0.24, "3": 0.1}}, "review_effort": {"type": "score", "score": 2.01, "confidence": 0.9, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.04, "2": 0.91, "3": 0.05}}, "security_flag": {"type": "noul", "noul": 0.17}}, "usage": {"input_tokens": 1414, "output_tokens": 198}, "binding": "bc66ca1bfcf2272c9eb85f60afb6c5f722088f944cc114af119e1cc0e783ab78", "input": {"pr": {"title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers-test.sh ```", "author": "paulogeyer", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "a2414cac2cab635241fc6be0fa965339f9ce009e1ebf86bca2f6fdd089c627ba", "head_sha": "40fc412e5e7fd6b9a5c883e7b4ac361b8b4544b4", "updated_at": "2026-10-01T04:31:40Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:20:16.417984+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.89, "probabilities": {"install-setup": 0.01, "update-release": 0.09, "agents-ai": 0.0, "fix-misc": 0.0, "unclear": 0.0, "shell-cli": 0.0, "apps-integrations": 0.0, "desktop-config": 0.0, "docs": 0.0, "hardware-drivers": 0.9}}, "risk": {"type": "score", "score": 2.87, "confidence": 0.82, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.03, "2": 0.1, "3": 0.83, "4": 0.04}}, "is_fix": {"type": "noul", "noul": 0.9}, "dupe_signal": {"type": "noul", "noul": 0.23}, "finished_form": {"type": "score", "score": 1.49, "confidence": 0.51, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.56, "2": 0.39, "3": 0.05}}, "review_effort": {"type": "score", "score": 1.73, "confidence": 0.63, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.32, "2": 0.63, "3": 0.05}}, "security_flag": {"type": "noul", "noul": 0.09}}, "usage": {"input_tokens": 1674, "output_tokens": 198}, "binding": "0ba19cfe712c2376cf887e7bd4b8d854952225570841213744d47a81bdce3e2a", "input": {"pr": {"title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or BCM4331 then come back from the Quattro upgrade with no driver bound and no Wi-Fi device at all. The installer's `fix-bcm43xx.sh` never runs on those machines, and `1789444024` only covers `linux-omarchy` and `linux-t2`. `1789325478` will give `linux-omarchy` its headers, but it deliberately leaves the stock kernel installed as the boot fallback. On these Macs that fallback still has no Wi-Fi, which is usually the way back to a working system. This migration installs headers for any installed Arch kernel (`linux`, `linux-lts`, `linux-zen`, `linux-hardened`) when `broadcom-wl-dkms` is present. The dkms pacman hook triggers on `usr/lib/modules/*/build/include/`, so installing the headers builds the module. ## Testing - `test/shell.d/broadcom-wl-headers-migration-test.sh` covers the repair, i", "author": "oliverox", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "86890d152811b26b501368c12374bdc24574fcd333cc3b9100165573aafbbb9e", "head_sha": "18378142c12b85565c460ddfb1279226d42c977e", "updated_at": "2026-10-01T04:29:47Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T10:20:16.765043+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "answers": {"review_effort": {"type": "score", "score": 1.06, "confidence": 0.93, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.94, "2": 0.06, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}, "category": {"type": "choice", "choice": "desktop-config", "confidence": 0.98, "probabilities": {"shell-cli": 0.0, "unclear": 0.0, "user-experience": 0.0, "agents-ai": 0.0, "hardware-drivers": 0.0, "docs": 0.0, "fix-misc": 0.01, "apps-integrations": 0.0, "update-release": 0.0, "desktop-config": 0.99, "install-setup": 0.0}}, "risk": {"type": "score", "score": 1.04, "confidence": 0.96, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.98, "2": 0.01, "3": 0.0, "4": 0.01}}, "is_fix": {"type": "noul", "noul": 0.93}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 1.65, "confidence": 0.56, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.39, "2": 0.56, "3": 0.05}}}, "usage": {"input_tokens": 1424, "output_tokens": 208}, "binding": "7c8e37dbcaf0088b692f3bd7cd3a67156411994b6c87f28bbce5a303258c4976", "input": {"pr": {"title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "3ed7bb42a4d99748a46df06890fe0f1980dc14b1c8c661c3ba5561830a8f31f7", "head_sha": "00ef70cbf708e0b1542ea01c4b1d88e3284be76d", "updated_at": "2026-09-29T21:12:09Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:26.860477+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "answers": {"category": {"type": "choice", "choice": "user-experience", "confidence": 0.53, "probabilities": {"install-setup": 0.0, "agents-ai": 0.0, "hardware-drivers": 0.0, "desktop-config": 0.33, "shell-cli": 0.0, "update-release": 0.0, "fix-misc": 0.06, "user-experience": 0.57, "docs": 0.0, "apps-integrations": 0.02, "unclear": 0.02}}, "risk": {"type": "score", "score": 0.77, "confidence": 0.8, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.23, "1": 0.77, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.93}, "dupe_signal": {"type": "noul", "noul": 0.04}, "finished_form": {"type": "score", "score": 1.33, "confidence": 0.67, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.75, "2": 0.16, "3": 0.09}}, "review_effort": {"type": "score", "score": 1.05, "confidence": 0.95, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.95, "2": 0.05, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1440, "output_tokens": 211}, "binding": "10ac1db8147d389e0b3184efc33af4e373170dc83459e140b8948261374026dc", "input": {"pr": {"title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "9e0036efdb167f48533c9e32ac2502dc3186bf0c42b08dd449af6d7b654dd575", "head_sha": "151b281f28d647691a983141689026b29349e569", "updated_at": "2026-09-29T21:10:02Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:28.776216+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.92, "probabilities": {"fix-misc": 0.07, "unclear": 0.0, "docs": 0.0, "user-experience": 0.0, "hardware-drivers": 0.0, "shell-cli": 0.0, "update-release": 0.0, "agents-ai": 0.0, "desktop-config": 0.93, "install-setup": 0.0, "apps-integrations": 0.0}}, "risk": {"type": "score", "score": 1.08, "confidence": 0.92, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.96, "2": 0.01, "3": 0.0, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 2.37, "confidence": 0.48, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.07, "2": 0.48, "3": 0.45}}, "review_effort": {"type": "score", "score": 1.12, "confidence": 0.88, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.88, "2": 0.12, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1516, "output_tokens": 208}, "binding": "48cd17a83ac4a693889b8133533327fb0062e3be11f84fcd07c6fe38f6628f35", "input": {"pr": {"title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out nameless and `FALLBACK` screens in `BarModel.realScreens`, ensuring bar surfaces are only created for real outputs with confirmed geometry. Fixes #13072 ## Testing - Updated `test/shell.d/bar-test.sh` with assertions for screen filtering. - Ran `bash test/shell.d/bar-test.sh` (all 98 assertions pass).", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "dfd6b9b48d36332717d20cd87c0092a3f353c7a76f10616c9e707bee5f1c2f04", "head_sha": "ec58ce82fdc5521e5109f1760df1fb502f3f45c2", "updated_at": "2026-09-29T21:09:30Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:34.585458+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13463, "title": "Scale the clock panel hero text with fontScale", "answers": {"category": {"type": "choice", "choice": "user-experience", "confidence": 0.52, "probabilities": {"install-setup": 0.0, "desktop-config": 0.29, "user-experience": 0.5599999999999999, "shell-cli": 0.01, "apps-integrations": 0.01, "hardware-drivers": 0.0, "update-release": 0.0, "agents-ai": 0.0, "docs": 0.0, "fix-misc": 0.12, "unclear": 0.01}}, "risk": {"type": "score", "score": 0.87, "confidence": 0.88, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.14, "1": 0.86, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.94}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 1.73, "confidence": 0.61, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.33, "2": 0.61, "3": 0.06}}, "review_effort": {"type": "score", "score": 1.03, "confidence": 0.95, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.01, "1": 0.95, "2": 0.04, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1685, "output_tokens": 211}, "binding": "d03dc83f752f077ff7335f4ffa3182117ba43970009e7471ddce7085d7f25fa3", "input": {"pr": {"title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the card drops 560 \u2192 420px while the hero stayed at 52px. This scales the hero date and its decorative glyph with `Style.fontScale` using the codebase's standard `Math.max(1, Math.round(...))` idiom. The glyph/date ratio stays deliberately outside the `Style.font.*` scale \u2014 both now track the card that contains them instead. At the default `base-size = 12`, `fontScale` is exactly 1, so rendering is pixel-identical there. Fixes #13381 ## Testing - `test/shell.d` has no clock-panel geometry tests; the full suite was previously run on this tree with only the known environment failures (missing `omarchy-pkgs` checkout). - Rendering is provably unchanged at defaults (`fontScale == 1`); visual verification at `base-size = 9` per `agents/skills/visual-verification.md` on a dev-linked session is recom", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "bf696bf0cc001e0fbdbdafea7300d747e1752484dd71ba8c440c309ee069507d", "head_sha": "02cd42f24f5ef7aaaecdeaef68c023973eaea030", "updated_at": "2026-09-27T21:45:20Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:35.488295+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13459, "title": "Scale clock panel hero date with fontScale", "answers": {"category": {"type": "choice", "choice": "user-experience", "confidence": 0.46, "probabilities": {"update-release": 0.0, "unclear": 0.01, "user-experience": 0.52, "docs": 0.0, "desktop-config": 0.29, "shell-cli": 0.04, "hardware-drivers": 0.0, "install-setup": 0.0, "agents-ai": 0.0, "fix-misc": 0.12, "apps-integrations": 0.02}}, "risk": {"type": "score", "score": 0.93, "confidence": 0.93, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.08, "1": 0.92, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.93}, "dupe_signal": {"type": "noul", "noul": 0.04}, "finished_form": {"type": "score", "score": 2.15, "confidence": 0.67, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.09, "2": 0.67, "3": 0.24}}, "review_effort": {"type": "score", "score": 1.01, "confidence": 0.98, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.98, "2": 0.02, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1586, "output_tokens": 211}, "binding": "213a48adbe12022eb1344f1e83cf52907a1fa4bfbbc7c79ad0abde9191994813", "input": {"pr": {"title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales both the decorative calendar icon and hero date string using `Style.fontScale` (`Math.max(1, Math.round(size * Style.fontScale))`). At default `fontBaseSize = 12` (`fontScale = 1.0`), the rendered pixel sizes are completely unchanged (48 and 52), while at smaller or larger base sizes they scale in exact proportion with the popup card. Fixes #13381 ## Testing - `bash test/shell.d/clock-test.sh`: all tests pass, including new assertion verifying that the hero date and glyph scale with `Style.fontScale`. - `./test/cli`: passed.", "author": "AnPod", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "228db4dadf12518446ad7c8f9bcb8fb1cc69a7a61fb3df56df8b68d255de3df1", "head_sha": "d6c2c80815a222a27868c41bf8d2ff3cbf86bc66", "updated_at": "2026-09-27T21:32:33Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:35.724770+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13165, "title": "Skip placeholder screens when building bars", "answers": {"category": {"type": "choice", "choice": "desktop-config", "confidence": 0.84, "probabilities": {"update-release": 0.0, "fix-misc": 0.11, "desktop-config": 0.86, "docs": 0.0, "install-setup": 0.0, "agents-ai": 0.0, "hardware-drivers": 0.0, "shell-cli": 0.0, "apps-integrations": 0.0, "unclear": 0.01, "user-experience": 0.02}}, "risk": {"type": "score", "score": 1.01, "confidence": 0.98, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.99, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.06}, "finished_form": {"type": "score", "score": 1.15, "confidence": 0.85, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.86, "2": 0.14, "3": 0.0}}, "review_effort": {"type": "score", "score": 1.85, "confidence": 0.85, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.15, "2": 0.85, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1674, "output_tokens": 208}, "binding": "434db68528c11eb0f4bda004640afd71166f55d61b5dc65f3afe6e9df1600509", "input": {"pr": {"title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When the real monitors came back, the compositor dropped that orphaned bar onto the first monitor to return, stacked over its own bar, and the second monitor had no bar until the real ones finished building. ## Change - `BarModel.js` gets `isRealScreen()` / `realScreens()`: screens with a name that isn't `FALLBACK` and a non-zero size. It uses the same test `plugins/lock/Service.qml` uses in `realScreenCount()`, plus the `FALLBACK` exclusion. - `Bar.qml`: `readonly property var realScreens: BarModel.realScreens(Quickshell.screens)`, and the bar, `DragGhostPanel` and `BarMoveGhostPanel` `Variants` all use `root.realScreens`. - Qt names a screen before adding it, so only its size can arrive late. Those size reads are tracked by the binding, so a screen whose size lands afterwards still gets its ", "author": "dreed47", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "638cb3e72efed9055911cee03a8ee91cfec17a2d16acd6d5db0432b944c53aa0", "head_sha": "67a5645948c0b2981481ef89bb71a769269ecf54", "updated_at": "2026-09-28T14:19:58Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:42.843699+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.8, "probabilities": {"fix-misc": 0.06, "user-experience": 0.03, "hardware-drivers": 0.8099999999999999, "agents-ai": 0.0, "desktop-config": 0.09, "apps-integrations": 0.01, "install-setup": 0.0, "unclear": 0.0, "update-release": 0.0, "docs": 0.0, "shell-cli": 0.0}}, "risk": {"type": "score", "score": 0.97, "confidence": 0.95, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.05, "1": 0.94, "2": 0.01, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.95}, "dupe_signal": {"type": "noul", "noul": 0.17}, "finished_form": {"type": "score", "score": 2.78, "confidence": 0.78, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.0, "2": 0.21, "3": 0.79}}, "review_effort": {"type": "score", "score": 1.71, "confidence": 0.7, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.3, "2": 0.7, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1668, "output_tokens": 209}, "binding": "1884773c42958e7c0feb9b2df4084c9efc9f57bdcfc4f0c34f14b5410cf80475", "input": {"pr": {"title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negative current_now, which is the normal discharging sign), - rejects insane magnitudes (>150W) or values wildly above UPower's rate (>3x when UPower is solid), keeping the UPower value instead, - displays the rate as magnitude (state already says charging/discharging, so no more -1124W), - compares idle against magnitude so a large negative rate can't fake charge-idle, - omits cycle_count 0 when UPower reports charge-cycles N/A so the panel shows \u2014 instead of a misleading 0. Complements #12649/#12755 (those cover failed/empty reads); this covers bogus-but-numeric reads. Verified with the extended battery-status-test.sh scenarios (bogus -65A, non-numeric, sane negative discharge) plus live hardware: bogus -1113W discharge now shows 7.5W, and a sane 29.1W charge still uses the live sysfs value.", "author": "Kristijan-K", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "7a85df8e90c6002d9be1790c6236612b8c041f6032cedd1280e99ce95858ccac", "head_sha": "85b13dcd7d80423448877ef47bfda0f2ebd7f61b", "updated_at": "2026-10-01T08:16:02Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:48.765682+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.69, "probabilities": {"hardware-drivers": 0.73, "user-experience": 0.0, "apps-integrations": 0.0, "fix-misc": 0.11, "install-setup": 0.0, "update-release": 0.0, "agents-ai": 0.0, "desktop-config": 0.0, "unclear": 0.0, "shell-cli": 0.16, "docs": 0.0}}, "risk": {"type": "score", "score": 1.0, "confidence": 1.0, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 1.0, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.97}, "dupe_signal": {"type": "noul", "noul": 0.05}, "finished_form": {"type": "score", "score": 2.48, "confidence": 0.48, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.14, "2": 0.24, "3": 0.62}}, "review_effort": {"type": "score", "score": 1.31, "confidence": 0.69, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.69, "2": 0.31, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1673, "output_tokens": 209}, "binding": "8a9e8ade3c3b485ec9c4864a202cd7c0d9bdcdce0649ca88137dfec220b2bc5d", "input": {"pr": {"title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same hazard in the `current_now`/`voltage_now` branch. ## Change - `bin/omarchy-battery-status`: only override the UPower rate when the sysfs read actually succeeds and is numeric (`cat ... 2>/dev/null` + `^[0-9]+$` guard, as suggested in the issue), for both the `power_now` and the `current_now`/`voltage_now` branches. Otherwise the UPower value stands. - `test/shell.d/battery-status-test.sh`: two new scenarios \u2014 a `power_now` node whose read fails (fake `cat` refusing `power_now`, standing in for the ENODEV kernel read) and a non-numeric `current_now` \u2014 both asserting the UPower rate survives. ## Verification - `bash test/shell.d/battery-status-test.sh`: pass (new assertions included) - Negative control: the new assertions fail against the pre-fix script (`not ok - battery status keeps the UPo", "author": "anandude", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "781de83ac5183236cd4eab66f7d52dd3be5179d65a077a96ff575631c1cccba5", "head_sha": "370a3b61fbb8f4c358bbb423b5d8c4c97bae33e8", "updated_at": "2026-09-27T19:29:39Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:56.417924+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.81, "probabilities": {"unclear": 0.01, "fix-misc": 0.01, "desktop-config": 0.0, "shell-cli": 0.0, "hardware-drivers": 0.83, "install-setup": 0.0, "agents-ai": 0.0, "apps-integrations": 0.0, "user-experience": 0.0, "update-release": 0.15, "docs": 0.0}}, "risk": {"type": "score", "score": 2.8, "confidence": 0.81, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.01, "1": 0.06, "2": 0.07, "3": 0.84, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.76}, "dupe_signal": {"type": "noul", "noul": 0.65}, "finished_form": {"type": "score", "score": 0.99, "confidence": 0.95, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.03, "1": 0.95, "2": 0.02, "3": 0.0}}, "review_effort": {"type": "score", "score": 2.65, "confidence": 0.65, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.02, "2": 0.3, "3": 0.68}}, "security_flag": {"type": "noul", "noul": 0.09}}, "usage": {"input_tokens": 1667, "output_tokens": 209}, "binding": "7a0c892a50e86845d6a1004bafc80b68ac6b46d9f26b345fa1f62cb81d9055dc", "input": {"pr": {"title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware or merge-readiness certification is claimed. Part of the [14-feature Intel Mac series]( with three package companions. **Contribute:** open follow-up PRs in `andrew-boyd/omarchy` with base **`intel-mac/p02-kernel-headers`**. Use `[Intel Mac P02]` in the title and a contributor branch such as `intel-mac/p02/describe-change`. Link this feature in the series index. Merging a follow-up into this branch updates its roll-up. This existing draft: [ ## Full Intel Mac scope and current revision The project covers **all 64-bit Intel Macs: pre-T1, T1 and T2**. MacBookPro13,3 is only the first available physical test machine. Each feature has its own hardware boundary; one model's success does not validate the rest. Candidate head: `803260c8feff6d9ed5dbac60d5f630cd45ae1b56`; reconciled upstream: `8f324", "author": "andrew-boyd", "diffstat": "unknown (not supplied by the captured PR list)", "draft": true, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "c83eb4adb2ecaeb0e085f1ecd7ce80eb2f03c04bfb368dbf4addaf817ea22514", "head_sha": "803260c8feff6d9ed5dbac60d5f630cd45ae1b56", "updated_at": "2026-09-27T19:29:10Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:58.738409+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.96, "probabilities": {"shell-cli": 0.01, "desktop-config": 0.0, "agents-ai": 0.0, "apps-integrations": 0.0, "docs": 0.0, "update-release": 0.0, "install-setup": 0.0, "user-experience": 0.0, "fix-misc": 0.02, "unclear": 0.0, "hardware-drivers": 0.97}}, "risk": {"type": "score", "score": 1.0, "confidence": 0.99, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 1.0, "2": 0.0, "3": 0.0, "4": 0.0}}, "is_fix": {"type": "noul", "noul": 0.97}, "dupe_signal": {"type": "noul", "noul": 0.42}, "finished_form": {"type": "score", "score": 2.27, "confidence": 0.63, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.05, "2": 0.63, "3": 0.32}}, "review_effort": {"type": "score", "score": 1.4, "confidence": 0.6, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.6, "2": 0.4, "3": 0.0}}, "security_flag": {"type": "noul", "noul": 0.02}}, "usage": {"input_tokens": 1580, "output_tokens": 209}, "binding": "6b5d2fb742bcd0d348a40b019cd7530310b77cf42302432a1d06d81a113161c1", "input": {"pr": {"title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split out from #6845 per @bjarneo's request \u2014 that PR grew to cover 3 failure modes and was closed as a dup of #10392, which only handles multi-battery percentage and keeps this bug. This is the minimal fix for #6895 with regression tests for both empty-read cases. Fixes #6895. Extracted from #6845 (`3c40745`). Verified: existing `battery-status-test.sh` + 2 new ENODEV cases pass.", "author": "ujo4eva", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "f78454ca5db5b065576c3e5f93486154aeef2bd3c38a71424b211deadd8f9b93", "head_sha": "50a935005cd82b5726ae21a19e86069b57f7ba21", "updated_at": "2026-09-27T19:29:00Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:06:59.689833+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 1.0, "probabilities": {"unclear": 0.0, "install-setup": 0.0, "fix-misc": 0.0, "user-experience": 0.0, "docs": 0.0, "shell-cli": 0.0, "hardware-drivers": 1.0, "apps-integrations": 0.0, "update-release": 0.0, "agents-ai": 0.0, "desktop-config": 0.0}}, "risk": {"type": "score", "score": 3.0, "confidence": 0.97, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.0, "2": 0.02, "3": 0.96, "4": 0.02}}, "is_fix": {"type": "noul", "noul": 0.96}, "dupe_signal": {"type": "noul", "noul": 0.07}, "finished_form": {"type": "score", "score": 1.44, "confidence": 0.56, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.64, "2": 0.27, "3": 0.09}}, "review_effort": {"type": "score", "score": 2.0, "confidence": 0.91, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.04, "2": 0.91, "3": 0.05}}, "security_flag": {"type": "noul", "noul": 0.18}}, "usage": {"input_tokens": 1465, "output_tokens": 209}, "binding": "877de3d3bd75669b9c4929a895b2861c3cdbba0534932c5548822234a8a2e0f1", "input": {"pr": {"title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers-test.sh ```", "author": "paulogeyer", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": false}}, "source_digest": "ad25fbf97d81dcbfb377fdf85af0e335c727e20eed5fc9d8ba42c27c5a220091", "head_sha": "40fc412e5e7fd6b9a5c883e7b4ac361b8b4544b4", "updated_at": "2026-10-01T04:31:40Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:07:13.938278+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} +{"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "answers": {"category": {"type": "choice", "choice": "hardware-drivers", "confidence": 0.85, "probabilities": {"install-setup": 0.02, "docs": 0.0, "update-release": 0.12, "shell-cli": 0.0, "fix-misc": 0.0, "agents-ai": 0.0, "user-experience": 0.0, "unclear": 0.0, "desktop-config": 0.0, "hardware-drivers": 0.86, "apps-integrations": 0.0}}, "risk": {"type": "score", "score": 2.82, "confidence": 0.79, "legend": {"0": "Text-only: docs, themes, wallpapers, menu definitions; nothing executes", "1": "Config or script change that is scoped and revertible; no root-side effects at install/update time", "2": "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults", "3": "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware", "4": "Could break existing installs outright: data loss, boot failure, or user lockout"}, "probabilities": {"0": 0.0, "1": 0.05, "2": 0.12, "3": 0.79, "4": 0.04}}, "is_fix": {"type": "noul", "noul": 0.91}, "dupe_signal": {"type": "noul", "noul": 0.21}, "finished_form": {"type": "score", "score": 1.47, "confidence": 0.53, "legend": {"0": "Empty or near-empty body; no description of what or why", "1": "Says what it does but not why, or shows no evidence it was tried", "2": "Clear what and why; states that it was tested on a real system", "3": "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused"}, "probabilities": {"0": 0.0, "1": 0.57, "2": 0.38, "3": 0.05}}, "review_effort": {"type": "score", "score": 1.75, "confidence": 0.64, "legend": {"0": "Trivial and mechanical: a typo, version number, or one-line constant", "1": "Small: one focused change a reviewer can hold in their head", "2": "Moderate: several related edits that must be checked together", "3": "Substantial: architectural or many-part change needing deep review"}, "probabilities": {"0": 0.0, "1": 0.3, "2": 0.64, "3": 0.06}}, "security_flag": {"type": "noul", "noul": 0.09}}, "usage": {"input_tokens": 1725, "output_tokens": 209}, "binding": "e621bdcb7138c0d9ff98207f35ba299bb56b299690ab49a97e07f4754eaeb8f2", "input": {"pr": {"title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or BCM4331 then come back from the Quattro upgrade with no driver bound and no Wi-Fi device at all. The installer's `fix-bcm43xx.sh` never runs on those machines, and `1789444024` only covers `linux-omarchy` and `linux-t2`. `1789325478` will give `linux-omarchy` its headers, but it deliberately leaves the stock kernel installed as the boot fallback. On these Macs that fallback still has no Wi-Fi, which is usually the way back to a working system. This migration installs headers for any installed Arch kernel (`linux`, `linux-lts`, `linux-zen`, `linux-hardened`) when `broadcom-wl-dkms` is present. The dkms pacman hook triggers on `usr/lib/modules/*/build/include/`, so installing the headers builds the module. ## Testing - `test/shell.d/broadcom-wl-headers-migration-test.sh` covers the repair, i", "author": "oliverox", "diffstat": "unknown (not supplied by the captured PR list)", "draft": false, "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified", "diffstat_available": false, "body_truncated": true}}, "source_digest": "9c764310ee6e05b6fff8c3cf3ae71f45c240cc08ed18c8822d94ffb70d71a837", "head_sha": "18378142c12b85565c460ddfb1279226d42c977e", "updated_at": "2026-10-01T04:29:47Z", "requested_model": "jev-latest", "judged_at": "2026-10-01T18:07:14.149524+00:00", "resolved_model": "jev-1.13.0", "request_id": null, "normalization_errors": []} diff --git a/crates/tranche-core/tests/fixture/out/pair_verdicts.jsonl b/crates/tranche-core/tests/fixture/out/pair_verdicts.jsonl new file mode 100644 index 0000000..a9a8d9d --- /dev/null +++ b/crates/tranche-core/tests/fixture/out/pair_verdicts.jsonl @@ -0,0 +1,48 @@ +{"a": 13459, "b": 13463, "similarity": 0.909, "verdict": "same_change", "probabilities": {"same_change": 1.0, "unrelated": 0.0, "related_but_different": 0.0}, "usage": {"input_tokens": 697, "output_tokens": 49}} +{"a": 13477, "b": 13645, "similarity": 0.911, "verdict": "same_change", "probabilities": {"related_but_different": 0.0, "unrelated": 0.0, "same_change": 1.0}, "usage": {"input_tokens": 640, "output_tokens": 49}} +{"a": 13165, "b": 13645, "similarity": 0.869, "verdict": "same_change", "probabilities": {"same_change": 1.0, "related_but_different": 0.0, "unrelated": 0.0}, "usage": {"input_tokens": 654, "output_tokens": 49}} +{"a": 12649, "b": 12755, "similarity": 0.824, "verdict": "same_change", "probabilities": {"related_but_different": 0.0, "same_change": 1.0, "unrelated": 0.0}, "usage": {"input_tokens": 711, "output_tokens": 49}} +{"a": 13459, "b": 13613, "similarity": 0.808, "verdict": "same_change", "probabilities": {"same_change": 0.87, "unrelated": 0.0, "related_but_different": 0.13}, "usage": {"input_tokens": 662, "output_tokens": 49}} +{"a": 13165, "b": 13477, "similarity": 0.768, "verdict": "same_change", "probabilities": {"related_but_different": 0.0, "same_change": 1.0, "unrelated": 0.0}, "usage": {"input_tokens": 668, "output_tokens": 49}} +{"a": 12074, "b": 12090, "similarity": 0.76, "verdict": "same_change", "probabilities": {"same_change": 0.9, "unrelated": 0.0, "related_but_different": 0.1}, "usage": {"input_tokens": 740, "output_tokens": 49}} +{"a": 13463, "b": 13613, "similarity": 0.741, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "related_but_different": 0.27, "same_change": 0.73}, "usage": {"input_tokens": 693, "output_tokens": 49}} +{"a": 12755, "b": 13009, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.6900000000000001, "unrelated": 0.0, "related_but_different": 0.31}, "usage": {"input_tokens": 697, "output_tokens": 49}} +{"a": 12649, "b": 13009, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.81, "unrelated": 0.0, "related_but_different": 0.19}, "usage": {"input_tokens": 696, "output_tokens": 49}} +{"a": 12074, "b": 12680, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.9, "unrelated": 0.0, "related_but_different": 0.1}, "usage": {"input_tokens": 710, "output_tokens": 49}} +{"a": 12090, "b": 12680, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.93, "unrelated": 0.0, "related_but_different": 0.07}, "usage": {"input_tokens": 670, "output_tokens": 49}} +{"a": 12755, "b": 13009, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.74, "unrelated": 0.0, "related_but_different": 0.26}, "usage": {"input_tokens": 741, "output_tokens": 49}, "binding": "baee639b4c89ad5961f6d41636b91fab0846c9026ad6e02c9882ec47c7c39d23", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:12.093522+00:00", "input": {"pr_a": {"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same h", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negat", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12649, "b": 13009, "similarity": 1.0, "verdict": "same_change", "probabilities": {"related_but_different": 0.2, "unrelated": 0.0, "same_change": 0.8}, "usage": {"input_tokens": 740, "output_tokens": 49}, "binding": "fab8bb4c54fdb2457e122f6e6b19aa476c47bba53eadebb0ac1d5089d5d446d6", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:12.141748+00:00", "input": {"pr_a": {"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negat", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12090, "b": 12680, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.91, "unrelated": 0.0, "related_but_different": 0.09}, "usage": {"input_tokens": 714, "output_tokens": 49}, "binding": "3af3f4db880be708a991ae2ababa02b87077bc4cf5202299b5c13b10a3b7f35b", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:19.613359+00:00", "input": {"pr_a": {"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12074, "b": 12680, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.89, "related_but_different": 0.11, "unrelated": 0.0}, "usage": {"input_tokens": 754, "output_tokens": 49}, "binding": "a8df5dd355897e2438743009b1ee14c58a734b410dfe0062a30392770ace5b94", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:19.665949+00:00", "input": {"pr_a": {"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13459, "b": 13463, "similarity": 0.909, "verdict": "same_change", "probabilities": {"related_but_different": 0.0, "unrelated": 0.0, "same_change": 1.0}, "usage": {"input_tokens": 741, "output_tokens": 49}, "binding": "bb1b7ffd6e18936657c6871d28e95acf356b7912f3d96bde1a2bd257151ba189", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:42.035432+00:00", "input": {"pr_a": {"number": 13459, "title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales bo", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13463, "title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13477, "b": 13645, "similarity": 0.911, "verdict": "same_change", "probabilities": {"same_change": 1.0, "unrelated": 0.0, "related_but_different": 0.0}, "usage": {"input_tokens": 684, "output_tokens": 49}, "binding": "39b48960db8beb5a508b8c89a25bbb00398a3ec5403eb918452909a65c5c071a", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:42.076381+00:00", "input": {"pr_a": {"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out namel", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13165, "b": 13645, "similarity": 0.869, "verdict": "same_change", "probabilities": {"related_but_different": 0.01, "unrelated": 0.0, "same_change": 0.99}, "usage": {"input_tokens": 698, "output_tokens": 49}, "binding": "bfe89b1c1bc95c60333437b1c7046674ce9c1cfa7b6e71db2234b2a6104416ed", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:43.690910+00:00", "input": {"pr_a": {"number": 13165, "title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12649, "b": 12755, "similarity": 0.824, "verdict": "same_change", "probabilities": {"same_change": 0.98, "unrelated": 0.0, "related_but_different": 0.02}, "usage": {"input_tokens": 755, "output_tokens": 49}, "binding": "a766bc95f8c7c377f16605e9967621549adf3f2a2042472d095da3645c7eae14", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:48.047248+00:00", "input": {"pr_a": {"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same h", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13459, "b": 13613, "similarity": 0.808, "verdict": "same_change", "probabilities": {"related_but_different": 0.14, "same_change": 0.86, "unrelated": 0.0}, "usage": {"input_tokens": 706, "output_tokens": 49}, "binding": "5ac14eb0dc08e0556a725e34ba80c50abd331dc8ce0b55cd057142dda0cc40e4", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:50.808657+00:00", "input": {"pr_a": {"number": 13459, "title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales bo", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13165, "b": 13477, "similarity": 0.768, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "same_change": 0.99, "related_but_different": 0.01}, "usage": {"input_tokens": 712, "output_tokens": 49}, "binding": "ebbbfb029fd8448aea01ca41cc8ed6c912b3f007769e1c03b8cde2a3fd4e5a29", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:53.882623+00:00", "input": {"pr_a": {"number": 13165, "title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out namel", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12074, "b": 12090, "similarity": 0.76, "verdict": "same_change", "probabilities": {"related_but_different": 0.18, "unrelated": 0.0, "same_change": 0.82}, "usage": {"input_tokens": 784, "output_tokens": 49}, "binding": "0bf59d1fbd806a42591e3240bc9ba7c6c3b7c09134e1aef63378fe0b9ef64c45", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:54.553628+00:00", "input": {"pr_a": {"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13463, "b": 13613, "similarity": 0.741, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "same_change": 0.73, "related_but_different": 0.27}, "usage": {"input_tokens": 737, "output_tokens": 49}, "binding": "4d70cf889d2338d7a35fb0e42f7bdbb760fa0687927ee36b97301e0f202be164", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-09-30T14:34:56.563516+00:00", "input": {"pr_a": {"number": 13463, "title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12649, "b": 13009, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.78, "unrelated": 0.0, "related_but_different": 0.22}, "usage": {"input_tokens": 740, "output_tokens": 49}, "binding": "a790d28810a9bc3c6f3ac565f453eaa58b18c06b747d117f18aeaebd666b6562", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:24:09.508609+00:00", "input": {"pr_a": {"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negat", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12755, "b": 13009, "similarity": 1.0, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "same_change": 0.74, "related_but_different": 0.26}, "usage": {"input_tokens": 741, "output_tokens": 49}, "binding": "7e8d8284d23439e643170219908738e087927521afdd8189d68c22f8a1166c6b", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:24:09.550431+00:00", "input": {"pr_a": {"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same h", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negat", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12074, "b": 12680, "similarity": 1.0, "verdict": "same_change", "probabilities": {"related_but_different": 0.09, "same_change": 0.91, "unrelated": 0.0}, "usage": {"input_tokens": 754, "output_tokens": 49}, "binding": "2ef385cf123ffd27bc2e88eb5f590cfb6a898a2e6c7a9740f4d77595d48ddafc", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:24:17.169318+00:00", "input": {"pr_a": {"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12090, "b": 12680, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.93, "unrelated": 0.0, "related_but_different": 0.07}, "usage": {"input_tokens": 714, "output_tokens": 49}, "binding": "ce242889658f5e99959f1388bbfcc4b1bef1de678fa17c61fbe2505ba5ec45b7", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:24:17.516333+00:00", "input": {"pr_a": {"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13477, "b": 13645, "similarity": 0.911, "verdict": "same_change", "probabilities": {"related_but_different": 0.0, "same_change": 1.0, "unrelated": 0.0}, "usage": {"input_tokens": 684, "output_tokens": 49}, "binding": "2ab8acbd6f20aed04bc7f4672c8fd19f15ebc858c5fdd9c346856b61e87ba1d6", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:40:02.445645+00:00", "input": {"pr_a": {"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out namel", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13459, "b": 13463, "similarity": 0.909, "verdict": "same_change", "probabilities": {"same_change": 1.0, "unrelated": 0.0, "related_but_different": 0.0}, "usage": {"input_tokens": 741, "output_tokens": 49}, "binding": "3696c4aa4eab98f3040ec090021319fb1d249ef5500153ef4e1a9ca2a84d5cb0", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:40:02.701033+00:00", "input": {"pr_a": {"number": 13459, "title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales bo", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13463, "title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13165, "b": 13645, "similarity": 0.869, "verdict": "same_change", "probabilities": {"related_but_different": 0.01, "same_change": 0.99, "unrelated": 0.0}, "usage": {"input_tokens": 698, "output_tokens": 49}, "binding": "131e523c86af9e72d7fc943e34157b5c57b2a722078acb0b320e724e78073309", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:40:04.320728+00:00", "input": {"pr_a": {"number": 13165, "title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12649, "b": 12755, "similarity": 0.824, "verdict": "same_change", "probabilities": {"related_but_different": 0.01, "same_change": 0.99, "unrelated": 0.0}, "usage": {"input_tokens": 755, "output_tokens": 49}, "binding": "e19bc3eae1a6166c73e225fd9d663dd273ab2f8acdd33b5dea59b6e287f11439", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:40:09.152987+00:00", "input": {"pr_a": {"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same h", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13459, "b": 13613, "similarity": 0.808, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "same_change": 0.84, "related_but_different": 0.16}, "usage": {"input_tokens": 706, "output_tokens": 49}, "binding": "409b77a5e49bd8ced14b7e4eeeba9ef5b2051959e652b3e71f7101a1f7553088", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:40:11.256743+00:00", "input": {"pr_a": {"number": 13459, "title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales bo", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13165, "b": 13477, "similarity": 0.768, "verdict": "same_change", "probabilities": {"related_but_different": 0.01, "same_change": 0.99, "unrelated": 0.0}, "usage": {"input_tokens": 712, "output_tokens": 49}, "binding": "1d9078c26f9fd2cb4216a58af1cb1c84c420d3f5ceff85c0a3f643ddb94550e8", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:40:15.484885+00:00", "input": {"pr_a": {"number": 13165, "title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out namel", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12074, "b": 12090, "similarity": 0.76, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "same_change": 0.87, "related_but_different": 0.13}, "usage": {"input_tokens": 784, "output_tokens": 49}, "binding": "76b683499884576bde1746cb09bb0ef69927805c6ffc8291f8766ea858288433", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:40:16.110668+00:00", "input": {"pr_a": {"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 13463, "b": 13613, "similarity": 0.741, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "same_change": 0.72, "related_but_different": 0.28}, "usage": {"input_tokens": 737, "output_tokens": 49}, "binding": "dd91f4ad7dcee7d1ceeea9053ef76420bebf7609a9597c6bd296f8c750e0cb9b", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T10:40:18.339679+00:00", "input": {"pr_a": {"number": 13463, "title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": []} +{"a": 12649, "b": 13009, "similarity": 1.0, "verdict": "same_change", "probabilities": {"related_but_different": 0.23, "unrelated": 0.0, "same_change": 0.77}, "binding": "f466d18925738b421c68b309d183873b655010a6fd10930f5b5db4dcc3e01ff1", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:11:22.416830+00:00", "input": {"pr_a": {"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negat", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 740, "output_tokens": 49} +{"a": 12755, "b": 13009, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.74, "related_but_different": 0.26, "unrelated": 0.0}, "binding": "052536413ce3640ff3bac786549b21fa16b3dc98167507968b17b609f4da4c35", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:11:22.735537+00:00", "input": {"pr_a": {"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same h", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13009, "title": "Guard battery sysfs rate against bogus EC readings", "body": "On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W. The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This: - only trusts sysfs reads that succeed and are numeric (allows negat", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 741, "output_tokens": 49} +{"a": 12074, "b": 12680, "similarity": 1.0, "verdict": "same_change", "probabilities": {"same_change": 0.88, "related_but_different": 0.12, "unrelated": 0.0}, "binding": "89f452b35c1e9f0400ac8dcb8ee12207becc1512786aea2ff20e7f5f0c7f3014", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:11:32.190427+00:00", "input": {"pr_a": {"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 754, "output_tokens": 49} +{"a": 12090, "b": 12680, "similarity": 1.0, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "same_change": 0.9, "related_but_different": 0.1}, "binding": "28d193661160243261478edca8b7fe6cd3bd0f2d839051a1976ed08d9bfd9fe4", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:11:32.403056+00:00", "input": {"pr_a": {"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "body": "# [Intel Mac P02] Repair headers for retained stock kernels Carry the existing omacom/omarchy#12074 migration that installs missing stock-kernel headers when broadcom-wl-dkms is present, including retained fallback kernels. The production migration is unchanged; local additions are fixtures. **Draft consolidation for source review and hardware-owner follow-up.** Known defects remain; no hardware o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 714, "output_tokens": 49} +{"a": 13477, "b": 13645, "similarity": 0.911, "verdict": "same_change", "probabilities": {"same_change": 1.0, "unrelated": 0.0, "related_but_different": 0.0}, "binding": "3579e0effc833523a4583b679071b6e5952a8a4a325125d964f0a577869f16f4", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:17:02.476632+00:00", "input": {"pr_a": {"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out namel", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 684, "output_tokens": 49} +{"a": 13459, "b": 13463, "similarity": 0.909, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "related_but_different": 0.0, "same_change": 1.0}, "binding": "bcb330a58aa5caef72b6a0a3ba28c15974c69210f4f712e1ca93b28bbe6c2645", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:17:02.513262+00:00", "input": {"pr_a": {"number": 13459, "title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales bo", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13463, "title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 741, "output_tokens": 49} +{"a": 13165, "b": 13645, "similarity": 0.869, "verdict": "same_change", "probabilities": {"related_but_different": 0.01, "unrelated": 0.0, "same_change": 0.99}, "binding": "872ac07bbfcce048cecdc6141464c7dcbecda84416e42e2b4c7a58bd5b79b810", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:17:04.454146+00:00", "input": {"pr_a": {"number": 13165, "title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13645, "title": "Skip placeholder and FALLBACK screens when building bars", "body": "## Summary Fixes Idle wake recreated panels / duplicate IpcHandlers because Qt\u2019s nameless placeholder and Hyprland `FALLBACK` spawned bars. ## Change - Bar `Variants` use `BarModel.realScreens()` so placeholder/FALLBACK screens do not get bars ## Test plan - [x] `bash test/shell.d/bar-test.sh`", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 698, "output_tokens": 49} +{"a": 12649, "b": 12755, "similarity": 0.824, "verdict": "same_change", "probabilities": {"same_change": 0.99, "related_but_different": 0.01, "unrelated": 0.0}, "binding": "e49b8f0fa901c26bc6a155ccbf450c4eb0823194d06ef2eb8c8a43a352d6cd26", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:17:08.971124+00:00", "input": {"pr_a": {"number": 12649, "title": "Keep UPower rate when sysfs power read fails with ENODEV", "body": "Single-battery HP/ACPI machines expose a `power_now` that passes `[[ -r ]]` but whose `read()` fails with `ENODEV`, so the script gets `\"\"` and `awk` coerces it to `0W`, discarding UPower's correct `energy-rate` (~16-30W). Only trust numeric sysfs reads, otherwise keep UPower's `energy-rate`. Same guard for the `current_now`/`voltage_now` fallback, which had the identical coerce-to-0 hole. Split o", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12755, "title": "Keep UPower rate when sysfs power reads fail or are non-numeric", "body": "Fixes #12735. ## Problem `omarchy battery status` shows `0W` while discharging, even though UPower knows the real rate (time-left is correct, only wattage is wrong). On affected machines `/sys/class/power_supply/BAT0/power_now` exists, so `[[ -r ... ]]` passes \u2014 but the read itself fails with `ENODEV`, leaving an empty value that `awk` turns into `0`, clobbering the good `5.5W` from UPower. Same h", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 755, "output_tokens": 49} +{"a": 13459, "b": 13613, "similarity": 0.808, "verdict": "same_change", "probabilities": {"related_but_different": 0.13, "unrelated": 0.0, "same_change": 0.87}, "binding": "4f0ff445072c299d5a03687211c12942dea2a1009b365deb6e44ebd2241b1cd1", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:17:11.100809+00:00", "input": {"pr_a": {"number": 13459, "title": "Scale clock panel hero date with fontScale", "body": "## Summary With `[font] base-size` configured below 12 (the default), the clock panel scales down via `Style.space(560)` (and `effectiveSpacingScale`), but the hero calendar glyph (48px) and date string (52px) remained hardcoded numbers outside the scale. In months with longer names (e.g. \"September\"), the text overflowed the narrowed card width and clipped against the right border. This scales bo", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 706, "output_tokens": 49} +{"a": 13165, "b": 13477, "similarity": 0.768, "verdict": "same_change", "probabilities": {"unrelated": 0.0, "same_change": 1.0, "related_but_different": 0.0}, "binding": "3e351c0c08500d88b2f5a37f37f23432b16975619a20b206174e77b2786d4a28", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:17:15.375883+00:00", "input": {"pr_a": {"number": 13165, "title": "Skip placeholder screens when building bars", "body": "Fixes #13163 ## Problem With every monitor unplugged (e.g. a KVM switched to another machine), `Quickshell.screens` briefly holds screens that aren't real monitors: - Qt's nameless **placeholder screen** (`There are no outputs - creating placeholder screen`) - Hyprland's headless **`FALLBACK`** output The bar's `Variants { model: Quickshell.screens }` built a full `BarPanel` for each of them. When", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13477, "title": "Skip placeholder and FALLBACK screens when creating bars", "body": "## Summary When monitors sleep or are unplugged, Qt substitutes a nameless placeholder screen and Hyprland creates its headless `FALLBACK` output. A bar built for either outlives the monitors' return: the compositor drops it onto whichever monitor comes back first, where it stacks over that monitor's bar with duplicate `ShellIpc` handlers and leaked child processes (#13072). This filters out namel", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 712, "output_tokens": 49} +{"a": 12074, "b": 12090, "similarity": 0.76, "verdict": "same_change", "probabilities": {"related_but_different": 0.16, "same_change": 0.84, "unrelated": 0.0}, "binding": "457137ac66aac3ac522d80a058bbe2413b5f37dbe12658d3f52c34fbb1d0ddc3", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:17:16.016519+00:00", "input": {"pr_a": {"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "body": "Arch dropped the prebuilt `broadcom-wl` on 2026-09-02, and `broadcom-wl-dkms` carries `replaces=(broadcom-wl)`. On an upgrade, pacman swaps the package in and pulls `dkms`, but nothing pulls `linux-headers`, so the module never builds: ``` running '70-dkms-install.hook'... ==> ERROR: Missing 7.2.3-arch1-3 kernel headers for module broadcom-wl/6.30.223.271. ``` 2012-2015 MacBooks with a BCM4360 or ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "body": "Closes ## Summary The 4.0.3 upgrade swapped `broadcom-wl` for `broadcom-wl-dkms` without headers on stock `linux` (older MacBooks). The module never built, so Wi-Fi died after reboot. Install matching headers in `fix-bcm43xx.sh`, and repair existing DKMS installs with a migration that covers `linux` / `linux-lts` as well as Omarchy/T2 kernels. ## Test plan ```bash bash test/shell.d/bcm43xx-headers", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 784, "output_tokens": 49} +{"a": 13463, "b": 13613, "similarity": 0.741, "verdict": "same_change", "probabilities": {"same_change": 0.8, "related_but_different": 0.2, "unrelated": 0.0}, "binding": "4f145359f595cd92651eda3b507dbb75fd8f7751a7d8708c78801508fa3a56f7", "requested_model": "jev-latest", "resolved_model": "jev-1.13.0", "request_id": null, "judged_at": "2026-10-01T18:17:18.167245+00:00", "input": {"pr_a": {"number": 13463, "title": "Scale the clock panel hero text with fontScale", "body": "## Summary With `[font] base-size` below 12, the clock panel's hero date is clipped by the card's border \u2014 at `base-size = 9` (fontScale 0.75) \"September 26\" renders as \"September 2\" plus a cut-off glyph (#13381). The card sizes itself through `panel.fittedContentWidth(Style.space(560))`, and `Style.space()` tracks `fontScale` (`spacingScaleWithFont` defaults to `true`), so at `base-size = 9` the ", "evidence_basis": "shortened descriptions only; source equivalence not verified"}, "pr_b": {"number": 13613, "title": "Scale clock panel hero date with fontScale and fit long months", "body": "## Summary Fixes With `[font] base-size` below 12, the clock panel hero month was clipped by the card border. ## Change - Scale the hero glyph and date with `Style.fontScale` - Use `Text.HorizontalFit` so long month names stay inside the scaled card width ## Test plan - [ ] Set `[font] base-size = 9` and open the clock panel; month name should remain fully visible", "evidence_basis": "shortened descriptions only; source equivalence not verified"}}, "normalization_errors": [], "input_tokens": 737, "output_tokens": 49} diff --git a/crates/tranche-core/tests/fixture/out/parked.json b/crates/tranche-core/tests/fixture/out/parked.json new file mode 100644 index 0000000..b4f9c2f --- /dev/null +++ b/crates/tranche-core/tests/fixture/out/parked.json @@ -0,0 +1 @@ +{"format_version": 1, "repo": "omacom/omarchy", "dupes_digest": "9134de30ccfb58390e5e9c73ca7218810c9c970846a9cbb4824526312c5170b5", "parked": 3, "meaning": "Parked before batching (issue #8): drafts, PRs without finished form, PRs without a current judgment, and same_change groups holding for a parked member. A hold with a named unblock path, never a close; re-entry is automatic when the reason clears.", "members": [{"number": 12074, "title": "Install stock kernel headers for broadcom-wl-dkms on upgraded Macs", "author": "oliverox", "reasons": ["same_change_hold"], "unblock": "Held with its same_change group: atomic units are never split, so the group re-enters together when every member clears its own park reason.", "head_sha": "18378142c12b85565c460ddfb1279226d42c977e", "url": "https://github.com/omacom/omarchy/pull/12074", "created": "2026-09-16T08:20:51Z", "security_flag": 0.09}, {"number": 12090, "title": "Install matching kernel headers before broadcom-wl-dkms", "author": "paulogeyer", "reasons": ["same_change_hold"], "unblock": "Held with its same_change group: atomic units are never split, so the group re-enters together when every member clears its own park reason.", "head_sha": "40fc412e5e7fd6b9a5c883e7b4ac361b8b4544b4", "url": "https://github.com/omacom/omarchy/pull/12090", "created": "2026-09-16T10:28:25Z", "security_flag": 0.18}, {"number": 12680, "title": "[Intel Mac P02] Repair headers for retained stock kernels", "author": "andrew-boyd", "reasons": ["draft", "finished_form", "same_change_hold"], "unblock": "Author marks the pull request ready for review; the next fetch recaptures it and the next batches run re-packs it. Author adds the missing description or QA evidence; judge --resume re-binds the judgment and the PR re-enters on the next refresh. Held with its same_change group: atomic units are never split, so the group re-enters together when every member clears its own park reason.", "head_sha": "803260c8feff6d9ed5dbac60d5f630cd45ae1b56", "url": "https://github.com/omacom/omarchy/pull/12680", "created": "2026-09-20T21:00:07Z", "security_flag": 0.09}]} \ No newline at end of file diff --git a/crates/tranche-core/tests/fixture/out/summary.json b/crates/tranche-core/tests/fixture/out/summary.json new file mode 100644 index 0000000..6c26c34 --- /dev/null +++ b/crates/tranche-core/tests/fixture/out/summary.json @@ -0,0 +1 @@ +{"format_version": 2, "repo": "omacom/omarchy", "prs_in_corpus": 12, "judged": 12, "unjudged_or_stale": 0, "unbound_judgments": 0, "allow_unbound": false, "report_binding": "7fbab168bf506c4dfafd64e9cf55e9576e073d830f7bab20555e423a9be70b7f", "dupe_groups": 4, "review_groups": 0, "uncertain_pairs": 0, "prs_in_dupe_groups": 12, "superseded": 0, "ready_tranches": 0, "ready_prs": 0, "recommendation_kind": "review-candidates", "needs_author_followup": 0, "escalate_review": 1, "security_priority": 0, "unknown_risk_or_security": 0, "tokens": {"input": 19103, "output": 2511}, "output_digests": {"clusters.json": "2ae8ff3658c685d760c562dde3ab08a63cfa5d15fcf802f74bc35070af10712f", "dupes.json": "9134de30ccfb58390e5e9c73ca7218810c9c970846a9cbb4824526312c5170b5"}} \ No newline at end of file diff --git a/crates/tranche-core/tests/fixture/out/tranches.md b/crates/tranche-core/tests/fixture/out/tranches.md new file mode 100644 index 0000000..9924c3e --- /dev/null +++ b/crates/tranche-core/tests/fixture/out/tranches.md @@ -0,0 +1,116 @@ +# Tranche — PR review candidates + +Corpus: 12 observed open PRs; 12 matching judgments; 0 unjudged/stale; 0 unbound legacy judgments. +Review candidates: 0. Model-consistent groups: 4. Groups needing relationship review: 0. Security-priority items: 0 (meta-category, reviewed first). + +Evidence: titles and shortened descriptions (1200 characters per PR; 400 per pair). Diffstat is unknown unless captured input supplies it. Patches, CI, reproductions, fix coverage and security have not been verified. Model scores are suggestions, not calibrated guarantees or approval to merge/close. Pagination records an observation, not a point-in-time GitHub snapshot. + +## Model-consistent candidate groups — verify fix coverage; no survivor selected + +- #12074, #12090, #12680 +- #12649, #12755, #13009 +- #13165, #13477, #13645 +- #13459, #13463, #13613 + +## Escalate for risk/security review + +- #12090 Install matching kernel headers before broadcom-wl-dkms + +# Suggested pre-release batches (issue #4) + +A batch is **5 PRs merged together as one tranche**. Jev determines +the composition: model-consistent same_change groups are atomic — their PRs combine into +ONE pull request inside the batch. Batches are disjoint (every PR is in at most one +batch); review groups are excluded on purpose. Ordered security-first, then +risk band and evidenced head idle time. Model-suggested, never verified safe to merge. + +Batches: 3 · security-first batches: 0 · same-change groups: 3 · review-group PRs excluded: 0. + +| Batch | Size | Security | Avg risk | Groups | Members | +|---|---|---|---|---|---| +| B001 | 3 | — | 0.9 | 1 | #13459 #13463 #13613 | +| B002 | 3 | — | 1.0 | 1 | #13165 #13477 #13645 | +| B003 | 3 | — | 1.0 | 1 | #12649 #12755 #13009 | + +## Reviewer agent prompts + +Copy-paste a prompt into an agent to start a thorough, methodical review that +produces one unified proposal + merge plan for the batch. + +### B001 + +``` +You are reviewing Omarchy pre-release batch B001 (3 PRs to be merged together as one tranche). + +Pull requests in this batch: +- #13459: Scale clock panel hero date with fontScale — https://github.com/omacom/omarchy/pull/13459 +- #13463: Scale the clock panel hero text with fontScale — https://github.com/omacom/omarchy/pull/13463 +- #13613: Scale clock panel hero date with fontScale and fit long months — https://github.com/omacom/omarchy/pull/13613 + +Work through the batch methodically: +1. Read every PR fully — description, diff, and review comments. For PRs Jev flagged as the same change, verify they truly overlap and identify the strongest implementation of each. +2. Map dependencies between the PRs (shared files, ordering constraints, conflicts) and check each PR's CI status. +3. Produce ONE unified proposal for the batch: what merges, in which order, what gets squashed or dropped, and why — as a single coherent plan, not per-PR verdicts. +4. Verify the plan: does the combined result still build and pass tests? Any PR that cannot be verified stays out — say so explicitly. +5. Deliver: (a) the unified proposal, (b) a step-by-step merge plan with exact commands, (c) risks with mitigations, (d) an explicit list of anything excluded and why. + +Facts over plausibility: base every claim on the actual diffs and CI state, never on titles alone. You are proposing — the human decides. +``` + +### B002 + +``` +You are reviewing Omarchy pre-release batch B002 (3 PRs to be merged together as one tranche). + +Pull requests in this batch: +- #13165: Skip placeholder screens when building bars — https://github.com/omacom/omarchy/pull/13165 +- #13477: Skip placeholder and FALLBACK screens when creating bars — https://github.com/omacom/omarchy/pull/13477 +- #13645: Skip placeholder and FALLBACK screens when building bars — https://github.com/omacom/omarchy/pull/13645 + +Work through the batch methodically: +1. Read every PR fully — description, diff, and review comments. For PRs Jev flagged as the same change, verify they truly overlap and identify the strongest implementation of each. +2. Map dependencies between the PRs (shared files, ordering constraints, conflicts) and check each PR's CI status. +3. Produce ONE unified proposal for the batch: what merges, in which order, what gets squashed or dropped, and why — as a single coherent plan, not per-PR verdicts. +4. Verify the plan: does the combined result still build and pass tests? Any PR that cannot be verified stays out — say so explicitly. +5. Deliver: (a) the unified proposal, (b) a step-by-step merge plan with exact commands, (c) risks with mitigations, (d) an explicit list of anything excluded and why. + +Facts over plausibility: base every claim on the actual diffs and CI state, never on titles alone. You are proposing — the human decides. +``` + +### B003 + +``` +You are reviewing Omarchy pre-release batch B003 (3 PRs to be merged together as one tranche). + +Pull requests in this batch: +- #12649: Keep UPower rate when sysfs power read fails with ENODEV — https://github.com/omacom/omarchy/pull/12649 +- #12755: Keep UPower rate when sysfs power reads fail or are non-numeric — https://github.com/omacom/omarchy/pull/12755 +- #13009: Guard battery sysfs rate against bogus EC readings — https://github.com/omacom/omarchy/pull/13009 + +Work through the batch methodically: +1. Read every PR fully — description, diff, and review comments. For PRs Jev flagged as the same change, verify they truly overlap and identify the strongest implementation of each. +2. Map dependencies between the PRs (shared files, ordering constraints, conflicts) and check each PR's CI status. +3. Produce ONE unified proposal for the batch: what merges, in which order, what gets squashed or dropped, and why — as a single coherent plan, not per-PR verdicts. +4. Verify the plan: does the combined result still build and pass tests? Any PR that cannot be verified stays out — say so explicitly. +5. Deliver: (a) the unified proposal, (b) a step-by-step merge plan with exact commands, (c) risks with mitigations, (d) an explicit list of anything excluded and why. + +Facts over plausibility: base every claim on the actual diffs and CI state, never on titles alone. You are proposing — the human decides. +``` + +# Parked before batching (issue #8) + +3 PRs are parked: drafts, PRs without finished form, PRs without a +current judgment, and same_change groups holding for a parked member. Park is a +**hold with a named unblock path, never a close** — re-entry is automatic when the +reason clears and the next refresh re-packs. No batch lists a parked PR. + +Reasons: draft 1 · finished_form 1 · unjudged_or_stale 0 · same_change_hold 3. + +| PR | Reasons | Unblocked by | +|---|---|---| +| #12074 | same_change_hold | Held with its same_change group: atomic units are never split, so the group re-enters together when every member clears its own park reason. | +| #12090 | same_change_hold | Held with its same_change group: atomic units are never split, so the group re-enters together when every member clears its own park reason. | +| #12680 | draft, finished_form, same_change_hold | Author marks the pull request ready for review; the next fetch recaptures it and the next batches run re-packs it. Author adds the missing description or QA evidence; judge --resume re-binds the judgment and the PR re-enters on the next refresh. Held with its same_change group: atomic units are never split, so the group re-enters together when every member clears its own park reason. | + +Parked does not remove a security-flagged PR from the security meta-category; +it only removes it from merge batches. Full record: out/parked.json. diff --git a/crates/tranche-core/tests/packing_the_corpus.rs b/crates/tranche-core/tests/packing_the_corpus.rs new file mode 100644 index 0000000..ffa770b --- /dev/null +++ b/crates/tranche-core/tests/packing_the_corpus.rs @@ -0,0 +1,101 @@ +//! The human report reproduces from the stored corpus. +//! +//! The committed file is the report `cluster` writes followed by the plan and +//! park record `batches` appends, so reproducing it means running both stages in +//! order — which is also the only way to catch a trailing-newline difference, +//! because that shifts every appended line by one. + +mod support; + +use std::collections::BTreeMap; + +use serde_json::Value; +use support::{Judgment, Prs, REPO, built, corpus, read}; +use tranche_core::domain::batch::{ + batch_plan_section, merge_batches, park_section, park_state, parked_payload, +}; +use tranche_core::domain::cluster::{Clustered, render}; +use tranche_core::util::digest; + +/// The batches and the park state for one corpus read. +fn packed( + report: &Clustered, + judgments: &std::collections::HashMap, + prs: &Prs, +) -> (Value, BTreeMap>) { + let dupes_digest = digest(&report.dupes); + let batches = merge_batches(&report.dupes, judgments, prs, &dupes_digest, REPO).expect("packs"); + (batches, park_state(&report.dupes, judgments, prs)) +} + +#[test] +fn the_human_report_reproduces_from_the_same_corpus() { + let root = corpus(); + let (prs, judgments, report) = built(&root); + let (batches, parks) = packed(&report, &judgments, &prs); + + let mut rendered = render(&report, REPO); + rendered.push_str(&batch_plan_section(&batches)); + rendered.push_str(&park_section(&parks, &prs)); + + let published = std::fs::read_to_string(root.out_dir().join("tranches.md")) + .expect("the published report reads"); + assert!( + !published.is_empty(), + "the committed report is not truncated" + ); + assert_eq!(rendered, published, "tranches.md reproduces byte for byte"); +} + +#[test] +fn the_batch_and_park_records_reproduce() { + let root = corpus(); + let (prs, judgments, report) = built(&root); + let (batches, parks) = packed(&report, &judgments, &prs); + let parked = parked_payload(&parks, &prs, &judgments, &digest(&report.dupes), REPO); + + assert_eq!(digest(&batches), digest(&read(&root, "batches.json"))); + assert_eq!(digest(&parked), digest(&read(&root, "parked.json"))); +} + +#[test] +fn a_batch_never_claims_a_parked_pr() { + // The issue-#8 gate. A parked PR is a hold with an unblock path, so letting + // one into a batch would claim work the pipeline deliberately set aside. + let root = corpus(); + let (prs, judgments, report) = built(&root); + let (batches, parks) = packed(&report, &judgments, &prs); + + let mut claimed: Vec = batches["batches"] + .as_array() + .expect("batches") + .iter() + .flat_map(|batch| batch["members"].as_array().cloned().unwrap_or_default()) + .filter_map(|number| number.as_u64()) + .collect(); + let overlap: Vec = parks + .keys() + .copied() + .filter(|number| claimed.contains(number)) + .collect(); + assert!( + overlap.is_empty(), + "parked PRs entered a batch: {overlap:?}" + ); + + // Disjoint, and every declared size is the size actually present. + claimed.sort_unstable(); + let mut unique = claimed.clone(); + unique.dedup(); + assert_eq!(unique.len(), claimed.len(), "a PR appears in two batches"); + assert_eq!( + claimed.len(), + batches["batches"] + .as_array() + .expect("batches") + .iter() + .map(|batch| batch["count"].as_u64().unwrap_or(0) as usize) + .sum::(), + "a batch declares a size it does not have" + ); +} diff --git a/crates/tranche-core/tests/reading_a_capture.rs b/crates/tranche-core/tests/reading_a_capture.rs new file mode 100644 index 0000000..294c310 --- /dev/null +++ b/crates/tranche-core/tests/reading_a_capture.rs @@ -0,0 +1,219 @@ +//! Reading a stored capture. +//! +//! A capture on disk was written by an earlier run, and every identity it claims +//! is re-derived here rather than believed: an accepted-but-wrong manifest lets a +//! corrupt capture be resumed from or exported. + +use tranche_core::evidence::components::groups_for; +use tranche_core::evidence::coverage::{fresh_components, is_complete, roll_up}; +use tranche_core::evidence::manifest::{build_manifest, read_manifest}; +use tranche_core::evidence::selection::{generation_id, is_sha1, selection_from_json, source_id}; +use tranche_core::report::Root; + +const CAPTURE: &str = "108dbe75ccac6ea366b543791c8f168e"; + +fn corpus() -> Root { + Root::new( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(std::path::Path::parent) + .expect("nested in the repository"), + ) +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_stored_capture_reports_the_batch_it_was_taken_from() { + let root = corpus(); + let manifest = read_manifest(&root, CAPTURE).expect("the real capture verifies"); + assert_eq!(manifest["format"], "tranche.evidence-packet/v1"); + assert_eq!(manifest["profile"], "pr-review/v1"); + assert!(is_complete(&manifest)); + + let selection = selection_from_json(&manifest["selection"]).expect("selection"); + assert_eq!(selection.numbers(), vec![11720, 12891, 7087, 12582]); + assert_eq!(selection.batch_id, "B001"); + assert_eq!(selection.batch_ordinal, 1); + assert_eq!(selection.repository["full_name"], "omacom/omarchy"); + assert_eq!(selection.repository["id"], 994093166); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_capture_identity_recomputes_from_what_it_stored() { + let root = corpus(); + let manifest = read_manifest(&root, CAPTURE).expect("verifies"); + let selection = selection_from_json(&manifest["selection"]).expect("selection"); + assert_eq!( + selection.membership_digest(), + "4a1b1efca71051df3a3d6ac686a2ff8550587f9735971430c5e091579eb6e569" + ); + assert_eq!( + generation_id(&selection, CAPTURE), + manifest["generation"].as_str().unwrap(), + "the generation recomputes from the selection it stores" + ); + + // And it changes when the thing it names changes. + let mut moved = manifest.clone(); + moved["selection"]["members"][0]["head_sha"] = serde_json::json!("1".repeat(40)); + let moved_selection = selection_from_json(&moved["selection"]).expect("selection"); + assert_ne!( + generation_id(&moved_selection, CAPTURE), + manifest["generation"].as_str().unwrap() + ); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_thread_update_does_not_mint_a_new_capture_generation() { + // `updated_at` is observed upstream data. Treating it as a revision marker + // would force re-downloading unchanged code. + let root = corpus(); + let manifest = read_manifest(&root, CAPTURE).expect("verifies"); + let mut touched = manifest.clone(); + touched["selection"]["members"][0]["updated_at"] = serde_json::json!("2099-01-01T00:00:00Z"); + let selection = selection_from_json(&touched["selection"]).expect("selection"); + assert_eq!( + generation_id(&selection, CAPTURE), + manifest["generation"].as_str().unwrap() + ); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn every_recorded_source_proves_its_own_identity() { + let root = corpus(); + let manifest = read_manifest(&root, CAPTURE).expect("verifies"); + let generation = manifest["generation"].as_str().expect("generation"); + let sources = manifest["sources"].as_array().expect("sources"); + assert!(!sources.is_empty()); + for source in sources { + assert_eq!( + source_id(generation, source), + source["id"].as_str().unwrap(), + "every source id recomputes from its own contents" + ); + } +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_capture_that_is_not_there_is_refused() { + let root = corpus(); + let error = read_manifest(&root, &"0".repeat(32)).expect_err("an absent capture is refused"); + assert!(error.to_string().contains("no capture"), "{error}"); + // A malformed id never becomes a path. + assert!(read_manifest(&root, "not-a-capture").is_err()); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_manifest_that_lost_a_field_is_refused() { + let root = corpus(); + let manifest = read_manifest(&root, CAPTURE).expect("verifies"); + for field in ["format", "selection", "sources", "components", "citations"] { + let mut stripped = manifest.clone(); + stripped.as_object_mut().expect("object").remove(field); + assert!( + selection_from_json(&stripped["selection"]).is_err() || stripped.get(field).is_none(), + "{field} matters" + ); + } + // A selection carrying a foreign key is refused rather than ignored. + let mut wrong = manifest.clone(); + wrong["selection"]["unexpected"] = serde_json::json!(1); + assert!(selection_from_json(&wrong["selection"]).is_err()); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_fresh_capture_claims_nothing_is_acquired() { + let root = corpus(); + let manifest = read_manifest(&root, CAPTURE).expect("verifies"); + let selection = selection_from_json(&manifest["selection"]).expect("selection"); + let fresh = fresh_components(&selection); + // Eight components per member, every one missing. + assert_eq!(fresh.len(), selection.members.len() * 8); + for entry in &fresh { + assert_eq!(entry["status"], "missing"); + assert_eq!(entry["reason"], "not acquired"); + } + let rebuilt = build_manifest(&selection, CAPTURE, 200, Some("2026-01-01T00:00:00Z")); + assert_eq!(rebuilt["generation"], manifest["generation"]); + assert_eq!(rebuilt["capture"]["requests_used"], 0); + assert!(!is_complete(&rebuilt)); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn component_groups_follow_the_repositories_a_check_lives_in() { + assert_eq!(groups_for("metadata"), vec!["metadata".to_owned()]); + // A PR's own checks live in its base repository while a fork's head carries + // its own, so `checks` is four groups inside one component. + assert_eq!( + groups_for("checks"), + vec![ + "check_runs".to_owned(), + "statuses".to_owned(), + "fork_check_runs".to_owned(), + "fork_statuses".to_owned() + ] + ); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn an_incomplete_component_names_why() { + let mut entry = serde_json::json!({ + "component": "checks", + "groups": [ + {"group": "check_runs", "status": "complete", "reason": null}, + {"group": "statuses", "status": "complete", "reason": null}, + {"group": "fork_check_runs", "status": "partial", "reason": "GitHub reports 3 items but 2 were observed"}, + {"group": "fork_statuses", "status": "complete", "reason": null} + ] + }); + roll_up(&mut entry); + assert_eq!(entry["status"], "partial"); + assert!( + entry["reason"] + .as_str() + .unwrap() + .contains("GitHub reports 3 items"), + "{}", + entry["reason"] + ); + + // A blocked group is the more specific failure. + entry["groups"][2]["status"] = serde_json::json!("blocked"); + entry["groups"][2]["reason"] = serde_json::json!("response exceeds the transport bound"); + roll_up(&mut entry); + assert_eq!(entry["status"], "blocked"); + + // A group never acquired outranks a partial one: nothing about it is known. + entry["groups"][2] = serde_json::json!({"group": "fork_check_runs", "status": "missing", "reason": "not acquired"}); + roll_up(&mut entry); + assert_eq!(entry["status"], "missing"); + + for group in entry["groups"].as_array_mut().expect("groups") { + group["status"] = serde_json::json!("complete"); + group["reason"] = serde_json::Value::Null; + } + roll_up(&mut entry); + assert_eq!(entry["status"], "complete"); + assert!( + entry["reason"].is_null(), + "a complete component carries no reason" + ); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_revision_must_be_a_full_commit_sha() { + assert!(is_sha1("d7c44f2670a0d18598cd6eadee07c0e8d0885cc4")); + // A short or uppercase revision is never substituted or normalised. + assert!(!is_sha1("d7c44f26")); + assert!(!is_sha1(&"D".repeat(40))); + assert!(!is_sha1(&"g".repeat(40))); +} diff --git a/crates/tranche-core/tests/reading_a_stored_capture.rs b/crates/tranche-core/tests/reading_a_stored_capture.rs new file mode 100644 index 0000000..29e138d --- /dev/null +++ b/crates/tranche-core/tests/reading_a_stored_capture.rs @@ -0,0 +1,192 @@ +//! Reading a capture back: coverage, windows and citations. +//! +//! These answer from the stored state alone, which is what makes a capture +//! checkable by someone who has only the directory. The escape test matters as +//! much as the resolution ones: a captured body is untrusted text and must not be +//! able to drive the terminal that reads it. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; +use tranche_core::evidence::report; +use tranche_core::report::Root; + +const CAPTURE: &str = "108dbe75ccac6ea366b543791c8f168e"; + +/// A checkout carrying the real capture, copied so a read never touches it. +fn root() -> Option { + let source = Path::new("/srv/lab/hack/omarchy-pr-jev-triage").join("out/evidence"); + if !source.join(CAPTURE).join("manifest.json").exists() { + return None; + } + let root = tempfile::tempdir().expect("a root"); + copy(&source, &root.path().join("out/evidence")); + Some(root) +} + +fn copy(source: &Path, destination: &Path) { + std::fs::create_dir_all(destination).expect("a directory"); + for entry in std::fs::read_dir(source).expect("the capture reads") { + let entry = entry.expect("an entry"); + let target = destination.join(entry.file_name()); + if entry.file_type().expect("a type").is_dir() { + copy(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).expect("a file"); + } + } +} + +fn manifest(root: &Path) -> Value { + let path = root.join(format!("out/evidence/{CAPTURE}/manifest.json")); + serde_json::from_str(&std::fs::read_to_string(path).expect("the manifest reads")) + .expect("the manifest parses") +} + +fn checkout(root: &Path) -> Root { + Root::new(root.to_path_buf()) +} + +#[test] +fn coverage_counts_what_the_manifest_recorded() { + let Some(root) = root() else { + return; + }; + let manifest = manifest(root.path()); + let coverage = report::coverage(&manifest); + assert_eq!(coverage["capture_id"], CAPTURE); + assert!(coverage["members"].is_array()); + + // Every component of every member appears exactly once, and a component that + // completed carries no reason while a stopped one does. + let expected = manifest["components"].as_array().expect("components").len(); + let seen: usize = coverage["members"] + .as_array() + .expect("members") + .iter() + .map(|member| member["components"].as_array().expect("components").len()) + .sum(); + assert_eq!(seen, expected, "one entry per recorded component"); + + // Page counts roll up from the groups. + for member in coverage["members"].as_array().expect("members") { + for component in member["components"].as_array().expect("components") { + let groups: u64 = component["groups"] + .as_array() + .expect("groups") + .iter() + .map(|group| group["pages"].as_u64().unwrap_or(0)) + .sum(); + assert_eq!(component["pages"].as_u64().unwrap_or(9), groups); + } + } + assert_eq!( + coverage["citations"], + manifest["citations"].as_array().unwrap().len() + ); +} + +#[test] +fn a_window_walks_a_source_in_bounded_steps() { + let Some(root) = root() else { + return; + }; + let manifest = manifest(root.path()); + let checkout = checkout(root.path()); + let Some(source_id) = manifest["sources"][0]["id"].as_str() else { + return; + }; + + let mut start = 0usize; + let mut walked = 0usize; + let total = + report::window(&checkout, &manifest, source_id, 0, 64).expect("a window")["body_bytes"] + .as_u64() + .expect("a byte count") as usize; + // Walk in small windows and prove the concatenation covers the whole body + // exactly once: no gap, no repeat. + while start < total { + let window = report::window(&checkout, &manifest, source_id, start, 64).expect("a window"); + let delivered = window["end_byte"].as_u64().expect("an end") as usize - start; + assert!(delivered > 0, "a window delivers something"); + walked += delivered; + match window["next_start"].as_u64() { + Some(next) => start = next as usize, + None => break, + } + } + assert_eq!(walked, total, "the windows cover the body once"); + + // A start past the end is refused rather than silently clamped. + assert!(report::window(&checkout, &manifest, source_id, total + 1, 64).is_err()); + // And a window has a bound. + assert!(report::window(&checkout, &manifest, source_id, 0, 0).is_err()); + assert!(report::window(&checkout, &manifest, source_id, 0, 10_000_000).is_err()); +} + +#[test] +fn a_window_escapes_bytes_a_terminal_must_not_receive() { + // An escape sequence in captured bytes must arrive as text, not as a command. + let hostile = b"plain \x1b[31mred\x1b[0m and \x07bell"; + let rendered = report::printable(hostile); + assert!(!rendered.contains('\u{1b}'), "no escape character survives"); + assert!(!rendered.contains('\u{7}'), "no bell survives"); + assert!(rendered.contains("\\u001b"), "the escape is shown as text"); + // Newlines stay literal: a diff is unreadable without them. + assert_eq!(report::printable(b"a\nb"), "a\nb"); +} + +#[test] +fn a_citation_resolves_and_a_mismatch_is_reported() { + let Some(root) = root() else { + return; + }; + let manifest = manifest(root.path()); + let checkout = checkout(root.path()); + let citations = manifest["citations"].as_array().expect("citations"); + let Some(id) = citations[0]["id"].as_str() else { + return; + }; + let resolved = report::resolve_citation(&checkout, &manifest, id).expect("resolved"); + // The reported digest is the recorded one, and it recomputes from the raw + // range the citation names — not from the escaped text shown to a reader. + let body = tranche_core::evidence::store::read_body( + &checkout, + citations[0]["source_sha256"].as_str().expect("a digest"), + ) + .expect("the body reads"); + let start = citations[0]["start_byte"].as_u64().expect("a start") as usize; + let end = citations[0]["end_byte"].as_u64().expect("an end") as usize; + assert_eq!( + tranche_core::util::sha256_hex(&body[start..end]), + citations[0]["excerpt_sha256"].as_str().expect("recorded"), + "the raw range digests to the recorded excerpt digest" + ); + assert_eq!( + resolved["excerpt_sha256"], + citations[0]["excerpt_sha256"].clone(), + "resolution reports the recorded digest" + ); + assert!( + !resolved["excerpt"].as_str().unwrap_or("").is_empty(), + "and the excerpt itself is shown" + ); + + // An unknown citation is refused, not answered with nothing. + assert!(report::resolve_citation(&checkout, &manifest, "not-a-citation").is_err()); +} + +#[test] +fn a_missing_source_is_refused_by_name() { + let Some(root) = root() else { + return; + }; + let manifest = manifest(root.path()); + let checkout = checkout(root.path()); + let error = report::window(&checkout, &manifest, "no-such-source", 0, 64).expect_err("refused"); + assert!(error.contains("no-such-source"), "{error}"); +} + +/// The unused-import guard. +#[allow(dead_code)] +fn _path_type(_: PathBuf) {} diff --git a/crates/tranche-core/tests/reading_github.rs b/crates/tranche-core/tests/reading_github.rs new file mode 100644 index 0000000..59d694d --- /dev/null +++ b/crates/tranche-core/tests/reading_github.rs @@ -0,0 +1,101 @@ +//! The GitHub transport's contract, with a fake `gh` in a directory. +//! +//! The property that matters is the refusal: a failure or an unexpected body must +//! never read as "no more PRs", because that would silently truncate the corpus +//! and every report built from it would be short without saying so. +//! +//! The fake command lives in its own directory and is passed in, so no test +//! changes what a test beside it sees. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; + +use tranche_core::gh::{GitHubError, Transport, page_with}; + +const URL: &str = + "https://api.github.com/repos/omacom/omarchy/pulls?state=open&per_page=100&page=1"; + +/// A directory holding one fake command that prints the given streams and exits +/// with the given status. +fn fake(name: &str, stdout: &str, stderr: &str, status: i32) -> tempfile::TempDir { + let directory = tempfile::tempdir().expect("a temporary directory"); + let binary: PathBuf = directory.path().join(name); + // `printf` rather than a heredoc: a heredoc appends a newline and needs care + // with quoting inside JSON. + let escape = |text: &str| text.replace('\\', "\\\\").replace('\'', "'\\''"); + let script = format!( + "#!/bin/sh\nprintf '%s' '{}'\nprintf '%s' '{}' >&2\nexit {status}\n", + escape(stdout), + escape(stderr) + ); + fs::write(&binary, script).expect("write the fake"); + fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)).expect("make it runnable"); + // Make sure the inode is fully written and the handle released before the + // file is executed, or the kernel reports "text file busy". + let handle = fs::OpenOptions::new() + .read(true) + .open(&binary) + .expect("reopen the fake"); + handle.sync_all().expect("flush the fake"); + drop(handle); + directory +} + +fn read(directory: &tempfile::TempDir) -> Result, GitHubError> { + page_with(Transport::Gh, URL, Some(Path::new(directory.path()))) +} + +#[test] +fn a_page_is_the_json_array_the_api_returned() { + let path = fake("gh", r#"[{"number": 1}, {"number": 2}]"#, "", 0); + let items = read(&path).expect("a page comes back"); + assert_eq!(items.len(), 2); + assert_eq!(items[0]["number"], 1); +} + +#[test] +fn an_empty_array_is_an_empty_page_not_an_error() { + let path = fake("gh", "[]", "", 0); + assert!(read(&path).expect("an empty page").is_empty()); +} + +#[test] +fn a_failed_command_reports_and_does_not_look_like_an_empty_page() { + // The whole point: a failure must not be read as "no more PRs". + let path = fake("gh", "", "HTTP 403: rate limit exceeded", 1); + let error = read(&path).expect_err("a failure is fatal"); + let message = error.to_string(); + assert!(message.contains("rate limit exceeded"), "{message}"); + assert!( + message.contains("previous snapshot is retained"), + "{message}" + ); +} + +#[test] +fn a_non_array_body_is_refused() { + // An error document returned with a success status would otherwise read as a + // page with no PRs. + let path = fake("gh", r#"{"message": "Not Found"}"#, "", 0); + let error = read(&path).expect_err("a non-array is fatal"); + assert!( + error.to_string().contains("did not return a PR list"), + "{error}" + ); +} + +#[test] +fn a_body_that_is_not_json_is_refused() { + let path = fake("gh", "gateway timeout", "", 0); + let error = read(&path).expect_err("unreadable JSON is fatal"); + assert!(error.to_string().contains("unreadable JSON"), "{error}"); +} + +#[test] +fn curl_is_a_separate_transport_with_the_same_contract() { + let path = fake("curl", r#"[{"number": 7}]"#, "", 0); + let items = page_with(Transport::Curl, URL, Some(Path::new(path.path()))) + .expect("curl reads the same shape"); + assert_eq!(items[0]["number"], 7); +} diff --git a/crates/tranche-core/tests/rebuilding_the_report.rs b/crates/tranche-core/tests/rebuilding_the_report.rs new file mode 100644 index 0000000..4b75723 --- /dev/null +++ b/crates/tranche-core/tests/rebuilding_the_report.rs @@ -0,0 +1,143 @@ +//! Clustering and batching, checked against the committed report. +//! +//! Rebuilding the committed `out/` files and comparing digests is the check that +//! matters: the report gate compares these same digests, so a mismatch would make +//! every report read as modified and every stored judgment foreign. + +use tranche_core::domain::batch::{merge_batches, park_state, parked_payload}; +use tranche_core::domain::cluster::cluster; +use tranche_core::domain::dupe::current_pairs; +use tranche_core::domain::judge::current_judgments; +use tranche_core::domain::pr::load_prs; +use tranche_core::report::{REPOSITORY, Root}; +use tranche_core::util::digest; + +const MODEL: &str = "jev-latest"; +const CLUSTERS_DIGEST: &str = "8cddc06fc66c8123b960a44e7582770094e7cd348912a04e56a13787a7b4435e"; +const DUPES_DIGEST: &str = "d241a64a38b2cfe5ebe5d8242b29e12f49b50f420e2e694eb2180fc60cf4fe70"; +const REPORT_BINDING: &str = "d756202ba10f2e8a373c0a66b36ab23e745e42a22d8cd4ad97923d7eaa2ca661"; + +fn corpus() -> Root { + Root::new( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(std::path::Path::parent) + .expect("nested in the repository"), + ) +} + +fn rebuilt() -> ( + Root, + tranche_core::domain::pr::Prs, + std::collections::HashMap, + Vec, +) { + let root = corpus(); + let prs = load_prs(&root, REPOSITORY).expect("the capture loads"); + let judgments = current_judgments(&root, &prs, REPOSITORY, MODEL, false).expect("judgments"); + let verdicts = current_pairs(&root, &prs, &judgments, REPOSITORY, MODEL, false).expect("pairs"); + (root, prs, judgments, verdicts) +} + +#[test] +#[ignore = "pins the digests of the local 111 MiB corpus"] +fn the_cluster_output_matches_the_committed_report() { + let (_root, prs, judgments, verdicts) = rebuilt(); + let report = cluster(&prs, &judgments, &verdicts, REPOSITORY, MODEL, false); + assert_eq!(digest(&report.clusters), CLUSTERS_DIGEST, "clusters.json"); + assert_eq!(digest(&report.dupes), DUPES_DIGEST, "dupes.json"); + assert_eq!( + report.summary["report_binding"].as_str(), + Some(REPORT_BINDING), + "report binding" + ); +} + +#[test] +#[ignore = "pins the digests of the local 111 MiB corpus"] +fn the_summary_counts_match_the_committed_report() { + let (_root, prs, judgments, verdicts) = rebuilt(); + let summary = cluster(&prs, &judgments, &verdicts, REPOSITORY, MODEL, false).summary; + let counts = [ + ("prs_in_corpus", 2817), + ("judged", 2817), + ("unjudged_or_stale", 0), + ("unbound_judgments", 0), + ("dupe_groups", 84), + ("review_groups", 10), + ("uncertain_pairs", 57), + ("prs_in_dupe_groups", 209), + ("superseded", 0), + ("ready_tranches", 10), + ("ready_prs", 612), + ("needs_author_followup", 87), + ("escalate_review", 382), + ("security_priority", 371), + ("unknown_risk_or_security", 0), + ]; + for (key, expected) in counts { + assert_eq!(summary[key].as_u64(), Some(expected), "{key}"); + } + assert_eq!( + summary["tokens"]["input"].as_i64(), + Some(4_484_571), + "input tokens" + ); + assert_eq!( + summary["tokens"]["output"].as_i64(), + Some(587_861), + "output tokens" + ); +} + +#[test] +#[ignore = "pins the digests of the local 111 MiB corpus"] +fn the_batch_plan_matches_the_committed_report() { + let (root, prs, judgments, verdicts) = rebuilt(); + let report = cluster(&prs, &judgments, &verdicts, REPOSITORY, MODEL, false); + let batches = merge_batches(&report.dupes, &judgments, &prs, DUPES_DIGEST, REPOSITORY) + .expect("batches pack"); + let committed = serde_json::from_str::( + &std::fs::read_to_string(root.batches_path()).expect("committed batches"), + ) + .expect("valid JSON"); + + // Every field except the digests and prompts is compared structurally; the + // prompt text is compared through the whole-file digest below. + assert_eq!( + batches["batches"].as_array().map(Vec::len), + Some(522), + "batch count" + ); + assert_eq!( + batches["security_batches"].as_u64(), + Some(66), + "security batches" + ); + assert_eq!(batches["parked_prs"].as_u64(), Some(187), "parked"); + assert_eq!( + batches["excluded_review_prs"].as_u64(), + Some(37), + "excluded" + ); + assert_eq!( + batches["same_change_groups"].as_u64(), + Some(75), + "same-change groups" + ); + assert_eq!( + batches["batches"][0]["members"], committed["batches"][0]["members"], + "first batch members" + ); + + // The committed file is the contract; the rebuild must reproduce it byte for + // byte apart from the digest of dupes, which is passed in identically. + let produced = digest(&batches); + let expected = digest(&committed); + assert_eq!(produced, expected, "batches.json digest"); + + let parks = park_state(&report.dupes, &judgments, &prs); + assert_eq!(parks.len(), 187, "parked PRs"); + let parked = parked_payload(&parks, &prs, &judgments, DUPES_DIGEST, REPOSITORY); + assert_eq!(parked["parked"].as_u64(), Some(187), "park record count"); +} diff --git a/crates/tranche-core/tests/reporting_the_corpus.rs b/crates/tranche-core/tests/reporting_the_corpus.rs new file mode 100644 index 0000000..e022502 --- /dev/null +++ b/crates/tranche-core/tests/reporting_the_corpus.rs @@ -0,0 +1,140 @@ +//! The report and its summary reproduce from the stored corpus. +//! +//! Everything under `out/` is the interface every reader depends on, so code that +//! reads the same logs must arrive at the same bytes — not merely similar ones. +//! The expected values are read from the committed files rather than restated, so +//! this fails if either side drifts. + +mod support; + +use support::{MODEL, REPO, built, corpus, read, reconstructed}; +use tranche_core::domain::cluster::cluster; +use tranche_core::util::digest; + +#[test] +fn the_report_reconstructs_from_the_stored_corpus() { + let root = corpus(); + let (_, _, report) = built(&root); + + let committed_clusters = read(&root, "clusters.json"); + let committed_dupes = read(&root, "dupes.json"); + let committed_summary = read(&root, "summary.json"); + + assert_eq!( + digest(&report.clusters), + digest(&committed_clusters), + "clusters.json reproduces byte for byte" + ); + assert_eq!( + digest(&report.dupes), + digest(&committed_dupes), + "dupes.json reproduces byte for byte" + ); + assert_eq!( + report.summary["report_binding"], committed_summary["report_binding"], + "the report binding identifies the same observation" + ); + assert_eq!( + report.summary["output_digests"], committed_summary["output_digests"], + "the recorded output digests match" + ); +} + +#[test] +fn the_summary_agrees_on_every_count() { + let root = corpus(); + let (_, _, report) = built(&root); + let committed = read(&root, "summary.json"); + + for field in [ + "format_version", + "repo", + "prs_in_corpus", + "judged", + "unjudged_or_stale", + "unbound_judgments", + "allow_unbound", + "dupe_groups", + "review_groups", + "uncertain_pairs", + "prs_in_dupe_groups", + "superseded", + "ready_tranches", + "ready_prs", + "recommendation_kind", + "needs_author_followup", + "escalate_review", + "security_priority", + "unknown_risk_or_security", + "tokens", + ] { + assert_eq!( + report.summary.get(field), + committed.get(field), + "summary.{field} disagrees with the published report" + ); + } +} + +#[test] +fn the_security_meta_category_leads_the_report() { + let root = corpus(); + let (_, _, report) = built(&root); + + // A first-class key, ordered before every category. + let keys: Vec<&String> = report + .clusters + .as_object() + .expect("clusters is an object") + .keys() + .collect(); + assert_eq!( + keys.first().map(|key| key.as_str()), + Some("security-review") + ); + + // Ranked probability-first, then by number. + let mut previous: Option<(f64, u64)> = None; + for item in report.clusters["security-review"] + .as_array() + .expect("a list of items") + { + let flag = item["security_flag"].as_f64().unwrap_or(-1.0); + let number = item["number"].as_u64().expect("a number"); + if let Some((last_flag, last_number)) = previous { + assert!( + flag < last_flag || (flag == last_flag && number > last_number), + "#{number} is out of order: {flag} after {last_flag}" + ); + } + previous = Some((flag, number)); + } +} + +#[test] +fn an_unbound_report_admits_what_it_cannot_establish() { + let root = corpus(); + let (_, _, report) = built(&root); + let summary = &report.summary; + + assert_eq!(summary["allow_unbound"], false); + // Unjudged is a count, never an assumption: every observed PR is accounted + // for as either judged or not. + assert_eq!( + summary["prs_in_corpus"].as_u64().unwrap(), + summary["judged"].as_u64().unwrap() + summary["unjudged_or_stale"].as_u64().unwrap() + ); +} + +#[test] +fn rebuilding_twice_reaches_the_same_bytes() { + // The pipeline is deterministic: two runs over the same logs must agree, or + // the digests that gate every reader are meaningless. + let root = corpus(); + let (prs, judgments, verdicts) = reconstructed(&root); + let first = cluster(&prs, &judgments, &verdicts, REPO, MODEL, false); + let second = cluster(&prs, &judgments, &verdicts, REPO, MODEL, false); + assert_eq!(digest(&first.clusters), digest(&second.clusters)); + assert_eq!(digest(&first.dupes), digest(&second.dupes)); + assert_eq!(first.summary, second.summary); +} diff --git a/crates/tranche-core/tests/support.rs b/crates/tranche-core/tests/support.rs new file mode 100644 index 0000000..001c843 --- /dev/null +++ b/crates/tranche-core/tests/support.rs @@ -0,0 +1,75 @@ +//! Shared setup for the tests that rebuild the report from a stored corpus. +//! +//! Included by each of those test binaries rather than built as its own, so a +//! binary is created only for the cases it actually runs. +//! +//! The tests read `tests/fixture/`, a committed slice of a real corpus. The full +//! corpus is 111 MiB and stays local, so a test that read it would pass on a +//! developer's machine and fail in a fresh checkout — which is exactly what +//! happened in CI. Regenerate the fixture with: +//! +//! ```text +//! cargo run --release -p tranche-core --example slice_fixture +//! ``` + +#![allow(dead_code)] + +use std::collections::HashMap; +use std::path::Path; + +use serde_json::Value; +use tranche_core::domain::cluster::{Clustered, cluster}; +use tranche_core::domain::dupe::current_pairs; +use tranche_core::domain::judge::current_judgments; +use tranche_core::domain::pr::load_prs; +use tranche_core::report::Root; + +pub use tranche_core::domain::judge::Judgment; +pub use tranche_core::domain::pr::Prs; + +pub const REPO: &str = "omacom/omarchy"; +pub const MODEL: &str = "jev-latest"; + +/// How many PRs the committed fixture holds. Asserted so a truncated or +/// regenerated fixture cannot quietly weaken every comparison below. +pub const FIXTURE_PRS: usize = 12; + +/// The checkout holding the committed fixture. +pub fn corpus() -> Root { + Root::new( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("fixture"), + ) +} + +/// One committed output, read from disk. +pub fn read(root: &Root, name: &str) -> Value { + let path = root.out_dir().join(name); + let text = std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("{}: {error}", path.display())); + serde_json::from_str(&text).expect("the committed output parses") +} + +/// The fixture, judged and pair-compared. +pub fn reconstructed(root: &Root) -> (Prs, HashMap, Vec) { + let prs = load_prs(root, REPO).expect("the fixture loads"); + let judgments = current_judgments(root, &prs, REPO, MODEL, false).expect("judgments bind"); + let verdicts = + current_pairs(root, &prs, &judgments, REPO, MODEL, false).expect("verdicts bind"); + // A read that returned nothing would satisfy every equality below. + assert_eq!( + prs.len(), + FIXTURE_PRS, + "the fixture holds the PRs it claims" + ); + assert!(!judgments.is_empty(), "the fixture's judgments were read"); + (prs, judgments, verdicts) +} + +/// The report the fixture produces, with the inputs it was built from. +pub fn built(root: &Root) -> (Prs, HashMap, Clustered) { + let (prs, judgments, verdicts) = reconstructed(root); + let report = cluster(&prs, &judgments, &verdicts, REPO, MODEL, false); + (prs, judgments, report) +} diff --git a/crates/tranche-core/tests/talking_to_the_model.rs b/crates/tranche-core/tests/talking_to_the_model.rs new file mode 100644 index 0000000..c9aa5f1 --- /dev/null +++ b/crates/tranche-core/tests/talking_to_the_model.rs @@ -0,0 +1,168 @@ +//! The Jev client's retry rules, against a local server. +//! +//! The classification is the whole contract: a 401 or a 422 must never be +//! retried, because they are question-shape bugs rather than load, and retrying +//! them would only spend the budget slower. A 429, a 529 and any 5xx must be +//! retried. The key must never appear in an error message. +//! +//! Each test runs its own server on its own port and passes that endpoint in, so +//! nothing here shares state with a test running beside it. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +use std::time::Duration; + +use tranche_core::jev::{JevError, ask_at}; + +/// A server that answers each request with the next scripted response, and +/// counts the requests it received. +struct Stub { + endpoint: String, + seen: Arc, +} + +/// Responses are `(status, body)` in order; the last one repeats. +fn serve(script: &'static [(u16, &'static str)]) -> Stub { + let listener = TcpListener::bind("127.0.0.1:0").expect("a free port"); + let port = listener.local_addr().expect("address").port(); + let seen = Arc::new(AtomicU32::new(0)); + let counter = Arc::clone(&seen); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + let index = counter.fetch_add(1, Ordering::SeqCst) as usize; + let (status, body) = script[index.min(script.len() - 1)]; + drain(&mut stream); + let reason = match status { + 200 => "OK", + 401 => "Unauthorized", + 422 => "Unprocessable Entity", + 429 => "Too Many Requests", + _ => "Internal Server Error", + }; + let response = format!( + "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + Stub { + endpoint: format!("http://127.0.0.1:{port}"), + seen, + } +} + +/// Read the request head and body so the client does not see a reset. +fn drain(stream: &mut TcpStream) { + let Ok(handle) = stream.try_clone() else { + return; + }; + let mut reader = BufReader::new(handle); + let mut length = 0usize; + let mut line = String::new(); + while reader.read_line(&mut line).unwrap_or(0) > 0 { + if let Some(value) = line.to_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + if line == "\r\n" { + break; + } + line.clear(); + } + if length > 0 { + let mut body = vec![0u8; length]; + let _ = reader.read_exact(&mut body); + } +} + +fn call(stub: &Stub) -> Result { + // SAFETY: the key is a fixed test literal, set on the calling thread before + // any request is made. Tests that touch the environment are serialised by + // `cargo test`'s own thread-per-test model only for this one variable, and + // every value written is the same, so a race cannot change the outcome. + unsafe { + std::env::set_var("TYPESAFE_API_KEY", "test-key-never-real"); + } + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime") + .block_on(ask_at( + &stub.endpoint, + &serde_json::json!({"pr": {"title": "x"}}), + &serde_json::json!({"category": {}}), + "jev-latest", + // Milliseconds rather than the real seconds: this exercises the + // exhaustion path without a sixty-second test. + Duration::from_millis(1), + Duration::from_millis(4), + )) +} + +#[test] +fn a_successful_answer_is_returned_without_retrying() { + let stub = serve(&[(200, r#"{"answer":"ok"}"#)]); + let answer = call(&stub).expect("the answer comes back"); + assert_eq!(answer["answer"], "ok"); + assert_eq!(stub.seen.load(Ordering::SeqCst), 1, "asked once"); +} + +#[test] +fn a_rejected_key_is_never_retried() { + // Retrying a 401 would spend the budget six times on a key that cannot work. + let stub = serve(&[(401, r#"{"error":"bad key"}"#)]); + let error = call(&stub).expect_err("401 is fatal"); + assert!(error.to_string().contains("401"), "{error}"); + assert!(error.to_string().contains("check the key"), "{error}"); + assert_eq!(stub.seen.load(Ordering::SeqCst), 1, "asked exactly once"); +} + +#[test] +fn a_question_shape_bug_is_never_retried() { + // A 422 means the request was malformed: retrying cannot fix it. + let stub = serve(&[(422, r#"{"error":"bad question"}"#)]); + let error = call(&stub).expect_err("422 is fatal"); + assert!(error.to_string().contains("422"), "{error}"); + assert_eq!(stub.seen.load(Ordering::SeqCst), 1, "asked exactly once"); +} + +#[test] +fn load_is_retried_until_it_succeeds() { + // A 429 then a 500 then success: two retries, then the answer. + let stub = serve(&[ + (429, r#"{"error":"slow down"}"#), + (500, r#"{"error":"boom"}"#), + (200, r#"{"answer":"third"}"#), + ]); + let answer = call(&stub).expect("the third attempt succeeds"); + assert_eq!(answer["answer"], "third"); + assert_eq!(stub.seen.load(Ordering::SeqCst), 3, "three attempts"); +} + +#[test] +fn exhausted_retries_report_the_last_error() { + let stub = serve(&[(500, r#"{"error":"always down"}"#)]); + let error = call(&stub).expect_err("five hundred is retried to exhaustion"); + assert!(error.to_string().contains("retries exhausted"), "{error}"); + assert!(error.to_string().contains("always down"), "{error}"); + assert_eq!( + stub.seen.load(Ordering::SeqCst), + 6, + "six attempts, the documented cap" + ); +} + +#[test] +fn an_error_never_carries_the_key() { + let stub = serve(&[(401, r#"{"error":"bad key"}"#)]); + let error = call(&stub).expect_err("401 is fatal").to_string(); + assert!( + !error.contains("test-key-never-real"), + "the credential leaked into an error: {error}" + ); +} diff --git a/crates/tranche-core/tests/the_read_policy.rs b/crates/tranche-core/tests/the_read_policy.rs new file mode 100644 index 0000000..f8e3559 --- /dev/null +++ b/crates/tranche-core/tests/the_read_policy.rs @@ -0,0 +1,159 @@ +//! The read transport's URL policy. +//! +//! Every check here is a refusal, which is the point: the transport runs with +//! `gh`'s credential behind it, so a URL it follows is a URL that credential is +//! spent on. A lookalike origin, a fragment, a credential in the query or a hop +//! outside the repository must all stop before a request is made. + +use tranche_core::evidence::read::url; + +const REPO: &str = "omacom/omarchy"; + +#[test] +fn the_api_origin_and_a_repository_path_are_accepted() { + assert_eq!( + url::validate( + "https://api.github.com/repos/omacom/omarchy/pulls/123", + Some(REPO) + ) + .expect("accepted"), + "https://api.github.com/repos/omacom/omarchy/pulls/123" + ); + // The namespace itself, without a trailing path, is inside the scope. + assert!(url::validate("https://api.github.com/repos/omacom/omarchy", Some(REPO)).is_ok()); +} + +#[test] +fn a_lookalike_origin_is_refused() { + // Parsing alone accepts both of these; the origin check must not. + for host in [ + "https://api.github.com.evil.test/repos/omacom/omarchy", + "https://api.github.com@evil.test/repos/omacom/omarchy", + ] { + assert!(url::validate(host, Some(REPO)).is_err(), "refused: {host}"); + } +} + +#[test] +fn a_non_https_scheme_is_refused() { + assert!(url::validate("http://api.github.com/repos/omacom/omarchy", Some(REPO)).is_err()); + assert!(url::validate("file:///etc/passwd", Some(REPO)).is_err()); + assert!(url::validate("git://api.github.com/x", Some(REPO)).is_err()); +} + +#[test] +fn a_credential_shaped_query_parameter_is_refused() { + // A URL is the one part of a request that gets logged everywhere. + for parameter in [ + "?access_token=abc", + "?TOKEN=abc", + "?api_key=abc", + "?client_secret=abc", + "?Authorization=abc", + ] { + let url = format!("https://api.github.com/repos/omacom/omarchy/pulls{parameter}"); + assert!(url::validate(&url, Some(REPO)).is_err(), "refused: {url}"); + } + // An ordinary parameter is not a credential and stays allowed. + assert!( + url::validate( + "https://api.github.com/repos/omacom/omarchy/pulls?page=2", + Some(REPO) + ) + .is_ok() + ); +} + +#[test] +fn whitespace_a_fragment_and_an_empty_url_are_refused() { + assert!(url::validate("", Some(REPO)).is_err()); + assert!( + url::validate( + "https://api.github.com/repos/omacom/omarchy/pulls\nX-Injected: 1", + Some(REPO) + ) + .is_err(), + "a newline would be a header injection" + ); + assert!( + url::validate( + "https://api.github.com/repos/omacom/omarchy#frag", + Some(REPO) + ) + .is_err() + ); +} + +#[test] +fn a_hop_outside_the_repository_namespace_is_refused() { + // The scope check is what stops a capture from wandering into another + // repository's data on the same token. + assert!( + url::validate( + "https://api.github.com/repos/other/project/pulls/1", + Some(REPO) + ) + .is_err() + ); + // A prefix that only resembles the namespace is also outside it. + assert!( + url::validate( + "https://api.github.com/repos/omacom/omarchy-evil/pulls/1", + Some(REPO) + ) + .is_err() + ); + // Without a scope, the origin is the only restriction. + assert!(url::validate("https://api.github.com/repos/other/project/pulls/1", None).is_ok()); +} + +#[test] +fn the_continuation_link_selects_next_and_validates_it() { + let header = "; rel=\"next\", \ + ; rel=\"last\""; + assert_eq!( + url::next_link(Some(header)).expect("parsed"), + Some("https://api.github.com/repos/omacom/omarchy/pulls?page=2".to_owned()) + ); + // No continuation is not an error. + assert_eq!(url::next_link(None).expect("parsed"), None); + assert_eq!( + url::next_link(Some("; rel=\"last\"")).expect("parsed"), + None + ); + // A continuation pointing off-origin is refused rather than followed. + assert!(url::next_link(Some("; rel=\"next\"")).is_err()); +} + +#[test] +fn the_page_number_is_read_or_defaults_to_one() { + assert_eq!( + url::page_number("https://api.github.com/repos/omacom/omarchy/pulls?page=7").expect("read"), + 7 + ); + assert_eq!( + url::page_number("https://api.github.com/repos/omacom/omarchy/pulls").expect("default"), + 1 + ); + assert!( + url::page_number("https://api.github.com/repos/omacom/omarchy/pulls?page=abc").is_err() + ); +} + +#[test] +fn a_redirect_target_is_resolved_or_refused() { + assert_eq!( + url::absolute( + "/repos/omacom/omarchy/pulls?page=2", + "https://api.github.com/x" + ) + .expect("resolved"), + "https://api.github.com/repos/omacom/omarchy/pulls?page=2" + ); + assert_eq!( + url::absolute("https://api.github.com/y", "https://api.github.com/x").expect("resolved"), + "https://api.github.com/y" + ); + // A relative target without a leading slash cannot be resolved safely. + assert!(url::absolute("pulls?page=2", "https://api.github.com/x").is_err()); +} diff --git a/crates/tranche-core/tests/the_report_gate.rs b/crates/tranche-core/tests/the_report_gate.rs new file mode 100644 index 0000000..ef342b1 --- /dev/null +++ b/crates/tranche-core/tests/the_report_gate.rs @@ -0,0 +1,215 @@ +//! The report gate. +//! +//! Every reader — the CLI, the workbench and the MCP server — obtains its +//! observation through `load`, so these tests are the ones that decide whether a +//! stale, foreign or modified report can leak into a surface. A false accept +//! here is worse than a false refuse: it publishes an observation that is not +//! the one the report describes. + +use tranche_core::domain::cluster::cluster; +use tranche_core::domain::dupe::current_pairs; +use tranche_core::domain::judge::current_judgments; +use tranche_core::domain::pr::load_prs; +use tranche_core::report::{BoundReport, Limits, MODEL, REPOSITORY, Root, input_digests, load}; +use tranche_core::util::{atomic_json, digest}; + +fn corpus() -> Root { + Root::new( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(std::path::Path::parent) + .expect("nested in the repository"), + ) +} + +/// A disposable copy of the real report, so a tampered file never touches the +/// checkout. +fn copy_of_corpus() -> (tempfile::TempDir, Root) { + let source = corpus(); + let temp = tempfile::tempdir().expect("a temporary root"); + let dest = Root::new(temp.path()); + for path in source.source_paths() { + let Some(name) = path.file_name() else { + continue; + }; + let target = if name == "snapshot.json" { + dest.snapshot_path() + } else if let Some(stem) = name.to_str().filter(|n| n.starts_with("page_")) { + dest.pages_dir().join(stem) + } else { + dest.out_dir().join(name) + }; + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent).expect("the destination directory"); + } + std::fs::copy(&path, &target).expect("the report file"); + } + (temp, dest) +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn the_committed_report_is_accepted() { + let report = load(&corpus(), &Limits::default()).expect("the committed report is valid"); + assert_eq!(report.prs.len(), 2817); + assert_eq!(report.judgments.len(), 2817); + assert_eq!(report.pairs.len(), 890); + assert!(report.batches.is_some(), "a batch plan is bound"); + assert!(report.parked.is_some(), "a park record is bound"); + // The identity a reader quotes back to prove which report it saw. + assert_eq!( + report.identity["clusters.json"].as_str(), + Some("8cddc06fc66c8123b960a44e7582770094e7cd348912a04e56a13787a7b4435e") + ); + assert_eq!( + report.identity["report_binding"].as_str(), + Some("d756202ba10f2e8a373c0a66b36ab23e745e42a22d8cd4ad97923d7eaa2ca661") + ); + assert!( + report.identity["batches.json"].as_str().is_some(), + "the batch digest is part of the identity" + ); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_foreign_report_is_refused() { + let (_temp, root) = copy_of_corpus(); + let mut summary: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(root.summary_path()).expect("summary")) + .expect("valid JSON"); + summary["repo"] = serde_json::json!("someone/else"); + atomic_json(&root.summary_path(), &summary).expect("written"); + let error = load(&root, &Limits::default()).expect_err("a foreign report is refused"); + assert!(error.0.contains("foreign or modified"), "{error}"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_modified_cluster_output_is_refused() { + let (_temp, root) = copy_of_corpus(); + let mut clusters: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(root.clusters_path()).expect("clusters")) + .expect("valid JSON"); + // Append one PR to a category: the recorded digest no longer describes it. + clusters["docs"]["low"] + .as_array_mut() + .expect("a band array") + .pop(); + atomic_json(&root.clusters_path(), &clusters).expect("written"); + let error = load(&root, &Limits::default()).expect_err("a modified report is refused"); + assert!(error.0.contains("foreign or modified"), "{error}"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_stale_report_binding_is_refused() { + let (_temp, root) = copy_of_corpus(); + let mut summary: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(root.summary_path()).expect("summary")) + .expect("valid JSON"); + summary["report_binding"] = serde_json::json!("0".repeat(64)); + atomic_json(&root.summary_path(), &summary).expect("written"); + let error = load(&root, &Limits::default()).expect_err("a stale binding is refused"); + assert!(error.0.contains("foreign or modified"), "{error}"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_modified_batch_plan_is_refused() { + let (_temp, root) = copy_of_corpus(); + let mut batches: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(root.batches_path()).expect("batches")) + .expect("valid JSON"); + batches["batches"][0]["members"] + .as_array_mut() + .expect("members") + .pop(); + batches["batches"][0]["count"] = serde_json::json!(3); + atomic_json(&root.batches_path(), &batches).expect("written"); + let error = load(&root, &Limits::default()).expect_err("a modified batch plan is refused"); + assert!(error.0.contains("batches.json is stale"), "{error}"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_modified_park_record_is_refused() { + let (_temp, root) = copy_of_corpus(); + let mut parked: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(root.parked_path()).expect("parked")) + .expect("valid JSON"); + parked["parked"] = serde_json::json!(0); + atomic_json(&root.parked_path(), &parked).expect("written"); + let error = load(&root, &Limits::default()).expect_err("a modified park record is refused"); + assert!(error.0.contains("parked.json is stale"), "{error}"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_missing_park_record_is_refused_when_batches_parked_prs() { + let (_temp, root) = copy_of_corpus(); + std::fs::remove_file(root.parked_path()).expect("removed"); + let error = load(&root, &Limits::default()).expect_err("a missing park record is refused"); + assert!(error.0.contains("parked.json is missing"), "{error}"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_malformed_judgment_log_is_refused() { + let (_temp, root) = copy_of_corpus(); + let mut log = std::fs::read_to_string(root.judgments_path()).expect("the log"); + // A line that parses as JSON but is not a record makes the whole log unsafe. + log.push_str("[1, 2, 3]\n"); + std::fs::write(root.judgments_path(), log).expect("written"); + let error = load(&root, &Limits::default()).expect_err("a malformed log is refused"); + assert!(error.0.contains("Invalid or missing"), "{error}"); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn load_produces_the_same_projection_the_builder_does() { + // The gate rebuilds the report to check the binding. This proves the rebuild + // and the direct construction agree, so the check cannot pass by comparing a + // value with itself. + let root = corpus(); + let report = load(&root, &Limits::default()).expect("valid"); + let prs = load_prs(&root, REPOSITORY).expect("capture"); + let judgments = current_judgments(&root, &prs, REPOSITORY, MODEL, false).expect("judgments"); + let pairs = current_pairs(&root, &prs, &judgments, REPOSITORY, MODEL, false).expect("pairs"); + let rebuilt = cluster(&prs, &judgments, &pairs, REPOSITORY, MODEL, false); + assert_eq!(digest(&report.clusters), digest(&rebuilt.clusters)); + assert_eq!(digest(&report.dupes), digest(&rebuilt.dupes)); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn input_digests_fingerprint_every_bound_input() { + let root = corpus(); + let digests = input_digests(&root, &Limits::default()).expect("digests"); + let map = digests.as_object().expect("a map"); + // The snapshot, the two logs and the five report outputs. The page shards + // exist but are not fingerprinted while a snapshot is present. + assert_eq!(map.len(), 8, "{:?}", map.keys().collect::>()); + assert!(map.contains_key("/srv/lab/hack/omarchy-pr-jev-triage/data/pages/snapshot.json")); + assert!(map.contains_key("/srv/lab/hack/omarchy-pr-jev-triage/out/summary.json")); + assert!(map.values().all(|value| value.is_string())); + + // Absent files are omitted rather than recorded as null, so the key set is + // the set that exists. + let temp = tempfile::tempdir().expect("a temporary root"); + let empty = Root::new(temp.path()); + let digests = input_digests(&empty, &Limits::default()).expect("digests"); + assert_eq!(digests.as_object().expect("a map").len(), 0); +} + +#[test] +#[ignore = "reads the local 111 MiB corpus; the committed fixture covers the rest"] +fn a_root_without_the_service_modules_is_refused() { + let temp = tempfile::tempdir().expect("a temporary root"); + let root = Root::new(temp.path()); + let error = load(&root, &Limits::default()).expect_err("an empty root is refused"); + assert!(error.0.contains("Invalid or missing"), "{error}"); + // Nothing leaks as a usable observation. + let refused: Result = load(&root, &Limits::default()); + assert!(refused.is_err()); +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..6f22bbe --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,86 @@ +# Tranche is a Rust project + +`crates/tranche-core` holds the logic and `crates/tranche-cli` is the `tranche` +binary. Dependency direction is one-way: the binary depends on the library, and +the library never depends on a transport. + +## Layout + +``` +Cargo.toml workspace root +crates/ + tranche-core/ lib — logic, no I/O transport + src/report/ path vocabulary, input digests, binding, the gate + src/domain/pr/ membership, identity, evidence digests + src/domain/judge/ question policy, normalization, resume binding + src/domain/dupe/ candidate pairs, similarity, stored verdicts + src/domain/cluster/ grouping, predicates, the report and its binding + src/domain/batch/ packing, park decisions, report sections + src/domain/questions.rs the frozen question policy + src/evidence/ selection, coverage, manifest, lock, store + tranche-cli/ bin `tranche` + src/cli.rs the command tree + src/commands.rs dispatch +``` + +Dependency direction is one-way: `tranche-cli` → `tranche-core`. Core never +depends on a transport. + +## The on-disk artifacts are the contract + +`out/` is the interface between the pipeline and everything that reads it, so +the code is judged by whether it reproduces those bytes — not by whether it +looks correct. `crates/tranche-core/tests/the_published_report.rs` is that +judgement: it rebuilds the report from the stored corpus and asserts equality +against the committed files. + +Three properties of the format look like accidents and are not, because each one +silently changes a tracked artifact when it is got wrong: + +1. **Key order is insertion order, not sorted.** Categories in `clusters.json` + and the sections of `tranches.md` follow first appearance. The digests cannot + catch a mistake here, because they sort keys explicitly. +2. **Floats keep the shortest round-tripping form.** `0.6` stays `0.6` and + `0.5700000000000001` keeps all seventeen digits; rounding to a fixed number + of places is wrong. +3. **JSON separators carry a space** after each comma and colon, so a write that + uses a compact serializer restyles every artifact. + +`serde_json` needs `arbitrary_precision` (or a float parses to a different +double than the stored one) and `preserve_order` (or an object is written +sorted). Both are load-bearing, and the crate documents them as such. + +## Rules + +1. **No source file reaches 300 lines.** Split by responsibility into sibling + modules; a module that needs three concepts is three modules. This applies to + every crate's `src/`, not to tests. +2. **Tests live only in `tests/`**, never in a `#[cfg(test)]` module inside a + source file, and they are named for the outcome they protect rather than the + module they exercise. A test named after a module drifts into restating the + implementation; a test named after an outcome fails when the behaviour breaks. +3. **`gh` stays a subprocess.** The GitHub credential stays inside `gh`; do not + reimplement GitHub auth. + +## Not wired yet + +Dispatch exists for `cluster`, `batches` and `info`. `fetch`, `judge`, `dupes`, +`refresh`, `all`, `page` and the `evidence` verbs refuse until their transports +land. Jev is a plain HTTPS POST, so `judge` and `dupes` need an HTTP client and +nothing else. + +Two pieces of the codebase are still to be ported, and `mcp_server.py` and +`tests/test_mcp_server.py` are kept as the reference they will be verified +against rather than deleted: + +1. **The read projection.** The workbench and the MCP server each reconstruct + the report today. One `view` module should serve both, so the two surfaces + cannot disagree. +2. **`tranche-mcp`.** A second binary, not a subcommand: clients spawn one + process and speak JSON-RPC over stdio. The six tools are `surface`, `query`, + `pick`, `next_prompt`, `related` and `digests`. Its exit criterion is that a + real MCP client completes `initialize` → `tools/list` → `tools/call`, with the + 1 MiB response cap, 25/100 pagination and error `-32602` for unknown tools + preserved. + +The masthead GIF generator was not ported; the GIF stays as a committed asset. diff --git a/docs/EVIDENCE_CLI.md b/docs/EVIDENCE_CLI.md index a668707..add26e2 100644 --- a/docs/EVIDENCE_CLI.md +++ b/docs/EVIDENCE_CLI.md @@ -4,11 +4,14 @@ Capture the public GitHub evidence of a Tranche batch, inspect it offline, resum an interrupted capture and export a self-contained packet — all with Tranche. ```bash -python3 tranche.py evidence capture --batch B001 --request-budget 100 -python3 tranche.py evidence show --batch B001 -python3 tranche.py evidence export --batch B001 --output review-packet.json +tranche evidence capture --batch B001 --request-budget 100 +tranche evidence show --batch B001 +tranche evidence export --batch B001 --output review-packet.json ``` +Requires the `tranche` binary (`make cli-install`, or `cargo install --path .`). +Run it from the checkout, or pass `--root /path/to/Tranche` from anywhere. + Evidence capture is **optional, read-only toward GitHub and model-free**. It never runs a model, never writes to GitHub, never executes a patch or source file, and never opens a browser. It reads through `gh`, which keeps the credential inside diff --git a/docs/EVIDENCE_PACKET.md b/docs/EVIDENCE_PACKET.md index 58902f5..5a356f7 100644 --- a/docs/EVIDENCE_PACKET.md +++ b/docs/EVIDENCE_PACKET.md @@ -76,14 +76,14 @@ promise that every unknown field is refused. identity, rather than inventing missing projection fields. Selection uses the authoritative bound-report loader in -[`report_loader.py`](../report_loader.py), shared with the report consumers. +`tranche_core::report`, shared with the report consumers. Opaque report digests associate evidence with a validated report; they neither reconstruct that report offline nor authenticate the source bytes. A batch ID such as `B001` is a display ordinal, never a sufficient evidence identity. `generation_id(selection, capture_id)` computes the native object digest of: -```python +```text { "format": FORMAT, "profile": PROFILE, @@ -224,7 +224,7 @@ Native implementation tests are in [`tests/test_ghread.py`](../tests/test_ghread.py): ```bash -python3 -m unittest tests.test_evidence tests.test_ghread -v +cargo test -p tranche-core ``` The original proposal's @@ -245,7 +245,7 @@ valuable **historical synthetic conformance support**: acquisition behaviour. Run those preserved cases with -`python3 -m unittest tests.test_evidence_packet -v`. Keeping them credits and +`cargo test -p tranche-core`. Keeping them credits and retains the proposal work without requiring native state or exports to conform to its historical layout. Any native wire-format claim must instead be checked against the native producer and its tests. diff --git a/docs/NATIVE_CLI.md b/docs/NATIVE_CLI.md new file mode 100644 index 0000000..6a223d6 --- /dev/null +++ b/docs/NATIVE_CLI.md @@ -0,0 +1,82 @@ +# Native Tranche CLI + +The `tranche` binary exposes the Tranche command tree and is the pipeline +implementation. The commands that run today are marked below. + +## Install + +From a Tranche checkout, with a current Rust toolchain: + +```sh +cargo install --path . --locked +tranche --help +tranche --root /absolute/path/to/Tranche cluster +``` + +The binary is self-contained: it needs nothing but its checkout's data and +outputs at runtime. `--root` selects the checkout containing the captured corpus +and the derived reports; the default is the current working directory, not a +baked-in build path. + +## Commands + +Every command is wired except the `evidence` verbs, which still refuse. + +```sh +tranche fetch [--transport gh|urllib|curl] +tranche judge [--limit N] [--resume] +tranche dupes [--max-pairs N] +tranche cluster [--allow-unbound] +tranche batches +tranche refresh [--max-pairs N] [--no-page] [--dry-run] +tranche all [--limit N] [--resume] [--max-pairs N] +tranche page +tranche evidence capture --batch B001 [--request-budget N] [--max-bytes N] + [--fresh] [--reuse-capture ID] [--break-lock] +tranche evidence show [--batch B001 | --capture ID] [--source ID] [--citation ID] + [--start-byte N] [--length N] +tranche evidence export [--batch B001 | --capture ID] --output FILE + [--allow-historical] [--request-budget N] [--max-bytes N] +``` + +Use `tranche COMMAND --help` for its flags. The evidence service retains its +native capture, resume, selection, sharing gate and exit-code contracts; see +[the evidence guide](EVIDENCE_CLI.md). Repeat capture to resume, or explicitly +select a generation with `--reuse-capture ID`. Stored evidence stays local under +the checkout's ignored `out/evidence/` directory. + +`judge`, `dupes`, `refresh`, and `all` can make paid model calls; only explicit +commands start them. Captured CI remains an observation, not tests executed by +Tranche. + +## Automation + +`--json` emits machine-readable output in the stored format. Diagnostics go to +stderr, so stdout stays parseable. + +```sh +tranche --root /absolute/path/to/Tranche cluster --json +tranche evidence show --capture ID --json +tranche evidence export --capture ID --output - > packet.json +``` + +Export to `--output -` writes the packet to stdout. The native public-sharing +gate still applies. + +## Verify + +```sh +make check # format, strict clippy, tests and whitespace +make cli-install # build and install the binary from this checkout +``` + +Rust integration fixtures use disposable relocated checkouts and synthetic +transport responses. They verify service calls and packet parity without +acquiring contributor source trees or calling paid models. + +## Attribution + +Author: Vittorio Distefano ([blackopsrepl](https://github.com/blackopsrepl)). +Builds on Christopher's initial CLI POC +([@GreyforgeLabs](https://github.com/GreyforgeLabs)), with the Rust frontend and +native integration developed and maintained in Tranche. diff --git a/docs/decisions/native-evidence-cli.md b/docs/decisions/native-evidence-cli.md index c63291e..3779a3b 100644 --- a/docs/decisions/native-evidence-cli.md +++ b/docs/decisions/native-evidence-cli.md @@ -29,7 +29,8 @@ test support, not that wire specification. - `tests/test_ghread.py`, `tests/test_evidence.py` — offline synthetic suites. - `docs/decisions/native-evidence-cli.md` (this note), `docs/EVIDENCE_CLI.md` (user documentation, written from implemented behaviour at the end). -- `evidence` subparser wired into `tranche.py`'s existing `argparse` entry point. +- `evidence` subparser owned by `evidence.py`, exposed through the native `tranche + evidence ...` command tree. ## Four identities that must not be collapsed @@ -92,13 +93,13 @@ a missing group does not mean "no CI". ## Command semantics ``` -tranche.py evidence capture --batch B001 [--request-budget N] [--fresh] - [--reuse-capture ID] [--json] -tranche.py evidence show --batch B001 [--json] -tranche.py evidence show --capture ID [--json] -tranche.py evidence show --capture ID --source SOURCE_ID - [--start-byte N] [--length N] [--raw] [--json] -tranche.py evidence export --batch B001 --output FILE [--capture ID] [--json] +tranche evidence capture --batch B001 [--request-budget N] [--fresh] + [--reuse-capture ID] [--json] +tranche evidence show --batch B001 [--json] +tranche evidence show --capture ID [--json] +tranche evidence show --capture ID --source SOURCE_ID + [--start-byte N] [--length N] [--json] +tranche evidence export --batch B001 --output FILE [--capture ID] [--json] ``` - `capture` validates the current native selection, acquires or resumes, prints the capture @@ -193,9 +194,10 @@ terminal/HTML control content, duplicate JSON keys, non-finite values, integer b path escape, symlink attacks, hostile `next` links, redirects off the allowed origins, foreign resource identity, repeated cursors/ids, bad counts, mid-pagination edits. -**Operational.** Human and JSON output, help/README/Makefile integration, `make test` and -`make check` green, existing commands/reports/MCP/workbench unchanged when evidence is -absent, discovery and model caches untouched, no GitHub mutations from evidence commands. +**Operational.** Human and JSON output, help/README/Makefile integration, `make check` and +`make native-check` green, existing commands/reports/MCP/workbench unchanged when evidence +is absent, discovery and model caches untouched, no GitHub mutations from evidence +commands. **Remaining work not in this PR.** Workbench publication of evidence and MCP read/retrieve adapters (bounded schemas, progressive retrieval) are follow-ups; #9 is not closed by this diff --git a/evidence.py b/evidence.py deleted file mode 100644 index 1f92971..0000000 --- a/evidence.py +++ /dev/null @@ -1,2156 +0,0 @@ -#!/usr/bin/env python3 -"""Native evidence capture, inspection and export for a selected Tranche batch. - -Selecting a batch and capturing its public GitHub evidence is a Tranche operation, -not a handout to another application. This module owns the native state, the -inspection path and the export format; the workbench and the MCP server are -intended to read the same service rather than reimplementing acquisition. - -Read-only and model-free: the transport is `ghread`, which keeps the credential -inside `gh`, issues only GETs and GraphQL queries, and never mutates GitHub. No -command here calls a model, opens a browser, or executes captured content. - -The identities this module keeps apart are documented in -`docs/decisions/native-evidence-cli.md`: report association, code identity, -mutable observation, and capture generation. -""" -from __future__ import annotations - -import argparse -import base64 -import hashlib -import json -import os -import re -import sys -import time -from datetime import datetime, timezone -from pathlib import Path - -import ghread -import report_loader -import tranche - -FORMAT = "tranche.evidence-packet/v1" -PROFILE = "pr-review/v1" - -# The public operations a caller may rely on. `checks` keeps check-runs and -# commit statuses as two separately paginated groups inside one component: an -# empty check-run list and an empty status list are different observations and -# neither is proof that no CI is configured. -REST_COMPONENTS = ("metadata", "diff", "files", "discussion", "review_comments", "reviews") -COMPONENTS = (*REST_COMPONENTS, "checks", "closing_issues") -# component -> the endpoint groups it is made of. REST components are one group -# each. `checks` is four independently paginated collections, because a PR's -# checks are created where the suite was created and that has two possible homes: -# the base repository (the PR's own checks, which is what a reviewer means by -# "the CI") and, only when the head is a fork, the linked repository, whose CI is -# the contributor's own branch state. Both are recorded and each response names -# the repository it came from, so nothing here claims an absence that one source -# simply could not see. -COMPONENT_GROUPS = { - "metadata": ("metadata",), "diff": ("diff",), "files": ("files",), - "discussion": ("discussion",), "review_comments": ("review_comments",), - "reviews": ("reviews",), - "checks": ("check_runs", "statuses", "fork_check_runs", "fork_statuses"), - "closing_issues": ("closing_issues",), -} -GROUPS = tuple(group for groups in COMPONENT_GROUPS.values() for group in groups) -BASE_CI_GROUPS = ("check_runs", "statuses") -FORK_CI_GROUPS = ("fork_check_runs", "fork_statuses") -CI_GROUPS = (*BASE_CI_GROUPS, *FORK_CI_GROUPS) -# A check-runs response is capped at the 1000 most recent suites and a file list -# at 3000 entries; reaching either is a named gap, never silent completeness. -CHECK_RUN_CAP = 1000 -FILE_LIST_CAP = 3000 - - -def ci_targets(member: dict) -> list[tuple[str, str, int]]: - """Every repository whose CI is worth reading for this member, and why. - - The base repository holds the PR's own checks; the fork, when there is one, - holds whatever CI the contributor's branch has. Reading only the base would - quietly miss the second, and reading only the fork would present the wrong - repository's CI as the PR's. - """ - targets = [(group, member["base_repo_name"], member["base_repo_id"]) - for group in BASE_CI_GROUPS] - if member["head_repo_name"] != member["base_repo_name"]: - targets += [(group, member["head_repo_name"], member["head_repo_id"]) - for group in FORK_CI_GROUPS] - return targets - - -def groups_for(member: dict, component: str) -> tuple[str, ...]: - if component == "checks": - return tuple(group for group, _repo, _id in ci_targets(member)) - return COMPONENT_GROUPS[component] -# Components whose raw bytes are a document a person reads, so citations from -# them resolve against the decoded text of that same record. -CONTENT_COMPONENTS = ("files", "diff", "discussion", "review_comments", "reviews") - -EXIT_OK = 0 -EXIT_USABLE = 1 -EXIT_USAGE = 2 -EXIT_REFUSED = 3 -EXIT_INCOMPLETE = 4 - -DEFAULT_REQUEST_BUDGET = 200 -DEFAULT_MAX_BYTES = 64 * 1024 * 1024 -DEFAULT_EXPORT_BYTES = 64 * 1024 * 1024 -DEFAULT_WINDOW_BYTES = 16 * 1024 -MAX_PAGES = 20 -PER_PAGE = 100 -MAX_DIFF_BYTES = 3 * 1024 * 1024 -MAX_DIFF_LINES = 50_000 -MAX_CITATIONS = 5_000 -MAX_CITATIONS_PER_PAGE = 32 -RESERVED_BUDGET = 3 -LOCK_TTL = 900 - -CAPTURE_ID = re.compile(r"[0-9a-f]{32}") -BATCH_ID = re.compile(r"B[0-9]{3,6}") -LOCATOR = re.compile(r"(https?://\S+|@[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})|[A-Za-z0-9_-]+/[A-Za-z0-9_.-]+#\d+)") -TRAILING = ".,;:!?)]}'\"" -CLOSING_QUERY = ( - "query trancheClosingIssues($owner:String!,$name:String!,$number:Int!,$cursor:String){" - " repository(owner:$owner,name:$name){ pullRequest(number:$number){ number url" - " closingIssuesReferences(first:100,after:$cursor){ totalCount" - " pageInfo{hasNextPage endCursor} nodes{number url state title} } } } }" -) - - -class EvidenceError(RuntimeError): - """The evidence request cannot be satisfied as asked.""" - - -class SelectionError(EvidenceError): - """The current native selection refuses this request.""" - - -class IncompleteCapture(EvidenceError): - """The capture is usable but not complete; the message says how to resume.""" - - -def now() -> str: - return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def root() -> Path: - """The evidence root, resolved at call time so tests can move OUT_DIR.""" - return tranche.OUT_DIR / "evidence" - - -def evidence_digest(value) -> str: - """Tranche's own object digest, so evidence identity matches the repo's.""" - return tranche.digest(value) - - -# --------------------------------------------------------------------------- -# Paths, confinement and the writer lock -# --------------------------------------------------------------------------- - -def capture_dir(capture_id: str) -> Path: - if not isinstance(capture_id, str) or CAPTURE_ID.fullmatch(capture_id) is None: - raise EvidenceError("capture id must be 32 lowercase hex characters") - return root() / capture_id - - -def confined_file(path, base: Path) -> Path: - """A regular single-link file beneath `base`, with no symlink anywhere. - - Every level beneath the root is checked with `lstat`, so a symlinked - directory or a hard-linked body is refused rather than followed, and a - traversal that escapes the root is refused even if the final path exists. - """ - if not isinstance(path, str) or not path: - raise EvidenceError("empty evidence path") - if "\x00" in path: - raise EvidenceError("evidence path contains a NUL byte") - parts = Path(path).parts - if any(part in ("..", "") for part in parts) or Path(path).is_absolute(): - raise EvidenceError(f"refusing unconfined path {path!r}") - if not any(part not in (".",) for part in parts): - raise EvidenceError(f"refusing empty path {path!r}") - base = base.resolve() - current = base - for part in parts: - current = current / part - if current.is_symlink(): - raise EvidenceError(f"refusing symlink in evidence path: {path!r}") - if current.exists() and current.is_dir() and current != base: - continue - resolved = (base / Path(*parts)).resolve() - if resolved != base and base not in resolved.parents: - raise EvidenceError(f"refusing path outside the evidence root: {path!r}") - if resolved.is_symlink(): - raise EvidenceError(f"refusing symlinked evidence file: {path!r}") - if resolved.exists(): - info = resolved.lstat() - if not resolved.is_file(): - raise EvidenceError(f"refusing non-regular evidence file: {path!r}") - if info.st_nlink != 1: - raise EvidenceError(f"refusing multiply-linked evidence file: {path!r}") - return resolved - - -def atomic_bytes(path: Path, data: bytes) -> None: - """Publish bytes atomically, replacing any previous record only on success.""" - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.parent / f".pending-{os.getpid()}-{int(time.time() * 1000)}" - try: - with temporary.open("wb") as stream: - stream.write(data) - stream.flush() - os.fsync(stream.fileno()) - os.chmod(temporary, 0o600) - os.replace(temporary, path) - finally: - if temporary.exists(): - temporary.unlink() - - -def atomic_manifest(path: Path, value: dict) -> None: - atomic_bytes(path, json.dumps(value, ensure_ascii=False, allow_nan=False, - sort_keys=True).encode("utf-8")) - - -class Lock: - """One writer per capture, with a bounded TTL so a crash cannot strand work. - - The lock records the owning pid and when it started. It is released by the - owner, reclaimed when the recorded process no longer exists, and refused - while a live writer holds it. `break_lock` is the explicit operator override - for the remaining case: a live-looking pid that no longer owns the capture. - """ - - def __init__(self, capture_id: str, *, ttl: int = LOCK_TTL): - self.capture_id = capture_id - self.ttl = ttl - self.path = root() / f"{capture_id}.lock" - self.held = False - - def _owner(self) -> dict | None: - try: - value = json.loads(self.path.read_text()) - except (OSError, json.JSONDecodeError): - return None - return value if isinstance(value, dict) else None - - @staticmethod - def _alive(pid) -> bool: - if type(pid) is not int or pid <= 0: - return False - try: - os.kill(pid, 0) - except ProcessLookupError: - return False - except PermissionError: - return True - return True - - def acquire(self, *, break_lock: bool = False) -> None: - root().mkdir(parents=True, exist_ok=True) - for attempt in (1, 2): - try: - handle = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) - except FileExistsError: - owner = self._owner() or {} - stale = not self._alive(owner.get("pid")) - if self.path.exists(): - try: - age = time.time() - self.path.stat().st_mtime - except OSError: - age = 0 - # Age alone never grants permission to replace a live writer. - stale = stale and age > self.ttl if not owner else stale - if break_lock or stale: - self._release_file() - if attempt == 1: - continue - raise EvidenceError( - f"could not replace the writer lock at {self.path}") from None - raise EvidenceError( - f"another writer holds {self.capture_id} " - f"(pid {owner.get('pid', 'unknown')}); use --break-lock if it is gone") - with os.fdopen(handle, "w") as stream: - json.dump({"pid": os.getpid(), "started": now(), - "started_at": time.time()}, stream) - stream.flush() - os.fsync(stream.fileno()) - self.held = True - return - - def _release_file(self) -> None: - try: - self.path.unlink() - except OSError: - pass - - def release(self) -> None: - if self.held: - self._release_file() - self.held = False - - def __enter__(self) -> "Lock": - self.acquire() - return self - - def __exit__(self, *exc) -> None: - self.release() - - -# --------------------------------------------------------------------------- -# Selection: the exact batch, revisions and provenance this evidence belongs to -# --------------------------------------------------------------------------- - -def captured_items() -> dict: - """Raw captured PR items keyed by number, for base/head identity. - - `load_prs` projects the fields a judgment depends on and deliberately drops - the base revision and the repository identities, which code identity needs. - The membership itself is read through the same source selection and the same - checksum, never a parallel snapshot. - """ - snapshot = tranche.PAGES_DIR / "snapshot.json" - if snapshot.exists(): - value = json.loads(snapshot.read_text()) - if (not isinstance(value, dict) or value.get("repo") != tranche.REPO - or value.get("digest") != tranche.digest(value.get("items"))): - raise SelectionError("captured snapshot identity or checksum differs; fetch again") - pages = [value["items"]] - else: - pages = [json.loads(path.read_text()) - for path in sorted(tranche.PAGES_DIR.glob("page_*.json"))] - items: dict[int, dict] = {} - for page in pages: - if not isinstance(page, list): - raise SelectionError("captured PR membership must be a list; fetch again") - for item in page: - if not isinstance(item, dict) or type(item.get("number")) is not int: - raise SelectionError("invalid captured PR shape; fetch again") - items[item["number"]] = item - return items - - -SHA1 = re.compile(r"[0-9a-f]{40}") - - -def _revision(number: int, items: dict) -> dict: - """Full base/head identity for one member, or refuse the selection. - - A short or missing revision is never substituted: the whole point of the code - observation is that it names an exact pair of commits. - """ - item = items.get(number) - if item is None: - raise SelectionError(f"#{number} is not in the captured membership; fetch again") - head = item.get("head") or {} - base = item.get("base") or {} - head_repo = head.get("repo") - base_repo = base.get("repo") - if not isinstance(head_repo, dict) or not isinstance(base_repo, dict): - raise SelectionError( - f"#{number} no longer exposes its base/head repository (a deleted fork cannot be " - "captured); the selection cannot bind this member") - for name, value in (("base_sha", base.get("sha")), ("head_sha", head.get("sha"))): - if not isinstance(value, str) or SHA1.fullmatch(value) is None: - raise SelectionError(f"#{number} has no full 40-character {name}; fetch again") - identity = { - "number": number, - "base_sha": base["sha"], "head_sha": head["sha"], - "base_repo_id": base_repo.get("id"), "base_repo_name": base_repo.get("full_name"), - "head_repo_id": head_repo.get("id"), "head_repo_name": head_repo.get("full_name"), - "head_fork": bool(head_repo.get("fork")), - "updated_at": item.get("updated_at"), - } - for name in ("base_repo_id", "head_repo_id"): - if type(identity[name]) is not int or identity[name] <= 0: - raise SelectionError(f"#{number} has no usable {name}; fetch again") - for name in ("base_repo_name", "head_repo_name"): - if not isinstance(identity[name], str) or "/" not in identity[name]: - raise SelectionError(f"#{number} has no usable {name}; fetch again") - if identity["updated_at"] is not None and not isinstance(identity["updated_at"], str): - raise SelectionError(f"#{number} has an unreadable updated_at; fetch again") - return identity - - -def revision_key(identity: dict) -> dict: - """What a revision move actually means: commits and the repositories they sit in. - - `updated_at` is deliberately excluded. It is observed upstream data and a PR - update is thread activity, not a code revision; treating it as a universal - revision marker would force re-downloading unchanged code. - """ - return {name: identity[name] for name in - ("base_sha", "head_sha", "base_repo_id", "base_repo_name", - "head_repo_id", "head_repo_name")} - - -# Code components name a revision's content; mutable components are timestamped -# observations of a moving conversation. A thread update refreshes the second -# group without touching the first, and only a revision move touches the first. -CODE_COMPONENTS = ("metadata", "diff", "files") -MUTABLE_COMPONENTS = ("discussion", "review_comments", "reviews", "checks", - "closing_issues") - - -class Selection: - """The immutable native selection one capture generation is bound to.""" - - __slots__ = ("repository", "report", "batch", "members", "_prompt", "_membership") - - def __init__(self, repository: dict, report: dict, batch: dict, members: list): - self.repository = repository - self.report = report - self.batch = batch - self.members = members - self._prompt = batch["review_prompt"] - self._membership = [m["number"] for m in members] - - @property - def numbers(self) -> list[int]: - return list(self._membership) - - def as_json(self) -> dict: - """The frozen projection written into every manifest and export. - - The native batch is copied whole - ordinal, ordered membership and the - exact reviewer prompt - because the prompt is provenance a reader can - check, not a cache key. Freezing only these fields keeps a later native - presentation change from invalidating recorded evidence. - """ - return {"repository": self.repository, - "report": self.report, - "batch": {"id": self.batch["id"], "ordinal": self.batch["ordinal"], - "members": list(self._membership), "count": self.batch["count"], - "review_prompt": self._prompt}, - "members": [self._member_json(m) for m in self.members]} - - @staticmethod - def _member_json(member: dict) -> dict: - keys = ("number", "source_digest", "evidence_digest", "base_sha", "head_sha", - "base_repo_id", "base_repo_name", "head_repo_id", "head_repo_name", - "head_fork", "updated_at") - return {key: member[key] for key in keys} - - @property - def membership_digest(self) -> str: - return evidence_digest(self._membership) - - def revision(self) -> dict: - """The code identity of the whole selection, stable across thread churn.""" - return {str(m["number"]): revision_key(m) for m in self.members} - - -def select(batch_id: str, report: report_loader.BoundReport) -> Selection: - """Resolve one batch through the authoritative bound report, or refuse. - - Every refusal here is a refusal to attach evidence to the wrong thing: an - unknown ordinal, a batch file the loader rejected, a parked member, a member - whose revisions or repository identities are unavailable. - """ - if not isinstance(batch_id, str) or BATCH_ID.fullmatch(batch_id) is None: - raise SelectionError("expected an exact batch id such as B001") - if report.batches is None: - raise SelectionError("batches.json is unavailable; run tranche.py batches") - batch = next((b for b in report.batches["batches"] if b.get("id") == batch_id), None) - if batch is None: - raise SelectionError(f"unknown batch id {batch_id}; the current report has " - f"{len(report.batches['batches'])} batches") - parked = {m["number"] for m in (report.parked or {}).get("members", [])} - inconsistent = sorted(set(batch["members"]) & parked) - if inconsistent: - raise SelectionError( - "batch " + batch_id + " lists parked PRs " + - ", ".join(f"#{n}" for n in inconsistent) + - "; the batch plan and the park record disagree - rerun tranche.py batches") - items = captured_items() - members = [] - for number in batch["members"]: - identity = _revision(number, items) - pr = report.prs.get(number) - if pr is None: - raise SelectionError(f"#{number} is missing from the report projection") - identity["source_digest"] = pr["source_digest"] - identity["evidence_digest"] = pr["evidence_digest"] - members.append(identity) - base_repo = members[0] - repository = {"id": base_repo["base_repo_id"], "full_name": base_repo["base_repo_name"], - "visibility": base_repo.get("base_repo_visibility", "unknown")} - if any(m["base_repo_id"] != repository["id"] or m["base_repo_name"] != repository["full_name"] - for m in members): - raise SelectionError("batch members do not share one base repository") - report_block = {"report_binding": report.identity["report_binding"], - "output_digests": {name: report.identity[name] for name in - ("clusters.json", "dupes.json", - "batches.json", "parked.json")}} - return Selection(repository, report_block, batch, members) - - -def selection_of(capture_id: str) -> Selection: - """Rebuild the frozen selection of a stored capture (works offline, any report).""" - manifest = read_manifest(capture_id) - stored = manifest["selection"] - batch = stored["batch"] - members = [dict(m) for m in stored["members"]] - return Selection(dict(stored["repository"]), dict(stored["report"]), batch, members) - - -# --------------------------------------------------------------------------- -# Manifest, generation and stored bytes -# --------------------------------------------------------------------------- - -def strict_json_loads(data: bytes): - """Load JSON refusing the shapes that make a record ambiguous. - - Duplicate keys, NaN/Infinity and invalid UTF-8 are all refusal cases: a - checkpoint that can be read two ways cannot be trusted to resume from. - """ - def unique(pairs): - seen = {} - for key, value in pairs: - if key in seen: - raise EvidenceError(f"duplicate JSON key {key!r}") - seen[key] = value - return seen - - def reject(value): - raise EvidenceError(f"non-finite JSON number {value!r}") - - try: - return json.loads(data.decode("utf-8"), object_pairs_hook=unique, - parse_constant=reject) - except UnicodeDecodeError as exc: - raise EvidenceError(f"evidence record is not valid UTF-8 ({exc})") from exc - - -def manifest_path(capture_id: str) -> Path: - return capture_dir(capture_id) / "manifest.json" - - -def body_path(body_sha256: str) -> Path: - """Bodies live in one content-addressed store at the evidence root. - - Keying by digest rather than by capture is what lets a new association reuse - unchanged bytes without copying them, and it keeps a body a single immutable - artifact instead of one copy per capture that recorded it. The manifest - carries only the digest; the location is derived, never recorded, so there is - no second identity for the same bytes. - """ - if not isinstance(body_sha256, str) or re.fullmatch(r"[0-9a-f]{64}", body_sha256) is None: - raise EvidenceError("source body digest must be 64 lowercase hex characters") - return root() / "bodies" / f"{body_sha256}.bin" - - -def store_body(data: bytes) -> str: - """Persist immutable source bytes and return their sha256. - - Bytes are written and fsynced before any manifest may cite them, so a crash - between the two leaves an unreferenced file - swept later - and never a - checkpoint pointing at bytes that are not there. - """ - sha = hashlib.sha256(data).hexdigest() - path = body_path(sha) - if path.exists(): - read_body(sha) # identical name is not proof: verify before trusting it - return sha - atomic_bytes(path, data) - return sha - - -def read_body(body_sha256: str) -> bytes: - """Read stored bytes, verifying them against their digest before returning.""" - body_path(body_sha256) # validate the digest before deriving a confined path - path = confined_file(f"bodies/{body_sha256}.bin", root()) - if not path.exists(): - raise EvidenceError(f"stored source {body_sha256[:12]}… is missing") - data = path.read_bytes() - actual = hashlib.sha256(data).hexdigest() - if actual != body_sha256: - raise EvidenceError( - f"stored source {body_sha256[:12]}… is corrupted (computed {actual[:12]}…)") - return data - - -def referenced_bodies() -> set[str]: - """Every body digest any stored capture cites, for the orphan sweep.""" - referenced: set[str] = set() - directory = root() - if not directory.exists(): - return referenced - for path in directory.glob("*/manifest.json"): - try: - manifest = strict_json_loads(path.read_bytes()) - except (OSError, EvidenceError): - continue - if isinstance(manifest, dict) and isinstance(manifest.get("sources"), list): - for source in manifest["sources"]: - if isinstance(source, dict) and isinstance(source.get("body_sha256"), str): - referenced.add(source["body_sha256"]) - return referenced - - -def sweep_orphans() -> int: - """Remove stored bodies no capture cites. - - A crash can leave bytes written but not yet cited. They are harmless, but they - are also unreferenced state, so a completed run tidies them rather than - leaving unbounded growth behind. - """ - directory = root() / "bodies" - if not directory.exists(): - return 0 - keep = referenced_bodies() - removed = 0 - for path in directory.glob("*.bin"): - if path.stem not in keep: - try: - path.unlink() - removed += 1 - except OSError: - pass - return removed - - -def new_capture_id() -> str: - return os.urandom(16).hex() - - -def generation_id(selection: Selection, capture_id: str) -> str: - """The capture generation: what all its sources belong to and cannot escape. - - Built from the repository identity, the members' code identity and the report - association. It deliberately excludes `updated_at`: a thread update must not - mint a new generation or force re-downloading unchanged code, where a moved - base or head must. - """ - return evidence_digest({ - "format": FORMAT, "profile": PROFILE, "capture_id": capture_id, - "repository": selection.repository, "revision": selection.revision(), - "membership": selection.membership_digest, "batch": selection.batch["id"], - "report": selection.report, - }) - - -def component_slots(selection: Selection) -> list[tuple[int, str]]: - return [(number, component) for number in selection.numbers for component in COMPONENTS] - - -def fresh_components(selection: Selection) -> list[dict]: - entries = [] - for number, component in component_slots(selection): - entry = {"number": number, "component": component, "status": "missing", - "reason": "not acquired", "groups": []} - for group in groups_for(member_repo(number, selection), component): - entry["groups"].append({"group": group, "status": "missing", "pages": 0, - "next_url": None, "source_ids": [], - "reason": "not acquired"}) - entries.append(entry) - return entries - - -def roll_up(entry: dict) -> dict: - """Aggregate a component's groups into one honest status. - - A terminal cursor is not completeness: a group only counts as complete when - it produced at least one recorded page (or an explicitly captured empty - response) and had no continuation left and no blocking reason. - """ - statuses = [group["status"] for group in entry["groups"]] - if any(status == "blocked" for status in statuses): - entry["status"] = "blocked" - elif any(status == "missing" for status in statuses): - entry["status"] = "missing" - elif all(status == "complete" for status in statuses): - entry["status"] = "complete" - else: - entry["status"] = "partial" - problems = [f"{group['group']}: {group['reason']}" for group in entry["groups"] - if group["status"] != "complete" and group.get("reason")] - entry["reason"] = None if entry["status"] == "complete" else ( - "; ".join(problems) or "incomplete") - return entry - - -def build_manifest(selection: Selection, capture_id: str, *, request_limit: int, - observed_at: str | None = None) -> dict: - return { - "format": FORMAT, "profile": PROFILE, "capture_id": capture_id, - "generation": generation_id(selection, capture_id), - "created_at": observed_at or now(), "updated_at": observed_at or now(), - "selection": selection.as_json(), - "code_observation": {"observed_at": observed_at or now(), - "thread_updated_at": {str(m["number"]): m["updated_at"] - for m in selection.members}}, - "capture": {"observed_at": observed_at or now(), "request_limit": request_limit, - "requests_used": 0, "reserved": RESERVED_BUDGET, "failures": 0, - "retries": 0, "identity_checks": 0, "stop_reason": None, - "bytes_stored": 0}, - "sources": [], "components": fresh_components(selection), "citations": [], - } - - -def write_manifest(capture_id: str, manifest: dict) -> None: - manifest["updated_at"] = now() - atomic_manifest(manifest_path(capture_id), manifest) - - -def read_manifest(capture_id: str) -> dict: - """Load and structurally verify one capture checkpoint. - - Verifies the manifest is internally consistent - the generation recomputes - from its own selection, source ids recompute from their own records, ids are - unique, bodies the manifest cites are accounted for. It does not read body - bytes; those are verified when they are exposed. A historical capture stays - readable even if the whole report changes or disappears: nothing here consults - the current report. - """ - path = manifest_path(capture_id) - if not path.exists(): - raise EvidenceError(f"no capture {capture_id} under {root()}") - manifest = strict_json_loads(path.read_bytes()) - if not isinstance(manifest, dict): - raise EvidenceError("capture manifest is not a JSON object") - for field in ("format", "profile", "capture_id", "generation", "created_at", "updated_at", - "selection", "code_observation", "capture", "sources", "components", - "citations"): - if field not in manifest: - raise EvidenceError(f"capture manifest is missing {field!r}") - if manifest["format"] != FORMAT or manifest["profile"] != PROFILE: - raise EvidenceError("capture manifest declares a different format or profile") - if manifest["capture_id"] != capture_id: - raise EvidenceError("capture manifest does not match its directory") - if not isinstance(manifest["sources"], list) or not isinstance(manifest["components"], list): - raise EvidenceError("capture manifest records are malformed") - if not isinstance(manifest["citations"], list): - raise EvidenceError("capture manifest citations are malformed") - stored = manifest["selection"] - if not isinstance(stored, dict) or set(stored) != {"repository", "report", "batch", "members"}: - raise EvidenceError("capture manifest selection is malformed") - batch = stored["batch"] - if (not isinstance(batch, dict) or set(batch) != {"id", "ordinal", "members", "count", - "review_prompt"} - or not isinstance(batch.get("review_prompt"), str) - or not batch["review_prompt"].strip() - or not isinstance(batch.get("members"), list) - or any(type(n) is not int or n <= 0 for n in batch["members"]) - or batch.get("count") != len(batch["members"]) - or batch.get("id") != f"B{batch.get('ordinal'):03d}"): - raise EvidenceError("capture manifest batch provenance is malformed") - members = stored["members"] - if (not isinstance(members, list) or [m.get("number") for m in members] != batch["members"]): - raise EvidenceError("capture manifest membership does not match its batch") - for member in members: - if not isinstance(member, dict) or not isinstance(member.get("base_sha"), str) \ - or SHA1.fullmatch(member["base_sha"]) is None \ - or not isinstance(member.get("head_sha"), str) \ - or SHA1.fullmatch(member["head_sha"]) is None: - raise EvidenceError("capture manifest member revision is malformed") - selection = Selection(dict(stored["repository"]), dict(stored["report"]), - batch, [dict(m) for m in members]) - if manifest["generation"] != generation_id(selection, capture_id): - raise EvidenceError("capture manifest generation does not match its own selection") - seen_ids, seen_slots = set(), set() - for source in manifest["sources"]: - if not isinstance(source, dict): - raise EvidenceError("capture manifest source record is malformed") - for field in ("id", "number", "component", "group", "page", "cursor", "next_cursor", - "url", "accept", "media_type", "captured_at", "generation", - "body_sha256"): - if field not in source: - raise EvidenceError(f"source record is missing {field!r}") - if type(source["number"]) is not int or source["number"] not in batch["members"]: - raise EvidenceError("source record names a member outside the selection") - if source["component"] not in COMPONENTS or source["group"] not in GROUPS: - raise EvidenceError("source record names an unknown component or group") - if source["group"] not in COMPONENT_GROUPS[source["component"]]: - raise EvidenceError("source record group does not belong to its component") - if type(source["page"]) is not int or source["page"] < 1: - raise EvidenceError("source record page is malformed") - slot = (source["number"], source["component"], source["group"], source["page"]) - if slot in seen_slots or source["id"] in seen_ids: - raise EvidenceError("capture manifest repeats a source slot or id") - seen_slots.add(slot) - seen_ids.add(source["id"]) - if source["generation"] != manifest["generation"]: - raise EvidenceError("source record belongs to a different generation") - if source["id"] != evidence_digest( - {"generation": manifest["generation"], - "source": {k: v for k, v in source.items() if k != "id"}}): - raise EvidenceError("source record id does not match its own contents") - if body_path(source["body_sha256"]) is None: - raise EvidenceError("source record has no usable body digest") - for citation in manifest["citations"]: - if not isinstance(citation, dict) or set(citation) != { - "id", "number", "component", "source_id", "source_sha256", - "start_byte", "end_byte", "excerpt_sha256", "kind"}: - raise EvidenceError("capture manifest citation is malformed") - if citation["source_id"] not in seen_ids: - raise EvidenceError("citation references a source outside the capture") - if (type(citation["start_byte"]) is not int or type(citation["end_byte"]) is not int - or citation["start_byte"] < 0 - or citation["end_byte"] <= citation["start_byte"]): - raise EvidenceError("citation byte range is not a nonempty half-open interval") - return manifest - - -# --------------------------------------------------------------------------- -# Endpoint mapping. Real GitHub endpoints; the #13 fixtures' synthetic -# /pulls/N/metadata, /discussion and /checks URLs are not endpoints. -# --------------------------------------------------------------------------- - -DIFF_ACCEPT = "application/vnd.github.diff" -JSON_MEDIA = "application/vnd.github+json" - - -def member_repo(number: int, selection: Selection) -> dict: - for member in selection.members: - if member["number"] == number: - return member - raise EvidenceError(f"#{number} is not a member of this selection") - - -def source_url(number: int, component: str, group: str, member: dict, *, - page_url: str | None = None) -> str: - """The exact URL for one endpoint group, or the recorded continuation URL.""" - if page_url: - return page_url - base = member["base_repo_name"] - if component == "metadata": - return f"{ghread.ORIGIN}/repos/{base}/pulls/{number}" - if component == "diff": - return f"{ghread.ORIGIN}/repos/{base}/pulls/{number}" - if component == "files": - return f"{ghread.ORIGIN}/repos/{base}/pulls/{number}/files" - if component == "discussion": - return f"{ghread.ORIGIN}/repos/{base}/issues/{number}/comments" - if component == "review_comments": - return f"{ghread.ORIGIN}/repos/{base}/pulls/{number}/comments" - if component == "reviews": - return f"{ghread.ORIGIN}/repos/{base}/pulls/{number}/reviews" - if component == "checks" and group in CI_GROUPS: - suffix = "check-runs" if group.endswith("check_runs") else "status" - return f"{ghread.ORIGIN}/repos/{ci_repo(member, group)}/commits/{member['head_sha']}/{suffix}" - if component == "closing_issues": - return ghread.GRAPHQL_URL - raise EvidenceError(f"no endpoint is mapped for {component}/{group}") - - -def ci_repo(member: dict, group: str) -> str: - """The repository a CI group is read from: the PR's own, or the linked fork.""" - return (member["head_repo_name"] if group in FORK_CI_GROUPS - else member["base_repo_name"]) - - -def ci_repo_id(member: dict, group: str) -> int: - return member["head_repo_id"] if group in FORK_CI_GROUPS else member["base_repo_id"] - - -def accept_for(component: str, group: str) -> str: - return DIFF_ACCEPT if component == "diff" else JSON_MEDIA - - -def list_params(component: str, group: str, page: int = 1) -> dict: - """Pagination parameters for a group; single-object groups take none. - - `per_page` is always sent rather than assumed: GitHub's default is 30, and a - page whose size we do not control cannot be reasoned about. - """ - if component in ("metadata", "diff"): - return {} - if component == "checks" and group == "statuses": - return {} # the combined status is one object, not a list - return {"per_page": str(PER_PAGE), "page": str(page)} - - -def closing_query() -> str: - return ("query trancheClosingIssues($owner:String!,$name:String!,$number:Int!,$cursor:String){" - " repository(owner:$owner,name:$name){ nameWithOwner id" - " pullRequest(number:$number){ number url" - " closingIssuesReferences(first:100,after:$cursor){ totalCount" - " pageInfo{hasNextPage endCursor} nodes{number url state title} } } } }") - - -def closing_variables(member: dict, cursor: str | None) -> dict: - owner, name = member["base_repo_name"].split("/", 1) - return {"owner": owner, "name": name, "number": member["number"], "cursor": cursor} - - -def component_sources(manifest: dict, number: int, component: str, group: str) -> list[dict]: - return [s for s in manifest["sources"] - if s["number"] == number and s["component"] == component and s["group"] == group] - - -def component_entry(manifest: dict, number: int, component: str) -> dict: - for entry in manifest["components"]: - if entry["number"] == number and entry["component"] == component: - return entry - entry = {"number": number, "component": component, "status": "missing", - "reason": "not acquired", "groups": []} - manifest["components"].append(entry) - return entry - - -def group_entry(manifest: dict, number: int, component: str, group: str) -> dict: - entry = component_entry(manifest, number, component) - for state in entry["groups"]: - if state["group"] == group: - return state - state = {"group": group, "status": "missing", "pages": 0, "next_url": None, - "source_ids": [], "reason": "not acquired"} - entry["groups"].append(state) - return state - - -# --------------------------------------------------------------------------- -# Live identity: what a response must prove before its bytes are accepted -# --------------------------------------------------------------------------- - -class LiveCheck: - """Counts and bounds the live identity reads a capture performs.""" - - def __init__(self, budget: ghread.Budget): - self.budget = budget - - def verify_pr(self, member: dict, *, reserve=None) -> dict: - """Re-read the PR's own revisions and prove the recorded ones still hold. - - This is the check that makes reuse honest: checksums prove bytes were not - corrupted, only a live read shows they still describe the revision they - claim. It also notices a fork that has been deleted or renamed since the - capture was made. - """ - url = source_url(member["number"], "metadata", "metadata", member) - self.budget.identity_checks += 1 - response = ghread.read(url, accept=JSON_MEDIA, budget=self.budget, reserve=reserve, - repo_prefix=member["base_repo_name"]) - data = response.json() - if not isinstance(data, dict) or data.get("number") != member["number"]: - raise EvidenceError( - f"live metadata for #{member['number']} reports a different pull request") - live_base = (data.get("base") or {}).get("repo") or {} - live_head = (data.get("head") or {}).get("repo") or {} - live = {"base_sha": (data.get("base") or {}).get("sha"), - "head_sha": (data.get("head") or {}).get("sha"), - "base_repo_id": live_base.get("id"), "base_repo_name": live_base.get("full_name"), - "head_repo_id": live_head.get("id"), "head_repo_name": live_head.get("full_name")} - if live["head_sha"] is None or live["base_sha"] is None: - raise EvidenceError(f"#{member['number']} no longer exposes its revisions") - recorded = revision_key(member) - if {k: live[k] for k in recorded} != recorded: - raise SelectionError( - f"#{member['number']} moved: recorded " - f"{recorded['head_sha'][:12]}… is now {str(live['head_sha'])[:12]}…; " - "start a fresh capture for the new revision") - return data - - def verify_ci_scope(self, member: dict, group: str, payload: dict) -> None: - """A CI response must name the repository and revision we asked about. - - A repository-prefix check on the URL is not proof that a response belongs - to the resource we asked for, so the returned repository identity is - compared against the repository this group was read from. - """ - expected_repo = ci_repo(member, group) - expected_id = ci_repo_id(member, group) - repo = payload.get("repository") - if isinstance(repo, dict): - if repo.get("full_name") != expected_repo: - raise EvidenceError( - f"CI for #{member['number']} came from {repo.get('full_name')!r}, " - f"not {expected_repo!r}") - if type(repo.get("id")) is int and repo["id"] != expected_id: - raise EvidenceError( - f"CI for #{member['number']} came from repository id {repo['id']}, " - f"not {expected_id}") - sha = payload.get("sha") if "sha" in payload else None - if sha is not None and sha != member["head_sha"]: - raise EvidenceError( - f"CI for #{member['number']} names revision {sha}, not {member['head_sha']}") - for run in payload.get("check_runs") or []: - if not isinstance(run, dict): - raise EvidenceError(f"CI for #{member['number']} returned a malformed check run") - if run.get("head_sha") is not None and run["head_sha"] != member["head_sha"]: - raise EvidenceError( - f"a check run for #{member['number']} names revision {run['head_sha']}") - - -def parse_closing(payload: dict, member: dict) -> tuple[str | None, list[dict]]: - """Read one closing-issues GraphQL page, or refuse a malformed/foreign answer.""" - if not isinstance(payload, dict): - raise EvidenceError("closing-issues query returned a non-object") - if payload.get("errors"): - raise EvidenceError(f"closing-issues query reported errors: {payload['errors']}") - data = payload.get("data") - repository = data.get("repository") if isinstance(data, dict) else None - if not isinstance(repository, dict): - raise EvidenceError("closing-issues query returned no repository") - if repository.get("nameWithOwner") != member["base_repo_name"]: - raise EvidenceError( - f"closing-issues query answered for {repository.get('nameWithOwner')!r}, " - f"not {member['base_repo_name']!r}") - pull = repository.get("pullRequest") - if not isinstance(pull, dict) or pull.get("number") != member["number"]: - raise EvidenceError("closing-issues query answered about a different pull request") - connection = pull.get("closingIssuesReferences") - if not isinstance(connection, dict): - raise EvidenceError("closing-issues query returned no connection") - page_info = connection.get("pageInfo") or {} - nodes = connection.get("nodes") - if not isinstance(nodes, list): - raise EvidenceError("closing-issues query returned no node list") - has_next = bool(page_info.get("hasNextPage")) - cursor = page_info.get("endCursor") - if has_next and (not isinstance(cursor, str) or not cursor): - raise EvidenceError("closing-issues query claims more pages without a cursor") - return (cursor if has_next else None), [n for n in nodes if isinstance(n, dict)] - - -# --------------------------------------------------------------------------- -# Acquisition -# --------------------------------------------------------------------------- - -class Capture: - """One bounded acquisition run over a capture's missing work.""" - - def __init__(self, selection: Selection, capture_id: str, manifest: dict, *, - budget: ghread.Budget, max_bytes: int = DEFAULT_MAX_BYTES, - log=None, max_pages: int = MAX_PAGES): - self.selection = selection - self.capture_id = capture_id - self.manifest = manifest - self.budget = budget - self.budget.reserved = max(self.budget.reserved, len(selection.members)) - self.live = LiveCheck(budget) - self.max_bytes = max_bytes - self.max_pages = max_pages - self.log = log or (lambda message: None) - self.dirty = False - self.stop_reason: str | None = None - self.reused = 0 - self.fetched = 0 - - # -- bookkeeping ------------------------------------------------------ - - @property - def stored_bytes(self) -> int: - return self.manifest["capture"]["bytes_stored"] - - def _spend_bytes(self, count: int) -> None: - self.manifest["capture"]["bytes_stored"] = self.stored_bytes + count - if self.stored_bytes > self.max_bytes: - self.stop_reason = "storage_budget" - raise ghread.BudgetExhausted( - f"stored bytes reached {self.stored_bytes} of {self.max_bytes}") - - def _record(self, number: int, component: str, group: str, data: bytes, *, url: str, - accept: str, media_type: str, cursor, next_cursor) -> None: - sha = store_body(data) - state = group_entry(self.manifest, number, component, group) - source = { - "id": "", "number": number, "component": component, "group": group, - "page": state["pages"] + 1, "cursor": cursor, "next_cursor": next_cursor, - "url": url, "accept": accept, "media_type": media_type, - "captured_at": now(), "generation": self.manifest["generation"], - "body_sha256": sha, - } - source["id"] = evidence_digest( - {"generation": self.manifest["generation"], - "source": {k: v for k, v in source.items() if k != "id"}}) - self.manifest["sources"].append(source) - state["pages"] += 1 - state["source_ids"].append(source["id"]) - if "items_seen" in state: - state["items_observed"] = state.pop("items_seen") - if "items_total" in state: - state["items_reported"] = state.pop("items_total") - state["next_url"] = next_cursor - self._spend_bytes(len(data)) - self.dirty = True - - def _finish_group(self, number: int, component: str, group: str, *, complete: bool, - reason: str | None) -> None: - state = group_entry(self.manifest, number, component, group) - state["status"] = "complete" if complete else "partial" - state["reason"] = reason - if complete: - state["next_url"] = None - roll_up(component_entry(self.manifest, number, component)) - self.dirty = True - - def _block_group(self, number: int, component: str, group: str, reason: str) -> None: - state = group_entry(self.manifest, number, component, group) - state["status"] = "blocked" - state["reason"] = reason - roll_up(component_entry(self.manifest, number, component)) - self.dirty = True - - def _checkpoint(self) -> None: - capture = self.manifest["capture"] - capture.update(requests_used=self.budget.used, failures=self.budget.failures, - retries=self.budget.retries, identity_checks=self.budget.identity_checks, - reserved=self.budget.reserved) - if self.stop_reason: - capture["stop_reason"] = self.stop_reason - elif self.manifest["capture"].get("stop_reason") == "request_budget": - # A resumed capture that got past the point where it ran out of budget - # is no longer stopped by it; a stop reason describes the last run. - capture["stop_reason"] = None - capture["observed_at"] = now() - write_manifest(self.capture_id, self.manifest) - - def _reserve(self) -> None: - """Stop cleanly when the completion checks can no longer be afforded.""" - if not self.budget.can(self.budget.reserved): - self.stop_reason = "request_budget" - raise ghread.BudgetExhausted( - "request budget cannot cover acquisition and the completion checks") - - # -- group acquisition ------------------------------------------------ - - def acquire_group(self, number: int, component: str, group: str) -> None: - member = member_repo(number, self.selection) - state = group_entry(self.manifest, number, component, group) - if state["status"] == "complete": - self.reused += 1 - return - if component == "closing_issues": - self._acquire_graphql(member, state) - return - self._acquire_rest(member, component, group, state) - - def _acquire_rest(self, member: dict, component: str, group: str, state: dict) -> None: - page = state["pages"] + 1 - url = state["next_url"] or source_url(member["number"], component, group, member) - accept = accept_for(component, group) - while True: - self._reserve() - params = list_params(component, group, page) - try: - response = ghread.read(url, accept=accept, params=params, budget=self.budget, - reserve=self.budget.reserved, - repo_prefix=(ci_repo(member, group) if component == "checks" - else member["base_repo_name"])) - except ghread.ResponseTooLarge as exc: - self._block_group(member["number"], component, group, - f"response exceeds the transport bound: {exc}") - return - except ghread.BudgetExhausted: - self.stop_reason = "request_budget" - raise - except ghread.ReadError as exc: - self._block_group(member["number"], component, group, f"acquisition failed: {exc}") - return - if component == "checks": - try: - payload = response.json() - except ghread.ReadError as exc: - self._block_group(member["number"], component, group, - f"CI response is not JSON: {exc}") - return - try: - self.live.verify_ci_scope(member, group, payload) - except EvidenceError as exc: - self._block_group(member["number"], component, group, str(exc)) - return - try: - if component == "diff": - next_cursor, complete, reason = self._accept_diff(response) - else: - next_cursor, complete, reason = self._accept_list( - member, component, group, response, page, state) - except _Blocked as exc: - self._block_group(member["number"], component, group, str(exc)) - return - self._record(member["number"], component, group, response.body, url=response.url, - accept=accept, media_type=response.media_type, - cursor=None if page == 1 else str(page), next_cursor=next_cursor) - self.fetched += 1 - if complete: - shortfall = self._shortfall(state) - if shortfall: - self._finish_group(member["number"], component, group, complete=False, - reason=shortfall) - return - self._finish_group(member["number"], component, group, complete=True, reason=None) - return - if next_cursor is None: - self._finish_group(member["number"], component, group, complete=False, - reason=reason or "incomplete: no continuation") - return - if page >= self.max_pages: - self._finish_group(member["number"], component, group, complete=False, - reason=f"incomplete: stopped at the {self.max_pages}-page bound") - return - url = next_cursor - page += 1 - - def _accept_diff(self, response: ghread.Response): - """Bound the diff and report honestly what was and was not captured. - - An oversized diff is blocked, not truncated: half a patch presented as a - diff would be worse than a named gap, and GitHub itself omits patches for - large or unsupported files, which the file list shows separately. - """ - body = response.body - lines = body.count(b"\n") - if len(body) > MAX_DIFF_BYTES or lines > MAX_DIFF_LINES: - raise _Blocked( - f"diff exceeds the review bound ({len(body)} bytes, {lines} lines); " - "not captured in full and not presented as complete") - return None, True, None - - def _accept_list(self, member: dict, component: str, group: str, - response: ghread.Response, page: int, state: dict): - """Validate one list page and decide what it says about completeness. - - Each collection has its own envelope, so each is read in its own terms: - check-runs answer with `{total_count, check_runs}` while the other lists - are bare arrays. The reported total is recorded separately and compared - against what was actually observed, because a terminal cursor on a - truncated collection is not completeness. - """ - try: - payload = response.json() - except ghread.ReadError as exc: - raise _Blocked(f"{component} response is not JSON: {exc}") from exc - if component == "metadata": - if not isinstance(payload, dict) or payload.get("number") != member["number"]: - raise _Blocked("metadata response is not this pull request") - if (payload.get("head") or {}).get("sha") != member["head_sha"]: - raise _Blocked("metadata response names a different head revision") - return None, True, None - if component == "checks" and group in ("check_runs", "fork_check_runs"): - if not isinstance(payload, dict): - raise _Blocked("check-runs response is not an object") - runs = payload.get("check_runs") - if not isinstance(runs, list): - raise _Blocked("check-runs response carries no check-run list") - state["items_seen"] = state.get("items_observed", 0) + len(runs) - if type(payload.get("total_count")) is int: - state["items_total"] = payload["total_count"] - elif component == "checks" and group in ("statuses", "fork_statuses"): - if not isinstance(payload, dict): - raise _Blocked("combined status response is not an object") - statuses = payload.get("statuses") - if not isinstance(statuses, list): - raise _Blocked("combined status response carries no status list") - state["items_seen"] = state.get("items_observed", 0) + len(statuses) - if type(payload.get("total_count")) is int: - state["items_total"] = payload["total_count"] - elif not isinstance(payload, list): - raise _Blocked(f"{component} response is not a list") - next_url = response.next_url - if next_url is not None: - if ghread.page_param(next_url) <= page: - raise _Blocked("continuation URL does not advance the page number") - return next_url, False, None - return None, True, None - - @staticmethod - def _shortfall(state: dict) -> str | None: - """A group that reported more items than it delivered is not complete. - - A terminal cursor says the pagination ended; it does not say the - collection was fully observed. Both the reported-vs-observed count and - GitHub's own documented ceilings are checked here, and either gap is - named rather than smoothed over. - """ - seen, total = state.get("items_observed"), state.get("items_reported") - if type(seen) is int and type(total) is int: - if total < 0: - return "incomplete: GitHub reported an unusable item count" - if seen < total: - return (f"incomplete: GitHub reports {total} items but {seen} were observed; " - "the collection changed or is capped") - if state["group"] in ("check_runs", "fork_check_runs") and total >= CHECK_RUN_CAP: - return (f"incomplete: GitHub caps check runs at the {CHECK_RUN_CAP} most " - "recent suites; iterate the suites to see them all") - if state["group"] == "files" and total >= FILE_LIST_CAP: - return (f"incomplete: GitHub caps the file list at {FILE_LIST_CAP} entries") - return None - - def _acquire_graphql(self, member: dict, state: dict) -> None: - cursor = None - page = state["pages"] + 1 - while True: - self._reserve() - variables = closing_variables(member, cursor) - try: - response = ghread.graphql(closing_query(), variables, budget=self.budget, - reserve=self.budget.reserved) - payload = response.json() - except ghread.BudgetExhausted: - self.stop_reason = "request_budget" - raise - except ghread.ReadError as exc: - self._block_group(member["number"], "closing_issues", "closing_issues", - f"acquisition failed: {exc}") - return - try: - next_cursor, _nodes = parse_closing(payload, member) - except EvidenceError as exc: - self._block_group(member["number"], "closing_issues", "closing_issues", str(exc)) - return - self._record(member["number"], "closing_issues", "closing_issues", response.body, - url=response.url, accept=JSON_MEDIA, media_type=response.media_type, - cursor=cursor, next_cursor=next_cursor) - self.fetched += 1 - if next_cursor is None: - self._finish_group(member["number"], "closing_issues", "closing_issues", - complete=True, reason=None) - return - if page >= self.max_pages: - self._finish_group(member["number"], "closing_issues", "closing_issues", - complete=False, - reason=f"incomplete: stopped at the {self.max_pages}-page bound") - return - cursor = next_cursor - page += 1 - - def _refresh_mutable(self, member: dict, thread_updated: str) -> None: - """Mark mutable components for re-acquisition without touching code bytes. - - The previously captured immutable sources stay in place and stay - readable; only the mutable groups go back to `missing` so this run or a - later one refreshes them. The generation does not change, so historical - citations keep resolving. - """ - number = member["number"] - for component in MUTABLE_COMPONENTS: - entry = component_entry(self.manifest, number, component) - for state in entry["groups"]: - state["status"] = "missing" - state["reason"] = f"thread updated upstream ({thread_updated}); refresh pending" - roll_up(entry) - self.manifest["code_observation"]["thread_updated_at"][str(number)] = thread_updated - self.dirty = True - - # -- the run ---------------------------------------------------------- - - def run(self) -> str | None: - """Acquire everything missing, reusing what the live revision allows.""" - if self.manifest["capture"].get("stop_reason") == "revision_drift": - raise SelectionError("capture generation is invalidated; start a fresh capture") - try: - # Live revision check first: it decides whether any recorded code - # evidence may be reused at all, and it must happen before the - # checks that reserve capacity is meant to protect. - for member in self.selection.members: - self._reserve() - metadata = self.live.verify_pr(member) - # A thread-only update refreshes the mutable observations and - # leaves the code observation alone: the diffs and file lists - # still describe the same two commits. - live_updated = metadata.get("updated_at") - recorded = self.manifest["code_observation"]["thread_updated_at"].get( - str(member["number"])) - if isinstance(live_updated, str) and live_updated != recorded: - self._refresh_mutable(member, live_updated) - self._checkpoint() - for number in self.selection.numbers: - member = member_repo(number, self.selection) - for component in COMPONENTS: - for group in groups_for(member, component): - state = group_entry(self.manifest, number, component, group) - if state["status"] == "complete": - self.reused += 1 - continue - try: - self.acquire_group(number, component, group) - except _Blocked: - pass - self._checkpoint() - # Spend the held-back capacity only after acquisition: sources may - # not be certified against a revision that moved during the run. - for member in self.selection.members: - self.live.verify_pr(member, reserve=0) - except ghread.BudgetExhausted as exc: - self.log(str(exc)) - self.stop_reason = self.stop_reason or "request_budget" - except ghread.ReadError as exc: - self.log(f"acquisition stopped: {exc}") - self.stop_reason = self.stop_reason or "transport_error" - except SelectionError: - self.stop_reason = "revision_drift" - raise - finally: - self._checkpoint() - return self.stop_reason - - -class _Blocked(Exception): - """A group failed its own identity or content check; recorded, not raised.""" - - -# --------------------------------------------------------------------------- -# Citations: which reviewable evidence this capture actually points at -# --------------------------------------------------------------------------- - -def extract_citations(manifest: dict) -> list[dict]: - """Derive citations inside the native capture, from the recorded bytes. - - Citations are a projection of what was captured, computed here once and - stored, so every reader - export, a windowed source read, a future MCP - adapter - resolves the same offsets without reparsing anything or inventing - its own eligibility rules. Discussion and review bodies are JSON, so their - text is quoted exactly and the offsets are computed against the stored bytes - of the response that carried them. - - Deliberately absent: the pull request's own description, which is the - report's evidence and not source evidence, and any citation into a `patch` - field GitHub omitted for a large or unsupported file, which the file list - reports separately as a gap. - """ - citations: list[dict] = [] - - def add(number: int, component: str, source: dict, body: bytes, text: str) -> None: - if not text or len(citations) >= MAX_CITATIONS: - return - encoded = json.dumps(text, ensure_ascii=False).encode("utf-8")[1:-1] - start = body.find(encoded) - if start < 0: - return - citations.append({ - "id": "", "number": number, "component": component, "source_id": source["id"], - "source_sha256": hashlib.sha256(body).hexdigest(), - "start_byte": start, "end_byte": start + len(encoded), - "excerpt_sha256": hashlib.sha256(encoded).hexdigest(), "kind": "body", - }) - - for source in manifest["sources"]: - if source["component"] not in CONTENT_COMPONENTS or len(citations) >= MAX_CITATIONS: - continue - body = read_body(source["body_sha256"]) - try: - payload = json.loads(body.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError): - continue - if source["component"] == "files": - for entry in (payload if isinstance(payload, list) else [])[:MAX_CITATIONS_PER_PAGE]: - if not isinstance(entry, dict): - continue - for key in ("patch", "filename"): - value = entry.get(key) - if isinstance(value, str) and value: - add(source["number"], "files", source, body, value) - elif source["component"] in ("discussion", "review_comments", "reviews"): - for entry in payload if isinstance(payload, list) else []: - if isinstance(entry, dict) and isinstance(entry.get("body"), str): - add(source["number"], source["component"], source, body, entry["body"]) - for citation in citations: - citation["id"] = evidence_digest({key: value for key, value in citation.items() - if key != "id"}) - return citations - - -def index_sources(manifest: dict) -> dict: - return {source["id"]: source for source in manifest["sources"]} - - -def source_for_window(manifest: dict, source_id: str) -> dict: - source = index_sources(manifest).get(source_id) - if source is None: - raise EvidenceError(f"no source {source_id!r} in capture {manifest['capture_id']}") - return source - - -PRINTABLE = re.compile(r"[^\x20-\x7e\n]") - - -def printable(data: bytes) -> str: - """A terminal-safe rendering of stored bytes. - - Control characters, escape sequences and non-ASCII are shown as escapes - rather than emitted, so a captured body - including a hostile patch or a - description aimed at the operator's terminal - cannot drive the terminal that - reads it. The stored and hashed bytes are never changed; only this rendering - is. - """ - text = data.decode("utf-8", errors="replace") - return PRINTABLE.sub( - lambda match: text[match.start():match.end()].encode("unicode_escape").decode("ascii"), - text) - - -def window(manifest: dict, source_id: str, *, start: int = 0, - length: int = DEFAULT_WINDOW_BYTES) -> dict: - """A bounded, escape-safe window into one stored source. - - Returns the half-open byte range actually delivered and where the next window - begins, so a reader walks a large body in bounded steps instead of asking for - a whole packet. - """ - if type(start) is not int or start < 0: - raise EvidenceError("start byte must be a nonnegative integer") - if type(length) is not int or not 1 <= length <= DEFAULT_WINDOW_BYTES: - raise EvidenceError(f"length must be 1..{DEFAULT_WINDOW_BYTES} bytes") - source = source_for_window(manifest, source_id) - body = read_body(source["body_sha256"]) - if start > len(body): - raise EvidenceError(f"start byte {start} is past the end of a {len(body)} byte source") - end = min(len(body), start + length) - chunk = body[start:end] - return { - "capture_id": manifest["capture_id"], "source_id": source_id, - "number": source["number"], "component": source["component"], - "group": source["group"], "page": source["page"], "url": source["url"], - "media_type": source["media_type"], "body_sha256": source["body_sha256"], - "body_bytes": len(body), "start_byte": start, "end_byte": end, - "next_start": end if end < len(body) else None, - "window_sha256": hashlib.sha256(chunk).hexdigest(), - "content": printable(chunk), - } - - -def resolve_citation(manifest: dict, citation_id: str) -> dict: - """Resolve one citation against the stored bytes it names, offline. - - This is the operation a reader must be able to perform without the state - store, the network or another application: look the source up, verify its - bytes, and re-derive the excerpt digest that was recorded. - """ - for citation in manifest["citations"]: - if citation["id"] != citation_id: - continue - body = read_body(citation["source_sha256"]) - excerpt = body[citation["start_byte"]:citation["end_byte"]] - digest = hashlib.sha256(excerpt).hexdigest() - if digest != citation["excerpt_sha256"]: - raise EvidenceError( - f"citation {citation_id[:12]}… no longer matches its stored bytes") - return {"citation": citation, "source": index_sources(manifest)[citation["source_id"]], - "excerpt_sha256": digest, "excerpt": printable(excerpt)} - raise EvidenceError(f"no citation {citation_id!r} in capture {manifest['capture_id']}") - - -# --------------------------------------------------------------------------- -# Export: the self-contained, versioned packet -# --------------------------------------------------------------------------- - -def is_complete(manifest: dict) -> bool: - """True when every component of every member completed and nothing stopped us. - - A terminal cursor on every group is necessary but not sufficient: a capture - that ran out of budget, storage or the page bound is not complete even if the - pages it did fetch look terminal. - """ - if manifest["capture"].get("stop_reason"): - return False - return all(entry["status"] == "complete" for entry in manifest["components"]) - - -def build_packet(manifest: dict) -> dict: - """Freeze a small, versioned projection of the capture for an external reader. - - The packet is deliberately not the manifest. It carries what a reader needs to - resolve citations with no state store, no network and no second application: - the copied native selection (including the exact reviewer prompt), the ordered - members with full revisions, the component coverage, the sources with their - URLs and media types, and the exact bytes of every body it cites, base64 of - the decoded response. Bodies are stored once per digest and referenced by it, - so identical bytes are not repeated. - """ - bodies: dict[str, dict] = {} - for source in manifest["sources"]: - sha = source["body_sha256"] - if sha in bodies: - continue - raw = read_body(sha) - bodies[sha] = {"sha256": sha, "bytes": len(raw), - "base64": base64.b64encode(raw).decode("ascii")} - selection = stored_selection(manifest) - packet = { - "format": FORMAT, "profile": PROFILE, - "capture_id": manifest["capture_id"], "generation": manifest["generation"], - "selection": manifest["selection"], "membership_digest": selection.membership_digest, - "complete": is_complete(manifest), - "capture": {key: manifest["capture"][key] for key in - ("observed_at", "request_limit", "requests_used", "reserved", "failures", - "retries", "identity_checks", "stop_reason")}, - "components": manifest["components"], - "sources": [{key: source[key] for key in - ("id", "number", "component", "group", "page", "cursor", "next_cursor", - "url", "accept", "media_type", "captured_at", "generation", - "body_sha256")} - for source in manifest["sources"]], - "bodies": bodies, - "citations": manifest["citations"], - "notes": ( - "Captured from public GitHub by Tranche; read-only and model-free. Digests prove " - "integrity, not authenticity: they show the bytes are the bytes recorded, not that " - "GitHub served them. A captured CI run is an observation, not a test performed by " - "Tranche. Complete means every endpoint group reported a terminal page within the " - "recorded budgets; it is not a review, a test run or approval to merge."), - } - packet["packet_digest"] = evidence_digest(packet) - return packet - - -def packet_bytes(manifest: dict, *, limit: int = DEFAULT_EXPORT_BYTES) -> bytes: - """Serialize the packet under an explicit bound, checked on the exact bytes.""" - packet = build_packet(manifest) - try: - data = json.dumps(packet, ensure_ascii=False, allow_nan=False, sort_keys=True, - separators=(",", ":")).encode("utf-8") - except (TypeError, ValueError) as exc: - raise EvidenceError(f"packet cannot be serialized ({exc})") from exc - if len(data) > limit: - raise EvidenceError( - f"packet serializes to {len(data)} bytes, over the {limit} byte export bound; " - "narrow the batch or raise the bound deliberately") - return data - - -def repository_scope(full_name: str, budget: ghread.Budget, expected_id=None) -> dict: - """Read one repository's live identity and visibility.""" - response = ghread.read(f"{ghread.ORIGIN}/repos/{full_name}", budget=budget, - reserve=budget.reserved, repo_prefix=full_name) - data = response.json() - if not isinstance(data, dict) or data.get("full_name") != full_name: - raise SelectionError(f"repository {full_name!r} answered with a different identity") - if expected_id is not None and data.get("id") != expected_id: - raise SelectionError(f"repository {full_name!r} is no longer id {expected_id}") - return {"id": data.get("id"), "full_name": data.get("full_name"), - "visibility": data.get("visibility"), "private": bool(data.get("private")), - "archived": bool(data.get("archived")), "url": data.get("html_url")} - - -def require_shareable(selection: Selection, budget: ghread.Budget) -> dict: - """The fresh public-scope gate export must pass, for every repository that enters. - - A previously public capture is not permission: visibility revocation blocks - new sharing. A network failure is not permission either, so a failed check - raises rather than falling through to writing the packet. - """ - base = repository_scope(selection.repository["full_name"], budget, - selection.repository.get("id")) - if base["private"] or base["visibility"] != "public": - raise SelectionError( - f"repository {base['full_name']} is {base['visibility'] or 'private'}; " - "refusing to export a packet that would share it") - linked = [] - for name in sorted({m["head_repo_name"] for m in selection.members - if m["head_repo_name"] != base["full_name"]}): - head = repository_scope(name, budget) - if head["private"] or head["visibility"] != "public": - raise SelectionError( - f"linked repository {name} is not public; refusing to export its evidence") - linked.append(head) - return {"repository": base, "linked": linked} - - -def export_bytes(manifest: dict, selection: Selection, *, - limit: int = DEFAULT_EXPORT_BYTES) -> bytes: - return packet_bytes(manifest, limit=limit) - - -def stored_selection(manifest: dict) -> Selection: - stored = manifest["selection"] - return Selection(dict(stored["repository"]), dict(stored["report"]), - stored["batch"], [dict(m) for m in stored["members"]]) - - -def find_captures(selection: Selection) -> dict[str, dict]: - """Stored captures whose frozen selection matches this one exactly.""" - matches: dict[str, dict] = {} - directory = root() - if not directory.exists(): - return matches - for path in sorted(directory.glob("*/manifest.json")): - capture_id = path.parent.name - try: - manifest = read_manifest(capture_id) - except EvidenceError: - continue - if manifest["selection"] == selection.as_json(): - matches[capture_id] = manifest - return matches - - -# --------------------------------------------------------------------------- -# Reuse across associations: unchanged code is never downloaded twice -# --------------------------------------------------------------------------- - -def carry_over_code(selection: Selection, manifest: dict) -> int: - """Adopt complete code evidence from any capture of the same revision. - - Reuse is keyed to what a code observation actually claims - the repository - identities and the full base/head revisions - never to the report digest, the - batch ordinal, the reviewer prompt or the thread's `updated_at`. So a - re-cluster, a renumbered batch, an edited prompt or ordinary thread churn - changes the association and the mutable observations while leaving the diffs - and file lists exactly where they are, with no network request at all. - - The adopted records keep their original acquisition time, URL and media type; - what changes is the generation they are bound to, so the new association owns - them and the old capture remains readable on its own terms. - """ - adopted = 0 - donors: dict[int, tuple[str, dict, dict]] = {} - directory = root() - if not directory.exists(): - return 0 - for path in sorted(directory.glob("*/manifest.json")): - donor_id = path.parent.name - if donor_id == manifest["capture_id"]: - continue - try: - donor = read_manifest(donor_id) - except EvidenceError: - continue - index = index_sources(donor) - for member in donor["selection"]["members"]: - number = member["number"] - if number in donors: - continue - if number not in selection.numbers: - continue - if revision_key(member) != revision_key(member_repo(number, selection)): - continue - donors[number] = (donor_id, donor, index) - for number, (_donor_id, donor, index) in donors.items(): - for component in CODE_COMPONENTS: - for group in COMPONENT_GROUPS[component]: - source_state = group_entry(donor, number, component, group) - if source_state["status"] != "complete" or not source_state["source_ids"]: - continue - target = group_entry(manifest, number, component, group) - if target["status"] == "complete": - continue - for source_id in source_state["source_ids"]: - source = index.get(source_id) - if source is None: - break - clone = {key: value for key, value in source.items() if key != "id"} - clone["generation"] = manifest["generation"] - clone["id"] = evidence_digest({"generation": manifest["generation"], - "source": clone}) - manifest["sources"].append(clone) - target["source_ids"].append(clone["id"]) - adopted += 1 - target["pages"] = len(target["source_ids"]) - target["status"] = "complete" - target["reason"] = None - target["next_url"] = None - roll_up(component_entry(manifest, number, component)) - return adopted - - - -# --------------------------------------------------------------------------- -# Commands -# --------------------------------------------------------------------------- - -def human(status: str) -> str: - return {"complete": "complete", "partial": "partial", "missing": "missing", - "blocked": "blocked"}.get(status, status) - - -def coverage_report(manifest: dict) -> dict: - """Per-member and per-component coverage, from the recorded state alone.""" - members = [] - for member in manifest["selection"]["members"]: - number = member["number"] - components = [] - for entry in manifest["components"]: - if entry["number"] != number: - continue - components.append({ - "component": entry["component"], "status": entry["status"], - "pages": sum(state["pages"] for state in entry["groups"]), - "reason": entry["reason"], - "groups": [{"group": state["group"], "status": state["status"], - "pages": state["pages"], "reason": state["reason"]} - for state in entry["groups"]], - "citations": sum(1 for c in manifest["citations"] - if c["number"] == number and c["component"] == entry["component"]), - }) - members.append({"number": number, "base_sha": member["base_sha"], - "head_sha": member["head_sha"], "components": components}) - return {"capture_id": manifest["capture_id"], "generation": manifest["generation"], - "batch": manifest["selection"]["batch"]["id"], - "observed_at": manifest["capture"]["observed_at"], - "stop_reason": manifest["capture"].get("stop_reason"), - "complete": is_complete(manifest), - "requests": {key: manifest["capture"][key] for key in - ("request_limit", "requests_used", "reserved", "failures", - "retries", "identity_checks")}, - "bytes_stored": manifest["capture"].get("bytes_stored", 0), - "citations": len(manifest["citations"]), "members": members} - - -def print_coverage(report: dict, stream=sys.stdout) -> None: - state = "COMPLETE" if report["complete"] else "INCOMPLETE" - print(f"capture {report['capture_id']} batch {report['batch']} " - f"generation {report['generation'][:12]}… {state}", file=stream) - requests = report["requests"] - print(f" observed {report['observed_at']} stop {report['stop_reason'] or 'none'} " - f"requests {requests['requests_used']}/{requests['request_limit']} " - f"(failures {requests['failures']}, identity checks {requests['identity_checks']})", - file=stream) - print(f" {report['bytes_stored']} bytes stored, {report['citations']} citations", file=stream) - for member in report["members"]: - print(f" #{member['number']} head {member['head_sha'][:12]}… " - f"base {member['base_sha'][:12]}…", file=stream) - for component in member["components"]: - detail = "" - if component["status"] != "complete" and component["reason"]: - detail = f" — {component['reason']}" - groups = ", ".join(f"{g['group']}={g['status']}" for g in component["groups"]) - print(f" {component['component']:<16} {human(component['status']):<9} " - f"{component['pages']:>3}p {component['citations']:>4}c [{groups}]{detail}", - file=stream) - - -def resume_hint(capture_id: str, manifest: dict) -> str: - batch = manifest["selection"]["batch"]["id"] - return (f"resume: python3 tranche.py evidence capture --batch {batch} " - f"--reuse-capture {capture_id}") - - -def resolve_current(batch_id: str, *, request_limit: int | None = None, - need_batch: bool = True): - """Validate the current report and resolve the batch, or refuse with a reason.""" - report = report_loader.load() - if not need_batch: - return report, None - return report, select(batch_id, report) - - -def cmd_capture(args) -> int: - report, selection = resolve_current(args.batch) - existing: dict[str, dict] = {} - if not args.fresh: - existing = find_captures(selection) - capture_id = None - if args.reuse_capture: - manifest = read_manifest(args.reuse_capture) - if manifest["selection"] != selection.as_json(): - raise SelectionError( - f"capture {args.reuse_capture} belongs to a different selection; " - "omit --reuse-capture to start a fresh one") - capture_id = args.reuse_capture - elif existing and not args.fresh: - capture_id = sorted(existing)[0] - if capture_id is None: - capture_id = new_capture_id() - lock = Lock(capture_id) - lock.acquire(break_lock=args.break_lock) - try: - if capture_id in existing: - manifest = existing[capture_id] - elif manifest_path(capture_id).exists(): - manifest = read_manifest(capture_id) - else: - manifest = build_manifest(selection, capture_id, request_limit=args.request_budget) - # First pass: adopt every unchanged, complete code observation from - # any stored capture of the same revision, so nothing is downloaded - # twice because a report, a batch or a prompt changed. - adopted = carry_over_code(selection, manifest) - if adopted: - print(f" reused {adopted} stored code source(s) for the unchanged revision(s)") - write_manifest(capture_id, manifest) - manifest["selection"] = selection.as_json() # re-bind the association, keep bodies - manifest["capture"]["request_limit"] = args.request_budget - budget = ghread.Budget(args.request_budget, reserved=RESERVED_BUDGET) - capture = Capture(selection, capture_id, manifest, budget=budget, - max_bytes=args.max_bytes, log=lambda message: print(f" {message}")) - print(f"capture {capture_id} for batch {args.batch} " - f"({len(selection.members)} members, {len(COMPONENTS)} components each, " - f"budget {args.request_budget})") - if existing and not args.fresh: - print(f" resuming stored progress ({len(manifest['sources'])} sources already recorded)") - stop = capture.run() - manifest["citations"] = extract_citations(manifest) - write_manifest(capture_id, manifest) - if stop is None: - removed = sweep_orphans() - if removed: - print(f" swept {removed} unreferenced body file(s)") - report_text = coverage_report(manifest) - finally: - lock.release() - if args.json: - print(json.dumps({"coverage": report_text, - "next": None if report_text["complete"] else - resume_hint(capture_id, manifest)}, - ensure_ascii=False, allow_nan=False, indent=1)) - else: - print_coverage(report_text) - if not report_text["complete"]: - print(f" {resume_hint(capture_id, manifest)}") - return EXIT_OK if report_text["complete"] else EXIT_INCOMPLETE - - -def current_association(batch_id: str) -> tuple[dict | None, str]: - """The capture that currently matches this batch, or why there is none. - - Kept separate from historical inspection on purpose: `show --batch` must never - present an older capture of the same ordinal as if it were the current one. - """ - try: - report, selection = resolve_current(batch_id) - except report_loader.ReportError as exc: - return None, f"the current report cannot be read ({exc})" - except SelectionError as exc: - return None, f"the current report refuses this batch ({exc})" - matches = find_captures(selection) - if not matches: - return None, (f"no capture is associated with the current {batch_id}; run " - f"evidence capture --batch {batch_id}") - if len(matches) > 1: - newest = max(matches, key=lambda cid: matches[cid]["updated_at"]) - others = ", ".join(sorted(set(matches) - {newest})) - return (matches[newest], - f"several captures match the current {batch_id}; showing the newest " - f"({newest}); also present: {others}") - capture_id = next(iter(matches)) - return matches[capture_id], "" - - -def cmd_show(args) -> int: - note = "" - if args.capture: - manifest = read_manifest(args.capture) # historical: no report consulted at all - if args.batch: - stored = manifest["selection"]["batch"]["id"] - if stored != args.batch: - note = (f"capture {args.capture} belongs to batch {stored}, not {args.batch}; " - "showing the recorded capture") - else: - manifest, note = current_association(args.batch) - if manifest is None: - print(note, file=sys.stderr) - return EXIT_REFUSED - if args.source: - windowed = window(manifest, args.source, start=args.start_byte, length=args.length) - if args.json: - print(json.dumps(windowed, ensure_ascii=False, allow_nan=False, indent=1)) - else: - print(f"source {windowed['source_id']} #{windowed['number']} " - f"{windowed['component']}/{windowed['group']} page {windowed['page']}") - print(f" {windowed['url']} {windowed['media_type']} " - f"{windowed['body_bytes']} bytes sha256 {windowed['body_sha256']}") - print(f" bytes {windowed['start_byte']}..{windowed['end_byte']}" - + (f" next --start-byte {windowed['next_start']}" - if windowed["next_start"] is not None else " (end of source)")) - sys.stdout.write(windowed["content"]) - if not windowed["content"].endswith("\n"): - sys.stdout.write("\n") - return EXIT_OK - if args.citation: - resolved = resolve_citation(manifest, args.citation) - if args.json: - print(json.dumps(resolved, ensure_ascii=False, allow_nan=False, indent=1)) - else: - citation = resolved["citation"] - print(f"citation {citation['id']} #{citation['number']} {citation['component']}") - print(f" source {citation['source_id']} bytes " - f"{citation['start_byte']}..{citation['end_byte']} " - f"excerpt sha256 {resolved['excerpt_sha256']}") - sys.stdout.write(resolved["excerpt"]) - if not resolved["excerpt"].endswith("\n"): - sys.stdout.write("\n") - return EXIT_OK - report_text = coverage_report(manifest) - if args.json: - payload = {"coverage": report_text, "historical": bool(args.capture), - "note": note or None, - "sources": [{"id": s["id"], "number": s["number"], - "component": s["component"], "group": s["group"], - "page": s["page"], "bytes": body_path(s["body_sha256"]).exists()} - for s in manifest["sources"]], - "citations": manifest["citations"]} - text = json.dumps(payload, ensure_ascii=False, allow_nan=False, indent=1) - sys.stdout.write(text if len(text) <= DEFAULT_WINDOW_BYTES else - text[:DEFAULT_WINDOW_BYTES] + "\n… (truncated; use --source to read bytes)") - print() - else: - if note: - print(note) - if args.capture: - print("historical capture — nothing here is checked against the current report") - print_coverage(report_text) - if not report_text["complete"]: - print(f" {resume_hint(manifest['capture_id'], manifest)}") - return EXIT_OK - - -def cmd_export(args) -> int: - historical = bool(args.capture) - if historical: - manifest = read_manifest(args.capture) - selection = stored_selection(manifest) - else: - manifest, note = current_association(args.batch) - if manifest is None: - print(note, file=sys.stderr) - return EXIT_REFUSED - selection = stored_selection(manifest) - before = report_loader.input_digests() if not historical else None - budget = ghread.Budget(max(args.request_budget, 4), reserved=2) - gate = require_shareable(selection, budget) - if historical and not args.allow_historical: - print(f"capture {args.capture} is being exported as history: it claims no " - f"current-batch compatibility and the report association it records is " - f"the one from its own capture. Pass --allow-historical to confirm.", - file=sys.stderr) - return EXIT_USAGE - if not historical and report_loader.input_digests() != before: - raise SelectionError("report inputs changed during export; retry") - data = export_bytes(manifest, selection, limit=args.max_bytes) - if args.output == "-": - sys.stdout.buffer.write(data) - sys.stdout.buffer.write(b"\n") - destination = "stdout" - else: - destination_path = Path(args.output) - if destination_path.exists() and destination_path.is_dir(): - raise EvidenceError(f"{args.output} is a directory") - atomic_bytes(destination_path, data) - written = destination_path.read_bytes() - if written != data: - raise EvidenceError(f"exported bytes at {args.output} differ from what was written") - destination = str(destination_path) - summary = {"capture_id": manifest["capture_id"], "batch": selection.batch["id"], - "historical": historical, "complete": is_complete(manifest), - "bytes": len(data), "citations": len(manifest["citations"]), - "sources": len(manifest["sources"]), "output": destination, - "repository": gate["repository"]["full_name"], - "visibility": gate["repository"]["visibility"], - "linked": [repo["full_name"] for repo in gate["linked"]], - "packet_digest": build_packet_digest(data)} - if args.json: - print(json.dumps(summary, ensure_ascii=False, allow_nan=False, indent=1)) - else: - print(f"wrote {summary['bytes']} bytes to {destination} " - f"({summary['sources']} sources, {summary['citations']} citations, " - f"{'complete' if summary['complete'] else 'INCOMPLETE'})") - print(f" packet digest {summary['packet_digest']}") - print(f" sharing gate: {summary['repository']} is {summary['visibility']}" - + (f"; linked public: {', '.join(summary['linked'])}" if summary["linked"] else "")) - return EXIT_OK - - -def build_packet_digest(data: bytes) -> str: - """The packet's own digest, read back from the serialized bytes.""" - try: - packet = json.loads(data.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise EvidenceError(f"exported packet is not readable JSON ({exc})") from exc - return packet.get("packet_digest", "") - - -def attach_commands(commands) -> None: - """The three public operations, attached to whichever parser owns them.""" - capture = commands.add_parser("capture", help="acquire or resume a batch's public evidence") - capture.add_argument("--batch", required=True, help="native batch id, e.g. B001") - capture.add_argument("--request-budget", type=int, default=DEFAULT_REQUEST_BUDGET, - help=f"requests this run may attempt (default {DEFAULT_REQUEST_BUDGET})") - capture.add_argument("--max-bytes", type=int, default=DEFAULT_MAX_BYTES, - help=f"bytes this capture may store (default {DEFAULT_MAX_BYTES})") - capture.add_argument("--fresh", action="store_true", - help="start a new capture generation even if one is stored") - capture.add_argument("--reuse-capture", default=None, - help="resume or extend one explicit capture id") - capture.add_argument("--break-lock", action="store_true", - help="replace a writer lock whose process is gone") - capture.add_argument("--json", action="store_true", help="machine-readable summary") - - show = commands.add_parser("show", help="inspect coverage, sources or citations offline") - show.add_argument("--batch", default=None, help="native batch id: the current association") - show.add_argument("--capture", default=None, help="explicit capture id: historical, offline") - show.add_argument("--source", default=None, help="source id to read a byte window from") - show.add_argument("--citation", default=None, help="citation id to resolve offline") - show.add_argument("--start-byte", type=int, default=0, help="first byte of the window") - show.add_argument("--length", type=int, default=DEFAULT_WINDOW_BYTES, - help=f"window size (max {DEFAULT_WINDOW_BYTES})") - show.add_argument("--json", action="store_true", help="machine-readable output") - - export = commands.add_parser("export", help="write a self-contained packet") - export.add_argument("--batch", default=None, help="native batch id: the current association") - export.add_argument("--capture", default=None, help="explicit capture id: historical export") - export.add_argument("--output", required=True, help="destination file, or - for stdout") - export.add_argument("--allow-historical", action="store_true", - help="confirm an export of a capture that is not the current one") - export.add_argument("--request-budget", type=int, default=8, - help="requests the sharing gate may attempt") - export.add_argument("--max-bytes", type=int, default=DEFAULT_EXPORT_BYTES, - help=f"packet byte bound (default {DEFAULT_EXPORT_BYTES})") - export.add_argument("--json", action="store_true", help="machine-readable summary") - - -def add_parser(sub) -> None: - """Attach the `evidence` command tree to Tranche's existing entry point.""" - parser = sub.add_parser( - "evidence", help="capture, inspect and export the evidence of a native batch (issue #9)") - attach_commands(parser.add_subparsers(dest="evidence_cmd", required=True)) - - -def validate(args) -> str | None: - """Reject a combination this command cannot honour, with a usable message.""" - if args.evidence_cmd == "capture": - if args.max_bytes <= 0: - return "--max-bytes must be positive" - if args.request_budget <= RESERVED_BUDGET: - return (f"--request-budget must exceed the {RESERVED_BUDGET} held back for the " - "completion checks") - return None - if args.evidence_cmd in ("show", "export"): - if bool(args.batch) == bool(args.capture): - return ("give exactly one of --batch (the current association) or " - "--capture (historical, offline)") - if args.evidence_cmd == "show": - if args.source and args.citation: - return "give at most one of --source or --citation" - if args.length < 1 or args.length > DEFAULT_WINDOW_BYTES: - return f"--length must be 1..{DEFAULT_WINDOW_BYTES}" - if args.start_byte < 0: - return "--start-byte must be nonnegative" - if args.evidence_cmd == "export": - if args.max_bytes <= 0: - return "--max-bytes must be positive" - if args.request_budget < 2: - return ("--request-budget must be at least 2 so the sharing gate can check " - "the base repository and every linked one") - return None - - -def dispatch(args) -> int: - """Run one evidence command. Exit codes are stable for scripts: - 0 success, 1 unusable local state, 2 usage, 3 refused selection, 4 incomplete. - """ - try: - problem = validate(args) - if problem: - print(f"usage: {problem}", file=sys.stderr) - return EXIT_USAGE - if args.evidence_cmd == "capture": - return cmd_capture(args) - if args.evidence_cmd == "show": - return cmd_show(args) - if args.evidence_cmd == "export": - return cmd_export(args) - return EXIT_USAGE - except (report_loader.ReportError, SelectionError) as exc: - print(f"refused: {exc}", file=sys.stderr) - return EXIT_REFUSED - except IncompleteCapture as exc: - print(f"incomplete: {exc}", file=sys.stderr) - return EXIT_INCOMPLETE - except (EvidenceError, ghread.ReadError) as exc: - print(f"error: {exc}", file=sys.stderr) - return EXIT_USABLE - - -def main(argv=None) -> int: - """Standalone entry point: `python3 evidence.py `.""" - parser = argparse.ArgumentParser(prog="evidence.py", description=__doc__) - attach_commands(parser.add_subparsers(dest="evidence_cmd", required=True)) - return dispatch(parser.parse_args(argv)) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/gen_page.py b/gen_page.py deleted file mode 100644 index 7ae42e5..0000000 --- a/gen_page.py +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/env python3 -"""Render the PR workbench from mutually consistent, bound report inputs.""" - -import html -import json -import os -import tempfile -from pathlib import Path - -import tranche - - -def atomic_text(path: Path, text: str) -> None: - """Replace path with text atomically; a failed render never truncates it.""" - path.parent.mkdir(parents=True, exist_ok=True) - fd, temporary = tempfile.mkstemp(prefix=".pending-", dir=path.parent) - try: - with os.fdopen(fd, "w", encoding="utf-8") as stream: - stream.write(text) - stream.flush() - os.fsync(stream.fileno()) - os.replace(temporary, path) - finally: - if os.path.exists(temporary): - os.unlink(temporary) - - -ROOT = Path(__file__).resolve().parent -OUT = ROOT / "out" -DOCS = ROOT / "docs" -TEMPLATE = ROOT / "page" / "template.html" - -summary = json.loads((OUT / "summary.json").read_text()) -dupes = json.loads((OUT / "dupes.json").read_text()) -clusters = json.loads((OUT / "clusters.json").read_text()) -prs = tranche.load_prs() -allow_unbound = summary.get("allow_unbound", False) -judgments = tranche.current_judgments(prs, allow_unbound=allow_unbound) -verdicts = tranche.current_pairs(prs, judgments, allow_unbound=allow_unbound) -if (summary.get("format_version") != 2 - or summary.get("repo") != tranche.REPO - or summary.get("report_binding") != tranche.report_binding(prs, judgments, verdicts) - or summary.get("output_digests") != {"clusters.json": tranche.digest(clusters), - "dupes.json": tranche.digest(dupes)}): - raise tranche.TrancheFatal("Report inputs changed or are legacy/mixed; rerun cluster before rendering") - -# Issue #4: merge batches ship with the workbench when present; a stale or -# foreign batches file must never be shown against a newer dupe run. -batches_path = OUT / "batches.json" -batches = None -if batches_path.exists(): - batches = json.loads(batches_path.read_text()) - if (batches.get("format_version") != 3 or batches.get("repo") != tranche.REPO - or batches.get("dupes_digest") != summary["output_digests"]["dupes.json"]): - raise tranche.TrancheFatal("batches.json is stale or foreign; rerun 'tranche.py batches' before rendering") -# Issue #8: the park record renders beside the batches it gated. A batches -# run that parked PRs without its park record - or against a mutated one - -# must never render, same discipline as gen_page's other bound inputs. -parked = None -parked_path = OUT / "parked.json" -if parked_path.exists(): - parked = json.loads(parked_path.read_text()) - expected_parked = tranche.parked_payload( - tranche.park_state(dupes, judgments, prs), prs, judgments, summary["output_digests"]["dupes.json"]) - if parked != expected_parked: - raise tranche.TrancheFatal("parked.json is stale, foreign or modified; rerun 'tranche.py batches' before rendering") -if (batches or {}).get("parked_prs") and parked is None: - raise tranche.TrancheFatal("batches.json parked PRs but parked.json is missing; rerun 'tranche.py batches'") -batch_of = {} -for batch in (batches or {}).get("batches", []): - tag = {"id": batch["id"], "count": batch["count"]} - for number in batch["members"]: - batch_of.setdefault(number, []).append(tag) -merge_batches = [ - {"id": batch["id"], "count": batch["count"], "members": batch["members"], - "security_members": batch["security_members"], - "average_risk": batch["average_risk"], "created": batch["created"], - "review_prompt": batch["review_prompt"]} - for batch in (batches or {}).get("batches", []) -] - -CAT_LABELS = { - "security-review": "Security (meta)", - "install-setup": "Install & Setup", "desktop-config": "Desktop Config", - "user-experience": "User Experience", - "shell-cli": "Shell & CLI", "apps-integrations": "Apps & Integrations", - "hardware-drivers": "Hardware & Drivers", "update-release": "Update & Release", - "agents-ai": "Agents & AI", "docs": "Docs", "fix-misc": "Fixes & Misc", - "unclear": "Unclear", "unknown": "Unknown", -} - -# Eligibility stays in the CLI policy; this renderer never reclassifies a judgment. -in_dupe = {n for g in dupes["confirmed_groups"] for n in g} | {n for g in dupes["review_groups"] for n in g["members"]} -related = in_dupe | {n for pair in dupes["uncertain_pairs"] for n in (pair["a"], pair["b"])} -parked_by_number = {m["number"]: m for m in (parked or {}).get("members", [])} -rows = [] -latest_judgments = tranche.load_done() -for n, pr in sorted(prs.items()): - judgment = judgments.get(n, {}) - finished = tranche.metric(judgment, "finished_form") - rows.append({ - "number": n, "title": pr["title"], "body": pr["body"], - "body_truncated": pr["body_truncated"], "author": pr["author"], - "created": pr["created"], "draft": pr["draft"], - "activity": tranche.pr_activity(pr, latest_judgments.get(n, {})), - "category": tranche.category(judgment) if judgment else "unknown", - "categories": ([ "security-review" ] - if judgment and tranche.security_priority(judgment) else []), - "freshness": judgment.get("freshness", "unjudged or stale"), - "risk": tranche.metric(judgment, "risk"), - "security": tranche.metric(judgment, "security_flag", "noul"), - "security_priority": bool(judgment) and tranche.security_priority(judgment), - "finished": finished, "effort": tranche.metric(judgment, "review_effort"), - "is_fix": tranche.metric(judgment, "is_fix", "noul"), - "diffstat": tranche.pr_state(pr)["pr"]["diffstat"], - "candidate": bool(judgment) and tranche.review_candidate(pr, judgment, in_dupe), - "senior": tranche.escalated(judgment), - "followup": finished is not None and finished <= 1 and n not in in_dupe, - "related": n in related, - "parked": parked_by_number.get(n, {}).get("reasons", []), - "batches": batch_of.get(n, []), - }) -# The workbench data ships as docs/data/workbench.json and is fetched at boot: -# the HTML shell parses immediately and the payload is cacheable across -# refreshes. Same strict escaping discipline as the former inline payload; -# the JSON bytes are unchanged, only the transport moved. -payload = json.dumps({"prs": rows, "categories": CAT_LABELS, "groups": dupes, - "batches": merge_batches, - "batches_available": batches is not None, - "parked": parked}, - ensure_ascii=True, allow_nan=False, separators=(",", ":")) -payload = payload.replace("&", "\\u0026").replace("<", "\\u003c").replace(">", "\\u003e") -# The shell is HTML in page/template.html: {{options}}, {{count}} and -# {{count_commas}} are filled by literal replacement - the same cheap, -# deterministic fill the f-string gave, with HTML out of the Python source. -options = ''.join(f'' for cat, label in CAT_LABELS.items()) -page = TEMPLATE.read_text() -page = page.replace("{{options}}", options) -page = page.replace("{{count_commas}}", f"{len(prs):,}").replace("{{count}}", str(len(prs))) -DOCS.mkdir(exist_ok=True) -atomic_text(DOCS / "data" / "workbench.json", payload) -(DOCS / "index.html").write_text(page) -print(f"wrote docs/index.html ({len(page)//1024} KB) and docs/data/workbench.json " - f"({len(payload)//1024} KB); {len(rows)} captured PRs") -print(f"candidates: {sum(r['candidate'] for r in rows)}, senior: {sum(r['senior'] for r in rows)}, " - f"follow-up: {sum(r['followup'] for r in rows)}, parked: {len(parked_by_number)}, " - f"related: {sum(r['related'] for r in rows)}") diff --git a/ghread.py b/ghread.py deleted file mode 100644 index 76b126d..0000000 --- a/ghread.py +++ /dev/null @@ -1,447 +0,0 @@ -#!/usr/bin/env python3 -"""Bounded, GET-only read transport for GitHub evidence acquisition. - -`tranche.fetch_page` returns a parsed page and throws away the HTTP status, -headers and raw bytes; evidence needs all three. This module is the narrow -extension: it keeps the existing credential ownership (`gh` holds the token, the -process never reads it and never puts it in an argv) while returning exact -response bytes, the status, the headers and the continuation link. - -Everything here is read-only. REST requests are explicit GET. GraphQL requests -are queries only and are refused if the document is not a query. Redirects and -continuation links are validated against the allowed origin and repository scope -before they are followed, and every attempted request is charged to a budget. -""" -from __future__ import annotations - -import json -import os -import re -import select -import subprocess -import time -from urllib.parse import parse_qsl, urlsplit - -ORIGIN = "https://api.github.com" -GRAPHQL_URL = f"{ORIGIN}/graphql" -MAX_RESPONSE_BYTES = 4 * 1024 * 1024 -MAX_STDERR_BYTES = 64 * 1024 -MAX_GRAPHQL_BODY_BYTES = 256 * 1024 -MAX_REDIRECTS = 3 -CHUNK_BYTES = 64 * 1024 -GH_TIMEOUT = 60 - -CREDENTIAL_KEYS = frozenset({ - "token", "access_token", "authorization", "api_key", "client_secret", - "private_token", "password", "key", "auth", "credentials", -}) -REDIRECT_STATUSES = (301, 302, 303, 307, 308) - - -class ReadError(RuntimeError): - """The transport could not produce a usable response.""" - - -class BudgetExhausted(ReadError): - """No request budget is left for an attempt (or for a reserved one).""" - - -class ResponseTooLarge(ReadError): - """The response body exceeded the configured bound.""" - - -class Budget: - """Attempt accounting: every invocation counts, failures included. - - `reserved` capacity is held back from ordinary requests so work that must not - be starved - the final identity checks a capture performs before it certifies - anything - can still run. A caller that is spending that reserved capacity - says so explicitly with ``reserve=0``. - """ - - def __init__(self, limit: int, reserved: int = 0): - if type(limit) is not int or type(limit) is bool or limit < 0: - raise ReadError("request budget must be a nonnegative integer") - if type(reserved) is not int or type(reserved) is bool or reserved < 0 or reserved > limit: - raise ReadError("reserved budget must be within the request budget") - self.limit = limit - self.reserved = reserved - self.used = 0 - self.failures = 0 - self.retries = 0 - self.identity_checks = 0 - - @property - def remaining(self) -> int: - return max(0, self.limit - self.used) - - def can(self, reserve: int | None = None) -> bool: - """True when one more request fits while keeping `reserve` (default: the floor).""" - keep = self.reserved if reserve is None else reserve - return self.used + 1 + keep <= self.limit - - def charge(self, reserve: int | None = None) -> None: - """Consume one attempt, keeping `reserve` requests available for later work.""" - keep = self.reserved if reserve is None else reserve - if not self.can(keep): - raise BudgetExhausted( - f"request budget exhausted ({self.used}/{self.limit}, " - f"{keep} held back)") - self.used += 1 - - def summary(self) -> dict: - return {"limit": self.limit, "used": self.used, "reserved": self.reserved, - "failures": self.failures, "retries": self.retries, - "identity_checks": self.identity_checks} - - -class Response: - """One HTTP response: exact decoded bytes plus the metadata it arrived with.""" - - __slots__ = ("status", "url", "headers", "body", "truncated", "attempts") - - def __init__(self, status, url, headers, body, truncated=False, attempts=1): - self.status = status - self.url = url - self.headers = headers - self.body = body - self.truncated = truncated - self.attempts = attempts - - @property - def media_type(self) -> str: - return (self.headers.get("content-type") or "").split(";")[0].strip() - - @property - def next_url(self) -> str | None: - return parse_next_link(self.headers.get("link")) - - def json(self): - """Parse the body as JSON. Truncated bodies are never parsed silently.""" - if self.truncated: - raise ResponseTooLarge("truncated response body cannot be parsed as JSON") - try: - return json.loads(self.body.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise ReadError(f"response body is not UTF-8 JSON ({exc})") from exc - - -# --------------------------------------------------------------------------- -# URL policy -# --------------------------------------------------------------------------- - -def validate_url(url: str, repo_prefix: str | None = None) -> str: - """A URL we are willing to request: allowed origin, no credentials, no fragment. - - `repo_prefix` is `owner/repo` when the request must stay inside one - repository's REST namespace. It is a scope check on the URL, never proof that - a response belongs to the resource we asked for - that is verified against - the returned payload at acquisition time. - """ - if not isinstance(url, str) or not url: - raise ReadError("refusing empty or non-string URL") - if any(character in url for character in "\r\n\t "): - raise ReadError("refusing URL containing whitespace or control characters") - parts = urlsplit(url) - if parts.scheme != "https" or parts.netloc != "api.github.com": - raise ReadError(f"refusing URL outside {ORIGIN}: {url}") - if parts.fragment: - raise ReadError("refusing URL with a fragment") - if url[: len(ORIGIN)] != ORIGIN: - raise ReadError(f"refusing URL that only resembles {ORIGIN}: {url}") - keys = {key.lower() for key, _ in parse_qsl(parts.query, keep_blank_values=True)} - if keys & CREDENTIAL_KEYS: - raise ReadError("refusing URL carrying credential-shaped query parameters") - if repo_prefix is not None: - prefix = f"/repos/{repo_prefix}" - if parts.path != prefix and not parts.path.startswith(f"{prefix}/"): - raise ReadError(f"refusing URL outside repository {repo_prefix}: {url}") - return url - - -def parse_next_link(link_header: str | None) -> str | None: - """The `rel="next"` continuation URL, validated; other relations are ignored.""" - if not link_header: - return None - for entry in re.split(r",(?=\s*<)", link_header): - match = re.match(r"\s*<([^>]*)>\s*(.*)", entry) - if not match: - continue - relations = match.group(2) - if not re.search(r"rel\s*=\s*\"?next\"?", relations): - continue - return validate_url(match.group(1)) - return None - - -def page_param(url: str) -> int: - values = dict(parse_qsl(urlsplit(url).query, keep_blank_values=True)) - try: - return int(values.get("page", "1")) - except (TypeError, ValueError) as exc: - raise ReadError(f"unreadable page parameter in {url}") from exc - - -# --------------------------------------------------------------------------- -# Process invocation -# --------------------------------------------------------------------------- - -class RawResult: - __slots__ = ("returncode", "stdout", "stderr", "truncated", "timed_out") - - def __init__(self, returncode, stdout, stderr, truncated=False, timed_out=False): - self.returncode = returncode - self.stdout = stdout - self.stderr = stderr - self.truncated = truncated - self.timed_out = timed_out - - -def run_gh(argv, *, timeout=GH_TIMEOUT, max_bytes=MAX_RESPONSE_BYTES, stdin_data=None): - """Run `gh` with bounded, streamed output. - - stdout and stderr are read in chunks on non-blocking pipes and the child is - killed the moment stdout exceeds the bound, so an unbounded response can - never be buffered whole. No shell is involved and no credential ever enters - the argv. - """ - process = subprocess.Popen( - argv, - stdin=subprocess.PIPE if stdin_data is not None else subprocess.DEVNULL, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - if stdin_data is not None: - try: - process.stdin.write(stdin_data) - finally: - process.stdin.close() - out_pipe, err_pipe = process.stdout, process.stderr - if out_pipe is None or err_pipe is None: # unreachable with PIPE, keeps types honest - raise ReadError("gh pipes are unavailable") - out_fd, err_fd = out_pipe.fileno(), err_pipe.fileno() - deadline = time.monotonic() + timeout if timeout else None - streams = { - out_fd: {"data": b"", "limit": max_bytes, "truncated": False, "done": False}, - err_fd: {"data": b"", "limit": MAX_STDERR_BYTES, "truncated": False, "done": False}, - } - for fd in (out_fd, err_fd): - os.set_blocking(fd, False) - handles = {out_fd: out_pipe, err_fd: err_pipe} - timed_out = False - try: - while not all(stream["done"] for stream in streams.values()): - remaining = None if deadline is None else deadline - time.monotonic() - if remaining is not None and remaining <= 0: - timed_out = True - process.kill() - break - watch = [fd for fd, stream in streams.items() if not stream["done"]] - try: - ready, _, _ = select.select(watch, [], [], remaining) - except InterruptedError: - continue - if not ready: - timed_out = True - process.kill() - break - for fd in ready: - stream = streams[fd] - try: - chunk = os.read(fd, CHUNK_BYTES) - except (BlockingIOError, InterruptedError): - continue - except OSError: - stream["done"] = True - continue - if not chunk: - stream["done"] = True - continue - room = stream["limit"] - len(stream["data"]) - if room > 0: - stream["data"] += chunk[:room] - if len(chunk) > room: - stream["truncated"] = True - if fd == out_fd: - process.kill() - stream["done"] = True - # stderr overflow is dropped, never fatal. - try: - process.wait(timeout=5) - except subprocess.TimeoutExpired: - timed_out = True - process.kill() - process.wait(timeout=5) - finally: - for handle in handles.values(): - try: - handle.close() - except OSError: - pass - return RawResult(process.returncode if process.returncode is not None else -1, - streams[out_fd]["data"], streams[err_fd]["data"], - streams[out_fd]["truncated"], timed_out) - - -def _split_response(raw: bytes): - """Split `gh api --include` output into header blocks and the body. - - `gh` emits one header block per HTTP hop, CRLF-terminated, followed by the - body. Redirects therefore appear as several blocks; the last one is the - response we act on. - """ - blocks, index = [], 0 - while True: - match = re.search(rb"\r?\n\r?\n", raw[index:]) - if not match: - break - end = index + match.start() - block = raw[index:end] - if not block.lstrip().upper().startswith(b"HTTP/"): - break - blocks.append(block) - index = index + match.end() - if not blocks: - raise ReadError("gh api --include produced no HTTP status line") - return blocks, raw[index:] - - -def _headers(block: bytes) -> dict: - lines = block.decode("utf-8", errors="replace").splitlines() - headers: dict[str, str] = {} - for line in lines[1:]: - if ":" in line: - key, value = line.split(":", 1) - headers[key.strip().lower()] = value.strip() - return headers - - -def _status(block: bytes) -> int: - match = re.match(rb"HTTP/[\d.]+\s+(\d{3})", block.strip()) - if not match: - raise ReadError("unreadable HTTP status line from gh") - return int(match.group(1)) - - -def invoke(argv, *, timeout=GH_TIMEOUT, max_bytes=MAX_RESPONSE_BYTES, stdin_data=None): - """The single place a subprocess is spawned; tests replace this seam. - - Returns `(status, headers, body, truncated, hops)` for the final response. - """ - result = run_gh(argv, timeout=timeout, max_bytes=max_bytes, stdin_data=stdin_data) - if result.timed_out: - raise ReadError(f"gh timed out after {timeout}s") - if result.returncode != 0 and not result.stdout.strip(): - detail = _diagnostic(result.stderr) - raise ReadError(f"gh failed ({detail})") - blocks, body = _split_response(result.stdout) - # gh writes the body for every hop it follows itself; our own redirect - # handling only sees the ones it does not follow. - headers = _headers(blocks[-1]) - if "content-length" in headers and not result.truncated: - try: - if int(headers["content-length"]) > max_bytes: - raise ResponseTooLarge( - f"response declares {headers['content-length']} bytes, over the " - f"{max_bytes} byte bound") - except ValueError: - pass - if result.returncode != 0: - raise ReadError(f"gh failed with HTTP {_status(blocks[-1])} ({_diagnostic(result.stderr)})") - return _status(blocks[-1]), headers, body, result.truncated, len(blocks) - - -def _diagnostic(stderr: bytes) -> str: - """A short, credential-free diagnostic line for the operator.""" - text = stderr.decode("utf-8", errors="replace").strip() - lines = [line.strip() for line in text.splitlines() if line.strip()] - detail = lines[-1] if lines else "no detail" - detail = re.sub(r"(?i)(token|authorization|password)[=:\s]+\S+", r"\1=REDACTED", detail) - return detail[:200] - - -def read(url: str, *, accept: str | None = None, params: dict | None = None, - budget: Budget | None = None, reserve: int | None = None, - timeout: int = GH_TIMEOUT, - max_bytes: int = MAX_RESPONSE_BYTES, repo_prefix: str | None = None) -> Response: - """One bounded GET, following validated redirects, charging every attempt.""" - attempt_url = validate_url(url, repo_prefix) - hops = 0 - attempts = 0 - while True: - if budget is not None: - budget.charge(reserve) - attempts += 1 - argv = ["gh", "api", "--include", "--method", "GET", attempt_url] - if accept: - argv += ["-H", f"accept: {accept}"] - for key, value in (params or {}).items(): - argv += ["-f", f"{key}={value}"] - try: - status, headers, body, truncated, blocks = invoke( - argv, timeout=timeout, max_bytes=max_bytes) - except ReadError: - if budget is not None: - budget.failures += 1 - raise - hops += blocks - 1 - if status in REDIRECT_STATUSES and headers.get("location"): - if hops >= MAX_REDIRECTS: - raise ReadError(f"too many redirects from {attempt_url}") - attempt_url = validate_url(_absolute(headers["location"], attempt_url), repo_prefix) - continue - if status >= 400: - if budget is not None: - budget.failures += 1 - raise ReadError(f"HTTP {status} from {attempt_url}") - if truncated: - raise ResponseTooLarge( - f"response from {attempt_url} exceeded the {max_bytes} byte bound") - return Response(status, attempt_url, headers, body, truncated=False, attempts=attempts) - - -def _absolute(location: str, base: str) -> str: - if location.startswith("https://"): - return location - if not location.startswith("/"): - raise ReadError(f"refusing relative redirect target {location!r}") - return f"{ORIGIN}{location}" - - -QUERY_DOCUMENT = re.compile(r"^\s*(query\b|\{)", re.IGNORECASE) -MUTATION_DOCUMENT = re.compile(r"\b(mutation|subscription)\b", re.IGNORECASE) - - -def graphql(query: str, variables: dict | None = None, *, budget: Budget | None = None, - reserve: int | None = None, timeout: int = GH_TIMEOUT, - max_bytes: int = MAX_RESPONSE_BYTES) -> Response: - """One GraphQL query. Mutations and subscriptions are refused by construction. - - The document is sent on stdin rather than in the argv, so the query text - never appears in `ps` output and no credential-shaped value can be mistaken - for an argument. The recorded provenance keeps the query text and the - variables, never the transport. - """ - if not isinstance(query, str) or not query.strip() or not QUERY_DOCUMENT.match(query): - raise ReadError("refusing a GraphQL document that is not a query") - if MUTATION_DOCUMENT.search(query): - raise ReadError("refusing a GraphQL document mentioning mutation/subscription") - body = json.dumps({"query": query, "variables": variables or {}}, - ensure_ascii=False, allow_nan=False).encode("utf-8") - if len(body) > MAX_GRAPHQL_BODY_BYTES: - raise ReadError("GraphQL request body exceeds the bound") - argv = ["gh", "api", "--include", "--method", "POST", GRAPHQL_URL, "--input", "-"] - try: - if budget is not None: - budget.charge(reserve) - status, headers, payload, truncated, _hops = invoke( - argv, timeout=timeout, max_bytes=max_bytes, stdin_data=body) - except ReadError: - if budget is not None: - budget.failures += 1 - raise - if status >= 400: - raise ReadError(f"HTTP {status} from {GRAPHQL_URL}") - if truncated: - raise ResponseTooLarge(f"GraphQL response exceeded the {max_bytes} byte bound") - return Response(status, GRAPHQL_URL, headers, payload) diff --git a/hostpython.py b/hostpython.py deleted file mode 100644 index 15c42f1..0000000 --- a/hostpython.py +++ /dev/null @@ -1,53 +0,0 @@ -"""One canonical interpreter, resolved by the standard library. - -`PYTHON` overrides every consumer (Makefile, tests, MCP client configs). -`MINIMUM` is the floor the code requires. `CANDIDATES` lists the names probed, -in order, when no override is set. -""" - -import os -import shutil -import sys - -# Oldest CPython the code has been exercised on. -MINIMUM = (3, 10) - -# Versioned names first, so an unrelated `python3` earlier on PATH cannot decide. -CANDIDATES = ("python3.14", "python3.13", "python3.12", "python3.11", "python3.10") - - -def host_interpreter(): - """The absolute path of the interpreter to use, or None when none qualifies. - - PYTHON wins when set and usable. Otherwise the first `CANDIDATES` name on - PATH, falling back to `python3`. - """ - override = os.environ.get("PYTHON") - if override: - resolved = shutil.which(override) - if resolved is None and os.path.isfile(override): - resolved = os.path.abspath(override) - return resolved - for name in CANDIDATES: - resolved = shutil.which(name) - if resolved: - return resolved - return shutil.which("python3") - - -def describe(interpreter): - """`path (X.Y.Z)` for a resolved interpreter, for failure messages.""" - return f"{interpreter} ({sys.version.split()[0]})" - - -if __name__ == "__main__": - resolved = host_interpreter() - if resolved is None: - print(f"No Python interpreter found (need CPython >= {'.'.join(map(str, MINIMUM))})", - file=sys.stderr) - raise SystemExit(1) - if sys.version_info < MINIMUM: - print(f"{sys.version.split()[0]} is below the required floor " - f"{'.'.join(map(str, MINIMUM))}", file=sys.stderr) - raise SystemExit(1) - print(resolved) diff --git a/mcp_server.py b/mcp_server.py index 6995535..c6a93bd 100644 --- a/mcp_server.py +++ b/mcp_server.py @@ -159,7 +159,7 @@ def _batch(self, batch_id): if not isinstance(batch_id, str) or re.fullmatch(r"B[0-9]{3,6}", batch_id) is None: raise ReportError("Expected exact batch id such as B001") if self.batches is None: - raise ReportError("batches.json is unavailable; run tranche.py batches") + raise ReportError("batches.json is unavailable; run `tranche batches`") for batch in self.batches["batches"]: if batch["id"] == batch_id: return batch @@ -175,7 +175,7 @@ def pick(self, batch_id: str): def next_prompt(self, after: int | str | None = None): self._load() if self.batches is None: - raise ReportError("batches.json is unavailable; run tranche.py batches") + raise ReportError("batches.json is unavailable; run `tranche batches`") if isinstance(after, str): after = self._batch(after)["ordinal"] if after is None: diff --git a/report_loader.py b/report_loader.py deleted file mode 100644 index e07e7c3..0000000 --- a/report_loader.py +++ /dev/null @@ -1,142 +0,0 @@ -#!/usr/bin/env python3 -"""The one authority for reading Tranche's bound report outputs. - -Every consumer of a report - the MCP server and the evidence CLI - must apply -exactly the same gates: current snapshot, judgment and pair bindings, the -recorded output digests, the recomputed batches and park record, and no input -file changing under the read. Those gates used to live inside the MCP server's -response formatting; they live here now so a second consumer cannot end up with -a second, weaker set of predicates. - -This module deliberately knows nothing about MCP or about evidence storage. It -returns the validated projection and raises `ReportError` when the local -observation cannot safely be used. -""" -from __future__ import annotations - -import hashlib -import json -from pathlib import Path -from typing import NamedTuple - -import tranche - - -class ReportError(ValueError): - """The local observation cannot safely be used.""" - - -class Limits(NamedTuple): - """Byte and file-count bounds for fingerprinting the bound inputs.""" - - max_file_bytes: int = 128 * 1024 * 1024 - max_total_bytes: int = 256 * 1024 * 1024 - max_input_files: int = 512 - - -DEFAULT_LIMITS = Limits() - - -class BoundReport(NamedTuple): - """The validated report projection: inputs, derived records and identity.""" - - summary: dict - clusters: dict - dupes: dict - batches: dict | None - parked: dict | None - prs: dict - judgments: dict - pairs: list - latest_judgments: dict - identity: dict - - -def source_paths() -> list[Path]: - """The captured membership, then the report outputs, in a fixed order.""" - snapshot = tranche.PAGES_DIR / "snapshot.json" - sources = [snapshot] if snapshot.exists() else sorted(tranche.PAGES_DIR.glob("page_*.json")) - return [snapshot, *sources, tranche.JUDGMENTS_PATH, tranche.PAIRS_PATH, - *(tranche.OUT_DIR / name for name in - ("summary.json", "clusters.json", "dupes.json", "batches.json", "parked.json"))] - - -def input_digests(limits: Limits = DEFAULT_LIMITS) -> dict: - """Bounded byte fingerprints include optional files and corpus membership.""" - paths = source_paths() - if len(set(paths)) > limits.max_input_files: - raise ReportError("Input file count exceeds limit") - result, total = {}, 0 - for path in dict.fromkeys(paths): - if not path.exists(): - result[str(path)] = None - continue - with path.open("rb") as stream: - data = stream.read(limits.max_file_bytes + 1) - total += len(data) - if len(data) > limits.max_file_bytes or total > limits.max_total_bytes: - raise ReportError("Input bytes exceed limit") - result[str(path)] = hashlib.sha256(data).hexdigest() - return result - - -def load(limits: Limits = DEFAULT_LIMITS) -> BoundReport: - """Read and validate the bound report, or raise `ReportError`. - - Raises before returning anything the caller could mistake for a usable - observation: a stale, unbound, foreign or modified input is refused here, not - downstream. - """ - try: - return _read(limits) - except ReportError: - raise - except (OSError, ValueError, TypeError, KeyError, AttributeError, tranche.TrancheFatal) as exc: - raise ReportError("Invalid or missing bound reports; rerun cluster and batches") from exc - - -def _read(limits: Limits) -> BoundReport: - out = tranche.OUT_DIR - summary = json.loads((out / "summary.json").read_text()) - clusters = json.loads((out / "clusters.json").read_text()) - dupes = json.loads((out / "dupes.json").read_text()) - prs = tranche.load_prs() - if tranche.JUDGMENTS_PATH.exists(): - for line in tranche.JUDGMENTS_PATH.read_text().splitlines(): - if line.strip() and not isinstance(json.loads(line), dict): - raise ReportError("Malformed judgment record") - judgments = tranche.current_judgments(prs) - # Only the producer's current projection, which the report must bind. - pairs = tranche.current_pairs(prs, judgments) - if tranche.PAIRS_PATH.exists(): - for line in tranche.PAIRS_PATH.read_text().splitlines(): - if line.strip() and not isinstance(json.loads(line), dict): - raise ReportError("Malformed pair record") - expected = {"clusters.json": tranche.digest(clusters), "dupes.json": tranche.digest(dupes)} - if (summary.get("format_version") != 2 or summary.get("repo") != tranche.REPO - or summary.get("allow_unbound") is not False - or summary.get("report_binding") != tranche.report_binding(prs, judgments, pairs) - or summary.get("output_digests") != expected): - raise ReportError("Reports are stale, unbound, foreign or modified; rerun cluster") - batches_path = out / "batches.json" - batches = json.loads(batches_path.read_text()) if batches_path.exists() else None - if batches is not None and tranche.digest(batches) != tranche.digest(tranche.merge_batches( - dupes, judgments, prs, expected["dupes.json"])): - raise ReportError("batches.json is stale or modified; rerun batches") - # Issue #8: the park record is part of the same observation as the batches it - # gated. It must match the producer predicate byte for byte whenever batches - # parked PRs, and is otherwise refused as modified. - parked_path = out / "parked.json" - parked = json.loads(parked_path.read_text()) if parked_path.exists() else None - if parked is not None and tranche.digest(parked) != tranche.digest(tranche.parked_payload( - tranche.park_state(dupes, judgments, prs), prs, judgments, expected["dupes.json"])): - raise ReportError("parked.json is stale or modified; rerun batches") - if (batches or {}).get("parked_prs") and parked is None: - raise ReportError("batches.json parked PRs but parked.json is missing; rerun batches") - identity = {"report_binding": summary["report_binding"], - "batches.json": tranche.digest(batches) if batches is not None else None, - "parked.json": tranche.digest(parked) if parked is not None else None, - **summary["output_digests"]} - return BoundReport(summary=summary, clusters=clusters, dupes=dupes, batches=batches, - parked=parked, prs=prs, judgments=judgments, pairs=pairs, - latest_judgments=tranche.load_done(), identity=identity) diff --git a/tests/evidence_contract.py b/tests/evidence_contract.py deleted file mode 100644 index a155a0d..0000000 --- a/tests/evidence_contract.py +++ /dev/null @@ -1,283 +0,0 @@ -"""Offline executable specification for the *proposed* evidence packet v1. - -Test support only: no capture, persistence, network, or production CLI API. -""" -import base64 -import binascii -import hashlib -import json -import math -import re -from datetime import datetime -from urllib.parse import parse_qs, urlsplit - -FORMAT = "tranche.evidence-packet/v1" -PROFILE = "pr-review/v1" -COMPONENTS = ("metadata", "diff", "files", "discussion", "review_comments", - "reviews", "checks", "closing_issues") -MAX_PACKET_BYTES = 1024 * 1024 # Small conformance profile, not a CLI default. - - -def require(condition, message): - if not condition: - raise ValueError(message) - - -def encode(value): - return json.dumps(value, sort_keys=True, separators=(",", ":"), - ensure_ascii=False, allow_nan=False).encode("utf-8") - - -def digest(value): - return hashlib.sha256(encode(value)).hexdigest() - - -def byte_digest(value): - return hashlib.sha256(value).hexdigest() - - -def fields(value, names): - require(type(value) is dict and set(value) == set(names.split()), "fields") - - -def integer(value, minimum=0): - require(type(value) is int and value >= minimum, "integer") - - -def sha(value, length=64): - require(type(value) is str and re.fullmatch(f"[0-9a-f]{{{length}}}", value), "digest") - - -def timestamp(value): - require(type(value) is str and re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", value), - "UTC timestamp") - datetime.strptime(value, "%Y-%m-%dT%H:%M:%S%z") - - -def seal(packet): - packet["packet_digest"] = digest({k: v for k, v in packet.items() if k != "packet_digest"}) - return packet - - -def generation(selection, capture_id): - return digest({"format": FORMAT, "profile": PROFILE, "selection": selection, - "capture_id": capture_id}) - - -def source_id(generation_id, source): - return digest({"generation": generation_id, "source": - {k: v for k, v in source.items() if k != "id"}}) - - -def parse(data, max_bytes=MAX_PACKET_BYTES): - """Reject ambiguous JSON and bound the complete serialized input first.""" - require(type(data) is bytes and len(data) <= max_bytes, "packet byte limit") - - def unique_pairs(pairs): - result = {} - for key, value in pairs: - require(key not in result, "duplicate JSON key") - result[key] = value - return result - - def invalid_constant(value): - raise ValueError("non-finite JSON number") - - def finite_float(value): - number = float(value) - require(math.isfinite(number), "non-finite JSON number") - return number - - return json.loads(data.decode("utf-8"), object_pairs_hook=unique_pairs, - parse_constant=invalid_constant, parse_float=finite_float) - - -def validate(packet, expected_selection=None, max_bytes=MAX_PACKET_BYTES): - """Validate bytes/relationships; expected_selection comes from bound reports. - - Without it this proves internal consistency only, never current report state. - """ - try: - return _validate(packet, expected_selection, max_bytes) - except (KeyError, TypeError, AttributeError, OverflowError, RecursionError) as exc: - raise ValueError("malformed packet") from exc - - -def _validate(packet, expected_selection, max_bytes): - require(len(encode(packet)) <= max_bytes, "packet byte limit") - fields(packet, "format profile selection membership_digest capture_id generation complete capture " - "coverage sources citations packet_digest") - require(packet["format"] == FORMAT and packet["profile"] == PROFILE, "version/profile") - require(packet["packet_digest"] == digest( - {k: v for k, v in packet.items() if k != "packet_digest"}), "packet digest") - selection = packet["selection"] - fields(selection, "repository report batch members") - repository = selection["repository"] - fields(repository, "id full_name visibility") - integer(repository["id"], 1) - require(type(repository["full_name"]) is str and re.fullmatch( - r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository["full_name"]), "repository name") - require(repository["visibility"] == "public", "public repository required") - report = selection["report"] - fields(report, "report_binding output_digests") - sha(report["report_binding"]) - fields(report["output_digests"], "clusters.json dupes.json batches.json parked.json") - for name, value in report["output_digests"].items(): - if name != "parked.json" or value is not None: - sha(value) - # Copy the selected native batch unchanged, including the exact prompt. - batch = selection["batch"] - require(type(batch) is dict and {"id", "ordinal", "members", "count", "review_prompt"} - <= set(batch), "batch fields") - integer(batch["ordinal"], 1) - require(batch["id"] == f"B{batch['ordinal']:03d}", "batch ordinal") - require(type(batch["review_prompt"]) is str and bool(batch["review_prompt"]), "prompt") - require(type(selection["members"]) is list and bool(selection["members"]), "members") - numbers = [] - for member in selection["members"]: - fields(member, "number source_digest evidence_digest base_sha head_sha updated_at") - integer(member["number"], 1) - numbers.append(member["number"]) - for name in ("source_digest", "evidence_digest"): - sha(member[name]) - for name in ("base_sha", "head_sha"): - sha(member[name], 40) - timestamp(member["updated_at"]) - require(len(set(numbers)) == len(numbers), "duplicate member") - require(type(batch["members"]) is list and all(type(n) is int for n in batch["members"]) - and batch["members"] == numbers, "ordered batch membership") - integer(batch["count"], 1) - require(batch["count"] == len(numbers), "batch count") - require(packet["membership_digest"] == digest(numbers), "membership digest") - sha(packet["capture_id"], 32) - require(packet["generation"] == generation(selection, packet["capture_id"]), "generation binding") - if expected_selection is not None: - require(encode(selection) == encode(expected_selection), "stale/foreign report selection") - capture = packet["capture"] - fields(capture, "observed_at request_limit requests_used stop_reason") - timestamp(capture["observed_at"]) - integer(capture["request_limit"]) - integer(capture["requests_used"]) - require(capture["requests_used"] <= capture["request_limit"], "request budget") - require(capture["stop_reason"] in (None, "request_budget", "storage_budget", "interrupted", - "transport_error", "visibility_revoked", "revision_drift"), - "stop reason") - if capture["stop_reason"] == "request_budget": - require(capture["requests_used"] == capture["request_limit"], "unexhausted request budget") - require(type(packet["sources"]) is list, "sources") - sources, slots, source_bytes = {}, set(), {} - for source in packet["sources"]: - fields(source, "id number component page cursor next_cursor url media_type captured_at " - "body_base64 body_sha256") - integer(source["number"], 1) - require(source["number"] in numbers and source["component"] in COMPONENTS, "source scope") - integer(source["page"], 1) - slot = (source["number"], source["component"], source["page"]) - require(slot not in slots and source["id"] not in sources, "duplicate source") - slots.add(slot) - for name in ("cursor", "next_cursor"): - require(source[name] is None or (type(source[name]) is str and bool(source[name])), - "cursor") - # Reference URLs are labels only, never fetched by this specification. - require(type(source["url"]) is str and not any(c in source["url"] for c in "\r\n"), "source URL") - url = urlsplit(source["url"]) - prefix = f"/repos/{repository['full_name']}/" - require(url.scheme == "https" and url.netloc == "api.github.com" and not url.fragment - and (url.path.startswith(prefix) or url.path == "/graphql"), "source URL") - require(not {key.lower() for key in parse_qs(url.query)} & - {"token", "access_token", "authorization", "api_key", "client_secret"}, "credential URL") - require(source["media_type"] in ("application/json", "text/plain", "text/x-diff"), - "media type") - timestamp(source["captured_at"]) - require(source["captured_at"] <= capture["observed_at"], "source observed in future") - require(type(source["body_base64"]) is str, "source body") - try: - body = base64.b64decode(source["body_base64"], validate=True) - except (ValueError, binascii.Error) as exc: - raise ValueError("source base64") from exc - require(base64.b64encode(body).decode("ascii") == source["body_base64"], "canonical base64") - require(byte_digest(body) == source["body_sha256"], "source bytes digest") - require(source["id"] == source_id(packet["generation"], source), "source generation") - sources[source["id"]], source_bytes[source["id"]] = source, body - require(type(packet["coverage"]) is list, "coverage") - covered, referenced, completed = set(), set(), [] - for component in packet["coverage"]: - fields(component, "number component status source_ids next_cursor reason") - integer(component["number"], 1) - key = (component["number"], component["component"]) - require(key[0] in numbers and key[1] in COMPONENTS and key not in covered, "coverage scope") - covered.add(key) - require(component["status"] in ("missing", "partial", "complete", "blocked"), "coverage status") - require(type(component["source_ids"]) is list, "source ids") - pages = [] - for index, source_key in enumerate(component["source_ids"], 1): - require(type(source_key) is str and source_key in sources, "missing source") - source = sources[source_key] - require((source["number"], source["component"], source["page"]) == (*key, index), - "page binding/order") - require(source["cursor"] == (pages[-1]["next_cursor"] if pages else None), "cursor chain") - if pages: - require(pages[-1]["next_cursor"] is not None, "page after terminal") - pages.append(source) - referenced.add(source_key) - cursors = [p["cursor"] for p in pages] - require(len(set(cursors)) == len(cursors), "pagination cursor cycle") - end = pages[-1]["next_cursor"] if pages else None - require(end is None or end not in cursors, "pagination cursor cycle") - require(component["next_cursor"] == end, "resume cursor") - if component["status"] == "complete": - require(bool(pages) and end is None and component["reason"] is None, "incomplete pagination") - else: - require(type(component["reason"]) is str and bool(component["reason"]), "missing reason") - if component["status"] == "missing": - require(not pages, "missing has sources") - if component["status"] == "partial": - require(bool(pages) and end is not None, "partial needs continuation") - completed.append(component["status"] == "complete") - require(covered == {(n, c) for n in numbers for c in COMPONENTS}, "missing coverage component") - require(referenced == set(sources), "orphan source") - require(type(packet["complete"]) is bool and packet["complete"] == all(completed), "completeness") - require(not packet["complete"] or capture["stop_reason"] is None, "complete but stopped") - require(type(packet["citations"]) is list, "citations") - citation_ids = set() - for citation in packet["citations"]: - fields(citation, "id source_id source_sha256 start_byte end_byte excerpt_sha256") - require(type(citation["id"]) is str and bool(citation["id"]) - and citation["id"] not in citation_ids, "citation id") - citation_ids.add(citation["id"]) - require(type(citation["source_id"]) is str and citation["source_id"] in sources, "citation source") - body = source_bytes[citation["source_id"]] - integer(citation["start_byte"]) - integer(citation["end_byte"], 1) - require(citation["start_byte"] < citation["end_byte"] <= len(body), "citation range") - require(citation["source_sha256"] == byte_digest(body), "citation source digest") - require(citation["excerpt_sha256"] == byte_digest( - body[citation["start_byte"]:citation["end_byte"]]), "citation excerpt digest") - return packet - - -def validate_resume(previous, resumed): - """A resumed observation can add pages; it cannot rewrite prior evidence.""" - validate(previous) - require(previous["capture"]["stop_reason"] not in ("revision_drift", "visibility_revoked"), - "capture invalidated; fresh capture required") - validate(resumed, previous["selection"]) - require(resumed["generation"] == previous["generation"], "resume generation") - require(resumed["capture"]["observed_at"] >= previous["capture"]["observed_at"], "resume time") - for name in ("sources", "citations"): - indexed = {entry["id"]: entry for entry in resumed[name]} - require(all(indexed.get(entry["id"]) == entry for entry in previous[name]), "resume rewrites evidence") - indexed = {(c["number"], c["component"]): c for c in resumed["coverage"]} - for component in previous["coverage"]: - new = indexed[(component["number"], component["component"])] - require(new["source_ids"][:len(component["source_ids"])] == component["source_ids"], "resume pages") - if component["status"] == "complete": - require(new == component, "resume regresses complete coverage") - - -def validate_sharing(packet, current_repository): - """Synthetic live-policy gate; offline bytes alone cannot grant sharing.""" - validate(packet) - require(current_repository == packet["selection"]["repository"], "visibility/identity changed") - require(packet["capture"]["stop_reason"] not in ("visibility_revoked", "revision_drift"), - "capture invalidated") diff --git a/tests/test_branding.py b/tests/test_branding.py deleted file mode 100644 index 833a8ff..0000000 --- a/tests/test_branding.py +++ /dev/null @@ -1,62 +0,0 @@ -"""Project identity checks; captured Omarchy evidence is intentionally unchanged.""" - -import shutil -import subprocess -import sys -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] - - -class BrandingTests(unittest.TestCase): - def test_cli_and_owned_surfaces_use_tranche(self): - result = subprocess.run([sys.executable, str(ROOT / "tranche.py"), "--help"], - capture_output=True, text=True, timeout=15) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("Tranche", result.stdout) - for name in ("README.md", "Makefile", "gen_page.py", "page/template.html", - "docs/index.html", "tools/make_title_gif.py"): - with self.subTest(path=name): - text = (ROOT / name).read_text() - self.assertNotIn("omarchy-pr-jev-triage", text) - self.assertNotIn("omarchy-triage.gif", text) - self.assertNotIn("OMARCHY TRIAGE", text) - self.assertTrue((ROOT / "docs/assets/tranche.gif").is_file()) - self.assertTrue((ROOT / "tools/omarchy-wordmark.svg").is_file()) - generator = (ROOT / "tools/make_title_gif.py").read_text() - self.assertIn('TAGLINE = "TRIAGE with Tranche (powered by Jev)"', generator) - shell = (ROOT / "page/template.html").read_text() - self.assertIn('assets/tranche-mascot.png', shell) - self.assertIn('OMARCHY — TRIAGE with Tranche (powered by Jev)', shell) - - def test_offline_check_runs_optional_node_frontend_tests(self): - makefile = (ROOT / "Makefile").read_text() - self.assertIn("node --test tests/workbench.test.cjs", makefile) - self.assertIn("command -v node", makefile) - - @unittest.skipUnless(shutil.which("rsvg-convert"), "Title generation needs optional librsvg") - def test_only_tranche_in_tagline_receives_the_animated_gradient(self): - try: - from tools import make_title_gif as title - from PIL import ImageChops, ImageFont - except ImportError: - self.skipTest("Title generation requires optional Pillow/numpy") - self.assertEqual(title.TAGLINE, "TRIAGE with Tranche (powered by Jev)") - frames = title.compose([[(255, 0, 0)] * title.PROBE_W, - [(0, 255, 0)] * title.PROBE_W]) - font = ImageFont.truetype(title.FONT_PATH, title.TAG_FONT_SIZE) - logo_height = title.logo_mask().shape[0] - top = title.PAD_Y + logo_height + title.TAG_GAP - region = (0, top, frames[0].width, frames[0].height) - changed = ImageChops.difference(frames[0].crop(region), frames[1].crop(region)).getbbox() - self.assertIsNotNone(changed) - width = font.getlength(title.TAGLINE) - start = (frames[0].width - width) / 2 + font.getlength("TRIAGE with ") - end = start + font.getlength("Tranche") - self.assertGreaterEqual(changed[0], int(start)) - self.assertLessEqual(changed[2], int(end) + 2) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_evidence.py b/tests/test_evidence.py deleted file mode 100644 index 26b9f98..0000000 --- a/tests/test_evidence.py +++ /dev/null @@ -1,833 +0,0 @@ -"""Offline tests for the native evidence service: synthetic reports and fake transport. - -No network, no `gh`, no model. Every test drives the production code path - -`evidence.select`, `evidence.Capture`, `evidence.export_bytes`, the CLI commands - -against a synthetic native report and a recorded transport, so the assertions are -about the real request construction and the real storage/identity rules rather -than a replacement implementation returning idealized dictionaries. -""" -import json -import os -import unittest -from unittest.mock import patch - -import evidence -import ghread -import report_loader -import tranche -from tests import test_tranche as fixtures - -pr = fixtures.pr -answers = fixtures.answers - -BASE_ID, BASE_NAME = 994093166, "omacom/omarchy" -FORK_ID, FORK_NAME = 1338981908, "contributor/omarchy" -SHA = {"base": "a" * 40, "head": "b" * 40} -HEAD_SHA2 = "c" * 40 - - -def captured(number, *, head_sha=None, updated="2026-01-02T00:00:00Z", fork=True, **changes): - """A captured PR item with the base/head identity evidence selection needs.""" - head_sha = head_sha or SHA["head"] - item = pr(number, **changes) - item["updated_at"] = updated - item["head"] = {"sha": head_sha, "ref": "feature", "label": f"{FORK_NAME.split('/')[0]}:feature", - "repo": {"id": FORK_ID if fork else BASE_ID, - "full_name": FORK_NAME if fork else BASE_NAME, "fork": fork}} - item["base"] = {"sha": SHA["base"], "ref": "master", - "repo": {"id": BASE_ID, "full_name": BASE_NAME, "fork": False}} - return item - - -def body(payload) -> bytes: - return json.dumps(payload, ensure_ascii=False).encode("utf-8") - - -class FakeGh: - """A recorded GitHub transport honouring the real request contract. - - Routes are keyed by a URL fragment and answer per page, so pagination, - continuation links, foreign identities and hostile next links are all - exercised through the same seam the capture uses. - """ - - def __init__(self): - self.calls = [] - self.routes = [] - self.graphql_calls = [] - self.fail = {} - - def on(self, fragment, payload, *, link=None, media="application/vnd.github+json", - status=200, raw=None, pages=None, repository=None, sha=None, - graphql_number=None): - self.routes.append({"fragment": fragment, "payload": payload, "link": link, - "media": media, "status": status, "raw": raw, - "pages": pages, "repository": repository, "sha": sha, - "graphql_number": graphql_number}) - return self - - def _ranked(self): - """Most specific fragment first; a later registration overrides an equal one.""" - return sorted(enumerate(self.routes), key=lambda pair: (-len(pair[1]["fragment"]), - -pair[0])) - - def _find(self, url, accept): - # Longest fragment wins (`/pulls/1/files` is not `/pulls/1`), and a test - # that registers an endpoint again is overriding the earlier answer. - for _index, route in self._ranked(): - if route["fragment"] in url: - if route["pages"] is not None: - page = int(dict(p.split("=", 1) for p in url.split("?", 1)[-1].split("&") - if "=" in p).get("page", "1")) if "?" in url else 1 - if page in route["pages"]: - entry = route["pages"][page] - return route, entry - continue - return route, route - return None, None - - def read(self, url, *, accept=None, params=None, budget=None, reserve=None, - timeout=None, max_bytes=None, repo_prefix=None): - if budget is not None: - budget.charge(reserve) - query = "&".join(f"{k}={v}" for k, v in sorted((params or {}).items())) - full = url + ("&" + query if query and "?" in url else - "?" + query if query else "") - self.calls.append({"url": url, "accept": accept, "params": dict(params or {}), - "repo_prefix": repo_prefix, "full": full}) - route, entry = self._find(full, accept) - if route is None: - raise ghread.ReadError(f"no recorded route for {full}") - if route["fragment"] in self.fail: - raise self.fail[route["fragment"]] - payload = entry.get("raw") - if payload is None: - data = entry["payload"] - if callable(data): - data = data(self.calls[-1]) - payload = body(data) - headers = {"content-type": entry.get("media") or "application/vnd.github+json"} - if entry.get("link"): - headers["link"] = entry["link"].format(base=ghread.ORIGIN) - if entry.get("repository") is not None: - payload = body({"repository": entry["repository"], "state": "pending", - "total_count": 0, "statuses": [], - "sha": entry.get("sha") or SHA["head"]}) - if route["status"] >= 400: - raise ghread.ReadError(f"HTTP {route['status']} from {full}") - return ghread.Response(route["status"], full, headers, payload) - - def graphql(self, query, variables=None, *, budget=None, reserve=None, timeout=None, - max_bytes=None): - if budget is not None: - budget.charge(reserve) - variables = dict(variables or {}) - self.graphql_calls.append({"query": query, "variables": variables}) - # A GraphQL answer is about one PR: select the route registered for the - # number this call asked for, exactly as a real endpoint would. - for _index, route in self._ranked(): - if route["fragment"] != "graphql": - continue - if route.get("graphql_number") not in (None, variables.get("number")): - continue - data = route["payload"] - if callable(data): - data = data(variables) - return ghread.Response(200, ghread.GRAPHQL_URL, - {"content-type": "application/json"}, body(data)) - raise ghread.ReadError(f"no recorded graphql route for {variables}") - - -def metadata_payload(member, *, head_sha=None, base_sha=None, updated=None, number=None, - head_repo=None, base_repo=None): - head_repo = head_repo if head_repo is not None else { - "id": member["head_repo_id"], "full_name": member["head_repo_name"], - "fork": member["head_fork"]} - base_repo = base_repo if base_repo is not None else { - "id": member["base_repo_id"], "full_name": member["base_repo_name"], "fork": False} - return {"number": number if number is not None else member["number"], - "head": {"sha": head_sha or member["head_sha"], "ref": "feature", "repo": head_repo}, - "base": {"sha": base_sha or member["base_sha"], "ref": "master", "repo": base_repo}, - "updated_at": updated if updated is not None else member["updated_at"]} - - -def closing_payload(number, *, has_next=False, cursor=None, nodes=None, repo=None, pr_number=None): - return {"data": {"repository": { - "nameWithOwner": repo or BASE_NAME, "id": BASE_ID, - "pullRequest": {"number": pr_number or number, "url": f"https://github.com/{BASE_NAME}/pull/{number}", - "closingIssuesReferences": { - "totalCount": len(nodes or []), - "pageInfo": {"hasNextPage": has_next, "endCursor": cursor}, - "nodes": nodes if nodes is not None else []}}}}} - - -class EvidenceTests(unittest.TestCase): - """Synthetic native report, fake transport, real service code.""" - - setUp = fixtures.WorkflowTests.setUp - inputs = fixtures.WorkflowTests.inputs - judgments = fixtures.WorkflowTests.judgments - pairs = fixtures.WorkflowTests.pairs - cluster = fixtures.WorkflowTests.cluster - - def build_report(self, items=None): - """A validated native report with one real batch of two members.""" - items = items or [captured(1), captured(2, fork=False)] - prs = self.inputs(items) - self.judgments(prs) - self.pairs(prs, []) - self.cluster() - dupes = json.loads((self.out / "dupes.json").read_text()) - judgments = tranche.current_judgments(prs) - digest = tranche.digest(dupes) - tranche.atomic_json(self.out / "batches.json", - tranche.merge_batches(dupes, judgments, prs, digest)) - tranche.atomic_json(self.out / "parked.json", - tranche.parked_payload(tranche.park_state(dupes, judgments, prs), - prs, judgments, digest)) - return prs - - def selection(self, batch="B001"): - return evidence.select(batch, report_loader.load()) - - def routes(self, gh, *, files=None, discussion=None): - """The full endpoint set for every member of the batch. - - Every member must have routes: the capture's live revision check reads - each member's metadata before it acquires anything, so a fixture that - only knows one member fail-stops - correctly - instead of acquiring. - """ - for member in self.selection().members: - self.member_routes(gh, member, files=files, discussion=discussion) - return self.selection().members[0] - - def member_routes(self, gh, member, *, files=None, discussion=None): - base = member["base_repo_name"] - head = member["head_sha"] - gh.on(f"/repos/{base}/pulls/{member['number']}", metadata_payload(member)) - gh.on(f"/repos/{base}/pulls/{member['number']}/files", files if files is not None else []) - gh.on(f"/repos/{base}/issues/{member['number']}/comments", discussion or []) - gh.on(f"/repos/{base}/pulls/{member['number']}/comments", []) - gh.on(f"/repos/{base}/pulls/{member['number']}/reviews", []) - gh.on(f"/repos/{base}/commits/{head}/check-runs", {"total_count": 0, "check_runs": []}) - gh.on(f"/repos/{base}/commits/{head}/status", None, - repository={"id": member["base_repo_id"], "full_name": base}, sha=head) - if member["head_repo_name"] != base: - gh.on(f"/repos/{member['head_repo_name']}/commits/{head}/check-runs", - {"total_count": 0, "check_runs": []}) - gh.on(f"/repos/{member['head_repo_name']}/commits/{head}/status", None, - repository={"id": member["head_repo_id"], "full_name": member["head_repo_name"]}, - sha=head) - gh.on("graphql", lambda variables: closing_payload(member["number"]), - graphql_number=member["number"]) - return member - - def capture(self, gh, *, batch="B001", budget=200, capture_id=None, **kwargs): - """Run one capture exactly as `cmd_capture` resolves its manifest. - - A supplied capture id resumes the stored checkpoint (re-binding the - association and carrying unchanged code over), which is what the CLI - does; it never silently starts from a blank manifest. - """ - selection = self.selection(batch) - capture_id = capture_id or evidence.new_capture_id() - if evidence.manifest_path(capture_id).exists(): - manifest = evidence.read_manifest(capture_id) - else: - manifest = evidence.build_manifest(selection, capture_id, request_limit=budget) - evidence.carry_over_code(selection, manifest) - manifest["selection"] = selection.as_json() - manifest["capture"]["request_limit"] = budget - evidence.write_manifest(capture_id, manifest) - with patch.object(evidence.ghread, "read", gh.read), \ - patch.object(evidence.ghread, "graphql", gh.graphql): - run = evidence.Capture(selection, capture_id, manifest, - budget=ghread.Budget(budget, reserved=evidence.RESERVED_BUDGET), - **kwargs) - run.run() - manifest["citations"] = evidence.extract_citations(manifest) - return capture_id, manifest, run - - -class SelectionTests(EvidenceTests): - """One authority for batch selection; every refusal is tested.""" - - def test_select_binds_identity_provenance_and_membership(self): - self.build_report() - selection = self.selection() - batch = json.loads((self.out / "batches.json").read_text())["batches"][0] - self.assertEqual(selection.numbers, batch["members"]) - self.assertEqual(selection.batch["review_prompt"], batch["review_prompt"]) - self.assertEqual(selection.repository, {"id": BASE_ID, "full_name": BASE_NAME, - "visibility": "unknown"}) - payload = selection.as_json() - self.assertEqual(payload["batch"]["members"], batch["members"]) - self.assertEqual(payload["batch"]["review_prompt"], batch["review_prompt"]) - self.assertEqual(payload["report"]["report_binding"], - json.loads((self.out / "summary.json").read_text())["report_binding"]) - self.assertEqual(set(payload["report"]["output_digests"]), - {"clusters.json", "dupes.json", "batches.json", "parked.json"}) - member = payload["members"][0] - self.assertEqual(member["base_sha"], SHA["base"]) - self.assertEqual(member["head_repo_name"], FORK_NAME) - self.assertTrue(member["head_fork"]) - # The generation is the report association and the code identity. - generation = evidence.generation_id(selection, "0" * 32) - self.assertEqual(generation, evidence.evidence_digest({ - "format": evidence.FORMAT, "profile": evidence.PROFILE, "capture_id": "0" * 32, - "repository": selection.repository, "revision": selection.revision(), - "membership": selection.membership_digest, "batch": selection.batch["id"], - "report": selection.report})) - - def test_select_refuses_unknown_and_malformed_batch_ids(self): - self.build_report() - report = report_loader.load() - for batch in ("B999", "b001", "B1", "", None, 1, "../B001", "B001\n"): - with self.subTest(batch=batch), self.assertRaises(evidence.SelectionError): - evidence.select(batch, report) - - def test_select_refuses_a_parked_member_batch(self): - """The batch plan and the park record must agree, or nothing is selected.""" - self.build_report() - parked = json.loads((self.out / "parked.json").read_text()) - parked["members"] = [{"number": 1, "reasons": ["draft"], - "unblock": "x", "title": "t", "author": "a", - "head_sha": None, "url": "u", "created": "", - "security_flag": None}] - (self.out / "parked.json").write_text(json.dumps(parked)) - with self.assertRaises(report_loader.ReportError): - self.selection() - - def test_select_refuses_a_short_or_missing_revision(self): - for change in ({"head": {"sha": "b" * 12, "repo": {"id": FORK_ID, - "full_name": FORK_NAME, "fork": True}}}, - {"head": {"sha": None, "repo": {"id": FORK_ID, - "full_name": FORK_NAME, "fork": True}}}, - {"base": {"sha": SHA["base"], "repo": None}}, - {"base": {"sha": SHA["base"], "repo": {"id": None, - "full_name": BASE_NAME}}}): - with self.subTest(change=list(change)): - item = captured(1) - for key, value in change.items(): - item[key] = value - self.build_report([item, captured(2, fork=False)]) - with self.assertRaises(evidence.SelectionError): - self.selection() - - def test_select_refuses_a_deleted_fork_head(self): - item = captured(1) - item["head"]["repo"] = None - self.build_report([item, captured(2, fork=False)]) - with self.assertRaisesRegex(evidence.SelectionError, "deleted fork"): - self.selection() - - def test_captured_items_checks_the_snapshot_checksum(self): - self.build_report() - path = self.pages / "snapshot.json" - value = json.loads(path.read_text()) - value["digest"] = "0" * 64 - path.write_text(json.dumps(value)) - with self.assertRaises(evidence.SelectionError): - evidence.captured_items() - - def test_a_reversed_batch_order_is_not_the_same_selection(self): - """Membership order is part of the batch identity, not presentation.""" - self.build_report() - selection = self.selection() - batch = json.loads((self.out / "batches.json").read_text())["batches"][0] - reversed_batch = dict(batch, members=list(reversed(batch["members"])), - review_prompt=batch["review_prompt"] + "\n(edited)") - other = evidence.Selection(selection.repository, selection.report, reversed_batch, - list(reversed(selection.members))) - self.assertNotEqual(other.as_json(), selection.as_json()) - self.assertNotEqual(evidence.generation_id(other, "0" * 32), - evidence.generation_id(selection, "0" * 32)) - - def test_prompt_edits_alone_do_not_change_the_generation(self): - """The prompt is recorded provenance; it is not a cache key.""" - self.build_report() - selection = self.selection() - rewritten = dict(selection.batch, review_prompt="a rewritten prompt") - other = evidence.Selection(selection.repository, selection.report, - rewritten, selection.members) - self.assertEqual(evidence.generation_id(other, "0" * 32), - evidence.generation_id(selection, "0" * 32)) - self.assertNotEqual(other.as_json()["batch"]["review_prompt"], - selection.as_json()["batch"]["review_prompt"]) - - -class CaptureTests(EvidenceTests): - """Acquisition through the production path with recorded responses.""" - - def test_capture_completes_every_component_of_both_members(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, run = self.capture(gh) - self.assertTrue(evidence.is_complete(manifest)) - self.assertIsNone(manifest["capture"]["stop_reason"]) - self.assertEqual({entry["status"] for entry in manifest["components"]}, {"complete"}) - # One component per member/component pair, and no orphans. - self.assertEqual(len(manifest["components"]), 2 * len(evidence.COMPONENTS)) - cited = {source["id"] for source in manifest["sources"]} - self.assertEqual({c["source_id"] for c in manifest["citations"]} - cited, set()) - # The base repo answers the PR's own checks; the fork answers its own. - status_urls = {call["url"] for call in gh.calls if call["url"].endswith("/status")} - self.assertIn(f"https://api.github.com/repos/{BASE_NAME}/commits/{SHA['head']}/status", - status_urls) - self.assertIn(f"https://api.github.com/repos/{FORK_NAME}/commits/{SHA['head']}/status", - status_urls) - # Every request was an explicit, bounded, credential-free GET. - for call in gh.calls: - self.assertEqual(call["repo_prefix"] in (BASE_NAME, FORK_NAME), True) - # REST sources plus GraphQL sources exclude both rounds of identity reads. - self.assertEqual(len(manifest["sources"]), - len(gh.calls) + len(gh.graphql_calls) - 2 * len(self.selection().members)) - - def test_requests_name_real_endpoints_and_media_types(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - self.capture(gh) - urls = {call["url"] for call in gh.calls} - self.assertIn(f"https://api.github.com/repos/{BASE_NAME}/pulls/1", urls) - self.assertIn(f"https://api.github.com/repos/{BASE_NAME}/pulls/1/files", urls) - self.assertIn(f"https://api.github.com/repos/{BASE_NAME}/issues/1/comments", urls) - self.assertNotIn("metadata", urls) # the proposal's synthetic endpoint - accepts = {call["accept"] for call in gh.calls} - self.assertIn(evidence.DIFF_ACCEPT, accepts) - self.assertIn(evidence.JSON_MEDIA, accepts) - self.assertTrue(gh.graphql_calls) - # The query is a query, and its provenance carries no credential. - for call in gh.graphql_calls: - self.assertTrue(call["query"].lstrip().startswith("query")) - self.assertNotIn("mutation", call["query"]) - self.assertEqual(set(call["variables"]), - {"owner", "name", "number", "cursor"}) - self.assertNotIn("token", json.dumps(call["variables"]).lower()) - - def test_empty_collections_are_captured_as_empty_not_invented(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - empty = [s for s in manifest["sources"] if s["component"] == "discussion"] - self.assertTrue(empty) - for source in empty: - self.assertEqual(json.loads(evidence.read_body(source["body_sha256"])), []) - # An empty response is captured evidence; it needs no fabricated citation. - self.assertEqual([c for c in manifest["citations"] if c["component"] == "discussion"], []) - - def test_ci_runs_and_statuses_are_separate_and_named(self): - self.build_report() - gh = FakeGh() - member = self.routes(gh) - runs = {"total_count": 1, "check_runs": [ - {"id": 7, "head_sha": member["head_sha"], "status": "completed", - "conclusion": "success", "name": "build"}]} - gh.on(f"/repos/{BASE_NAME}/commits/{member['head_sha']}/check-runs", runs) - gh.on(f"/repos/{FORK_NAME}/commits/{member['head_sha']}/check-runs", runs) - capture_id, manifest, _ = self.capture(gh) - groups = {g["group"]: g for entry in manifest["components"] - if entry["component"] == "checks" for g in entry["groups"]} - self.assertEqual(set(groups), {"check_runs", "statuses", - "fork_check_runs", "fork_statuses"}) - self.assertEqual(groups["check_runs"]["items_observed"], 1) - self.assertEqual(groups["check_runs"]["items_reported"], 1) - self.assertEqual(groups["statuses"]["items_observed"], 0) - - def test_a_delivered_check_run_cap_is_reported_instead_of_certified(self): - """A full, terminal page at GitHub's own ceiling is a named gap. - - GitHub returns at most the 1000 most recent suites' runs; a response that - reaches that ceiling with nothing left to page is not proof that every - run was observed, so it must not be recorded as complete. - """ - self.build_report() - gh = FakeGh() - member = self.routes(gh) - runs = [{"id": index, "head_sha": member["head_sha"], "name": f"job-{index}", - "status": "completed", "conclusion": "success"} - for index in range(evidence.CHECK_RUN_CAP)] - gh.on(f"/repos/{BASE_NAME}/commits/{member['head_sha']}/check-runs", - {"total_count": evidence.CHECK_RUN_CAP, "check_runs": runs}) - gh.on(f"/repos/{FORK_NAME}/commits/{member['head_sha']}/check-runs", - {"total_count": evidence.CHECK_RUN_CAP, "check_runs": runs}) - capture_id, manifest, _ = self.capture(gh) - entry = next(e for e in manifest["components"] - if e["component"] == "checks" and e["number"] == member["number"]) - group = next(g for g in entry["groups"] if g["group"] == "check_runs") - self.assertEqual(group["status"], "partial") - self.assertIn("caps check runs", group["reason"]) - # The captured bytes still hold every run that was delivered. - self.assertEqual(group["items_observed"], evidence.CHECK_RUN_CAP) - - def test_a_shortfall_between_reported_and_observed_is_named(self): - self.build_report() - gh = FakeGh() - member = self.routes(gh) - gh.on(f"/repos/{BASE_NAME}/commits/{member['head_sha']}/check-runs", - {"total_count": 5, "check_runs": []}) - capture_id, manifest, _ = self.capture(gh) - entry = next(e for e in manifest["components"] - if e["component"] == "checks" and e["number"] == member["number"]) - group = next(g for g in entry["groups"] if g["group"] == "check_runs") - self.assertEqual(group["status"], "partial") - self.assertIn("5 items", group["reason"]) - - -class IdentityTests(EvidenceTests): - """What forces a re-download, what is reused, and what is refused.""" - - def test_a_moved_head_invalidates_the_capture_instead_of_rebinding(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - sources_before = {s["id"]: s["body_sha256"] for s in manifest["sources"]} - self.assertTrue(evidence.is_complete(manifest)) - # The PR moves upstream. - moved = self.selection().members[0] - gh2 = FakeGh() - self.routes(gh2) - gh2.on(f"/repos/{BASE_NAME}/pulls/{moved['number']}", - metadata_payload(moved, head_sha=HEAD_SHA2)) - with self.assertRaises(evidence.SelectionError): - self.capture(gh2, capture_id=capture_id) - # Recorded bytes remain available; the generation is invalidated. - reread = evidence.read_manifest(capture_id) - self.assertEqual({s["id"]: s["body_sha256"] for s in reread["sources"]}, - sources_before) - self.assertEqual(reread["generation"], manifest["generation"]) - self.assertFalse(evidence.is_complete(reread)) - self.assertEqual(reread["capture"]["stop_reason"], "revision_drift") - for source in reread["sources"]: - evidence.read_body(source["body_sha256"]) - - def test_an_updated_at_change_refreshes_mutable_and_keeps_code_bytes(self): - """A thread update is not a revision: unchanged code must not be re-fetched.""" - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - code_before = {s["body_sha256"] for s in manifest["sources"] - if s["component"] in evidence.CODE_COMPONENTS} - self.assertTrue(code_before) - # Upstream thread churn only. - member = self.selection().members[0] - gh2 = FakeGh() - self.routes(gh2) - gh2.on(f"/repos/{BASE_NAME}/pulls/{member['number']}", - metadata_payload(member, updated="2026-05-05T05:05:05Z")) - capture_id2, manifest2, run = self.capture(gh2, capture_id=capture_id) - code_after = {s["body_sha256"] for s in manifest2["sources"] - if s["component"] in evidence.CODE_COMPONENTS} - self.assertTrue(code_before <= code_after) - # The generation survived, so historical citations still resolve. - self.assertEqual(manifest2["generation"], manifest["generation"]) - self.assertEqual(manifest2["code_observation"]["thread_updated_at"][str(member["number"])], - "2026-05-05T05:05:05Z") - # The stale mutable groups were re-acquired, not left complete. - entry = next(e for e in manifest2["components"] - if e["component"] == "discussion" and e["number"] == member["number"]) - self.assertEqual(entry["status"], "complete") - for citation in manifest["citations"]: - evidence.resolve_citation(manifest2, citation["id"]) - - def test_a_report_only_change_carries_code_evidence_over_without_requests(self): - """A re-cluster must not orphan captured bytes, or fetch them again.""" - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - code_before = [s for s in manifest["sources"] - if s["component"] in evidence.CODE_COMPONENTS] - # A different report association over the same revisions. - selection = self.selection() - rewritten = dict(selection.report, report_binding="f" * 64) - other = evidence.Selection(selection.repository, rewritten, selection.batch, - selection.members) - fresh_id = evidence.new_capture_id() - fresh = evidence.build_manifest(other, fresh_id, request_limit=200) - self.assertNotEqual(fresh["generation"], manifest["generation"]) - adopted = evidence.carry_over_code(other, fresh) - self.assertEqual(adopted, len(code_before)) - code_after = [s for s in fresh["sources"] - if s["component"] in evidence.CODE_COMPONENTS] - self.assertEqual({s["body_sha256"] for s in code_before}, - {s["body_sha256"] for s in code_after}) - # The adopted records belong to the new generation and the new capture. - for source in fresh["sources"]: - self.assertEqual(source["generation"], fresh["generation"]) - self.assertTrue(source["id"].startswith("")) # id recomputed, not copied - # A capture with adopted code needs no network for those components. - gh2 = FakeGh() - self.routes(gh2) - evidence.write_manifest(fresh_id, fresh) - with patch.object(evidence.ghread, "read", gh2.read), \ - patch.object(evidence.ghread, "graphql", gh2.graphql): - run = evidence.Capture(other, fresh_id, fresh, - budget=ghread.Budget(200, reserved=evidence.RESERVED_BUDGET)) - run.run() - fetched = {call["url"].rsplit("/", 1)[-1] for call in gh2.calls} - # Code components are not re-fetched: their bytes were adopted. - self.assertNotIn("files", fetched) - # Mutable components still are: CI and the thread move without a head move. - self.assertIn("check-runs", fetched) - self.assertIn("comments", fetched) - - def test_a_revision_move_is_not_carried_over(self): - """Reuse is keyed to the revision, so a moved head must not be adopted.""" - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - selection = self.selection() - moved = [dict(m) for m in selection.members] - moved[0] = dict(moved[0], head_sha=HEAD_SHA2) - other = evidence.Selection(selection.repository, selection.report, - selection.batch, moved) - fresh = evidence.build_manifest(other, evidence.new_capture_id(), request_limit=200) - adopted = evidence.carry_over_code(other, fresh) - # Only the unmoved member's code is adopted; the moved one is not. - self.assertEqual({s["number"] for s in fresh["sources"]}, {moved[1]["number"]}) - self.assertEqual(adopted, len([s for s in fresh["sources"] - if s["component"] in evidence.CODE_COMPONENTS])) - - def test_an_unrelated_corpus_change_does_not_touch_the_capture(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - before = evidence.read_manifest(capture_id) - # Add unrelated PRs and rebuild the report. - self.build_report([captured(1), captured(2, fork=False), captured(9, fork=False)]) - self.assertNotEqual(self.selection().numbers, [1, 2]) # membership really moved - # The stored capture is byte-for-byte what it was. - self.assertEqual(evidence.read_manifest(capture_id), before) - - def test_a_capture_from_another_selection_is_not_this_selection(self): - """A manifest that claims another batch is refused as inconsistent.""" - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, _, _ = self.capture(gh) - manifest = evidence.read_manifest(capture_id) - manifest["selection"]["batch"] = dict(manifest["selection"]["batch"], - id="B002", ordinal=2) - evidence.write_manifest(capture_id, manifest) - with self.assertRaisesRegex(evidence.EvidenceError, "generation"): - evidence.read_manifest(capture_id) - - def test_a_consistent_manifest_of_another_batch_is_a_different_selection(self): - """Renumbering the batch is a new selection even with identical members.""" - self.build_report() - selection = self.selection() - renumbered = dict(selection.batch, id="B002", ordinal=2) - other = evidence.Selection(selection.repository, selection.report, renumbered, - selection.members) - fresh = evidence.build_manifest(other, evidence.new_capture_id(), request_limit=200) - evidence.write_manifest(fresh["capture_id"], fresh) - reread = evidence.read_manifest(fresh["capture_id"]) - self.assertEqual(evidence.stored_selection(reread).batch["id"], "B002") - self.assertNotEqual(reread["selection"], selection.as_json()) - self.assertNotEqual(reread["generation"], - evidence.generation_id(selection, fresh["capture_id"])) - - def test_batch_renumbering_is_a_new_generation_unless_explicitly_reused(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - same = evidence.generation_id(self.selection(), capture_id) - self.assertEqual(same, manifest["generation"]) - fresh = evidence.generation_id(self.selection(), evidence.new_capture_id()) - self.assertNotEqual(fresh, manifest["generation"]) - - -class StorageTests(EvidenceTests): - """Bounds, confinement, corruption and crash windows.""" - - def test_stored_bytes_are_verified_on_read_and_corruption_is_refused(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - source = manifest["sources"][0] - path = evidence.body_path(source["body_sha256"]) - path.write_bytes(b"tampered") - with self.assertRaisesRegex(evidence.EvidenceError, "corrupted"): - evidence.read_body(source["body_sha256"]) - with self.assertRaises(evidence.EvidenceError): - evidence.window(manifest, source["id"]) - - def test_a_missing_body_is_refused_not_silently_empty(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - source = manifest["sources"][0] - evidence.body_path(source["body_sha256"]).unlink() - with self.assertRaisesRegex(evidence.EvidenceError, "missing"): - evidence.read_body(source["body_sha256"]) - - def test_the_storage_budget_stops_and_names_itself(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, run = self.capture(gh, max_bytes=200) - self.assertEqual(manifest["capture"]["stop_reason"], "storage_budget") - self.assertFalse(evidence.is_complete(manifest)) - # Whatever was stored before the stop is still readable. - for source in manifest["sources"][:1]: - evidence.read_body(source["body_sha256"]) - - def test_the_request_budget_stops_and_leaves_a_resumable_checkpoint(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id = evidence.new_capture_id() - selection = self.selection() - manifest = evidence.build_manifest(selection, capture_id, request_limit=9) - evidence.write_manifest(capture_id, manifest) - with patch.object(evidence.ghread, "read", gh.read), \ - patch.object(evidence.ghread, "graphql", gh.graphql): - run = evidence.Capture(selection, capture_id, manifest, - budget=ghread.Budget(9, reserved=evidence.RESERVED_BUDGET)) - run.run() - self.assertEqual(manifest["capture"]["stop_reason"], "request_budget") - self.assertLessEqual(manifest["capture"]["requests_used"], - manifest["capture"]["request_limit"]) - self.assertTrue(manifest["sources"]) - # The checkpoint on disk is the resumable one. - reread = evidence.read_manifest(capture_id) - self.assertEqual(reread["capture"]["stop_reason"], "request_budget") - self.assertTrue(reread["sources"]) - - def test_a_resumed_capture_does_not_restore_the_budget(self): - """Resuming must not silently refill the budget the operator set.""" - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id = evidence.new_capture_id() - selection = self.selection() - manifest = evidence.build_manifest(selection, capture_id, request_limit=9) - evidence.write_manifest(capture_id, manifest) - with patch.object(evidence.ghread, "read", gh.read), \ - patch.object(evidence.ghread, "graphql", gh.graphql): - evidence.Capture(selection, capture_id, manifest, - budget=ghread.Budget(9, reserved=evidence.RESERVED_BUDGET)).run() - used = manifest["capture"]["requests_used"] - gh2 = FakeGh() - self.routes(gh2) - with patch.object(evidence.ghread, "read", gh2.read), \ - patch.object(evidence.ghread, "graphql", gh2.graphql): - evidence.Capture(selection, capture_id, manifest, - budget=ghread.Budget(used, reserved=0)).run() - self.assertLessEqual(manifest["capture"]["requests_used"] + 0, used + len(gh2.calls)) - - def test_path_confinement_refuses_traversal_symlinks_and_links(self): - """Traversal, symlinks and hard links are all refused. - - The final resolved-path check in `confined_file` is deliberately kept as - defence in depth against a component being swapped for a symlink between - the walk and the resolve; no deterministic test isolates it, because the - `..` rejection and the symlink walk already catch every non-racing input. - """ - root = evidence.root() - root.mkdir(parents=True, exist_ok=True) - victim = root / "victim.txt" - victim.write_bytes(b"x") - (root / "escape").symlink_to("/etc/passwd") - (root / "hardlink").write_bytes(b"y") - os.link(root / "hardlink", root / "hardlink2") - for bad in ("../manifest.json", "a/../../etc/passwd", "/etc/passwd", - "escape", "hardlink", "sub/../victim.txt/sub", "", "x\x00y"): - with self.subTest(path=bad), self.assertRaises(evidence.EvidenceError): - evidence.confined_file(bad, root) - good = evidence.confined_file("victim.txt", root) - self.assertEqual(good, victim.resolve()) - - def test_the_writer_lock_refuses_a_live_holder_and_recovers_a_dead_one(self): - evidence.root().mkdir(parents=True, exist_ok=True) - capture_id = evidence.new_capture_id() - first = evidence.Lock(capture_id) - first.acquire() - try: - with self.assertRaisesRegex(evidence.EvidenceError, "another writer"): - evidence.Lock(capture_id).acquire() - finally: - first.release() - # A lock left by a process that no longer exists is reclaimed. - stale = evidence.Lock(capture_id) - stale.path.write_text(json.dumps({"pid": 2**22 + 12345, "started_at": 0})) - reclaimed = evidence.Lock(capture_id) - reclaimed.acquire() - reclaimed.release() - # And an explicit override replaces a live-looking one. - stale.path.write_text(json.dumps({"pid": os.getpid(), "started_at": 0})) - forced = evidence.Lock(capture_id) - forced.acquire(break_lock=True) - forced.release() - - -class GuardTests(EvidenceTests): - """Each of these fails if its guard is removed; verified by negative control.""" - - def test_ci_from_the_wrong_repository_is_refused(self): - """A repository-prefix URL check is not proof: the answer must name it too. - - Removing the identity comparison in `verify_ci_scope` makes this test - pass with foreign CI recorded, so it is the guard's own test. - """ - self.build_report() - gh = FakeGh() - member = self.routes(gh) - for group, path in (("check_runs", "check-runs"), ("statuses", "status")): - gh.on(f"/repos/{BASE_NAME}/commits/{member['head_sha']}/{path}", None, - repository={"id": 999999, "full_name": "someone/else"}, sha=member["head_sha"]) - capture_id, manifest, _ = self.capture(gh) - entry = next(e for e in manifest["components"] - if e["component"] == "checks" and e["number"] == member["number"]) - for group in entry["groups"]: - if group["group"] in ("check_runs", "statuses"): - self.assertEqual(group["status"], "blocked") - self.assertIn("someone/else", group["reason"]) - - def test_a_ci_answer_for_another_revision_is_refused(self): - self.build_report() - gh = FakeGh() - member = self.routes(gh) - gh.on(f"/repos/{BASE_NAME}/commits/{member['head_sha']}/check-runs", - {"total_count": 1, "check_runs": [{"id": 1, "head_sha": "d" * 40, - "name": "job"}]}) - capture_id, manifest, _ = self.capture(gh) - entry = next(e for e in manifest["components"] - if e["component"] == "checks" and e["number"] == member["number"]) - group = next(g for g in entry["groups"] if g["group"] == "check_runs") - self.assertEqual(group["status"], "blocked") - self.assertIn("revision", group["reason"]) - - def test_a_foreign_closing_issues_answer_is_refused(self): - self.build_report() - gh = FakeGh() - member = self.routes(gh) - gh.on("graphql", closing_payload(member["number"], repo="someone/else"), - graphql_number=member["number"]) - capture_id, manifest, _ = self.capture(gh) - entry = next(e for e in manifest["components"] - if e["component"] == "closing_issues" and e["number"] == member["number"]) - self.assertEqual(entry["status"], "blocked") - self.assertIn("someone/else", entry["reason"]) - - def test_a_closing_issues_graphql_error_is_refused_not_recorded_as_empty(self): - self.build_report() - gh = FakeGh() - member = self.routes(gh) - gh.on("graphql", {"errors": [{"message": "rate limited"}], "data": None}, - graphql_number=member["number"]) - capture_id, manifest, _ = self.capture(gh) - entry = next(e for e in manifest["components"] - if e["component"] == "closing_issues" and e["number"] == member["number"]) - self.assertEqual(entry["status"], "blocked") - self.assertIn("errors", entry["reason"]) diff --git a/tests/test_evidence_packet.py b/tests/test_evidence_packet.py deleted file mode 100644 index f87dbd8..0000000 --- a/tests/test_evidence_packet.py +++ /dev/null @@ -1,292 +0,0 @@ -"""Synthetic portable contract cases; no GitHub, model, or capture implementation.""" -import base64 -import copy -import json -import unittest -from pathlib import Path -from unittest.mock import patch - -import mcp_server -import tranche -from tests import evidence_contract as contract -from tests import test_tranche as native - -FIXTURES = Path(__file__).parent / "fixtures" / "evidence" -OBSERVED = "2026-01-03T00:00:00Z" - - -def fixture(name): - return contract.parse((FIXTURES / f"{name}.json").read_bytes()) - - -def make_packet(selection, complete=False, capture_id="c" * 32): - """Build only synthetic bytes, also reusable by native-binding tests.""" - packet = {"format": contract.FORMAT, "profile": contract.PROFILE, - "selection": copy.deepcopy(selection), - "membership_digest": contract.digest(selection["batch"]["members"]), - "capture_id": capture_id, - "generation": contract.generation(selection, capture_id), "complete": complete, - "capture": {"observed_at": OBSERVED, "request_limit": 20 if complete else 3, - "requests_used": 17 if complete else 3, - "stop_reason": None if complete else "request_budget"}, - "coverage": [], "sources": [], "citations": []} - for member in selection["members"]: - for component in contract.COMPONENTS: - captured = complete or (member["number"] == 1 and component in ("metadata", "diff", "files")) - pages = 2 if complete and member["number"] == 1 and component == "files" else 1 - coverage = {"number": member["number"], "component": component, - "status": "missing", "source_ids": [], "next_cursor": None, - "reason": "request_budget"} - if captured: - for page in range(1, pages + 1): - continued = member["number"] == 1 and component == "files" and page == 1 - # Include multibyte UTF-8 and hostile text; neither is executable. - body = (f"Synthetic #{member['number']} {component} page {page}: café\n" - "\n").encode() - source = {"number": member["number"], "component": component, "page": page, - "cursor": None if page == 1 else "page:2", - "next_cursor": "page:2" if continued else None, - "url": f"https://api.github.com/repos/{selection['repository']['full_name']}" - f"/pulls/{member['number']}/{component}?page={page}", - "media_type": "text/plain", "captured_at": OBSERVED, - "body_base64": base64.b64encode(body).decode(), - "body_sha256": contract.byte_digest(body)} - source["id"] = contract.source_id(packet["generation"], source) - packet["sources"].append(source) - coverage["source_ids"].append(source["id"]) - start = body.index("é".encode()) - packet["citations"].append({"id": f"{member['number']}:{component}:{page}", - "source_id": source["id"], - "source_sha256": source["body_sha256"], - "start_byte": start, "end_byte": start + 2, - "excerpt_sha256": contract.byte_digest("é".encode())}) - coverage["next_cursor"] = packet["sources"][-1]["next_cursor"] - coverage["status"] = "partial" if coverage["next_cursor"] else "complete" - coverage["reason"] = "request_budget" if coverage["next_cursor"] else None - packet["coverage"].append(coverage) - return contract.seal(packet) - - -class PacketTests(unittest.TestCase): - def test_portable_fixtures_and_exact_utf8_citations(self): - for name in ("partial", "resumed", "revision-drift"): - with self.subTest(name=name): - packet = contract.validate(fixture(name)) - for citation in packet["citations"]: - source = next(s for s in packet["sources"] if s["id"] == citation["source_id"]) - body = base64.b64decode(source["body_base64"]) - self.assertEqual(body[citation["start_byte"]:citation["end_byte"]], "é".encode()) - - def test_partial_resume_retains_generation_and_prior_bytes(self): - partial, resumed = fixture("partial"), fixture("resumed") - contract.validate_resume(partial, resumed) - self.assertFalse(partial["complete"]) - self.assertTrue(resumed["complete"]) - self.assertEqual(partial["generation"], resumed["generation"]) - self.assertNotEqual(partial["packet_digest"], resumed["packet_digest"]) - - def test_revision_drift_requires_a_new_generation(self): - previous, drift = fixture("partial"), fixture("revision-drift") - self.assertEqual(previous["selection"]["batch"]["id"], drift["selection"]["batch"]["id"]) - self.assertNotEqual(previous["generation"], drift["generation"]) - with self.assertRaises(ValueError): - contract.validate_resume(previous, drift) - - def test_fresh_capture_with_unchanged_selection_is_not_a_resume(self): - previous = fixture("partial") - fresh = make_packet(previous["selection"], True, capture_id="d" * 32) - contract.validate(fresh, previous["selection"]) - self.assertNotEqual(fresh["generation"], previous["generation"]) - with self.assertRaisesRegex(ValueError, "resume generation"): - contract.validate_resume(previous, fresh) - - def test_invalidated_capture_cannot_resume_and_fresh_capture_validates(self): - for reason in ("revision_drift", "visibility_revoked"): - with self.subTest(reason=reason): - previous = fixture("partial") - previous["capture"]["stop_reason"] = reason - contract.validate(contract.seal(previous)) - resumed = make_packet(previous["selection"], True) - contract.validate(resumed, previous["selection"]) - self.assertEqual(resumed["generation"], previous["generation"]) - self.assertIsNone(resumed["capture"]["stop_reason"]) - with self.assertRaisesRegex(ValueError, "capture invalidated"): - contract.validate_resume(previous, resumed) - fresh = make_packet(previous["selection"], True, capture_id="d" * 32) - contract.validate(fresh, previous["selection"]) - self.assertNotEqual(fresh["generation"], previous["generation"]) - - def test_resealed_tampering_cannot_pass_semantic_validation(self): - # Recompute the outer checksum, so these exercise relationships, not just integrity. - mutations = { - "unsupported version": lambda p: p.update(format="tranche.evidence-packet/v2"), - "boolean number": lambda p: p["selection"]["members"][0].update(number=True), - "short revision": lambda p: p["selection"]["members"][0].update(base_sha="abc"), - "wrong membership": lambda p: p.update(membership_digest="0" * 64), - "mixed generation": lambda p: p.update(generation="0" * 64), - "missing coverage": lambda p: p["coverage"].pop(), - "duplicate coverage": lambda p: p["coverage"].append(p["coverage"][0]), - "complete partial": lambda p: p.update(complete=True), - "duplicate source": lambda p: p["sources"].append(p["sources"][0]), - "source outside repository": lambda p: p["sources"][0].update(url="https://evil.invalid/"), - "URL credential": lambda p: p["sources"][0].update( - url=p["sources"][0]["url"] + "&access_token=synthetic"), - "corrupt body": lambda p: p["sources"][0].update(body_base64="ZmFrZQ=="), - "invalid base64": lambda p: p["sources"][0].update(body_base64="!!!"), - "future source": lambda p: p["sources"][0].update(captured_at="2027-01-01T00:00:00Z"), - "dangling citation": lambda p: p["citations"][0].update(source_id="0" * 64), - "wrong source digest": lambda p: p["citations"][0].update(source_sha256="0" * 64), - "wrong excerpt": lambda p: p["citations"][0].update(excerpt_sha256="0" * 64), - "range overflow": lambda p: p["citations"][0].update(end_byte=10000), - "duplicate citation": lambda p: p["citations"].append(p["citations"][0]), - "request overrun": lambda p: p["capture"].update(requests_used=21), - "unexpected local path": lambda p: p.update(artifact_path="../private"), - } - for name, mutate in mutations.items(): - with self.subTest(name=name): - packet = fixture("partial") - mutate(packet) - with self.assertRaises(ValueError): - contract.validate(contract.seal(packet)) - - def test_pagination_cannot_claim_completion_with_a_continuation(self): - packet = fixture("partial") - files = next(c for c in packet["coverage"] if c["status"] == "partial") - files.update(status="complete", reason=None) - with self.assertRaisesRegex(ValueError, "incomplete pagination"): - contract.validate(contract.seal(packet)) - - def test_resume_refuses_valid_rewrites_and_coverage_regression(self): - partial = fixture("partial") - changed = copy.deepcopy(partial["selection"]) - for field, value in (("base_sha", "e" * 40), ("head_sha", "f" * 40), - ("updated_at", "2026-01-04T00:00:00Z"), - ("source_digest", "1" * 64)): - with self.subTest(field=field): - selection = copy.deepcopy(changed) - selection["members"][0][field] = value - with self.assertRaises(ValueError): - contract.validate_resume(partial, make_packet(selection, True)) - with self.assertRaises(ValueError): - contract.validate_resume(fixture("resumed"), partial) - rewritten = make_packet(partial["selection"], True) - rewritten["citations"][0].update(start_byte=0, end_byte=1, - excerpt_sha256=contract.byte_digest(b"S")) - contract.seal(rewritten) - contract.validate(rewritten) - with self.assertRaisesRegex(ValueError, "rewrites evidence"): - contract.validate_resume(partial, rewritten) - - def test_full_serialized_limits_and_ambiguous_json(self): - packet = fixture("resumed") - data = contract.encode(packet) - contract.validate(contract.parse(data, len(data)), max_bytes=len(data)) - with self.assertRaises(ValueError): - contract.parse(b" " + data, len(data)) - with self.assertRaises(ValueError): - contract.validate(packet, max_bytes=len(data) - 1) - for data in (b'{"x":1,"x":2}', b'{"x":NaN}', b'\xff', b'{'): - with self.subTest(data=data), self.assertRaises(ValueError): - contract.parse(data) - - def test_parse_rejects_overflow_exponent_floats(self): - for data in (b'{"x":1e999}', b'{"x":-1e999}'): - with self.subTest(data=data), self.assertRaisesRegex(ValueError, "non-finite JSON number"): - contract.parse(data) - self.assertEqual(contract.parse(b'{"x":1e308}'), {"x": 1e308}) - - def test_visibility_revocation_and_repository_rename_block_sharing(self): - packet = fixture("resumed") - repository = packet["selection"]["repository"] - contract.validate_sharing(packet, repository) - for key, value in (("visibility", "private"), ("id", 2), ("full_name", "example/other")): - with self.subTest(key=key), self.assertRaises(ValueError): - contract.validate_sharing(packet, {**repository, key: value}) - - -class NativeBindingTests(unittest.TestCase): - setUp = native.WorkflowTests.setUp - inputs = native.WorkflowTests.inputs - judgments = native.WorkflowTests.judgments - pairs = native.WorkflowTests.pairs - cluster = native.WorkflowTests.cluster - - def selection(self, *, revision_drift=False): - # Exercise today's producer/MCP without consulting the committed corpus. - with patch.object(tranche, "REPO", "example/widgets"): - synthetic = {n: native.pr(n, head={"sha": str(n) * 40}, - base={"sha": "a" * 40}) for n in (1, 2)} - if revision_drift: - synthetic[1].update(head={"sha": "b" * 40}, updated_at=OBSERVED) - prs = self.inputs(list(synthetic.values())) - self.judgments(prs) - self.pairs(prs, []) - self.cluster() - dupes = json.loads((self.out / "dupes.json").read_text()) - judgments = tranche.current_judgments(prs) - tranche.atomic_json(self.out / "batches.json", tranche.merge_batches( - dupes, judgments, prs, tranche.digest(dupes))) - tranche.atomic_json(self.out / "parked.json", tranche.parked_payload( - tranche.park_state(dupes, judgments, prs), prs, judgments, tranche.digest(dupes))) - picked = mcp_server.Reports().pick("B001") - return {"repository": {"id": 1000001, "full_name": "example/widgets", "visibility": "public"}, - "report": {"report_binding": picked["digests"]["report_binding"], - "output_digests": {name: picked["digests"][name] for name in - ("clusters.json", "dupes.json", "batches.json", "parked.json")}}, - "batch": picked["batch"], - "members": [{"number": n, "source_digest": prs[n]["source_digest"], - "evidence_digest": prs[n]["evidence_digest"], - "base_sha": synthetic[n]["base"]["sha"], - "head_sha": prs[n]["head_sha"], "updated_at": prs[n]["updated"]} - for n in picked["batch"]["members"]]} - - def test_partial_and_resumed_fixtures_match_current_native_bindings(self): - selection = self.selection() - partial, resumed = fixture("partial"), fixture("resumed") - contract.validate(partial, selection) - contract.validate(resumed, selection) - self.assertEqual(partial, make_packet(selection)) - expected = make_packet(selection, True) - expected["capture"]["observed_at"] = "2026-01-03T00:01:00Z" - self.assertEqual(resumed, contract.seal(expected)) - - def test_revision_drift_fixture_matches_changed_native_bindings(self): - selection = self.selection(revision_drift=True) - drift, partial = fixture("revision-drift"), fixture("partial") - contract.validate(drift, selection) - self.assertEqual(drift, make_packet(selection)) - self.assertEqual(partial["selection"]["batch"], selection["batch"]) - for field in ("report_binding", "output_digests"): - self.assertNotEqual(partial["selection"]["report"][field], selection["report"][field]) - for field in ("source_digest", "evidence_digest", "head_sha", "updated_at"): - self.assertNotEqual(partial["selection"]["members"][0][field], selection["members"][0][field]) - self.assertEqual(selection["members"][0]["head_sha"], "b" * 40) - self.assertEqual(selection["members"][0]["updated_at"], OBSERVED) - self.assertEqual(partial["selection"]["members"][1], selection["members"][1]) - self.assertNotEqual(partial["generation"], drift["generation"]) - self.assertNotEqual(partial["sources"][0]["id"], drift["sources"][0]["id"]) - - def test_native_report_batch_prompt_and_member_bindings(self): - selection = self.selection() - packet = make_packet(selection, True) - contract.validate(packet, selection) - self.assertEqual(packet["selection"]["batch"]["review_prompt"].encode(), - selection["batch"]["review_prompt"].encode()) - for field in ("report_binding", "output_digests"): - stale = copy.deepcopy(selection) - stale["report"][field] = "0" * 64 if field == "report_binding" else { - **stale["report"][field], "batches.json": "0" * 64} - with self.subTest(field=field), self.assertRaises(ValueError): - contract.validate(make_packet(stale, True), selection) - for key, value in (("id", 2), ("full_name", "example/other")): - stale = copy.deepcopy(selection) - stale["repository"][key] = value - with self.subTest(key=key), self.assertRaises(ValueError): - contract.validate(make_packet(stale, True), selection) - for key, value in (("review_prompt", "changed prompt"), ("members", [2, 1])): - stale = copy.deepcopy(selection) - stale["batch"][key] = value - if key == "members": - stale["members"].reverse() - with self.subTest(key=key), self.assertRaises(ValueError): - contract.validate(make_packet(stale, True), selection) diff --git a/tests/test_evidence_regressions.py b/tests/test_evidence_regressions.py deleted file mode 100644 index 059427f..0000000 --- a/tests/test_evidence_regressions.py +++ /dev/null @@ -1,70 +0,0 @@ -"""Regressions for defects found while landing the native evidence CLI.""" -import os -import time - -import evidence -from tests.test_evidence import EvidenceTests, FakeGh, BASE_NAME, metadata_payload - - -class LandingRegressions(EvidenceTests): - def test_ci_pagination_counts_all_pages(self): - self.build_report() - gh = FakeGh() - member = self.routes(gh) - endpoint = f"/repos/{BASE_NAME}/commits/{member['head_sha']}/check-runs" - gh.on(endpoint, None, pages={ - 1: {"payload": {"total_count": 2, "check_runs": [{"head_sha": member['head_sha']}]}, - "link": f'; rel="next"'}, - 2: {"payload": {"total_count": 2, "check_runs": [{"head_sha": member['head_sha']}]}} - }) - _, manifest, _ = self.capture(gh) - state = evidence.group_entry(manifest, member['number'], 'checks', 'check_runs') - self.assertEqual(state['items_observed'], 2) - self.assertEqual(state['status'], 'complete') - - def test_live_writer_is_not_reclaimed_after_ttl(self): - first = evidence.Lock('1' * 32, ttl=1) - first.acquire() - self.addCleanup(first.release) - os.utime(first.path, (time.time() - 10, time.time() - 10)) - second = evidence.Lock('1' * 32, ttl=1) - self.addCleanup(second.release) - with self.assertRaisesRegex(evidence.EvidenceError, 'another writer'): - second.acquire() - - def test_body_reads_refuse_symlinks_even_with_matching_digest(self): - import hashlib - self.build_report() - data = b'outside evidence root' - sha = hashlib.sha256(data).hexdigest() - outside = self.out / 'outside.bin' - outside.write_bytes(data) - path = evidence.body_path(sha) - path.parent.mkdir(parents=True, exist_ok=True) - path.symlink_to(outside) - with self.assertRaisesRegex(evidence.EvidenceError, 'symlink'): - evidence.read_body(sha) - - def test_invalidated_capture_cannot_resume_even_if_revision_returns(self): - self.build_report() - gh = FakeGh() - self.routes(gh) - capture_id, manifest, _ = self.capture(gh) - manifest['capture']['stop_reason'] = 'revision_drift' - evidence.write_manifest(capture_id, manifest) - with self.assertRaisesRegex(evidence.SelectionError, 'invalidated'): - self.capture(gh, capture_id=capture_id) - - def test_revision_drift_after_acquisition_invalidates_capture(self): - self.build_report() - gh = FakeGh() - member = self.routes(gh) - reads = [] - - def moving_metadata(call): - reads.append(call) - return metadata_payload(member, head_sha='c' * 40 if len(reads) > 2 else None) - - gh.on(f"/repos/{BASE_NAME}/pulls/{member['number']}", moving_metadata) - with self.assertRaises(evidence.SelectionError): - self.capture(gh) diff --git a/tests/test_ghread.py b/tests/test_ghread.py deleted file mode 100644 index 00dc08e..0000000 --- a/tests/test_ghread.py +++ /dev/null @@ -1,288 +0,0 @@ -"""Offline tests for the bounded read transport: URL policy, bounds, request shape. - -No network and no `gh` invocation: `run_gh` is replaced with recorded output and -`invoke` with recorded responses, so the assertions are about the request that -would be constructed and the rules applied to the answer. -""" -import json -import sys -import unittest -from unittest.mock import patch - -import ghread - - -def block(status, headers=(), body=b"", version=b"HTTP/2.0"): - lines = [version + b" " + status] - lines += [f"{key}: {value}".encode() for key, value in headers] - return b"\r\n".join(lines) + b"\r\n\r\n" + body - - -class UrlPolicyTests(unittest.TestCase): - def test_accepts_only_https_api_github_com_without_fragment_or_credentials(self): - self.assertEqual(ghread.validate_url("https://api.github.com/repos/o/r/pulls/1"), - "https://api.github.com/repos/o/r/pulls/1") - for url in ("http://api.github.com/repos/o/r", - "https://api.github.com.evil.example/repos/o/r", - "https://evil.example/repos/o/r", - "https://token@api.github.com/repos/o/r", - "https://api.github.com/repos/o/r#frag", - "https://api.github.com/repos/o/r?access_token=abc", - "https://api.github.com/repos/o/r?client_secret=x", - "https://api.github.com/repos/o/r\nHost: evil", - "", - None, - 7): - with self.subTest(url=url), self.assertRaises(ghread.ReadError): - ghread.validate_url(url) - - def test_repository_prefix_is_enforced_when_requested(self): - ghread.validate_url("https://api.github.com/repos/o/r/pulls/1", "o/r") - for url in ("https://api.github.com/repos/o/other/pulls/1", - "https://api.github.com/repos/other/r/pulls/1", - "https://api.github.com/graphql"): - with self.subTest(url=url), self.assertRaises(ghread.ReadError): - ghread.validate_url(url, "o/r") - - def test_next_link_reads_only_the_next_relation_and_validates_it(self): - header = ('; rel="next", ' - '; rel="last"') - self.assertEqual(ghread.parse_next_link(header), - "https://api.github.com/repos/o/r/pulls?page=2") - self.assertEqual(ghread.parse_next_link('; rel="last"'), None) - self.assertEqual(ghread.parse_next_link(None), None) - self.assertEqual(ghread.parse_next_link(""), None) - for hostile in ('; rel="next"', - '; rel="next"', - '; rel="next"'): - with self.subTest(hostile=hostile), self.assertRaises(ghread.ReadError): - ghread.parse_next_link(hostile) - - -class BudgetTests(unittest.TestCase): - def test_every_attempt_counts_including_failures_and_reserved_capacity(self): - budget = ghread.Budget(3, reserved=1) - budget.charge() - budget.charge() - with self.assertRaises(ghread.BudgetExhausted): - budget.charge() # the third would eat the reserve - budget.charge(reserve=0) - self.assertEqual(budget.used, 3) - self.assertEqual(budget.remaining, 0) - with self.assertRaises(ghread.BudgetExhausted): - budget.charge(reserve=0) - budget.failures += 2 - summary = budget.summary() - self.assertEqual((summary["limit"], summary["used"], summary["reserved"], - summary["failures"]), (3, 3, 1, 2)) - for limit, reserved in ((-1, 0), (2, 5), (2, -1), (2.5, 0), (True, 0)): - with self.subTest(limit=limit, reserved=reserved), self.assertRaises(ghread.ReadError): - ghread.Budget(limit, reserved=reserved) - - -class ResponseParsingTests(unittest.TestCase): - def test_multi_hop_include_output_uses_the_final_status_and_headers(self): - raw = (block(b"301 Moved Permanently", [("location", "https://api.github.com/b")], b"") - + block(b"200 OK", [("content-type", "application/json; charset=utf-8"), - ("link", '; rel="next"')], - b'[{"number":1}]')) - blocks, body = ghread._split_response(raw) - self.assertEqual(len(blocks), 2) - self.assertEqual(ghread._status(blocks[-1]), 200) - self.assertEqual(body, b'[{"number":1}]') - self.assertEqual(ghread._headers(blocks[-1])["content-type"], - "application/json; charset=utf-8") - response = ghread.Response(200, "https://api.github.com/x", ghread._headers(blocks[-1]), body) - self.assertEqual(response.next_url, "https://api.github.com/repos/o/r/pulls?page=2") - self.assertEqual(response.json(), [{"number": 1}]) - - def test_truncated_or_unreadable_bodies_are_never_parsed_as_json(self): - response = ghread.Response(200, "u", {}, b'{"partial"', truncated=True) - with self.assertRaises(ghread.ResponseTooLarge): - response.json() - with self.assertRaises(ghread.ReadError): - ghread.Response(200, "u", {}, b"not json").json() - with self.assertRaises(ghread.ReadError): - ghread._split_response(b"not an http response") - - def test_declared_oversized_body_is_refused_before_it_is_read(self): - result = ghread.RawResult(0, block(b"200 OK", [("content-length", "999999999")], b"{}"), b"") - with patch.object(ghread, "run_gh", return_value=result): - with self.assertRaises(ghread.ResponseTooLarge): - ghread.invoke(["gh", "api", "x"], max_bytes=1024) - - -class RequestConstructionTests(unittest.TestCase): - def test_rest_read_is_an_explicit_get_with_bounded_output(self): - result = ghread.RawResult(0, block(b"200 OK", [("content-type", "application/json")], - b'{"ok":true}'), b"") - recorded = {} - - def fake_run(argv, **kwargs): - recorded["argv"] = argv - recorded["kwargs"] = kwargs - return result - - with patch.object(ghread, "run_gh", side_effect=fake_run): - response = ghread.read("https://api.github.com/repos/o/r/pulls/1", - accept="application/vnd.github.diff", budget=ghread.Budget(5)) - argv = recorded["argv"] - self.assertEqual(argv[:4], ["gh", "api", "--include", "--method"]) - self.assertEqual(argv[4], "GET") - self.assertIn("https://api.github.com/repos/o/r/pulls/1", argv) - self.assertLess(argv.index("https://api.github.com/repos/o/r/pulls/1"), - argv.index("accept: application/vnd.github.diff")) - self.assertEqual(argv[argv.index("accept: application/vnd.github.diff") - 1], "-H") - self.assertNotIn("--input", argv) - joined = " ".join(argv).lower() - self.assertNotIn("authorization", joined) - self.assertNotIn("token", joined) - self.assertEqual(response.body, b'{"ok":true}') - self.assertEqual(response.status, 200) - - def test_redirects_are_followed_only_within_the_allowed_origin(self): - moved = ghread.RawResult(0, block(b"302 Found", - [("location", "https://api.github.com/repos/o/r/pulls/2")], - b""), b"") - final = ghread.RawResult(0, block(b"200 OK", [("content-type", "application/json")], b"[]"), b"") - calls = [] - - def fake_run(argv, **kwargs): - calls.append(argv[-1]) - return moved if len(calls) == 1 else final - - with patch.object(ghread, "run_gh", side_effect=fake_run): - response = ghread.read("https://api.github.com/repos/o/r/pulls/1", budget=ghread.Budget(5)) - self.assertEqual(len(calls), 2) - self.assertEqual(response.url, "https://api.github.com/repos/o/r/pulls/2") - with patch.object(ghread, "run_gh", return_value=ghread.RawResult( - 0, block(b"302 Found", [("location", "https://evil.example/x")], b""), b"")): - with self.assertRaises(ghread.ReadError): - ghread.read("https://api.github.com/repos/o/r/pulls/1", budget=ghread.Budget(5)) - - def test_every_attempt_is_charged_and_failures_are_counted(self): - budget = ghread.Budget(2) - with patch.object(ghread, "run_gh", return_value=ghread.RawResult( - 1, block(b"500 Server Error", [], b""), b"boom")): - with self.assertRaises(ghread.ReadError): - ghread.read("https://api.github.com/repos/o/r/pulls/1", budget=budget) - self.assertEqual(budget.used, 1) - self.assertEqual(budget.failures, 1) - with patch.object(ghread, "run_gh", return_value=ghread.RawResult( - 0, block(b"404 Not Found", [], b"{}"), b"")) as run: - with self.assertRaisesRegex(ghread.ReadError, "404"): - ghread.read("https://api.github.com/repos/o/r/pulls/1", budget=budget) - self.assertEqual(budget.used, 2) - with self.assertRaises(ghread.BudgetExhausted): - ghread.read("https://api.github.com/repos/o/r/pulls/1", budget=budget) - self.assertEqual(run.call_count, 1) - - def test_graphql_is_a_query_only_and_never_carries_the_document_in_argv(self): - result = ghread.RawResult(0, block(b"200 OK", [("content-type", "application/json")], - b'{"data":{"ok":true}}'), b"") - recorded = {} - - def fake_run(argv, **kwargs): - recorded["argv"] = argv - recorded["stdin"] = kwargs.get("stdin_data") - return result - - with patch.object(ghread, "run_gh", side_effect=fake_run): - response = ghread.graphql( - "query($owner:String!){ repository(owner:$owner){ id } }", - {"owner": "o"}, budget=ghread.Budget(4)) - self.assertEqual(recorded["argv"][-2:], ["--input", "-"]) - self.assertEqual(recorded["argv"][recorded["argv"].index("--method") + 1], "POST") - payload = json.loads(recorded["stdin"]) - self.assertIn("query", payload["query"]) - self.assertEqual(payload["variables"], {"owner": "o"}) - self.assertEqual(response.json()["data"], {"ok": True}) - for document in ("mutation { deleteThing }", "subscription { x }", - "not a query", "", None): - with self.subTest(document=document), self.assertRaises(ghread.ReadError): - ghread.graphql(document) - - def test_diagnostics_are_short_and_credential_free(self): - detail = ghread._diagnostic(b"gh: Not Found (HTTP 404)\nfatal: token=ghp_secretvalue\n") - self.assertNotIn("ghp_secretvalue", detail) - self.assertIn("REDACTED", detail) - - -class SubprocessBoundTests(unittest.TestCase): - """The one place a real child process runs: output must be genuinely bounded.""" - - def test_oversized_stdout_is_truncated_and_the_child_is_stopped(self): - writer = "import sys; sys.stdout.write('x' * 5_000_000)" - result = ghread.run_gh([sys.executable, "-c", writer], timeout=30, max_bytes=4096) - self.assertTrue(result.truncated) - self.assertEqual(len(result.stdout), 4096) - self.assertNotEqual(result.returncode, 0) # killed, not merely ignored - - def test_normal_output_is_returned_intact_with_stderr_captured(self): - script = "import sys; sys.stdout.write('{\"a\":1}'); sys.stderr.write('note')" - result = ghread.run_gh([sys.executable, "-c", script], timeout=30, max_bytes=4096) - self.assertFalse(result.truncated) - self.assertEqual(result.stdout, b'{"a":1}') - self.assertEqual(result.stderr, b"note") - self.assertEqual(result.returncode, 0) - - def test_a_hanging_child_is_killed_within_the_timeout(self): - script = "import time; time.sleep(300)" - result = ghread.run_gh([sys.executable, "-c", script], timeout=1, max_bytes=4096) - self.assertTrue(result.timed_out) - self.assertEqual(result.returncode, -9) - - def test_stdin_payload_reaches_the_child(self): - script = "import sys; sys.stdout.buffer.write(sys.stdin.buffer.read())" - result = ghread.run_gh([sys.executable, "-c", script], timeout=30, - max_bytes=4096, stdin_data=b'{"query":"query{x}"}') - self.assertEqual(result.stdout, b'{"query":"query{x}"}') - self.assertEqual(result.returncode, 0) - - -class InvokeIntegrationTests(unittest.TestCase): - def test_invoke_parses_recorded_gh_output_without_running_gh(self): - raw = block(b"200 OK", [("content-type", "application/json; charset=utf-8")], b"[1,2,3]") - with patch.object(ghread, "run_gh", return_value=ghread.RawResult(0, raw, b"")): - status, headers, body, truncated, hops = ghread.invoke(["gh", "api", "x"]) - self.assertEqual((status, body, truncated, hops), - (200, b"[1,2,3]", False, 1)) - self.assertEqual(headers["content-type"], "application/json; charset=utf-8") - self.assertIsInstance(hops, int) - - def test_gh_failure_without_output_becomes_a_read_error(self): - with patch.object(ghread, "run_gh", return_value=ghread.RawResult( - 1, b"", b"gh: authentication required\n")): - with self.assertRaisesRegex(ghread.ReadError, "authentication required"): - ghread.invoke(["gh", "api", "x"]) - - -if __name__ == "__main__": - unittest.main() - - -class MutationRefusalTests(unittest.TestCase): - """The GraphQL seam must refuse anything that is not a read-only query.""" - - def test_mutations_and_subscriptions_are_refused_before_any_request(self): - recorded = [] - - def fake_run(argv, **kwargs): - recorded.append(argv) - return ghread.RawResult(0, b'HTTP/2.0 200 OK\r\n\r\n{"data":{}}', b"") - - for document in ("mutation { deleteIssue(input:{}) { clientMutationId } }", - "query { repository(owner:\"o\",name:\"r\") { id } } " - "mutation { deleteThing }", - "subscription { issues { number } }", - "{ repository(owner:\"o\",name:\"r\") { id } }"): - with self.subTest(document=document[:24]): - with patch.object(ghread, "run_gh", side_effect=fake_run): - if "mutation" in document or "subscription" in document: - with self.assertRaises(ghread.ReadError): - ghread.graphql(document) - else: - ghread.graphql(document) - # Exactly the one legal query reached a subprocess; every mutation, - # subscription and mixed document was refused before any request. - self.assertEqual(len(recorded), 1) diff --git a/tests/test_release_config.py b/tests/test_release_config.py deleted file mode 100644 index de24993..0000000 --- a/tests/test_release_config.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Check the release contract without bumping files or creating Git tags.""" - -import json -import shutil -import subprocess -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] - - -@unittest.skipUnless(shutil.which("node"), "Node is optional except when releasing") -class ReleaseConfigTests(unittest.TestCase): - def test_version_surface_and_repository_links(self): - result = subprocess.run(["node", "-e", """ - const c = require('./.versionrc.js'); - console.log(JSON.stringify(c)); - """], cwd=ROOT, capture_output=True, text=True, timeout=10) - self.assertEqual(result.returncode, 0, result.stderr) - config = json.loads(result.stdout) - surface = {"filename": "VERSION", "type": "plain-text"} - self.assertEqual(config["packageFiles"], [surface]) - self.assertEqual(config["bumpFiles"], [surface]) - self.assertEqual(config["tagPrefix"], "v") - self.assertEqual(config["releaseCommitMessageFormat"], - "chore(release): {{currentTag}}") - for field in ("commitUrlFormat", "compareUrlFormat", "issueUrlFormat"): - self.assertTrue(config[field].startswith("https://github.com/blackopsrepl/Tranche/")) - self.assertEqual(config["scripts"]["prerelease"], "make release-check") - self.assertRegex((ROOT / "VERSION").read_text(), r"^\d+\.\d+\.\d+\n?$") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_report_loader.py b/tests/test_report_loader.py deleted file mode 100644 index cd699fd..0000000 --- a/tests/test_report_loader.py +++ /dev/null @@ -1,155 +0,0 @@ -"""Parity tests for the extracted bound-report seam. - -`report_loader.load()` is the single authority for reading a bound report; the -MCP server and the evidence CLI both consume it. These tests pin that they -cannot drift: the same mutations must be refused by both, the served identity -must be the loader's identity, and the loader must carry no MCP response limit. -""" -import json -import sys -import unittest -from pathlib import Path - -import report_loader -import tranche -from tests import test_tranche as fixtures - -pr = fixtures.pr - - -class ReportLoaderTests(unittest.TestCase): - setUp = fixtures.WorkflowTests.setUp - inputs = fixtures.WorkflowTests.inputs - judgments = fixtures.WorkflowTests.judgments - pairs = fixtures.WorkflowTests.pairs - cluster = fixtures.WorkflowTests.cluster - - def core(self): - import mcp_server - return mcp_server - - def reports(self, *, batches=True, parked=True): - prs = self.inputs([pr(1), pr(2, draft=True), pr(3)]) - self.judgments(prs) - self.pairs(prs, []) - self.cluster() - dupes = json.loads((self.out / "dupes.json").read_text()) - judgments = tranche.current_judgments(prs) - if batches: - tranche.atomic_json(self.out / "batches.json", tranche.merge_batches( - dupes, judgments, prs, tranche.digest(dupes))) - if parked: - tranche.atomic_json(self.out / "parked.json", tranche.parked_payload( - tranche.park_state(dupes, judgments, prs), prs, judgments, tranche.digest(dupes))) - return prs - - def test_the_loader_and_the_mcp_server_refuse_the_same_mutations(self): - core = self.core() - for target, field, value in ( - ("summary.json", "allow_unbound", True), - ("summary.json", "format_version", 1), - ("summary.json", "repo", "foreign/repo"), - ("summary.json", "report_binding", "wrong"), - ("clusters.json", "tampered", True), - ("dupes.json", "tampered", True), - ("batches.json", "batch_size", 99), - ("parked.json", "parked", 999), - ): - with self.subTest(target=target, field=field): - self.reports() - path = self.out / target - data = json.loads(path.read_text()) - data[field] = value - path.write_text(json.dumps(data)) - with self.assertRaises(report_loader.ReportError): - report_loader.load() - with self.assertRaises(core.ReportError): - core.Reports().surface() - # A moved head and a changed judgment are refused by both, identically. - self.reports() - self.inputs([pr(1, head={"sha": "moved"}), pr(2, draft=True), pr(3)]) - with self.assertRaises(report_loader.ReportError): - report_loader.load() - with self.assertRaises(core.ReportError): - core.Reports().surface() - - def test_the_loader_refuses_a_park_record_that_is_missing_or_drifted(self): - self.reports() - parked = json.loads((self.out / "parked.json").read_text()) - parked["members"][0]["reasons"] = ["mutated"] - (self.out / "parked.json").write_text(json.dumps(parked)) - with self.assertRaises(report_loader.ReportError): - report_loader.load() - # Batches that parked PRs without their park record are incomplete evidence. - self.reports() - (self.out / "parked.json").unlink() - with self.assertRaises(report_loader.ReportError): - report_loader.load() - - def test_the_served_identity_is_the_loaders_identity(self): - self.reports() - core = self.core() - served = core.Reports().digests()["digests"] - loaded = report_loader.load().identity - for key, value in loaded.items(): - self.assertEqual(served[key], value, key) - # input_bytes is added by the server's own concurrent-read guard only. - self.assertNotIn("input_bytes", loaded) - self.assertIn("input_bytes", served) - - def test_the_loader_carries_no_mcp_response_limit(self): - """A large report must load even though no MCP response could carry it.""" - self.reports() - core = self.core() - loaded = report_loader.load() - self.assertEqual(sorted(loaded.prs), [1, 2, 3]) - self.assertEqual(loaded.summary["prs_in_corpus"], 3) - self.assertIsNotNone(loaded.batches) - # The MCP layer keeps its own response bound, distinct from the file bound. - self.assertEqual(core.MAX_RESULT_BYTES, 1024 * 1024) - self.assertEqual((core.MAX_FILE_BYTES, core.MAX_TOTAL_BYTES, core.MAX_INPUT_FILES), - (report_loader.DEFAULT_LIMITS.max_file_bytes, - report_loader.DEFAULT_LIMITS.max_total_bytes, - report_loader.DEFAULT_LIMITS.max_input_files)) - with self.assertRaises(report_loader.ReportError): - report_loader.input_digests(report_loader.Limits(max_file_bytes=1)) - - def test_a_report_without_batches_or_park_still_loads(self): - self.reports(batches=False, parked=False) - loaded = report_loader.load() - self.assertIsNone(loaded.batches) - self.assertIsNone(loaded.parked) - self.assertIsNone(loaded.identity["batches.json"]) - self.assertIsNone(loaded.identity["parked.json"]) - self.assertFalse(self.core().Reports().surface()["batches_available"]) - - def test_the_seam_has_no_circular_import(self): - """`report_loader` is the bottom of the stack: it must not import consumers.""" - source = Path(report_loader.__file__).read_text() - self.assertNotIn("import mcp_server", source) - self.assertNotIn("import evidence", source) - self.assertIn("import tranche", source) - for name in ("report_loader", "mcp_server"): - module = sys.modules.get(name) - self.assertIsNotNone(module, name) - - def test_the_concurrent_read_fingerprint_now_covers_the_park_record(self): - """The served park record gates batches, so it must be fingerprinted too. - - Before this seam existed the fingerprint list stopped at batches.json, so - parked.json could change under a read without the guard noticing. - """ - self.reports() - digests = report_loader.input_digests() - parked = str(self.out / "parked.json") - batches = str(self.out / "batches.json") - self.assertIn(parked, digests) - self.assertIn(batches, digests) - self.assertIsNotNone(digests[parked]) - fingerprint = digests[parked] - (self.out / "parked.json").write_text("{}") - self.assertNotEqual(report_loader.input_digests()[parked], fingerprint) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_tranche.py b/tests/test_tranche.py deleted file mode 100644 index c6264f3..0000000 --- a/tests/test_tranche.py +++ /dev/null @@ -1,1235 +0,0 @@ -"""Offline regressions: synthetic PRs and mocked acquisition/model transports.""" - -import argparse -import copy -import io -import json -import shutil -import subprocess -import sys -import tempfile -import unittest -import urllib.error -from contextlib import redirect_stdout -from pathlib import Path -from unittest.mock import patch - -import tranche - - -def pr(number, **changes): - item = { - "number": number, - "title": "Fix widget after suspend", - "body": "Fix widget initialization.", - "user": {"login": "fixture"}, - "created_at": "2026-01-01T00:00:00Z", - "updated_at": "2026-01-02T00:00:00Z", - "head": {"sha": f"head-{number}"}, - "draft": False, - "labels": [], - } - item.update(changes) - return item - - -def answers(): - return { - "category": {"choice": "fix-misc"}, - "risk": {"score": 1}, - "finished_form": {"score": 2}, - "review_effort": {"score": 1}, - "is_fix": {"noul": 0.9}, - "security_flag": {"noul": 0.1}, - } - - -class WorkflowTests(unittest.TestCase): - def setUp(self): - self.directory = tempfile.TemporaryDirectory() - self.addCleanup(self.directory.cleanup) - self.root = Path(self.directory.name) - self.out = self.root / "out" - self.pages = self.root / "data" / "pages" - self.out.mkdir() - self.pages.mkdir(parents=True) - for name, value in { - "ROOT": self.root, - "OUT_DIR": self.out, - "PAGES_DIR": self.pages, - "JUDGMENTS_PATH": self.out / "judgments.jsonl", - "PAIRS_PATH": self.out / "pair_verdicts.jsonl", - }.items(): - context = patch.object(tranche, name, value) - context.start() - self.addCleanup(context.stop) - self.stdout = redirect_stdout(io.StringIO()) - self.stdout.__enter__() - self.addCleanup(self.stdout.__exit__, None, None, None) - # An unexpected key read/network call must fail the test, never contact a service. - self.key = patch.object( - tranche, "read_key", side_effect=AssertionError("unexpected key read") - ).start() - self.network = patch.object( - tranche.urllib.request, "urlopen", side_effect=AssertionError("unexpected network") - ).start() - self.model = patch.object( - tranche, "ask", side_effect=AssertionError("unexpected model call") - ).start() - self.addCleanup(patch.stopall) - - def inputs(self, items): - tranche.atomic_json( - self.pages / "snapshot.json", - { - "version": 1, - "repo": tranche.REPO, - "items": items, - "digest": tranche.digest(items), - "observed_at": "2026-01-02T00:00:00Z", - }, - ) - return tranche.load_prs() - - def judgments(self, prs, *, legacy=False, custom=None): - records = [ - {"number": n, "answers": copy.deepcopy(custom or answers()), "usage": {}} for n in prs - ] - for record in records: - if not legacy: - record["binding"] = tranche.judgment_binding(prs[record["number"]]) - tranche.JUDGMENTS_PATH.write_text("".join(json.dumps(r) + "\n" for r in records)) - return tranche.current_judgments(prs, allow_unbound=legacy) - - def pairs(self, prs, relationships, *, legacy=False): - records = [] - for a, b, verdict, probability in relationships: - a, b = sorted((a, b)) - record = { - "a": a, - "b": b, - "verdict": verdict, - "probabilities": {"same_change": probability}, - } - if not legacy: - record["binding"] = tranche.pair_binding(prs, a, b) - records.append(record) - tranche.PAIRS_PATH.write_text("".join(json.dumps(r) + "\n" for r in records)) - - def cluster(self, *, allow_unbound=False): - tranche.cmd_cluster(argparse.Namespace(allow_unbound=allow_unbound)) - return json.loads((self.out / "summary.json").read_text()), json.loads( - (self.out / "dupes.json").read_text() - ) - - def render(self): - for name in ("tranche.py", "gen_page.py", "page/template.html"): - target = self.root / name - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copy(Path(tranche.__file__).parent / name, target) - return subprocess.run( - [sys.executable, str(self.root / "gen_page.py")], - cwd=self.root, - text=True, - capture_output=True, - timeout=15, - ) - - def test_unknown_diffstat_is_distinct_from_true_zero(self): - prs = self.inputs([pr(1), pr(2, changed_files=0, additions=0, deletions=0)]) - state = tranche.pr_state(prs[1])["pr"] - self.assertFalse(state["diffstat_available"]) - self.assertIn("unknown", state["diffstat"]) - self.assertNotIn("0 files", state["diffstat"]) - self.assertEqual(tranche.pr_state(prs[2])["pr"]["diffstat"], "0 files changed, +0/-0") - for count in (-1, True, "0", None): - prs = self.inputs([pr(1, changed_files=count, additions=0, deletions=0)]) - self.assertFalse(tranche.pr_state(prs[1])["pr"]["diffstat_available"]) - - def test_binding_tracks_full_source_even_outside_body_projection(self): - original = pr(1, body="x" * 1500) - prs = self.inputs([original]) - self.judgments(prs) - self.assertTrue(prs[1]["body_truncated"]) - self.assertEqual(len(prs[1]["body"]), 1200) - for change in ( - {"body": "x" * 1500 + "new text"}, - {"head": {"sha": "new"}}, - {"updated_at": "later"}, - {"labels": [{"name": "new"}]}, - ): - with self.subTest(change=change): - updated = dict(original, **change) - self.assertEqual(tranche.current_judgments(self.inputs([updated])), {}) - prs = self.inputs([original]) - with patch.object(tranche, "MODEL", "different-model"): - self.assertEqual(tranche.current_judgments(prs), {}) - questions = tranche.judge_questions() - questions["risk"]["instructions"]["question"] += " New policy." - with patch.object(tranche, "judge_questions", return_value=questions): - self.assertEqual(tranche.current_judgments(prs), {}) - - def test_resume_reuses_only_matching_records_and_saves_projection(self): - prs = self.inputs([pr(1)]) - self.judgments(prs) - args = argparse.Namespace(resume=True, limit=None) - tranche.cmd_judge(args) # No key read or model call. - self.inputs([pr(1, head={"sha": "updated"})]) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - self.model.return_value = { - "answers": answers(), - "model": "fixture-model", - "request_id": "fixture", - } - tranche.cmd_judge(args) - self.model.assert_called_once() - record = tranche.load_done()[1] - self.assertEqual(record["head_sha"], "updated") - self.assertEqual(record["input"], tranche.pr_state(tranche.load_prs()[1])) - self.assertEqual(record["resolved_model"], "fixture-model") - self.assertIn("judged_at", record) - self.assertEqual(len(tranche.current_judgments(tranche.load_prs())), 1) - - def test_judgment_bound_to_previous_questions_is_never_reused(self): - prs = self.inputs([pr(1)]) - old_questions = copy.deepcopy(tranche.judge_questions()) - del old_questions["category"]["criteria"]["user-experience"] - stale = {"number": 1, "answers": copy.deepcopy(answers()), "usage": {}, - "binding": tranche.digest({"version": tranche.BINDING_VERSION, - "repo": tranche.REPO, - "source": prs[1]["evidence_digest"], - "state": tranche.pr_state(prs[1]), - "questions": old_questions, - "model": tranche.MODEL}), - "input": tranche.pr_state(prs[1]), "requested_model": tranche.MODEL} - tranche.JUDGMENTS_PATH.write_text(json.dumps(stale) + "\n") - self.assertEqual(tranche.current_judgments(prs), {}) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - self.model.return_value = {"answers": answers()} - tranche.cmd_judge(argparse.Namespace(resume=True, limit=None)) - self.model.assert_called_once() - self.assertEqual(tranche.load_done()[1]["binding"], tranche.judgment_binding(prs[1])) - - def test_pair_verdict_bound_to_previous_questions_is_never_reused(self): - prs = self.inputs([pr(1), pr(2)]) - old_questions = copy.deepcopy(tranche.pair_questions()) - old_questions["sameness"]["instructions"]["question"] += " (older wording)" - stale = {"a": 1, "b": 2, "verdict": "same_change", - "probabilities": {"same_change": 0.9}, - "binding": tranche.digest({"version": tranche.BINDING_VERSION, - "repo": tranche.REPO, "model": tranche.MODEL, - "sources": [prs[1]["evidence_digest"], prs[2]["evidence_digest"]], - "state": [tranche.brief(prs[1]), tranche.brief(prs[2])], - "questions": old_questions}), - "input": {"pr_a": tranche.brief(prs[1]), "pr_b": tranche.brief(prs[2])}, - "requested_model": tranche.MODEL} - tranche.PAIRS_PATH.write_text(json.dumps(stale) + "\n") - self.assertEqual(tranche.current_pairs(prs, self.judgments(prs)), []) - - def test_legacy_judgment_is_not_resume_hit(self): - prs = self.inputs([pr(1)]) - self.judgments(prs, legacy=True) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - self.model.return_value = {"answers": answers()} - tranche.cmd_judge(argparse.Namespace(resume=True, limit=1)) - self.model.assert_called_once() - self.assertIn("binding", tranche.load_done()[1]) - - def test_enormous_json_integers_are_unknown_without_poisoning_caches(self): - huge = 10**400 - for value in (huge, -huge): - with self.subTest(value_sign=value > 0): - self.assertIsNone(tranche.metric({"answers": {"risk": {"score": value}}}, "risk")) - self.assertIsNone(tranche.p_same({"probabilities": {"same_change": value}})) - pair = tranche.normalize_pair({"verdict": "same_change", - "probabilities": {"same_change": 0.9, "unrelated": value}}) - self.assertEqual(pair["probabilities"]["same_change"], 0.9) - self.assertIsNone(pair["probabilities"]["unrelated"]) - tranche.JUDGMENTS_PATH.write_text(json.dumps({"number": 999, - "binding": "stale", "answers": {"risk": {"score": value}}}) + "\n") - self.assertEqual(tranche.current_judgments({}), {}) - self.inputs([]) - summary, _ = self.cluster() - self.assertEqual(summary["judged"], 0) - - def test_pair_reuse_is_bound_to_both_sources_questions_and_model(self): - prs = self.inputs([pr(1), pr(2)]) - judgments = self.judgments(prs) - self.pairs(prs, [(1, 2, "same_change", 0.9)]) - self.assertEqual(len(tranche.current_pairs(prs, judgments)), 1) - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) # No key/model calls. - changed = self.inputs([pr(1), pr(2, head={"sha": "new"})]) - new_judgments = self.judgments(changed) - self.assertEqual(tranche.current_pairs(changed, new_judgments), []) - with patch.object(tranche, "pair_questions", return_value={"new": {"type": "choice", "criteria": ["only"]}}): - self.assertEqual(tranche.current_pairs(prs, judgments), []) - with patch.object(tranche, "MODEL", "new-model"): - self.assertEqual(tranche.current_pairs(prs, judgments), []) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - self.model.return_value = { - "answers": { - "sameness": {"choice": "same_change", "probabilities": {"same_change": 0.9}} - } - } - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) - self.model.assert_called_once() - self.assertEqual(len(tranche.current_pairs(changed, new_judgments)), 1) - - def test_body_references_accept_bare_link_and_qualified_forms(self): - cases = { - "bare number": ("This replaces #123.", None, [123]), - "pasted pull link": ("This replaces https://github.com/omacom/omarchy/pull/123.", None, [123]), - "pasted issue link": ("Blocks https://github.com/omacom/omarchy/issues/123.", None, [123]), - "markdown link": ("See [#123](https://github.com/omacom/omarchy/pull/123).", None, [123]), - "www and http forms": ("Refs http://www.github.com/omacom/omarchy/pull/123", None, [123]), - "qualified own repository": ("Replaces omacom/omarchy#123.", None, [123]), - "all three forms at once": ("#123 then omacom/omarchy#123 then " - "https://github.com/omacom/omarchy/pull/123", None, [123]), - "cross-repository link": ("Companion to https://github.com/omacom/omarchy-pkgs/pull/123.", None, []), - "cross-repository qualified token": ("Companion to omacom/omarchy-pkgs#123.", None, []), - "qualified token with trailing sentence": ("Superseded by omacom/omarchy#123.", None, [123]), - "no reference": ("Polish the battery icon.", None, []), - "url fragment is not a reference": ("See https://example.com/changelog#123.", None, []), - "own number is never a reference": ("Supersedes itself: #123.", 123, []), - "own number in every form": ("#123 omacom/omarchy#123 " - "https://github.com/omacom/omarchy/pull/123", 123, []), - } - for name, (raw_body, own, expected) in cases.items(): - with self.subTest(case=name): - self.assertEqual(tranche.reference_numbers(raw_body, tranche.REPO, own), expected) - - def test_references_select_pairs_across_repositories_and_never_self_compare(self): - """Issue #10: only the repository under review is a comparison candidate.""" - prs = self.inputs([ - pr(1, title="Restore suspend resume for thinkpad audio"), - pr(2, title="Add wallpaper picker shortcut", - body="Companion to https://github.com/omacom/omarchy-pkgs/pull/1."), - pr(3, title="Bump starship prompt config", - body="Replaces https://github.com/omacom/omarchy/pull/1."), - pr(4, title="Improve waybar battery icon", - body="Same area as omacom/omarchy#1."), - pr(5, title="Teach walker to fuzzy match window titles", - body="Supersedes #5."), - ]) - # The cross-repository mention names this repository's PR #1, which is - # exactly the mistake the reading must not make. - self.assertEqual(prs[2]["refs"], []) - self.assertEqual(prs[3]["refs"], [1]) - self.assertEqual(prs[4]["refs"], [1]) - self.assertEqual(prs[5]["refs"], []) - judgments = self.judgments(prs) - self.assertEqual(sorted(tranche.lexical_pairs(prs, judgments)), - [(1.0, 1, 3), (1.0, 1, 4)]) - - def test_closed_members_do_not_reenter_pairs_or_reports(self): - prs = self.inputs([pr(1), pr(2)]) - self.judgments(prs) - self.pairs(prs, [(1, 2, "same_change", 0.9)]) - current = self.inputs([pr(1)]) - judgments = tranche.current_judgments(current) - self.assertEqual(tranche.lexical_pairs(current, judgments), []) - self.assertEqual(tranche.current_pairs(current, judgments), []) - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) - summary, dupes = self.cluster() - self.assertEqual(summary["judged"], 1) - self.assertEqual(dupes["confirmed_groups"], []) - self.assertEqual(summary["ready_prs"], 1) - - def test_connected_group_exposes_negative_uncertain_missing_relationships(self): - prs = self.inputs([pr(1), pr(2), pr(3)]) - self.judgments(prs) - edges = [(1, 2, "same_change", 0.9), (2, 3, "same_change", 0.9)] - for extra, field in ( - ([(1, 3, "related_but_different", 0.04)], "conflicting_pairs"), - ([(1, 3, "same_change", 0.59)], "uncertain_pairs"), - ([], "missing_pairs"), - ): - with self.subTest(field=field): - self.pairs(prs, edges + extra) - summary, dupes = self.cluster() - self.assertEqual(dupes["confirmed_groups"], []) - self.assertEqual(dupes["review_groups"][0]["members"], [1, 2, 3]) - self.assertTrue(dupes["review_groups"][0][field]) - self.assertEqual(summary["ready_prs"], 0) - self.assertIn(field, (self.out / "tranches.md").read_text()) - - def test_contradictory_pair_is_visible_standalone_and_inside_groups(self): - prs = self.inputs([pr(1), pr(2), pr(3)]) - self.judgments(prs) - for verdict, probability, classification in ( - ("unrelated", 0.9, "contradictory"), - ("related_but_different", 0.65, "contradictory"), - ("same_change", 0.1, "contradictory"), - ("same_change", 0.35, "uncertain"), - ("unrelated", 0.64, "uncertain"), - ("invalid", 0.9, "malformed"), - ("same_change", None, "malformed"), - ): - with self.subTest(verdict=verdict, probability=probability): - self.pairs(prs, [(1, 3, verdict, probability)]) - _, dupes = self.cluster() - self.assertEqual(len(dupes["uncertain_pairs"]), 1) - diagnostic = dupes["uncertain_pairs"][0] - self.assertEqual(diagnostic["classification"], classification) - self.assertEqual(diagnostic["p_same"], probability) - self.assertIn(classification, (self.out / "tranches.md").read_text()) - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn(classification, - (self.root / "docs" / "data" / "workbench.json").read_text()) - self.pairs(prs, [(1, 2, "same_change", 0.9), - (2, 3, "same_change", 0.9), (1, 3, verdict, probability)]) - _, dupes = self.cluster() - self.assertEqual(dupes["confirmed_groups"], []) - group = dupes["review_groups"][0] - field = "conflicting_pairs" if classification == "contradictory" else "uncertain_pairs" - self.assertEqual(group[field][0]["classification"], classification) - self.pairs(prs, [(1, 2, "unrelated", 0.1)]) - _, dupes = self.cluster() - self.assertEqual(dupes["uncertain_pairs"], []) - self.assertEqual(dupes["review_groups"], []) - - def test_consistent_group_does_not_choose_oldest_survivor(self): - prs = self.inputs([pr(1), pr(2), pr(3)]) - self.judgments(prs) - self.pairs( - prs, - [(1, 2, "same_change", 0.9), (2, 3, "same_change", 0.9), (1, 3, "same_change", 0.9)], - ) - summary, dupes = self.cluster() - self.assertEqual(dupes["confirmed_groups"], [[1, 2, 3]]) - self.assertEqual(summary["superseded"], 0) - items = json.loads((self.out / "clusters.json").read_text())["fix-misc"]["low"] - self.assertTrue(all(item["superseded_by"] is None for item in items)) - self.assertEqual(summary["ready_prs"], 0) - - def test_published_conflict_shape_does_not_become_confirmed_equivalence(self): - # Synthetic titles/bodies; numeric IDs preserve the observed public graph shape. - prs = self.inputs([pr(n) for n in (7765, 8065, 12635, 12651)]) - self.judgments(prs) - self.pairs( - prs, - [ - (7765, 8065, "related_but_different", 0.04), - (8065, 12635, "same_change", 0.96), - (7765, 12635, "same_change", 0.72), - (8065, 12651, "same_change", 0.94), - ], - ) - _, dupes = self.cluster() - self.assertEqual(dupes["confirmed_groups"], []) - diagnostic = dupes["review_groups"][0] - self.assertEqual(diagnostic["members"], [7765, 8065, 12635, 12651]) - self.assertEqual(diagnostic["conflicting_pairs"][0]["p_same"], 0.04) - self.assertEqual(len(diagnostic["missing_pairs"]), 2) - - def test_unknown_or_invalid_model_fields_do_not_enter_review_candidates(self): - prs = self.inputs([pr(1)]) - for field in ("risk", "security_flag", "finished_form", "is_fix", "review_effort"): - for value in ( - None, - {}, - {"score": True, "noul": True}, - {"score": -1, "noul": -1}, - {"score": 10, "noul": 10}, - ): - with self.subTest(field=field, value=value): - data = answers() - data[field] = value - self.judgments(prs, custom=data) - summary, _ = self.cluster() - self.assertEqual(summary["ready_prs"], 0) - for value in (float("nan"), float("inf"), "0", True): - self.assertIsNone(tranche.metric({"answers": {"risk": {"score": value}}}, "risk")) - self.assertIsNone(tranche.p_same({"probabilities": {"same_change": float("nan")}})) - - def test_model_judgments_normalize_before_save_and_retry_unknown_metrics(self): - self.inputs([pr(1)]) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - args = argparse.Namespace(resume=True, limit=None) - for value, usage in ((float("nan"), None), (float("inf"), []), - (-float("inf"), {"input_tokens": True, "output_tokens": -1}), - ("1", {"input_tokens": 2.5, "output_tokens": "3"})): - with self.subTest(value=value, usage=usage): - data = answers() - data["risk"]["score"] = value - self.model.return_value = {"answers": data, "usage": usage} - before = self.model.call_count - tranche.cmd_judge(args) - self.assertEqual(self.model.call_count, before + 1) - record = tranche.load_done()[1] - self.assertIsNone(record["answers"]["risk"]["score"]) - self.assertEqual(record["answers"]["finished_form"]["score"], 2) - self.assertEqual(record["usage"], {"input_tokens": 0, "output_tokens": 0}) - self.assertTrue(record["normalization_errors"]) - json.dumps(record, allow_nan=False) - self.assertEqual(self.cluster()[0]["ready_prs"], 0) - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - self.model.return_value = {"answers": answers(), "usage": {"input_tokens": 7}} - tranche.cmd_judge(args) - before = self.model.call_count - tranche.cmd_judge(args) - self.assertEqual(self.model.call_count, before) - self.assertEqual(self.cluster()[0]["tokens"], {"input": 7, "output": 0}) - - def test_pair_responses_and_poisoned_caches_recover_without_losing_evidence(self): - prs = self.inputs([pr(1), pr(2)]) - self.judgments(prs) - self.pairs(prs, [(1, 2, "same_change", float("nan"))]) - path = tranche.JUDGMENTS_PATH - rows = [json.loads(line) for line in path.read_text().splitlines()] - rows[0]["answers"]["risk"]["score"] = float("inf") - rows[0]["usage"] = None - junk = [None, [], 7, {}, {"number": []}, {"number": True}] - path.write_text("broken\n" + "".join(json.dumps(r) + "\n" for r in junk + rows)) - tranche.PAIRS_PATH.write_text("broken\n" + "".join(json.dumps(r) + "\n" for r in - [None, [], {}, {"a": [], "b": 2}, {"a": True, "b": 2}]) + tranche.PAIRS_PATH.read_text()) - before = path.read_bytes() - self.assertEqual(self.cluster()[0]["ready_prs"], 1) - self.assertEqual(self.render().returncode, 0) - self.assertEqual(path.read_bytes(), before) # Recovery is in memory, not binding retrofit. - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - self.model.return_value = {"answers": answers()} - tranche.cmd_judge(argparse.Namespace(resume=True, limit=None)) - self.model.assert_called_once() - for response in (None, {"answers": []}, {"answers": {"sameness": []}}, - {"answers": {"sameness": {"choice": [], "probabilities": []}}}, - *[{"answers": {"sameness": {"choice": "same_change", - "probabilities": {"same_change": v}}}, "usage": "invalid"} - for v in (float("nan"), float("inf"), -float("inf"), True, 2)]): - with self.subTest(response=response): - self.model.return_value = response - calls = self.model.call_count - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) - self.assertEqual(self.model.call_count, calls + 1) - records = tranche.current_pairs(prs, tranche.current_judgments(prs)) - self.assertEqual(len(records), 1) - self.assertIsNone(tranche.p_same(records[0])) - self.assertTrue(records[0]["normalization_errors"]) - for line in tranche.PAIRS_PATH.read_text().splitlines()[7:]: - json.loads(line, parse_constant=lambda token: self.fail(token)) - self.assertEqual(self.cluster()[1]["confirmed_groups"], []) - self.assertEqual(self.render().returncode, 0) - self.model.return_value = {"answers": {"sameness": {"choice": "same_change", - "probabilities": {"same_change": 0.9}}}, "usage": {"input_tokens": 3}} - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) - calls = self.model.call_count - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) - self.assertEqual(self.model.call_count, calls) - self.assertEqual(self.cluster()[1]["confirmed_groups"], [[1, 2]]) - self.assertEqual(self.render().returncode, 0) - - def test_invalid_category_and_answer_shapes_are_reportable_not_reusable(self): - prs = self.inputs([pr(1)]) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - args = argparse.Namespace(resume=True, limit=None) - for shape in (dict(answers(), category={"choice": []}), None, [], "bad"): - with self.subTest(shape=shape): - tranche.JUDGMENTS_PATH.write_text(json.dumps({"number": 1, - "answers": shape, "binding": tranche.judgment_binding(prs[1])}) + "\n") - self.assertEqual(self.cluster()[0]["ready_prs"], 0) - self.assertEqual(self.render().returncode, 0) - self.model.return_value = {"answers": shape} - calls = self.model.call_count - tranche.cmd_judge(args) - tranche.cmd_judge(args) - self.assertEqual(self.model.call_count, calls + 2) - self.assertEqual(self.cluster()[0]["ready_prs"], 0) - for response in (None, [], {}): - self.model.return_value = response - tranche.cmd_judge(args) - self.assertEqual(self.cluster()[0]["ready_prs"], 0) - - def test_drafts_cannot_enter_review_candidates(self): - prs = self.inputs([pr(1, draft=True)]) - self.judgments(prs) - self.assertEqual(self.cluster()[0]["ready_prs"], 0) - - def test_security_meta_category_has_top_priority(self): - prs = self.inputs([pr(n) for n in (1, 2, 3, 4)]) - records = {1: dict(answers(), security_flag={"noul": 0.9}), - 2: dict(answers(), security_flag={"noul": 0.5}), - 3: dict(answers(), security_flag={"noul": 0.49}), - 4: dict(answers(), security_flag={"noul": None})} - tranche.JUDGMENTS_PATH.write_text("".join( - json.dumps({"number": n, "answers": records[n], - "binding": tranche.judgment_binding(prs[n])}) + "\n" - for n in sorted(prs))) - summary, _ = self.cluster() - self.assertEqual(summary["security_priority"], 2) - clusters = json.loads((self.out / "clusters.json").read_text()) - self.assertEqual([item["number"] for item in clusters["security-review"]], [1, 2]) - markdown = (self.out / "tranches.md").read_text() - self.assertLess(markdown.index("Security review — top priority"), - markdown.index("## Review candidates:")) - report = self.render() - self.assertEqual(report.returncode, 0, report.stderr) - - def test_security_section_absent_when_nothing_flagged(self): - prs = self.inputs([pr(1)]) - self.judgments(prs) - summary, _ = self.cluster() - self.assertEqual(summary["security_priority"], 0) - clusters = json.loads((self.out / "clusters.json").read_text()) - self.assertEqual(clusters["security-review"], []) - self.assertNotIn("Security review — top priority", (self.out / "tranches.md").read_text()) - - def test_unbound_opt_in_is_inspection_not_freshness_or_readiness(self): - prs = self.inputs([pr(1), pr(2)]) - self.judgments(prs, legacy=True) - self.pairs(prs, [(1, 2, "same_change", 0.9)], legacy=True) - self.assertEqual(self.cluster()[0]["judged"], 0) - summary, dupes = self.cluster(allow_unbound=True) - self.assertEqual(summary["unbound_judgments"], 2) - self.assertEqual(summary["ready_prs"], 0) - self.assertEqual(dupes["confirmed_groups"], []) - self.assertTrue(dupes["review_groups"][0]["unbound_evidence"]) - self.judgments(prs) - self.inputs([pr(1, body="changed"), pr(2, body="changed")]) - self.assertEqual(self.cluster(allow_unbound=True)[0]["judged"], 0) - - def test_empty_fetch_removes_legacy_tail_membership(self): - (self.pages / "page_1.json").write_text(json.dumps([pr(99)])) - self.network.side_effect = [io.BytesIO(b"[]")] - tranche.cmd_fetch(argparse.Namespace(transport="urllib")) - self.assertEqual(tranche.load_prs(), {}) - self.assertTrue((self.pages / "page_1.json").exists()) # Ignored legacy input. - - def test_exact_page_boundary_ends_with_empty_page_and_replaces_membership(self): - self.inputs([pr(999)]) - items = [pr(n) for n in range(1, 101)] - self.network.side_effect = [io.BytesIO(json.dumps(items).encode()), io.BytesIO(b"[]")] - with patch.object(tranche.time, "sleep"): - tranche.cmd_fetch(argparse.Namespace(transport="urllib")) - self.assertEqual(set(tranche.load_prs()), set(range(1, 101))) - self.assertEqual(self.network.call_count, 2) - - def test_failed_or_duplicate_pagination_retains_committed_snapshot(self): - self.inputs([pr(999)]) - before = (self.pages / "snapshot.json").read_bytes() - items = [pr(n) for n in range(1, 101)] - for second in ( - urllib.error.URLError("offline fixture"), - io.BytesIO(json.dumps([pr(1)]).encode()), - ): - self.network.side_effect = [io.BytesIO(json.dumps(items).encode()), second] - with ( - patch.object(tranche.time, "sleep"), - self.assertRaises((urllib.error.URLError, tranche.TrancheFatal)), - ): - tranche.cmd_fetch(argparse.Namespace(transport="urllib")) - self.assertEqual((self.pages / "snapshot.json").read_bytes(), before) - - def test_malformed_fetch_does_not_replace_usable_snapshot(self): - self.inputs([pr(999)]) - before = (self.pages / "snapshot.json").read_bytes() - for item in ({"number": 1}, pr(1, body={"invalid": "type"}), pr(1, labels=None)): - self.network.side_effect = [io.BytesIO(json.dumps([item]).encode())] - with self.assertRaises(tranche.TrancheFatal): - tranche.cmd_fetch(argparse.Namespace(transport="urllib")) - self.assertEqual((self.pages / "snapshot.json").read_bytes(), before) - - def test_curl_transport_uses_same_atomic_membership_commit(self): - self.inputs([pr(999)]) - result = subprocess.CompletedProcess([], 0, json.dumps([pr(1)]), "") - with patch.object(tranche.subprocess, "run", return_value=result) as run: - tranche.cmd_fetch(argparse.Namespace(transport="curl")) - self.assertEqual(set(tranche.load_prs()), {1}) - self.assertIn("--max-time", run.call_args.args[0]) - before = (self.pages / "snapshot.json").read_bytes() - with patch.object( - tranche.subprocess, - "run", - return_value=subprocess.CompletedProcess([], 22, "", "fixture"), - ): - with self.assertRaises(tranche.TrancheFatal): - tranche.cmd_fetch(argparse.Namespace(transport="curl")) - self.assertEqual((self.pages / "snapshot.json").read_bytes(), before) - - def test_fetch_authenticates_through_gh_never_a_token_in_argv(self): - """Unauthenticated GitHub allows 60 requests/hour; a capture costs ~29.""" - self.inputs([pr(1)]) - result = subprocess.CompletedProcess([], 0, json.dumps([]), "") - with patch.object(tranche.subprocess, "run", return_value=result) as run: - tranche.cmd_fetch(argparse.Namespace(transport="gh")) - command = run.call_args.args[0] - self.assertEqual(command[:2], ["gh", "api"]) - # No credential may ever reach an argv: it would be visible in `ps`. - self.assertNotIn("Authorization", " ".join(command)) - self.assertFalse(any("token" in str(part).lower() for part in command)) - self.assertEqual(set(tranche.load_prs()), set()) - - def test_snapshot_repository_and_content_integrity_are_checked(self): - items = [pr(1)] - for field, replacement in (("repo", "other/repo"), ("items", [pr(2)]), ("version", 999)): - self.inputs(items) - path = self.pages / "snapshot.json" - value = json.loads(path.read_text()) - value[field] = replacement - path.write_text(json.dumps(value)) - with self.assertRaises(tranche.TrancheFatal): - tranche.load_prs() - - def test_user_experience_category_is_judge_selectable_and_labeled(self): - self.assertIn("user-experience", tranche.judge_questions()["category"]["criteria"]) - prs = self.inputs([pr(1)]) - self.judgments(prs, custom=dict(answers(), category={"choice": "user-experience"})) - self.assertEqual( - tranche.category(tranche.current_judgments(prs)[1]), "user-experience") - self.cluster() - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - payload = json.loads((self.root / "docs" / "data" / "workbench.json").read_text()) - self.assertEqual(payload["prs"][0]["category"], "user-experience") - self.assertEqual(payload["categories"]["user-experience"], "User Experience") - self.assertIn('value="user-experience"', (self.root / "docs" / "index.html").read_text()) - - def test_html_render_matches_cli_coverage_and_escapes_source_text(self): - prs = self.inputs([pr(1, title="Fix "), pr(2)]) - self.judgments({1: prs[1]}) - summary, _ = self.cluster() - self.assertEqual(summary["ready_prs"], 1) - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - page = (self.root / "docs" / "index.html").read_text() - json_text = (self.root / "docs" / "data" / "workbench.json").read_text() - rows = json.loads(json_text)["prs"] - self.assertEqual([row["number"] for row in rows], [1, 2]) - self.assertEqual(rows[0]["title"], "Fix ") - self.assertNotIn("", json_text) - self.assertNotIn("", page) - self.assertIn(r"\u003cscript\u003e", json_text) - self.assertNotIn('id="workbench-data"', page, "payload must not return inline") - self.assertIn('id="load-failure"', page) - self.assertTrue(rows[0]["candidate"]) - self.assertFalse(rows[1]["candidate"]) - self.assertIsNone(rows[1]["risk"]) - self.assertIsNone(rows[1]["security"]) - self.assertEqual(rows[1]["freshness"], "unjudged or stale") - self.assertEqual(rows[1]["category"], "unknown") - self.assertNotIn("reviewed & QA'd", page) - self.assertNotIn("security-clean", page) - self.assertIn("AI-assisted priorities; review code and tests before merging.", page) - - def test_html_exposes_group_conflicts(self): - prs = self.inputs([pr(1), pr(2), pr(3)]) - self.judgments(prs) - self.pairs( - prs, [(1, 2, "same_change", 0.9), (2, 3, "same_change", 0.9), (1, 3, "unrelated", 0.01)] - ) - self.cluster() - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("conflicting_pairs", - (self.root / "docs" / "data" / "workbench.json").read_text()) - - def test_html_refuses_stale_inputs_or_mixed_outputs_before_overwrite(self): - prs = self.inputs([pr(1)]) - self.judgments(prs) - self.cluster() - self.assertEqual(self.render().returncode, 0) - target = self.root / "docs" / "index.html" - before = target.read_bytes() - self.inputs([pr(1, head={"sha": "changed"})]) - self.assertNotEqual(self.render().returncode, 0) - self.assertEqual(target.read_bytes(), before) - self.inputs([pr(1)]) - (self.out / "dupes.json").write_text("{}") - self.assertNotEqual(self.render().returncode, 0) - self.assertEqual(target.read_bytes(), before) - - def test_workbench_has_native_controls_and_no_process_commentary(self): - self.inputs([pr(1, body='Snippet & text')]) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - self.model.return_value = {"answers": dict(answers(), security_flag={"noul": 0.8})} - tranche.cmd_judge(argparse.Namespace(resume=True, limit=None)) - self.cluster() - self.assertEqual(self.render().returncode, 0) - page = (self.root / "docs" / "index.html").read_text() - for text in ('assets/workbench.css', 'assets/workbench.js', '', - 'Method.', 'fetch → judge', ''): - self.assertNotIn(text, page) - json_text = (self.root / "docs" / "data" / "workbench.json").read_text() - self.assertIn(r'\u003c/script\u003e', json_text) - self.assertIn(r'\u0026', json_text) - - def test_render_embeds_batches_and_refuses_stale_batch_file(self): - self.merge_setup() - tranche.cmd_batches(argparse.Namespace()) - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - json_text = (self.root / "docs" / "data" / "workbench.json").read_text() - payload = json.loads(json_text) - self.assertTrue(payload["batches_available"]) - batched = [row for row in payload["prs"] if row["batches"]] - self.assertEqual(len(batched), 9, "nine batchable PRs across two batches") - by_number = {row["number"]: row["batches"] for row in payload["prs"]} - self.assertEqual(by_number[1][0]["id"], "B001") - self.assertEqual(by_number[12][0]["id"], "B002") - self.assertIn("B001", json_text) - self.assertIn("review_prompt", json_text) - self.assertIn("unified proposal", json_text) - # A batches file bound to a different dupe run must never render. - dupes = json.loads((self.out / "dupes.json").read_text()) - dupes["confirmed_groups"] = [] - (self.out / "dupes.json").write_text(json.dumps(dupes)) - self.assertNotEqual(self.render().returncode, 0) - - def test_empty_corpus_renders_without_credentials(self): - self.inputs([]) - self.cluster() - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn( - "0 captured PRs", (self.root / "docs" / "index.html").read_text() - ) - - def test_all_supports_documented_resume_and_pair_budget(self): - with ( - patch.object( - sys, "argv", ["tranche.py", "all", "--resume", "--limit", "2", "--max-pairs", "0"] - ), - patch.object(tranche, "cmd_judge") as judge, - patch.object(tranche, "cmd_dupes") as dupes, - patch.object(tranche, "cmd_cluster") as cluster, - patch.object(tranche, "cmd_batches") as batches, - ): - tranche.main() - self.assertTrue(judge.call_args.args[0].resume) - self.assertEqual(dupes.call_args.args[0].max_pairs, 0) - self.assertEqual(cluster.call_count, 1) - self.assertEqual(batches.call_count, 1) - - def merge_setup(self): - """Group [1,2] confirmed; [3,4,5] in review (conflict); 6-12 ungrouped. - - Batchable PRs: 1, 2, 6..12 = 9 → batches of 5 then 4. - """ - prs = self.inputs([pr(n) for n in range(1, 13)]) - records = {} - for n in range(1, 13): - data = answers() - if n == 1: - data["security_flag"] = {"noul": 0.9} - records[n] = data - tranche.JUDGMENTS_PATH.write_text("".join( - json.dumps({"number": n, "answers": records[n], - "binding": tranche.judgment_binding(prs[n])}) + "\n" - for n in sorted(prs))) - self.pairs(prs, [(1, 2, "same_change", 0.9), - (3, 4, "same_change", 0.9), (4, 5, "same_change", 0.9), - (3, 5, "unrelated", 0.1)]) - return prs, self.cluster()[0] - - def test_batches_are_size_five_disjoint_and_security_first(self): - prs, summary = self.merge_setup() - tranche.cmd_batches(argparse.Namespace()) - payload = json.loads((self.out / "batches.json").read_text()) - self.assertEqual(payload["format_version"], 3) - self.assertEqual(payload["dupes_digest"], summary["output_digests"]["dupes.json"]) - self.assertEqual(payload["batch_size"], 5) - batches = payload["batches"] - # Size: 9 batchable PRs pack into batches of 5 then 4. - self.assertEqual([b["count"] for b in batches], [5, 4]) - self.assertEqual([b["id"] for b in batches], ["B001", "B002"]) - # Security first: the security-related PR leads the first batch. - self.assertEqual(batches[0]["members"][0], 1) - self.assertEqual(batches[0]["security_members"], 1) - # The same-change group [1,2] stays atomic inside one batch. - batch_of = {n: i for i, b in enumerate(batches) for n in b["members"]} - self.assertEqual(batch_of[1], batch_of[2]) - # Strict disjointness and review-group exclusion. - flat = [n for b in batches for n in b["members"]] - self.assertEqual(len(flat), len(set(flat))) - self.assertEqual(set(flat), {1, 2, 6, 7, 8, 9, 10, 11, 12}) - self.assertEqual(payload["excluded_review_prs"], 3) - self.assertEqual(payload["same_change_groups"], 1) - # Every batch carries a copy-paste reviewer agent prompt pointing at all its PRs. - for batch in batches: - prompt = batch["review_prompt"] - self.assertIn(batch["id"], prompt) - self.assertIn("unified proposal", prompt) - for n in batch["members"]: - self.assertIn(f"#{n}", prompt) - markdown = (self.out / "tranches.md").read_text() - self.assertIn("Reviewer agent prompts", markdown) - self.assertIn("Copy-paste a prompt", markdown) - - # ------------------------------------------------------------------ - # Issue #8: parked PRs never enter a batch. Park is a pre-pack gate: - # draft, finished_form <= 1, or no current judgment. A same_change - # group with a parked member holds whole — atomic units are never - # split. Park is a hold with a named unblock path, never a close. - # ------------------------------------------------------------------ - - def park_setup(self): - """merge_setup plus park coverage: 7 draft (security-flagged), - 8 finished_form 1, 9 unjudged.""" - prs = self.inputs([pr(7, draft=True) if n == 7 else pr(n) for n in range(1, 13)]) - records = {} - for n in range(1, 13): - data = answers() - if n == 1: - data["security_flag"] = {"noul": 0.9} - if n == 7: - data["security_flag"] = {"noul": 0.8} - if n == 8: - data["finished_form"] = {"score": 1} - records[n] = data - tranche.JUDGMENTS_PATH.write_text("".join( - json.dumps({"number": n, "answers": records[n], - "binding": tranche.judgment_binding(prs[n])}) + "\n" - for n in sorted(prs) if n != 9)) - self.pairs(prs, [(1, 2, "same_change", 0.9), - (3, 4, "same_change", 0.9), (4, 5, "same_change", 0.9), - (3, 5, "unrelated", 0.1)]) - return prs, self.cluster()[0] - - def test_activity_uses_bound_head_and_never_thread_update(self): - observed = {"head_sha": "new", "created": "2026-01-01T00:00:00Z", - "updated": "2026-10-01T00:00:00Z"} - old = {"head_sha": "old", "judged_at": "2026-02-01T00:00:00Z"} - self.assertEqual(tranche.pr_activity(observed, old), - {"head_moved": True, "idle_since": None, "idle_basis": "unknown", - "thread_updated": observed["updated"]}) - current = dict(old, head_sha="new") - self.assertEqual(tranche.pr_activity(observed, current)["idle_since"], old["judged_at"]) - self.assertFalse(tranche.pr_activity(observed, current)["head_moved"]) - self.assertEqual(tranche.pr_activity(observed, {})["idle_since"], observed["created"]) - self.assertFalse(tranche.pr_activity(observed, {})["head_moved"]) - - def test_idle_first_within_risk_band_preserves_security_and_park(self): - prs = {n: dict(pr(n), created="2026-01-01T00:00:00Z", head_sha=f"sha{n}", - url=f"https://github.com/omacom/omarchy/pull/{n}") - for n in range(1, 8)} - judgments = {n: {"answers": answers(), "head_sha": f"sha{n}", - "judged_at": "2026-01-10T00:00:00Z" if n == 2 else - "2026-03-01T00:00:00Z"} for n in range(1, 8)} - judgments[3]["answers"] = dict(answers(), security_flag={"noul": 0.9}) - judgments[4]["answers"] = dict(answers(), finished_form={"score": 1}) - judgments[5]["head_sha"] = "old-head" - judgments[6]["answers"] = dict(answers(), risk={"score": 3}) - dupes = {"confirmed_groups": [], "review_groups": []} - result = tranche.merge_batches(dupes, judgments, prs, "digest") - order = [n for batch in result["batches"] for n in batch["members"]] - self.assertEqual(order[0], 3) - self.assertLess(order.index(2), order.index(1)) - self.assertLess(order.index(1), order.index(5)) - self.assertNotIn(4, order) - - def test_render_exposes_head_revision_and_idle_lower_bound(self): - prs = self.inputs([pr(1), pr(2)]) - self.judgments(prs) - records = [json.loads(line) for line in tranche.JUDGMENTS_PATH.read_text().splitlines()] - for record in records: - record.update(head_sha=prs[record["number"]]["head_sha"], - judged_at="2026-01-02T00:00:00+00:00") - tranche.JUDGMENTS_PATH.write_text("".join(json.dumps(r) + "\n" for r in records)) - self.inputs([pr(1, head={"sha": "revised"}), pr(2)]) - self.cluster() - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - rows = {r["number"]: r for r in json.loads( - (self.root / "docs" / "data" / "workbench.json").read_text())["prs"]} - self.assertTrue(rows[1]["activity"]["head_moved"]) - self.assertIsNone(rows[1]["activity"]["idle_since"]) - self.assertFalse(rows[2]["activity"]["head_moved"]) - self.assertTrue(rows[2]["activity"]["idle_since"]) - self.assertEqual(rows[1]["activity"]["thread_updated"], prs[1]["updated"]) - - def test_park_set_reads_only_pipeline_legible_facts(self): - prs = {1: pr(1), 2: pr(2, draft=True), 3: pr(3), 4: pr(4)} - judgments = {1: {"answers": answers()}, 2: {"answers": answers()}, - 3: {"answers": dict(answers(), finished_form={"score": 1})}} - self.assertEqual(tranche.park_set(prs, judgments), - {2: ["draft"], 3: ["finished_form"], 4: ["unjudged_or_stale"]}) - # A judgment just above the threshold is not parked. - judgments[1] = {"answers": dict(answers(), finished_form={"score": 1.01})} - self.assertNotIn(1, tranche.park_set(prs, judgments)) - # Reasons accumulate: a draft whose judgment went stale parks for both. - self.assertEqual(tranche.park_set({5: pr(5, draft=True)}, {}), - {5: ["draft", "unjudged_or_stale"]}) - - def test_parked_prs_never_enter_a_batch_and_ship_as_first_class_output(self): - prs, _ = self.park_setup() - tranche.cmd_batches(argparse.Namespace()) - payload = json.loads((self.out / "batches.json").read_text()) - packed = [n for batch in payload["batches"] for n in batch["members"]] - self.assertEqual(sorted(packed), [1, 2, 6, 10, 11, 12]) - self.assertEqual([batch["count"] for batch in payload["batches"]], [5, 1]) - self.assertEqual(payload["parked_prs"], 3) - parked = json.loads((self.out / "parked.json").read_text()) - self.assertEqual(parked["format_version"], 1) - self.assertEqual(parked["dupes_digest"], payload["dupes_digest"]) - self.assertEqual(parked["parked"], 3) - by_number = {row["number"]: row for row in parked["members"]} - self.assertEqual(by_number[7]["reasons"], ["draft"]) - self.assertEqual(by_number[8]["reasons"], ["finished_form"]) - self.assertEqual(by_number[9]["reasons"], ["unjudged_or_stale"]) - for row in parked["members"]: - self.assertTrue(row["unblock"]) - self.assertEqual(row["head_sha"], prs[row["number"]]["head_sha"]) - # Security routing survives parking: the draft security PR stays in - # the meta-category even though no batch may claim it. - clusters = json.loads((self.out / "clusters.json").read_text()) - self.assertIn(7, [row["number"] for row in clusters["security-review"]]) - - def test_same_change_group_with_a_parked_member_holds_whole(self): - prs = self.inputs([pr(1), pr(2, draft=True)] + [pr(n) for n in range(3, 7)]) - tranche.JUDGMENTS_PATH.write_text("".join( - json.dumps({"number": n, "answers": answers(), - "binding": tranche.judgment_binding(prs[n])}) + "\n" - for n in sorted(prs))) - self.pairs(prs, [(1, 2, "same_change", 0.9)]) - self.cluster() - tranche.cmd_batches(argparse.Namespace()) - payload = json.loads((self.out / "batches.json").read_text()) - packed = [n for batch in payload["batches"] for n in batch["members"]] - self.assertEqual(sorted(packed), [3, 4, 5, 6]) - parked = {row["number"]: row["reasons"] for row in json.loads( - (self.out / "parked.json").read_text())["members"]} - self.assertEqual(parked[2], ["draft", "same_change_hold"]) - self.assertEqual(parked[1], ["same_change_hold"]) - - def test_batch_prompts_never_mention_parked_prs(self): - prs, _ = self.park_setup() - tranche.cmd_batches(argparse.Namespace()) - payload = json.loads((self.out / "batches.json").read_text()) - for batch in payload["batches"]: - for n in (7, 8, 9): - self.assertNotIn(f"#{n}", batch["review_prompt"]) - self.assertNotIn("parked", batch["review_prompt"].lower()) - markdown = (self.out / "tranches.md").read_text() - self.assertIn("Parked before batching", markdown) - self.assertIn("unjudged_or_stale", markdown) - - def test_render_embeds_park_record_and_refuses_stale_park_file(self): - prs, _ = self.park_setup() - tranche.cmd_batches(argparse.Namespace()) - result = self.render() - self.assertEqual(result.returncode, 0, result.stderr) - page = (self.root / "docs" / "index.html").read_text() - payload = json.loads( - (self.root / "docs" / "data" / "workbench.json").read_text()) - self.assertEqual(payload["parked"]["parked"], 3) - self.assertEqual(sorted(m["number"] for m in payload["parked"]["members"]), [7, 8, 9]) - by_number = {row["number"]: row for row in payload["prs"]} - self.assertEqual(by_number[7]["parked"], ["draft"]) - self.assertEqual(by_number[8]["parked"], ["finished_form"]) - self.assertEqual(by_number[9]["parked"], ["unjudged_or_stale"]) - self.assertEqual(by_number[1]["parked"], []) - self.assertIn('data-queue="parked"', page) - self.assertIn("Parked", page) - # A batches run that parked PRs must never render without its park record... - (self.out / "parked.json").unlink() - self.assertNotEqual(self.render().returncode, 0) - # ...nor with a park record that no longer matches the corpus and dupes run. - tranche.cmd_batches(argparse.Namespace()) - parked = json.loads((self.out / "parked.json").read_text()) - parked["members"][0]["reasons"] = ["mutated"] - (self.out / "parked.json").write_text(json.dumps(parked)) - self.assertNotEqual(self.render().returncode, 0) - - def test_refresh_reports_parked_accounting(self): - self.park_setup() - tranche.cmd_batches(argparse.Namespace()) - for name in ("cmd_fetch", "cmd_judge", "cmd_dupes", "cmd_cluster", - "cmd_batches", "render_page"): - patcher = patch.object(tranche, name) - patcher.start() - self.addCleanup(patcher.stop) - capture = io.StringIO() - with redirect_stdout(capture): - tranche.cmd_refresh(argparse.Namespace(dry_run=False, no_page=False, max_pairs=0)) - output = capture.getvalue() - self.assertIn("parked", output) - self.assertIn("3", output.split("parked", 1)[1][:20]) - - def test_batches_refuse_outputs_that_drifted_from_the_summary(self): - self.merge_setup() - tranche.cmd_batches(argparse.Namespace()) - dupes = json.loads((self.out / "dupes.json").read_text()) - dupes["confirmed_groups"] = [] - (self.out / "dupes.json").write_text(json.dumps(dupes)) - with self.assertRaises(tranche.TrancheFatal): - tranche.cmd_batches(argparse.Namespace()) - clusters = json.loads((self.out / "clusters.json").read_text()) - clusters["fix-misc"]["low"][0]["title"] = "mutated" - (self.out / "clusters.json").write_text(json.dumps(clusters)) - with self.assertRaises(tranche.TrancheFatal): - tranche.cmd_batches(argparse.Namespace()) - - def test_evidence_digest_ignores_the_churning_repository_envelope(self): - """A refetch that only moves repo-wide counters must not invalidate work.""" - item = pr(1) - item["base"] = {"ref": "master", "sha": "base", "repo": { - "id": 1, "full_name": "omacom/omarchy", "stargazers_count": 43_000, - "open_issues_count": 4_900, "pushed_at": "2026-01-02T00:00:00Z"}} - item["_links"] = {"self": {"href": "https://api.github.com/repos/omacom/omarchy/pulls/1"}} - item["statuses_url"] = "https://api.github.com/repos/omacom/omarchy/statuses/old" - refetched = copy.deepcopy(item) - refetched["base"]["repo"].update(stargazers_count=43_014, open_issues_count=5_003, - pushed_at="2026-02-01T00:00:00Z") - refetched["_links"] = {"self": {"href": "https://api.github.com/other"}} - refetched["statuses_url"] = "https://api.github.com/repos/omacom/omarchy/statuses/new" - - prs = self.inputs([item, pr(2)]) - self.judgments(prs) - self.pairs(prs, [(1, 2, "same_change", 0.9)]) - later = self.inputs([refetched, pr(2)]) - self.assertEqual(later[1]["source_digest"] != prs[1]["source_digest"], True) - self.assertEqual(later[1]["evidence_digest"], prs[1]["evidence_digest"]) - self.assertEqual(len(tranche.current_judgments(later)), 2) - self.assertEqual(len(tranche.current_pairs(later, self.judgments(later))), 1) - - def test_real_pr_changes_still_invalidate_evidence_and_verdicts(self): - prs = self.inputs([pr(1), pr(2)]) - self.judgments(prs) - self.pairs(prs, [(1, 2, "same_change", 0.9)]) - for change in ({"body": "A different description."}, {"title": "Different title"}, - {"head": {"sha": "moved"}}, {"updated_at": "2026-03-01T00:00:00Z"}, - {"labels": [{"name": "needs-testing"}]}, {"draft": True}): - with self.subTest(change=change): - changed = self.inputs([pr(1, **change), pr(2)]) - self.assertNotIn(1, tranche.current_judgments(changed)) - self.assertEqual(tranche.current_pairs(changed, self.judgments(changed)), []) - self.assertEqual(tranche.pair_cache(changed, {})[(1, 2)]["freshness"], "stale") - - def test_dupes_reuses_bound_verdicts_and_reruns_only_what_moved(self): - prs = self.inputs([pr(1), pr(2)]) - self.judgments(prs) - self.pairs(prs, [(1, 2, "same_change", 0.9)]) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - self.model.return_value = { - "answers": {"sameness": {"choice": "same_change", - "probabilities": {"same_change": 0.9}}}, - "usage": {"input_tokens": 260, "output_tokens": 12}, - } - # Nothing moved: no call, and the cached verdict is still current. - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) - self.model.assert_not_called() - # The pair's PR changed: exactly one call, and the record replaces it. - moved = self.inputs([pr(1, body="Rewritten description."), pr(2)]) - judgments = self.judgments(moved) - self.assertEqual(tranche.pair_cache(moved, judgments)[(1, 2)]["freshness"], "stale") - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) - self.assertEqual(self.model.call_count, 1) - self.assertEqual(tranche.pair_cache(moved, judgments)[(1, 2)]["freshness"], "current") - self.assertEqual(len(tranche.current_pairs(moved, judgments)), 1) - - def test_refresh_dry_run_reports_work_without_writing(self): - prs = self.inputs([pr(1), pr(2)]) - self.judgments(prs) - self.pairs(prs, [(1, 2, "same_change", 0.9)]) - before = (self.out / "summary.json").exists() - with patch.object(sys, "argv", ["tranche.py", "refresh", "--dry-run", - "--max-pairs", "0"]): - tranche.main() - self.model.assert_not_called() # --dry-run spends nothing - self.assertFalse(before) - self.assertFalse((self.out / "summary.json").exists()) # and writes nothing - self.assertFalse((self.out / "dupes.json").exists()) - - def test_refresh_dry_run_and_dupes_report_the_same_work(self): - """One predicate, two consumers: the reported count must be the work done. - - A stale verdict for a pair that is no longer a candidate is not work: - nothing asks for that verdict, so re-running it would never converge and - the counter would report outstanding work forever. - """ - prs = self.inputs([pr(1), pr(2)]) - self.judgments(prs) - self.pairs(prs, [(1, 2, "same_change", 0.9)]) - # A stored verdict for a pair that is not a candidate pair at all. - (self.out / "pair_verdicts.jsonl").open("a").write( - json.dumps({"a": 81, "b": 82, "verdict": "same_change", - "probabilities": {"same_change": 0.9}}) + "\n") - judgments = tranche.current_judgments(prs) - # No candidate is outstanding: the orphan verdict is not work. - self.assertEqual(tranche.outstanding_pairs(prs, judgments), []) - self.model.assert_not_called() - # A candidate whose PR moved is reported as work by both consumers. - moved = self.inputs([pr(1, body="Rewritten."), pr(2)]) - moved_judgments = self.judgments(moved) - pending = tranche.outstanding_pairs(moved, moved_judgments) - self.assertEqual([(a, b) for _, a, b in pending], [(1, 2)]) - self.key.side_effect = None - self.key.return_value = "synthetic-key" - self.model.side_effect = None - self.model.return_value = { - "answers": {"sameness": {"choice": "same_change", - "probabilities": {"same_change": 0.9}}}, - } - tranche.cmd_dupes(argparse.Namespace(max_pairs=10)) - self.assertEqual(self.model.call_count, 1) # exactly the reported work - self.assertEqual(tranche.outstanding_pairs(moved, moved_judgments), []) - - def test_refresh_runs_the_documented_incremental_pipeline_once(self): - with ( - patch.object(sys, "argv", ["tranche.py", "refresh", "--max-pairs", "7"]), - patch.object(tranche, "cmd_fetch") as fetch, - patch.object(tranche, "cmd_judge") as judge, - patch.object(tranche, "cmd_dupes") as dupes, - patch.object(tranche, "cmd_cluster") as cluster, - patch.object(tranche, "cmd_batches") as batches, - patch.object(tranche, "render_page") as page, - ): - tranche.main() - self.assertEqual(fetch.call_args.args[0].transport, "gh") - self.assertTrue(judge.call_args.args[0].resume) - self.assertEqual(dupes.call_args.args[0].max_pairs, 7) - self.assertFalse(cluster.call_args.args[0].allow_unbound) - self.assertEqual(cluster.call_count, 1) - self.assertEqual(batches.call_count, 1) - self.assertEqual(page.call_count, 1) - # A second consecutive refresh with nothing changed spends no model call. - self.model.assert_not_called() - - def test_refresh_no_page_still_clusters(self): - with ( - patch.object(sys, "argv", ["tranche.py", "refresh", "--no-page"]), - patch.object(tranche, "cmd_fetch"), - patch.object(tranche, "cmd_judge"), - patch.object(tranche, "cmd_dupes"), - patch.object(tranche, "cmd_cluster") as cluster, - patch.object(tranche, "cmd_batches") as batches, - patch.object(tranche, "render_page") as page, - ): - tranche.main() - self.assertEqual(cluster.call_count, 1) - self.assertEqual(batches.call_count, 1) - page.assert_not_called() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/workbench.test.cjs b/tests/workbench.test.cjs index f347259..044624b 100644 --- a/tests/workbench.test.cjs +++ b/tests/workbench.test.cjs @@ -138,7 +138,10 @@ test('browser workbench renders safe text, inspects PRs, restores focus and URL server.once('error', reject); }); try { - const output = await new Promise((resolve, reject) => execFile(chromium, ['--headless', '--no-sandbox', '--disable-gpu', '--force-prefers-reduced-motion', '--virtual-time-budget=8000', '--dump-dom', `http://127.0.0.1:${port}/`], {encoding: 'utf8', timeout: 30000, maxBuffer: 4 * 1024 * 1024}, (error, stdout) => error ? reject(error) : resolve(stdout))); + // A cold CI runner can take well over 30s to fetch a 5.5 MB payload and + // render; when the timeout fires, chromium is killed and the probe never + // writes its verdict, which reads as `undefined` rather than a timeout. + const output = await new Promise((resolve, reject) => execFile(chromium, ['--headless', '--no-sandbox', '--disable-gpu', '--force-prefers-reduced-motion', '--virtual-time-budget=8000', '--dump-dom', `http://127.0.0.1:${port}/`], {encoding: 'utf8', timeout: 120000, maxBuffer: 4 * 1024 * 1024}, (error, stdout) => error ? reject(error) : resolve(stdout))); const result = output.match(/
([^<]*)<\/pre>/)?.[1];
       assert.equal(result, 'BROWSER_PASS');
     } finally { server.close(); }
diff --git a/tools/make_title_gif.py b/tools/make_title_gif.py
deleted file mode 100644
index abb507c..0000000
--- a/tools/make_title_gif.py
+++ /dev/null
@@ -1,277 +0,0 @@
-#!/usr/bin/env python3
-"""Render the official OMARCHY wordmark as a glyphfx-gradient GIF title.
-
-The official OMARCHY SVG is rasterized as a mask. glyphfx's colorshift effect is
-probed on a solid line in its native terminal habitat and the captured
-per-column color sequence is painted across the mask per animation frame,
-with "TRIAGE with Tranche (powered by Jev)" beneath; Tranche also carries the gradient. Output: docs/assets/tranche.gif.
-
-Usage: python3 tools/make_title_gif.py
-"""
-
-import io
-import os
-import subprocess
-import sys
-from pathlib import Path
-
-import numpy as np
-from PIL import Image, ImageDraw, ImageFont
-
-ROOT = Path(__file__).resolve().parent.parent
-OUT_GIF = ROOT / "docs" / "assets" / "tranche.gif"
-WORDMARK_SVG = ROOT / "tools" / "omarchy-wordmark.svg"
-
-EFFECT = "colorshift"
-PROBE_W = 54  # probe line width (glyphfx-native habitat)
-FRAME_RATE = 24
-MAX_FRAMES = 60
-TAGLINE = "TRIAGE with Tranche (powered by Jev)"
-BG = (0x16, 0x16, 0x1E)
-DEFAULT_FG = (0xC0, 0xCA, 0xF5)
-
-FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"
-TAG_FONT_SIZE = 46
-LOGO_W_PX = 1500  # wordmark width; height follows the font aspect
-PAD_X, PAD_Y, TAG_GAP = 30, 26, 30
-
-
-# ---------------------------------------------------------------------------
-# glyphfx probe: capture the traveling gradient as per-column colors per frame
-# ---------------------------------------------------------------------------
-
-def xterm256(idx):
-    base = [0, 95, 135, 175, 215, 255]
-    pal = [(0, 0, 0), (205, 0, 0), (0, 205, 0), (205, 205, 0),
-           (0, 0, 238), (205, 0, 205), (0, 205, 205), (229, 229, 229)]
-    for r in base:
-        for g in base:
-            for b in base:
-                pal.append((r, g, b))
-    for v in (95, 135, 175, 215, 255):
-        pal.append((v // 2,) * 3)
-    return pal[idx % 256]
-
-
-class Grid:
-    """Minimal terminal grid: SGR truecolor/256, CUP/CUU/CUF/EL/ED, ESC 7/8."""
-
-    def __init__(self, w, h):
-        self.w, self.h = w, h
-        self.cells = [[(" ", None) for _ in range(w)] for _ in range(h)]
-        self.row = self.col = 0
-        self.fg = None
-        self.saved = (0, 0)
-
-    def sgr(self, params):
-        if not params:
-            params = [0]
-        i = 0
-        while i < len(params):
-            p = params[i] or 0
-            if p in (0, 39):
-                self.fg = None
-            elif p == 38 and i + 2 < len(params):
-                if params[i + 1] == 2:
-                    self.fg = (params[i + 2], params[i + 3], params[i + 4])
-                    i += 4
-                elif params[i + 1] == 5:
-                    self.fg = xterm256(params[i + 2])
-                    i += 2
-            i += 1
-
-    def csi(self, private, params, final):
-        if private:
-            return
-        nums = [int(p) if p else 0 for p in params.split(";")] if params else []
-        n = nums[0] if nums else 1
-        if final == "m":
-            self.sgr(nums)
-        elif final in "Hf":
-            r = nums[0] if nums and nums[0] else 1
-            c = nums[1] if len(nums) > 1 and nums[1] else 1
-            self.row, self.col = r - 1, c - 1
-        elif final == "A":
-            self.row = max(0, self.row - max(1, n))
-        elif final == "C":
-            self.col = min(self.w - 1, self.col + max(1, n))
-        elif final == "D":
-            self.col = max(0, self.col - max(1, n))
-        elif final == "G":
-            self.col = max(0, (nums[0] if nums and nums[0] else 1) - 1)
-        elif final == "K":
-            mode = nums[0] if nums else 0
-            if mode == 0:
-                for c in range(self.col, self.w):
-                    self.cells[self.row][c] = (" ", None)
-            elif mode == 2:
-                self.cells[self.row] = [(" ", None) for _ in range(self.w)]
-        elif final == "J":
-            self.cells = [[(" ", None) for _ in range(self.w)] for _ in range(self.h)]
-            self.row = self.col = 0
-
-    def snapshot(self):
-        return tuple(tuple(row) for row in self.cells)
-
-
-def parse_snapshots(data: bytes, w: int, h: int):
-    """Walk the ANSI stream; snapshot at every cursor-home (frame repaint)."""
-    grid = Grid(w, h)
-    snaps = [grid.snapshot()]
-    i, n = 0, len(data)
-    while i < n:
-        b = data[i]
-        if b == 0x1B and i + 1 < n and data[i + 1] == ord("["):
-            j = i + 2
-            private = ""
-            if j < n and data[j:j + 1] in (b"?", b">", b"=", b"<"):
-                private = chr(data[j])
-                j += 1
-            k = j
-            while k < n and not (0x40 <= data[k] <= 0x7E):
-                k += 1
-            if k >= n:
-                break
-            final = chr(data[k])
-            params = data[j:k].decode("ascii", "replace")
-            nums = [int(p) if p else 0 for p in params.split(";")] if params else []
-            home = (not private and final == "H" and (not nums or nums[0] <= 1))
-            grid.csi(private, params, final)
-            if home:
-                snaps.append(grid.snapshot())
-            i = k + 1
-            continue
-        if b == 0x1B and i + 1 < n and data[i + 1] in (ord("7"), ord("8")):
-            if data[i + 1] == ord("7"):
-                grid.saved = (grid.row, grid.col)
-            else:
-                grid.row, grid.col = grid.saved
-                if grid.row == 0 and grid.col == 0:
-                    snaps.append(grid.snapshot())
-            i += 2
-            continue
-        if b == 0x0D:
-            grid.col = 0
-            i += 1
-            continue
-        if b == 0x0A:
-            i += 1
-            continue
-        length = 4 if b >= 0xF0 else 3 if b >= 0xE0 else 2 if b >= 0xC0 else 1
-        ch = data[i:i + length].decode("utf-8", "replace")
-        if grid.row < h and grid.col < w:
-            grid.cells[grid.row][grid.col] = (ch, grid.fg)
-        grid.col += 1
-        if grid.col >= w:
-            grid.col = 0
-            grid.row = min(h - 1, grid.row + 1)
-        i += length
-    return snaps
-
-
-def probe_gradient():
-    """glyphfx on a solid line -> list of per-frame column colors (len PROBE_W)."""
-    os.environ.setdefault("TERM", "xterm-256color")
-    cap = subprocess.run(
-        ["glyphfx", "--canvas-width", str(PROBE_W), "--canvas-height", "1",
-         "--frame-rate", str(FRAME_RATE), "--no-restore-cursor",
-         EFFECT, "--no-loop", "--cycles", "1"],
-        input=("M" * PROBE_W).encode(), capture_output=True, timeout=120,
-    )
-    if cap.returncode != 0 or len(cap.stdout) < 500:
-        sys.exit(f"glyphfx failed rc={cap.returncode}: {cap.stderr[:300]}")
-    frames = []
-    seen = set()
-    for snap in parse_snapshots(cap.stdout, PROBE_W, 1):
-        key = hash(snap)
-        if key in seen:
-            continue
-        seen.add(key)
-        frames.append([fg for _, fg in snap[0]])
-    def blank(row):
-        return all(fg is None for fg in row)
-    while frames and blank(frames[0]):
-        frames.pop(0)
-    while frames and blank(frames[-1]):
-        frames.pop()
-    return frames
-
-
-# ---------------------------------------------------------------------------
-# Wordmark mask + frame composition
-# ---------------------------------------------------------------------------
-
-def logo_mask():
-    raster = subprocess.run(["rsvg-convert", "-w", str(LOGO_W_PX), str(WORDMARK_SVG)],
-                            check=True, capture_output=True)
-    mask = Image.open(io.BytesIO(raster.stdout)).convert("RGBA")
-    return np.asarray(mask)[:, :, 3] > 32
-
-
-def compose(frames):
-    mask = logo_mask()
-    mh, mw = mask.shape
-    tag_font = ImageFont.truetype(FONT_PATH, TAG_FONT_SIZE)
-    tag_box = tag_font.getbbox(TAGLINE)
-    tag_w = tag_box[2] - tag_box[0]
-    W = max(mw, tag_w) + 2 * PAD_X
-    H = PAD_Y + mh + TAG_GAP + TAG_FONT_SIZE + PAD_Y
-    ox = (W - mw) // 2
-    out = []
-    for col_colors in frames:
-        # logo: paint the glyphfx gradient across the mask, sampled per column
-        color_cols = np.zeros((mw, 3), dtype=np.uint8)
-        for c in range(mw):
-            fg = col_colors[int(c * PROBE_W / mw) % PROBE_W]
-            color_cols[c] = fg if fg is not None else DEFAULT_FG
-        img = Image.new("RGB", (W, H), BG)
-        arr = np.asarray(img).copy()
-        ys, xs = np.nonzero(mask)
-        arr[ys + PAD_Y, xs + ox] = color_cols[xs]
-        img = Image.fromarray(arr)
-        # Keep the explanatory copy steady; animate only the Tranche name.
-        d = ImageDraw.Draw(img)
-        tag_x, tag_y = (W - tag_w) // 2 - tag_box[0], PAD_Y + mh + TAG_GAP
-        d.text((tag_x, tag_y), TAGLINE, font=tag_font, fill=DEFAULT_FG)
-        name_x = round(tag_x + tag_font.getlength("TRIAGE with "))
-        name_w = round(tag_font.getlength("Tranche"))
-        name_mask = Image.new("L", (W, H))
-        ImageDraw.Draw(name_mask).text((name_x, tag_y), "Tranche", font=tag_font, fill=255)
-        ys, xs = np.nonzero(np.asarray(name_mask))
-        arr = np.asarray(img).copy()
-        for x in range(name_x, name_x + name_w):
-            fg = col_colors[min(PROBE_W - 1, int((x - name_x) * PROBE_W / name_w))] or DEFAULT_FG
-            selected = xs == x
-            arr[ys[selected], xs[selected]] = fg
-        img = Image.fromarray(arr)
-        out.append(img)
-    while len(out) > 8 and out[-1].tobytes() == out[-2].tobytes():
-        out.pop()
-    if len(out) > MAX_FRAMES:
-        step = len(out) / MAX_FRAMES
-        out = [out[int(i * step)] for i in range(MAX_FRAMES)]
-    return out
-
-
-def main():
-    frames = probe_gradient()
-    print(f"probed gradient frames: {len(frames)}")
-    imgs = compose(frames)
-    OUT_GIF.parent.mkdir(parents=True, exist_ok=True)
-    imgs[0].save(
-        OUT_GIF, save_all=True, append_images=imgs[1:],
-        duration=int(1000 / FRAME_RATE), loop=0, optimize=True,
-    )
-    logo_bottom = PAD_Y + logo_mask().shape[0] + PAD_Y
-    logo_frames = [im.crop((0, 0, im.width, logo_bottom)) for im in imgs]
-    logo_frames[0].save(OUT_GIF.with_name("omarchy.gif"), save_all=True,
-                        append_images=logo_frames[1:], duration=int(1000 / FRAME_RATE),
-                        loop=0, optimize=True)
-    logo_frames[len(logo_frames) // 2].save(OUT_GIF.with_name("omarchy-title.png"))
-    imgs[len(imgs) // 2].save(OUT_GIF.with_name("tranche-title.png"))
-    print(f"frames kept: {len(imgs)} | size: {imgs[0].width}x{imgs[0].height} | "
-          f"file: {OUT_GIF.stat().st_size // 1024} KB")
-
-
-if __name__ == "__main__":
-    main()
diff --git a/tranche.py b/tranche.py
deleted file mode 100644
index 3dbb029..0000000
--- a/tranche.py
+++ /dev/null
@@ -1,1667 +0,0 @@
-#!/usr/bin/env python3
-"""Tranche — model-assisted PR discovery via TypeSafe Jev.
-
-Groups observed open PRs of omacom/omarchy into review candidates, proposes
-related groups, and flags items that may need follow-up — supporting the roll-up work DHH
-asked the triage team to do (x.com/dhh/status/2098755120540393908).
-
-Judgments come from TypeSafe's System One API (Jev). Code owns the workflow:
-fetch -> judge (one batched call per PR) -> compare candidate pairs -> cluster.
-
-Usage:
-  python3 tranche.py refresh            # the whole pipeline, incremental, one command
-  python3 tranche.py fetch              # refresh data/pages/snapshot.json
-  python3 tranche.py judge [--limit N] [--resume]
-  python3 tranche.py dupes [--max-pairs N]
-  python3 tranche.py cluster            # writes out/clusters.json, out/dupes.json,
-                                       #            out/tranches.md, out/summary.json
-  python3 tranche.py batches            # writes out/batches.json (cumulative pre-release batches)
-  python3 tranche.py all [--limit N]
-"""
-
-from __future__ import annotations
-
-import argparse
-import difflib
-import hashlib
-import json
-import math
-import os
-import random
-import re
-import subprocess
-import sys
-import tempfile
-import threading
-import time
-import urllib.error
-import urllib.request
-from collections import Counter, defaultdict
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from datetime import datetime, timezone
-from itertools import combinations
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parent
-PAGES_DIR = ROOT / "data" / "pages"
-OUT_DIR = ROOT / "out"
-JUDGMENTS_PATH = OUT_DIR / "judgments.jsonl"
-PAIRS_PATH = OUT_DIR / "pair_verdicts.jsonl"
-KEY_FILE = Path.home() / "Documents" / "jevapi.txt"
-
-API_URL = "https://api.typesafe.ai/v1/systemone"
-MODEL = "jev-latest"
-REPO = "omacom/omarchy"
-BODY_CHARS = 1200
-WORKERS = 6
-BINDING_VERSION = 1
-# Issue #3: security is a meta-category with top priority. A judgment at or above
-# this probability enters the security-first queue, which outranks every category.
-SECURITY_PRIORITY = 0.5
-
-
-def digest(value) -> str:
-    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"),
-                                     ensure_ascii=False, allow_nan=False).encode()).hexdigest()
-
-
-def atomic_json(path: Path, value) -> None:
-    path.parent.mkdir(parents=True, exist_ok=True)
-    fd, temporary = tempfile.mkstemp(prefix=".pending-", dir=path.parent)
-    try:
-        with os.fdopen(fd, "w", encoding="utf-8") as stream:
-            json.dump(value, stream, ensure_ascii=False, allow_nan=False)
-            stream.flush()
-            os.fsync(stream.fileno())
-        os.replace(temporary, path)
-    finally:
-        if os.path.exists(temporary):
-            os.unlink(temporary)
-
-# ---------------------------------------------------------------------------
-# Jev questions — one batched call per PR (independent questions over one state
-# run in parallel and are far cheaper than one call per question).
-# ---------------------------------------------------------------------------
-
-def judge_questions() -> dict:
-    return {
-        "category": {
-            "type": "choice",
-            "instructions": {
-                "question": (
-                    "Which area of Omarchy does this pull request mainly touch? "
-                    "Read `pr.title` and `pr.body`; `pr.diffstat` shows the size. "
-                    "Pick exactly one; use `unclear` only when the text is too thin to tell."
-                )
-            },
-            "criteria": {
-                "install-setup": "omarchy-setup menu, installer, first boot, ISO, dotfiles bootstrap",
-                "desktop-config": "Hyprland, Walker, waybar, wlogout, mako, keybinds, wallpapers, theming",
-                "user-experience": "a default/taste or look-and-feel proposal (themes, wallpapers, icons, fonts, bar or menu aesthetics); judge by the change's effect, not the subsystem it edits",
-                "shell-cli": "zsh config, aliases, starship, CLI tool defaults, terminal usage",
-                "apps-integrations": "default apps, mime handling, new application integrations (e.g. dropbox, spotify, 1password)",
-                "hardware-drivers": "NVIDIA, wifi, bluetooth, audio, power, HiDPI, laptops, ARM/Snapdragon, firmware",
-                "update-release": "omarchy-update, version bumps, release machinery, migration between versions, boot entries",
-                "agents-ai": "AI coding agents, agent hooks, MCP, integrations for Claude/Codex/Gemini-like tools",
-                "docs": "README, documentation, wiki, help text only",
-                "fix-misc": "a real change that fits none of the above",
-                "unclear": "cannot be placed from title and body alone",
-            },
-        },
-        "risk": {
-            "type": "score",
-            "instructions": {
-                "question": (
-                    "How risky is merging this pull request for existing Omarchy installations? "
-                    "Judge from `pr.title`, `pr.body` and `pr.diffstat`."
-                )
-            },
-            "criteria": [
-                "Text-only: docs, themes, wallpapers, menu definitions; nothing executes",
-                "Config or script change that is scoped and revertible; no root-side effects at install/update time",
-                "Runs as root during install or update, edits boot entries or mounts, or flips system-wide defaults",
-                "Touches disk layout, networking, sudo/permissions, security posture, or kernel drivers/firmware",
-                "Could break existing installs outright: data loss, boot failure, or user lockout",
-            ],
-        },
-        "is_fix": {
-            "type": "noul",
-            "instructions": (
-                "Is this pull request primarily a fix for a bug or regression, rather than "
-                "a new feature, a default/taste change, or a refactor? Judge from `pr.title` and `pr.body`."
-            ),
-        },
-        "dupe_signal": {
-            "type": "noul",
-            "instructions": (
-                "Do `pr.title` or `pr.body` indicate this pull request duplicates another change, "
-                "or is superseded by / supersedes one (another open PR, or already-merged upstream work)?"
-            ),
-        },
-        "finished_form": {
-            "type": "score",
-            "instructions": {
-                "question": (
-                    "Is this pull request in finished, reviewable form as described by `pr.body` "
-                    "(with `pr.title`)? DHH asked the triage team to ensure everything is ready "
-                    "for consideration in a finished form."
-                )
-            },
-            "criteria": [
-                "Empty or near-empty body; no description of what or why",
-                "Says what it does but not why, or shows no evidence it was tried",
-                "Clear what and why; states that it was tested on a real system",
-                "Clear what and why plus concrete QA evidence (before/after, screenshots, test steps); small and focused",
-            ],
-        },
-        "review_effort": {
-            "type": "score",
-            "instructions": {
-                "question": "How much reviewer effort does this pull request need, judging by `pr.diffstat` and the change described?"
-            },
-            "criteria": [
-                "Trivial and mechanical: a typo, version number, or one-line constant",
-                "Small: one focused change a reviewer can hold in their head",
-                "Moderate: several related edits that must be checked together",
-                "Substantial: architectural or many-part change needing deep review",
-            ],
-        },
-        "security_flag": {
-            "type": "noul",
-            "instructions": (
-                "Does this change touch credentials or secrets, download-and-execute remote code, "
-                "sudo/permission changes, network exposure, or crypto material? Judge from `pr.title` and `pr.body`."
-            ),
-        },
-    }
-
-
-def pair_questions() -> dict:
-    return {
-        "sameness": {
-            "type": "choice",
-            "instructions": {
-                "question": (
-                    "Do `pr_a` and `pr_b` propose the same underlying change to Omarchy? "
-                    "Judge by what they modify and the outcome, not by wording."
-                )
-            },
-            "criteria": {
-                "same_change": "two attempts at the same change; merging one makes the other redundant",
-                "related_but_different": "same area or theme but distinct outcomes; both could merge",
-                "unrelated": "different changes that merely share words",
-            },
-        },
-    }
-
-
-# ---------------------------------------------------------------------------
-# TypeSafe HTTP
-# ---------------------------------------------------------------------------
-
-class TrancheFatal(RuntimeError):
-    pass
-
-
-def read_key() -> str:
-    key = os.environ.get("TYPESAFE_API_KEY")
-    if key:
-        return key.strip()
-    if KEY_FILE.exists():
-        return KEY_FILE.read_text().strip()
-    raise TrancheFatal(f"No API key: set TYPESAFE_API_KEY or create {KEY_FILE}")
-
-
-def ask(state, questions: dict, key: str, timeout: int = 90) -> dict:
-    payload = json.dumps({"state": state, "model": MODEL, "questions": questions}).encode()
-    backoff = 2.0
-    last = ""
-    for _attempt in range(6):
-        req = urllib.request.Request(
-            API_URL,
-            data=payload,
-            headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
-            method="POST",
-        )
-        try:
-            with urllib.request.urlopen(req, timeout=timeout) as resp:
-                return json.load(resp)
-        except urllib.error.HTTPError as e:
-            last = f"HTTP {e.code}: {e.read().decode(errors='replace')[:300]}"
-            if e.code == 401:
-                raise TrancheFatal(f"Auth rejected (401). Check the key. {last}") from e
-            if e.code == 422:
-                raise TrancheFatal(f"Request rejected (422) — question shape bug. {last}") from e
-            if e.code in (429, 529) or e.code >= 500:
-                time.sleep(backoff + random.random())
-                backoff = min(backoff * 2, 60)
-                continue
-            raise TrancheFatal(last) from e
-        except urllib.error.URLError as e:
-            last = f"network: {e}"
-            time.sleep(backoff + random.random())
-            backoff = min(backoff * 2, 60)
-    raise TrancheFatal(f"Retries exhausted. Last error: {last}")
-
-
-# ---------------------------------------------------------------------------
-# Data loading
-# ---------------------------------------------------------------------------
-
-def validate_pr(item):
-    if (not isinstance(item, dict) or type(item.get("number")) is not int
-            or item["number"] <= 0 or not isinstance(item.get("title"), str)
-            or item.get("body") is not None and not isinstance(item["body"], str)):
-        raise TrancheFatal("Invalid captured PR shape; fetch again")
-    for field in ("head", "user", "author"):
-        if item.get(field) is not None and not isinstance(item[field], dict):
-            raise TrancheFatal(f"Invalid captured PR {field}; fetch again")
-    labels = item.get("labels", [])
-    if not isinstance(labels, list) or any(not isinstance(label, dict) or not isinstance(label.get("name"), str) for label in labels):
-        raise TrancheFatal("Invalid captured PR labels; fetch again")
-
-
-# Issue #10 — literal body references, repository-qualified (adapted from
-# Reposition's `relations.py`). A mention selects a comparison candidate only
-# when it names a pull request of the repository under review: a bare `#N` can
-# only mean this repository, while a GitHub link or `owner/repo#N` names its own
-# repository and must not be read as ours. Scanning order makes the reading
-# explicit and non-overlapping — links first, then qualified tokens, then bare
-# numbers that no earlier token already covers — so the `#123` inside
-# `other/repo#123` or inside a pasted URL is never re-read on its own.
-LINK_REFERENCE = re.compile(
-    r"https?://(?:www\.)?github\.com/(?P[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)"
-    r"/(?:issues|pull)/(?P\d+)"
-)
-QUALIFIED_REFERENCE = re.compile(r"(?P[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)#(?P\d+)")
-BARE_REFERENCE = re.compile(r"(?\d+)\b")
-
-
-# Captured fields that carry this PR's own reviewable evidence. Everything else
-# in a GitHub pull-list envelope churns without the PR changing: `base.repo`
-# embeds repository-wide counters (stargazers, forks, open_issues, pushed_at,
-# updated_at) that move on every unrelated event, `_links`/`statuses_url` are
-# URL scaffolding, and `user`/`head` embed whole nested objects whose remote
-# halves drift independently. Digesting the whole envelope made every PR look
-# changed after every fetch.
-PR_EVIDENCE_FIELDS = (
-    "number", "title", "body", "created_at", "updated_at", "state", "draft",
-    "labels", "milestone", "requested_reviewers", "requested_teams",
-    "changed_files", "additions", "deletions", "commits", "comments",
-    "review_comments", "merged_at", "merge_commit_sha", "user", "head",
-)
-# Nested objects inside the evidence set, reduced to the PR-owned half.
-PR_EVIDENCE_PROJECTION = {
-    "user": ("login",),
-    "head": ("sha", "ref", "label"),
-}
-
-
-def pr_evidence_digest(item: dict) -> str:
-    """Digest of the captured fields a judgment actually depends on."""
-    evidence = {}
-    for field in PR_EVIDENCE_FIELDS:
-        if field not in item:
-            continue
-        value = item[field]
-        keep = PR_EVIDENCE_PROJECTION.get(field)
-        if keep and isinstance(value, dict):
-            value = {key: value[key] for key in keep if key in value}
-        elif keep and isinstance(value, list):
-            value = [{key: part[key] for key in keep if key in part}
-                     if isinstance(part, dict) else part for part in value]
-        elif field == "labels":
-            value = [label.get("name") if isinstance(label, dict) else label for label in value]
-        evidence[field] = value
-    return digest(evidence)
-
-
-def reference_digest(item: dict) -> str:
-    """Digest of the body references a PR contributes as comparison candidates.
-
-    Kept out of `pr_evidence_digest`: refs come from the raw captured body, they
-    are not part of any judgment or pair binding, and only `dupes` reads them.
-    """
-    raw = item.get("body") or ""
-    number = item.get("number")
-    return digest({"references": reference_numbers(raw, REPO, number if type(number) is int else None)})
-
-
-def reference_numbers(raw_body: str, repository: str = REPO, own_number: int | None = None) -> list[int]:
-    """PR numbers of `repository` literally mentioned in a description.
-
-    Cross-repository mentions are dropped, never rewritten as bare numbers, and
-    the PR's own number is discarded so a description can never pair a PR with
-    itself.
-    """
-    spans: list[tuple[int, int]] = []
-    numbers: set[int] = set()
-    for pattern in (LINK_REFERENCE, QUALIFIED_REFERENCE):
-        for match in pattern.finditer(raw_body):
-            spans.append(match.span())
-            if match["repo"].lower() == repository.lower():
-                numbers.add(int(match["number"]))
-    for match in BARE_REFERENCE.finditer(raw_body):
-        if any(start <= match.start() < end for start, end in spans):
-            continue
-        numbers.add(int(match["number"]))
-    if own_number is not None:
-        numbers.discard(own_number)
-    return sorted(numbers)
-
-
-def load_prs() -> dict[int, dict]:
-    prs: dict[int, dict] = {}
-    snapshot = PAGES_DIR / "snapshot.json"
-    if snapshot.exists():
-        value = json.loads(snapshot.read_text())
-        if (not isinstance(value, dict) or type(value.get("version")) is not int
-                or value.get("version") != 1 or value.get("repo") != REPO
-                or value.get("digest") != digest(value.get("items"))):
-            raise TrancheFatal("Fetched snapshot identity or checksum differs; fetch again")
-        pages = [value["items"]]
-    else:
-        # Existing/enriched page caches remain readable until the next fetch.
-        pages = [json.loads(path.read_text()) for path in sorted(PAGES_DIR.glob("page_*.json"))]
-    for page in pages:
-        if not isinstance(page, list):
-            raise TrancheFatal("Captured PR membership must be a list; fetch again")
-        for p in page:
-            validate_pr(p)
-            if p["number"] in prs:
-                raise TrancheFatal("Repeated PR in captured membership; fetch again")
-            raw_body = p.get("body") or ""
-            refs = reference_numbers(raw_body, REPO, p["number"])
-            body = re.sub(r"", "", raw_body, flags=re.S)
-            body = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", body)  # images
-            body = re.sub(r"https?://\S+", "", body)          # bare links
-            body = re.sub(r"\s+", " ", body).strip()
-            prs[p["number"]] = {
-                "number": p["number"],
-                "title": p["title"].strip(),
-                "body": body[:BODY_CHARS],
-                "author": ((p.get("user") or p.get("author") or {}).get("login", "unknown")),
-                "created": p.get("created_at", ""),
-                "updated": p.get("updated_at", ""),
-                "draft": bool(p.get("draft")),
-                "files": p.get("changed_files"),
-                "additions": p.get("additions"),
-                "deletions": p.get("deletions"),
-                "labels": [label["name"] for label in p.get("labels", [])],
-                "refs": refs,
-                "head_sha": (p.get("head") or {}).get("sha"),
-                "url": p.get("html_url") or f"https://github.com/{REPO}/pull/{p['number']}",
-                "source_digest": digest(p),
-                "evidence_digest": pr_evidence_digest(p),
-                "ref_digest": digest({"references": refs}),
-                "body_truncated": len(body) > BODY_CHARS,
-            }
-    return prs
-
-
-def ref_index(prs) -> dict[int, list[int]]:
-    """PR number → the references it contributes as comparison candidates."""
-    return {n: pr.get("refs", []) for n, pr in prs.items()}
-
-
-def pr_state(pr: dict) -> dict:
-    sizes = [pr[key] for key in ("files", "additions", "deletions")]
-    known = all(type(size) is int and size >= 0 for size in sizes)
-    return {
-        "pr": {
-            "title": pr["title"],
-            "body": pr["body"] or "(empty body)",
-            "author": pr["author"],
-            "diffstat": f"{sizes[0]} files changed, +{sizes[1]}/-{sizes[2]}" if known else "unknown (not supplied by the captured PR list)",
-            "draft": pr["draft"],
-            "evidence_basis": "title and shortened description; patches, CI and reproduction results not verified",
-            "diffstat_available": known,
-            "body_truncated": pr["body_truncated"],
-        }
-    }
-
-
-# ---------------------------------------------------------------------------
-# Commands
-# ---------------------------------------------------------------------------
-
-GITHUB_API = "https://api.github.com"
-
-
-def fetch_page(url: str, transport: str) -> list:
-    """One page of the open-PR list, over `gh` (preferred), curl or urllib.
-
-    `gh api` is preferred because it is already authenticated: unauthenticated
-    GitHub allows 60 requests an hour and one capture of this backlog costs
-    about 29, so an unauthenticated refresh fails on the third pass. The token
-    stays inside `gh` — it is never read by this process and never placed in an
-    argv, where it would be visible to every user on the host via `ps`.
-    """
-    if transport == "gh":
-        result = subprocess.run(["gh", "api", url], capture_output=True, text=True, timeout=120)
-        if result.returncode:
-            detail = result.stderr.strip().splitlines()[-1] if result.stderr.strip() else "no detail"
-            raise TrancheFatal(f"gh api fetch failed ({detail}); previous snapshot retained")
-        return json.loads(result.stdout)
-    if transport == "curl":
-        # The original host's urllib/IPv6 workaround. Deliberately unauthenticated.
-        command = ["curl", "--fail", "--silent", "--show-error", "--max-time", "60", url]
-        result = subprocess.run(command, capture_output=True, text=True)
-        if result.returncode:
-            detail = result.stderr.strip().splitlines()[-1] if result.stderr.strip() else "no detail"
-            raise TrancheFatal(f"curl fetch failed ({detail}); previous snapshot retained")
-        return json.loads(result.stdout)
-    with urllib.request.urlopen(url, timeout=60) as response:
-        return json.load(response)
-
-
-def cmd_fetch(args) -> None:
-    PAGES_DIR.mkdir(parents=True, exist_ok=True)
-    page, total = 1, 0
-    captured = []
-    seen = set()
-    transport = getattr(args, "transport", "gh")
-    while True:
-        url = f"{GITHUB_API}/repos/{REPO}/pulls?state=open&per_page=100&page={page}"
-        arr = fetch_page(url, transport)
-        if not isinstance(arr, list):
-            raise TrancheFatal("GitHub did not return a PR list; previous snapshot retained")
-        if not arr:
-            break
-        for item in arr:
-            validate_pr(item)
-            if item["number"] in seen:
-                raise TrancheFatal("Invalid or repeated PR during pagination; previous snapshot retained")
-            seen.add(item["number"])
-        captured.extend(arr)
-        total += len(arr)
-        print(f"page {page}: {len(arr)} PRs (total {total})")
-        if len(arr) < 100:
-            break
-        page += 1
-        time.sleep(0.4)
-    # One atomic membership commit, including an empty or exact-page result.
-    # Failed/partial fetches leave the last committed observation untouched.
-    atomic_json(PAGES_DIR / "snapshot.json", {
-        "version": 1, "repo": REPO, "items": captured, "digest": digest(captured),
-        "observed_at": datetime.now(timezone.utc).isoformat(),
-    })
-    print(f"fetched {total} observed open PRs into {PAGES_DIR}")
-
-
-def finite_json(value):
-    """Keep evidence JSON-shaped while removing non-standard numeric constants."""
-    if isinstance(value, dict):
-        return {key: finite_json(item) for key, item in value.items()}
-    if isinstance(value, list):
-        return [finite_json(item) for item in value]
-    if isinstance(value, float) and not math.isfinite(value):
-        return None
-    return value
-
-
-def normalized_record(record):
-    record = {key: finite_json(value) for key, value in record.items()}
-    usage = record.get("usage")
-    usage = usage if isinstance(usage, dict) else {}
-    record["usage"] = {field: usage.get(field) if type(usage.get(field)) is int
-                       and usage[field] >= 0 else 0
-                       for field in ("input_tokens", "output_tokens")}
-    return record
-
-
-def normalize_pair(record):
-    record = normalized_record(record)
-    policy = pair_questions().get("sameness")
-    choices = policy.get("criteria", []) if isinstance(policy, dict) else []
-    verdict = record.get("verdict")
-    if not isinstance(verdict, str) or verdict not in choices:
-        record["verdict"] = None
-    probabilities = record.get("probabilities")
-    probabilities = dict(probabilities) if isinstance(probabilities, dict) else {}
-    for key, value in probabilities.items():
-        if type(value) not in (int, float) or not 0 <= value <= 1 or not math.isfinite(value):
-            probabilities[key] = None
-    record["probabilities"] = probabilities
-    probabilities["same_change"] = p_same(record)
-    record["normalization_errors"] = [field + ": invalid or missing" for field, value in
-        (("verdict", record.get("verdict")), ("probabilities.same_change", p_same(record)))
-        if value is None]
-    # The judgment block is what the report re-reads; the per-request token usage
-    # is not. Keep it out of the cached record so cluster can read the multi-megabyte
-    # log without holding every usage block in memory.
-    if type(record.get("input_tokens")) is not int or type(record.get("output_tokens")) is not int:
-        usage = record.get("usage") if isinstance(record.get("usage"), dict) else {}
-        record.pop("input_tokens", None)
-        record.pop("output_tokens", None)
-        for field in ("input_tokens", "output_tokens"):
-            value = usage.get(field)
-            record[field] = value if type(value) is int and value >= 0 else 0
-    record.pop("usage", None)
-    return record
-
-
-def pair_usage(record: dict) -> tuple[int, int]:
-    """Tokens spent on one pair verdict, for a cached record or a raw API reply."""
-    usage = record.get("usage")
-    usage = usage if isinstance(usage, dict) else {}
-    values = []
-    for field in ("input_tokens", "output_tokens"):
-        value = record.get(field)
-        if type(value) is not int or value < 0:
-            value = usage.get(field)
-        values.append(value if type(value) is int and value >= 0 else 0)
-    return values[0], values[1]
-
-
-def reusable_pair(record):
-    return record.get("verdict") is not None and p_same(record) is not None
-
-
-def normalize_judgment(record):
-    record = normalized_record(record)
-    data = record.get("answers")
-    data = data if isinstance(data, dict) else {}
-    record["answers"] = data
-    errors = []
-    for name, question in judge_questions().items():
-        answer = data.get(name)
-        answer = dict(answer) if isinstance(answer, dict) else {}
-        field = {"choice": "choice", "score": "score", "noul": "noul"}[question["type"]]
-        if field == "choice":
-            value = answer.get(field)
-            valid = isinstance(value, str) and value in question["criteria"]
-        else:
-            value = metric(record, name, field)
-            valid = value is not None
-        if not valid:
-            errors.append(f"answers.{name}.{field}: invalid or missing")
-            value = None
-        answer[field] = value
-        data[name] = answer
-    record["normalization_errors"] = errors
-    return record
-
-
-def judgment_is_current(pr, record) -> bool:
-    """True when a stored judgment still answers today's question for today's evidence.
-
-    The PR's own captured evidence and the model/question policy both bind a
-    judgment, so a changed description or a newer model re-asks the question,
-    while a re-fetch of unchanged evidence does not. The binding is the single
-    currency test: it digests the full question policy, so a judgment made
-    under an older question set is never presented as current. `input` and
-    `requested_model` stay on records as provenance only. Completeness is not
-    tested here: an answer with an unknown field is still the answer that was
-    given, and dropping it would turn a known category into an unknown one.
-    """
-    return record.get("binding") == judgment_binding(pr)
-
-
-def reusable_judgment(record):
-    return (record.get("answers", {}).get("category", {}).get("choice") is not None
-            and all(metric(record, name, field) is not None for name, field in (
-                ("risk", "score"), ("finished_form", "score"), ("review_effort", "score"),
-                ("is_fix", "noul"), ("security_flag", "noul"))))
-
-
-def load_done() -> dict[int, dict]:
-    """Latest usable judgment per PR, reading the cache without loading it twice.
-
-    The log is append-only, so one PR can hold several lines; only the last
-    valid record per number wins and a bounded tail of it is returned, because
-    the full log has multi-megabyte `input` and `usage` blocks that no caller
-    needs. A malformed tail (a truncated write) never costs the earlier records.
-    """
-    done: dict[int, dict] = {}
-    if not JUDGMENTS_PATH.exists():
-        return done
-    with JUDGMENTS_PATH.open(encoding="utf-8") as stream:
-        for line in stream:
-            if "\"number\"" not in line:
-                continue
-            try:
-                rec = json.loads(line)
-            except json.JSONDecodeError:
-                continue
-            if (isinstance(rec, dict) and "error" not in rec
-                    and type(rec.get("number")) is int and rec["number"] > 0):
-                done[rec["number"]] = rec
-    return {number: normalize_judgment(rec) for number, rec in done.items()}
-
-
-def judgment_binding(pr):
-    return digest({"version": BINDING_VERSION, "repo": REPO,
-                   "source": pr["evidence_digest"], "state": pr_state(pr),
-                   "questions": judge_questions(), "model": MODEL})
-
-
-def current_judgments(prs, *, allow_unbound=False):
-    current = {}
-    for number, record in load_done().items():
-        if number not in prs:
-            continue
-        matches = judgment_is_current(prs[number], record)
-        legacy = "binding" not in record and allow_unbound
-        if matches or legacy:
-            current[number] = dict(record, freshness="current" if matches else "unbound")
-    return current
-
-
-def brief(pr):
-    return {"number": pr["number"], "title": pr["title"], "body": pr["body"][:400],
-            "evidence_basis": "shortened descriptions only; source equivalence not verified"}
-
-
-def pair_binding(prs, a, b):
-    a, b = sorted((a, b))
-    return digest({"version": BINDING_VERSION, "repo": REPO, "model": MODEL,
-                   "sources": [prs[a]["evidence_digest"], prs[b]["evidence_digest"]],
-                   "state": [brief(prs[a]), brief(prs[b])], "questions": pair_questions()})
-
-
-def current_pairs(prs, judgments, *, allow_unbound=False):
-    """Pair verdicts a report may publish.
-
-    A verdict is published when the pair's current descriptions still verify
-    against the record (binding, or the byte-identical inputs it was shown) —
-    that is the same strict rule as before, and it never invents a relationship.
-    A pair whose similarity has since fallen below the discovery threshold is
-    still published when the model actually judged it: the threshold finds
-    candidates, it does not get to hide a verified dupe. Legacy records without a
-    binding are inspection-only behind `allow_unbound`.
-    """
-    pairs = {}
-    for pair, record in current_verdicts(prs).items():
-        a, b = pair
-        if a not in judgments or b not in judgments:
-            continue
-        matches = pair_is_current(prs, pair, record)
-        legacy = "binding" not in record and allow_unbound
-        if matches or legacy:
-            pairs[pair] = dict(record, a=a, b=b,
-                               freshness="current" if matches else "unbound")
-    return list(pairs.values())
-
-
-def pair_cache(prs, judgments) -> dict[tuple[int, int], dict]:
-    """Every captured pair with a stored verdict, newest first.
-
-    The reuse predicate for `dupes` is `reusable_pair` + `pair_is_current`, so a
-    verdict survives a refetch that does not move the evidence it was based on
-    and is replaced the moment evidence, model or policy changes.
-    """
-    return {pair: dict(record, a=pair[0], b=pair[1],
-                       freshness="current" if pair_is_current(prs, pair, record) else "stale")
-            for pair, record in current_verdicts(prs).items()}
-
-
-def cmd_judge(args) -> None:
-    prs = load_prs()
-    done = {n: rec for n, rec in current_judgments(prs).items()
-            if reusable_judgment(rec)} if args.resume else {}
-    if not args.resume:
-        JUDGMENTS_PATH.parent.mkdir(parents=True, exist_ok=True)
-        JUDGMENTS_PATH.write_text("")
-    JUDGMENTS_PATH.parent.mkdir(parents=True, exist_ok=True)
-    todo = [n for n in sorted(prs, reverse=True) if n not in done]
-    if args.limit:
-        todo = todo[: args.limit]
-    print(f"{len(prs)} PRs, {len(done)} already judged, {len(todo)} to go")
-    if not todo:
-        return
-    key = read_key()
-    lock = threading.Lock()
-    errors: list[str] = []
-    tokens_in = tokens_out = 0
-
-    def work(number: int) -> None:
-        nonlocal tokens_in, tokens_out
-        pr = prs[number]
-        try:
-            resp = ask(pr_state(pr), judge_questions(), key)
-            if not isinstance(resp, dict):
-                resp = {}
-            rec = {"number": number, "title": pr["title"], "answers": resp.get("answers"), "usage": resp.get("usage", {}),
-                   "binding": judgment_binding(pr), "input": pr_state(pr),
-                   "source_digest": pr["evidence_digest"], "head_sha": pr["head_sha"],
-                   "updated_at": pr["updated"], "requested_model": MODEL,
-                   "judged_at": datetime.now(timezone.utc).isoformat(),
-                   "resolved_model": resp.get("model"), "request_id": resp.get("request_id")}
-        except TrancheFatal as e:
-            with lock:
-                errors.append(f"#{number}: {e}")
-            if "401" in str(e):
-                raise
-            return
-        rec = normalize_judgment(rec)
-        with lock:
-            with JUDGMENTS_PATH.open("a") as f:
-                f.write(json.dumps(rec, allow_nan=False) + "\n")
-            tokens_in += rec["usage"]["input_tokens"]
-            tokens_out += rec["usage"]["output_tokens"]
-            n = len(done) + 1
-            done[number] = rec
-            if n % 25 == 0:
-                print(f"judged {n}/{len(todo)}  (in {tokens_in} tok / out {tokens_out} tok)")
-
-    try:
-        with ThreadPoolExecutor(max_workers=WORKERS) as ex:
-            futures = [ex.submit(work, n) for n in todo]
-            for f in as_completed(futures):
-                f.result()
-    except TrancheFatal as e:
-        print(f"FATAL: {e}", file=sys.stderr)
-        print("partial progress is saved; re-run with --resume", file=sys.stderr)
-        sys.exit(2)
-
-    print(f"done: {len(done)} matching judgments; errors: {len(errors)}")
-    for e in errors[:10]:
-        print("  " + e)
-    print(f"tokens: in={tokens_in} out={tokens_out}")
-
-
-def load_judgments() -> dict[int, dict]:
-    return load_done()
-
-
-def current_verdicts(prs) -> dict[tuple[int, int], dict]:
-    """Newest stored verdict per pair, for pairs whose members are both captured.
-
-    The log is append-only, so the same pair can appear many times; only the last
-    valid record wins. Records written by older code without a `binding` are kept
-    as unbound evidence, exactly as before.
-    """
-    verdicts: dict[tuple[int, int], dict] = {}
-    if not PAIRS_PATH.exists():
-        return verdicts
-    with PAIRS_PATH.open(encoding="utf-8") as stream:
-        for line in stream:
-            if "\"a\"" not in line:
-                continue
-            try:
-                record = json.loads(line)
-            except json.JSONDecodeError:
-                continue
-            if not isinstance(record, dict) or "error" in record:
-                continue
-            if any(type(record.get(key)) is not int or record[key] <= 0 for key in ("a", "b")):
-                continue
-            pair = (min(record["a"], record["b"]), max(record["a"], record["b"]))
-            if pair[0] == pair[1] or pair[0] not in prs or pair[1] not in prs:
-                continue
-            verdicts[pair] = normalize_pair(record)
-    return verdicts
-
-
-def pair_is_current(prs, pair, record) -> bool:
-    """True when a stored verdict still answers today's question for today's evidence.
-
-    Same rule as `judgment_is_current`: the binding is the single currency test
-    and it digests the full question policy, so a verdict made under an older
-    question set is never presented as current. A moved branch that leaves the
-    two descriptions alone still matches the binding. `input` and
-    `requested_model` are provenance.
-    """
-    a, b = pair
-    return record.get("binding") == pair_binding(prs, a, b)
-
-
-def lexical_pairs(prs, judgments, refs=None, threshold=0.72,
-                  jaccard_threshold=0.62) -> list[tuple[float, int, int]]:
-    """Candidate duplicate pairs: high title similarity within the same judged category."""
-
-    def toks(s):
-        return set(re.findall(r"[a-z0-9]+", s.lower())) - {
-            "the", "a", "an", "and", "or", "to", "of", "for", "in", "on", "with", "fix", "add",
-        }
-
-    by_cat: dict[str, list[int]] = defaultdict(list)
-    for n, j in judgments.items():
-        cat = category(j)
-        by_cat[cat].append(n)
-    pairs = []
-    for nums in by_cat.values():
-        nums = sorted(nums)
-        for i, a in enumerate(nums):
-            ta = prs[a]["title"].lower()
-            for b in nums[i + 1:]:
-                tb = prs[b]["title"].lower()
-                ratio = difflib.SequenceMatcher(None, ta, tb).ratio()
-                if ratio >= threshold:
-                    pairs.append((ratio, a, b))
-                    continue
-                A, B = toks(prs[a]["title"]), toks(prs[b]["title"])
-                if A and B:
-                    jac = len(A & B) / len(A | B)
-                    if jac >= jaccard_threshold:
-                        pairs.append((jac, a, b))
-    pairs.sort(reverse=True)
-    seen = {(a, b) for _, a, b in pairs}
-
-    def pair_key(a, b):
-        return (min(a, b), max(a, b))
-
-    # Cross-referenced PRs (body cites each other) are candidate duplicates even
-    # when titles differ — e.g. fixes to the same bug split across files.
-    for n, pr in prs.items():
-        if n not in judgments or (refs and n not in refs):
-            continue
-        for r in (refs or {}).get(n, pr.get("refs", [])):
-            a, b = pair_key(n, r)
-            if a != b and a in prs and b in prs and a in judgments and b in judgments and (a, b) not in seen:
-                seen.add((a, b))
-                pairs.append((1.0, a, b))
-    pairs.sort(key=lambda t: -t[0])
-    return pairs
-
-
-def candidate_pairs(prs, judgments=None, refs=None) -> dict[tuple[int, int], float]:
-    """The pairs worth a model verdict, as {(a, b): similarity}.
-
-    Similarity alone cannot be trusted as a proxy: the candidate set also
-    carries the title-independent body-reference edges, and it moves whenever
-    one side's title, category or refs change. So the pair cache is keyed by
-    membership in this exact set, not by a single pair's own score.
-    """
-    if judgments is not None:
-        scored = lexical_pairs(prs, judgments, refs=refs)
-    else:
-        scored = lexical_pairs(prs, current_judgments(prs), refs=refs)
-    return {(a, b): score for score, a, b in scored}
-
-
-def outstanding_pairs(prs, judgments) -> list[tuple[float, int, int]]:
-    """The exact work a `dupes` pass would do, best candidate first.
-
-    Defined once and consumed by both `dupes` and `refresh --dry-run`, so the
-    reported count can never disagree with the work performed. A stored verdict
-    that is still current is not work; neither is a pair that has stopped being
-    a candidate (its similarity fell below the threshold or its body reference
-    was removed) even though its verdict is now stale — re-running it would be
-    work that never converges, because nothing asks for that verdict.
-    """
-    cache = pair_cache(prs, judgments)
-    done = {pair for pair, rec in cache.items()
-            if reusable_pair(rec) and rec["freshness"] == "current"}
-    candidates = candidate_pairs(prs, judgments, ref_index(prs))
-    work = [(score, a, b) for (a, b), score in candidates.items() if (a, b) not in done]
-    work.sort(key=lambda item: -item[0])
-    return work
-
-
-def cmd_dupes(args) -> None:
-    prs = load_prs()
-    judgments = current_judgments(prs)
-    missing = len(prs) - len(judgments)
-    if missing > 100:
-        print(f"warning: {missing} PRs not judged yet; dupe pass runs on judged subset", file=sys.stderr)
-    candidates = candidate_pairs(prs, judgments, ref_index(prs))
-    pending = outstanding_pairs(prs, judgments)
-    print(f"{len(pending[:args.max_pairs])} candidate pairs to compare "
-          f"(skipping {len(candidates) - len(pending)} matching records)")
-    pairs = pending[: args.max_pairs]
-    if not pairs:
-        return
-    PAIRS_PATH.parent.mkdir(parents=True, exist_ok=True)
-    key = read_key()
-    lock = threading.Lock()
-    tokens_in = tokens_out = 0
-
-    def work(item):
-        nonlocal tokens_in, tokens_out
-        s, a, b = item
-        if a not in prs or b not in prs:
-            return  # candidate became stale (PR closed and refetched mid-run)
-        resp = ask({"pr_a": brief(prs[a]), "pr_b": brief(prs[b])}, pair_questions(), key)
-        resp = resp if isinstance(resp, dict) else {}
-        data = resp.get("answers")
-        data = data if isinstance(data, dict) else {}
-        answer = data.get("sameness")
-        answer = answer if isinstance(answer, dict) else {}
-        rec = {
-            "a": a, "b": b, "similarity": round(s, 3),
-            "verdict": answer.get("choice"),
-            "probabilities": answer.get("probabilities"),
-            "usage": resp.get("usage", {}),
-            "binding": pair_binding(prs, a, b),
-            "requested_model": MODEL, "resolved_model": resp.get("model"),
-            "request_id": resp.get("request_id"),
-            "judged_at": datetime.now(timezone.utc).isoformat(),
-            "input": {"pr_a": brief(prs[a]), "pr_b": brief(prs[b])},
-        }
-        rec = normalize_pair(rec)
-        with lock:
-            with PAIRS_PATH.open("a") as f:
-                f.write(json.dumps(rec, allow_nan=False) + "\n")
-            tokens_in += pair_usage(rec)[0]
-            tokens_out += pair_usage(rec)[1]
-
-    with ThreadPoolExecutor(max_workers=WORKERS) as ex:
-        futures = [ex.submit(work, it) for it in pairs]
-        for i, f in enumerate(as_completed(futures)):
-            f.result()
-            if (i + 1) % 25 == 0:
-                print(f"compared {i + 1}/{len(pairs)}")
-    print("candidate pair comparison complete")
-    print(f"tokens: in={tokens_in} out={tokens_out}")
-
-
-class DSU:
-    def __init__(self):
-        self.parent = {}
-
-    def find(self, x):
-        self.parent.setdefault(x, x)
-        while self.parent[x] != x:
-            self.parent[x] = self.parent[self.parent[x]]
-            x = self.parent[x]
-        return x
-
-    def union(self, a, b):
-        ra, rb = self.find(a), self.find(b)
-        if ra != rb:
-            self.parent[rb] = ra
-
-
-def metric(judgment, name, field="score"):
-    """Absent, non-finite or out-of-range model values are unknown, never zero."""
-    answer = (judgment.get("answers") or {}).get(name)
-    value = answer.get(field) if isinstance(answer, dict) else None
-    ceiling = 1 if field == "noul" else (4 if name == "risk" else 3)
-    if type(value) not in (int, float) or not 0 <= value <= ceiling or not math.isfinite(value):
-        return None
-    return value
-
-
-def category(judgment):
-    answer = (judgment.get("answers") or {}).get("category")
-    value = answer.get("choice") if isinstance(answer, dict) else None
-    return value if isinstance(value, str) and value in judge_questions()["category"]["criteria"] else "unclear"
-
-
-def p_same(pair):
-    probabilities = pair.get("probabilities")
-    value = probabilities.get("same_change") if isinstance(probabilities, dict) else None
-    return value if type(value) in (int, float) and 0 <= value <= 1 and math.isfinite(value) else None
-
-
-def pair_classification(pair):
-    """Separate genuine contradictions from the human-review threshold band."""
-    probability = p_same(pair)
-    verdict = pair.get("verdict")
-    if probability is None or verdict not in ("same_change", "related_but_different", "unrelated"):
-        return "malformed"
-    if verdict == "same_change":
-        return "same" if probability >= 0.65 else ("contradictory" if probability < 0.35 else "uncertain")
-    return "different" if probability < 0.35 else ("contradictory" if probability >= 0.65 else "uncertain")
-
-
-def accepted_pair(pair):
-    return pair_classification(pair) == "same"
-
-
-def duplicate_groups(verdicts):
-    """Connectivity proposes groups; every internal relationship remains visible."""
-    dsu = DSU()
-    indexed = {(v["a"], v["b"]): v for v in verdicts}
-    for v in verdicts:
-        if accepted_pair(v):
-            dsu.union(v["a"], v["b"])
-    connected = defaultdict(list)
-    for number in sorted(dsu.parent):
-        connected[dsu.find(number)].append(number)
-    consistent, review = [], []
-    for members in sorted(connected.values(), key=lambda g: (-len(g), g)):
-        if len(members) < 2:
-            continue
-        conflicts, uncertain, missing = [], [], []
-        unbound = False
-        for a, b in combinations(members, 2):
-            pair = indexed.get((a, b))
-            if pair is None:
-                missing.append([a, b])
-                continue
-            unbound |= pair.get("freshness") != "current"
-            if accepted_pair(pair):
-                continue
-            classification = pair_classification(pair)
-            diagnostic = {"a": a, "b": b, "verdict": pair.get("verdict"),
-                          "p_same": p_same(pair), "classification": classification}
-            # Strong difference evidence conflicts with the proposed group;
-            # a self-contradictory model response also requires relationship review.
-            if classification in ("different", "contradictory"):
-                conflicts.append(diagnostic)
-            else:
-                uncertain.append(diagnostic)
-        if conflicts or uncertain or missing or unbound:
-            review.append({"members": members, "conflicting_pairs": conflicts,
-                           "uncertain_pairs": uncertain, "missing_pairs": missing,
-                           "unbound_evidence": unbound})
-        else:
-            consistent.append(members)
-    return consistent, review
-
-
-def review_candidate(pr, judgment, grouped):
-    required = [metric(judgment, "risk"), metric(judgment, "finished_form"),
-                metric(judgment, "is_fix", "noul"), metric(judgment, "security_flag", "noul"),
-                metric(judgment, "review_effort")]
-    if (judgment.get("freshness") != "current" or not reusable_judgment(judgment) or pr["draft"]
-            or pr["number"] in grouped or any(value is None for value in required)):
-        return False
-    risk, finished, fix, security, _ = required
-    return risk <= 1.5 and finished >= 1.8 and fix >= 0.6 and security < 0.5
-
-
-def escalated(judgment):
-    risk, security = metric(judgment, "risk"), metric(judgment, "security_flag", "noul")
-    return (risk is not None and risk >= 3) or (security is not None and security >= 0.5)
-
-
-def security_priority(judgment):
-    """Issue #3: a cross-cutting meta-category ranked above every other category.
-
-    Membership uses the same 0.5 probability bar as senior escalation; unlike a
-    category choice it never replaces the PR's own area. Unknown stays unknown.
-    """
-    security = metric(judgment, "security_flag", "noul")
-    return security is not None and security >= SECURITY_PRIORITY
-
-
-# ---------------------------------------------------------------------------
-# Issue #4 — pre-release batches. A batch is 5 PRs merged together as one
-# tranche. Jev determines the composition: model-consistent same_change groups
-# are atomic units (their PRs combine into ONE pull request inside the batch),
-# remaining PRs fill the batch up to five. Units are ordered security-first,
-# then average model risk, then age. Batches are strictly disjoint — every PR
-# belongs to at most one batch — and review groups (contradictory or untested
-# internal evidence) are excluded entirely so no PR is claimed twice.
-# ---------------------------------------------------------------------------
-
-BATCH_SIZE = 5
-
-# Issue #8: park is a hold with a named unblock path, never a close. A parked
-# PR re-enters automatically: the author pushes, the judgment re-binds, the
-# next refresh re-packs. Closing remains a maintainer decision.
-PARK_UNBLOCK = {
-    "draft": "Author marks the pull request ready for review; the next fetch "
-             "recaptures it and the next batches run re-packs it.",
-    "finished_form": "Author adds the missing description or QA evidence; "
-                     "judge --resume re-binds the judgment and the PR re-enters "
-                     "on the next refresh.",
-    "unjudged_or_stale": "Run judge --resume (or refresh) to restore a current "
-                         "judgment; the PR re-enters on the next batches run.",
-    "same_change_hold": "Held with its same_change group: atomic units are never "
-                        "split, so the group re-enters together when every member "
-                        "clears its own park reason.",
-}
-
-
-def park_set(prs, judgments):
-    """Issue #8: pipeline-legible park decisions, keyed by PR number.
-
-    Reasons come only from facts the pipeline already holds — the draft bit,
-    the finished-form score, the judgment's freshness. One predicate serves
-    every consumer (batches, parked.json, workbench, MCP). A finished form
-    just above 1 is not parked; a missing judgment parks under its own reason.
-    """
-    parks = {}
-    for n, item in sorted(prs.items()):
-        reasons = []
-        if item.get("draft"):
-            reasons.append("draft")
-        judgment = judgments.get(n)
-        if judgment is None:
-            reasons.append("unjudged_or_stale")
-        else:
-            finished = metric(judgment, "finished_form")
-            if finished is not None and finished <= 1:
-                reasons.append("finished_form")
-        if reasons:
-            parks[n] = reasons
-    return parks
-
-
-def parked_payload(parks, prs, judgments, dupes_digest):
-    """First-class park record: the security meta-category's discipline, second
-    instance. Membership never replaces the PR's own category."""
-    members = []
-    for n in sorted(parks):
-        item = prs.get(n, {})
-        members.append({
-            "number": n, "title": item.get("title", ""), "author": item.get("author", ""),
-            "reasons": list(parks[n]),
-            "unblock": " ".join(PARK_UNBLOCK[reason] for reason in parks[n]),
-            "head_sha": item.get("head_sha"), "url": item.get("url"),
-            "created": item.get("created", ""),
-            "security_flag": metric(judgments.get(n, {}), "security_flag", "noul"),
-        })
-    return {
-        "format_version": 1, "repo": REPO, "dupes_digest": dupes_digest,
-        "parked": len(members),
-        "meaning": "Parked before batching (issue #8): drafts, PRs without finished "
-                   "form, PRs without a current judgment, and same_change groups "
-                   "holding for a parked member. A hold with a named unblock path, "
-                   "never a close; re-entry is automatic when the reason clears.",
-        "members": members,
-    }
-
-
-def batch_review_prompt(members, batch_id, prs):
-    """Reviewer agent prompt: point it at every PR of the batch and demand a
-    methodical unified proposal + plan. Deterministic, self-contained text."""
-    listed = "\n".join(f"- #{n}: {prs[n]['title']} — {prs[n]['url']}" for n in members
-                       if n in prs)
-    return (
-        f"You are reviewing Omarchy pre-release batch {batch_id} ({len(members)} PRs to be "
-        f"merged together as one tranche).\n\n"
-        f"Pull requests in this batch:\n{listed}\n\n"
-        "Work through the batch methodically:\n"
-        "1. Read every PR fully — description, diff, and review comments. For PRs Jev flagged "
-        "as the same change, verify they truly overlap and identify the strongest implementation "
-        "of each.\n"
-        "2. Map dependencies between the PRs (shared files, ordering constraints, conflicts) and "
-        "check each PR's CI status.\n"
-        "3. Produce ONE unified proposal for the batch: what merges, in which order, what gets "
-        "squashed or dropped, and why — as a single coherent plan, not per-PR verdicts.\n"
-        "4. Verify the plan: does the combined result still build and pass tests? Any PR that "
-        "cannot be verified stays out — say so explicitly.\n"
-        "5. Deliver: (a) the unified proposal, (b) a step-by-step merge plan with exact commands, "
-        "(c) risks with mitigations, (d) an explicit list of anything excluded and why.\n\n"
-        "Facts over plausibility: base every claim on the actual diffs and CI state, never on "
-        "titles alone. You are proposing — the human decides."
-    )
-
-
-def park_state(dupes, judgments, prs):
-    """One park predicate for every consumer: own reasons plus same_change_hold
-    for every member of a confirmed group that waits for a parked member.
-    Atomic units are never split — pulling one member out would leave the rest
-    of the group claimed twice or held entirely."""
-    parks = park_set(prs, judgments)
-    for members in dupes["confirmed_groups"]:
-        if any(m in parks for m in members):
-            for m in members:
-                entry = parks.setdefault(m, [])
-                if "same_change_hold" not in entry:
-                    entry.append("same_change_hold")
-    return parks
-
-
-def pr_activity(pr, record):
-    """Head evidence is distinct from GitHub thread churn (including bots).
-
-    A matching recorded head establishes an idle lower bound at judgment time.
-    An unjudged PR has only its creation date as an age proxy. GitHub's
-    updated_at is displayed as thread metadata, never used for priority.
-    """
-    bound_head = record.get("head_sha")
-    head_moved = bool(bound_head and pr.get("head_sha") and bound_head != pr["head_sha"])
-    idle_since = None if head_moved else (
-        record.get("judged_at") if bound_head and bound_head == pr.get("head_sha")
-        else pr.get("created"))
-    return {"head_moved": head_moved, "idle_since": idle_since,
-            "idle_basis": "unknown" if head_moved or not idle_since else
-                          "judgment" if bound_head and bound_head == pr.get("head_sha")
-                          and record.get("judged_at") else "creation",
-            "thread_updated": pr.get("updated")}
-
-
-def merge_batches(dupes, judgments, prs, dupes_digest):
-    """Pack PRs into security-first batches of five, Jev-determined.
-
-    Issue #8: parked PRs never enter a batch. A batch prompt claims exactly one
-    thing — these PRs merge together — so a draft, a PR without finished form,
-    or a PR without a current judgment must not appear in it."""
-    parks = park_state(dupes, judgments, prs)
-
-    def security_count(members):
-        return sum(1 for n in members
-                   if (metric(judgments.get(n, {}), "security_flag", "noul") or 0) >= SECURITY_PRIORITY)
-
-    def unit_stats(members):
-        risks = [value for n in members if (value := metric(judgments.get(n, {}), "risk")) is not None]
-        return (security_count(members),
-                round(sum(risks) / len(risks), 2) if risks else None,
-                min((prs[n]["created"] for n in members if n in prs), default=""))
-
-    grouped, units = set(), []
-    for members in dupes["confirmed_groups"]:
-        if any(m in parks for m in members):
-            grouped.update(members)
-            continue  # the whole atomic unit waits; it re-enters together
-        grouped.update(members)
-        security, average_risk, created = unit_stats(members)
-        units.append({"members": list(members), "same_change": True, "security": security,
-                      "risk": average_risk, "created": created})
-    excluded = set()
-    for group in dupes["review_groups"]:
-        excluded.update(group["members"])
-    for n in sorted(prs):
-        if n not in grouped and n not in excluded and n not in parks:
-            security, average_risk, created = unit_stats([n])
-            units.append({"members": [n], "same_change": False, "security": security,
-                          "risk": average_risk, "created": created})
-    # Security outranks all risk bands; within a band, the longest evidenced
-    # quiet head goes first. The newest bound in an atomic unit is its floor.
-    def unit_priority(unit):
-        activity = [pr_activity(prs[n], judgments.get(n, {})) for n in unit["members"]]
-        moving = any(item["head_moved"] for item in activity)
-        idle = max((item["idle_since"] or "9999" for item in activity), default="9999")
-        risk = unit["risk"]
-        band = 3 if risk is None else 0 if risk <= 1.5 else 1 if risk <= 2.5 else 2
-        return (-unit["security"], band, moving, idle, unit["created"], unit["members"][0])
-
-    units.sort(key=unit_priority)
-    packed, current = [], []
-    for unit in units:
-        if current and len(current) + len(unit["members"]) > BATCH_SIZE:
-            packed.append(current)
-            current = []
-        current.extend(unit["members"])
-    if current:
-        packed.append(current)
-    if {n for members in packed for n in members} & set(parks):
-        raise TrancheFatal("internal error: a parked PR entered a batch (issue #8 gate failed)")
-    batches = []
-    for ordinal, members in enumerate(packed, 1):
-        security, average_risk, created = unit_stats(members)
-        groups = sum(1 for unit in units if unit["same_change"] and set(unit["members"]) <= set(members))
-        batches.append({
-            "ordinal": ordinal, "id": f"B{ordinal:03d}",
-            "members": members, "count": len(members),
-            "target": "merged together as one tranche",
-            "same_change_groups": groups,
-            "security_members": security, "average_risk": average_risk, "created": created,
-            "review_prompt": batch_review_prompt(members, f"B{ordinal:03d}", prs),
-        })
-    return {
-        "format_version": 3, "repo": REPO, "dupes_digest": dupes_digest,
-        "batch_size": BATCH_SIZE,
-        "meaning": "A batch is 5 PRs merged together as one tranche (issue #4). Jev determines the "
-                   "composition: same_change groups are atomic and combine into ONE pull request "
-                   "inside their batch. Batches are disjoint: every PR belongs to at most one batch. "
-                   "Ordered security-first, then risk band and evidenced idle lower bound. "
-                   "Parked PRs are excluded before packing (issue #8). "
-                   "Model-suggested, not verified safe to merge.",
-        "batches": batches,
-        "security_batches": sum(1 for b in batches if b["security_members"] > 0),
-        "same_change_groups": sum(b["same_change_groups"] for b in batches),
-        "excluded_review_prs": len(excluded),
-        "parked_prs": len(parks),
-    }
-
-
-def cmd_batches(args) -> None:
-    """Write out/batches.json and the tranches.md batch plan (issue #4)."""
-    summary = json.loads((OUT_DIR / "summary.json").read_text())
-    dupes = json.loads((OUT_DIR / "dupes.json").read_text())
-    clusters = json.loads((OUT_DIR / "clusters.json").read_text())
-    if summary.get("format_version") != 2 or summary.get("repo") != REPO:
-        raise TrancheFatal("Unrecognized cluster observation; run cluster first")
-    digests = summary.get("output_digests", {})
-    if digests.get("clusters.json") != digest(clusters):
-        raise TrancheFatal("clusters.json does not match the recorded digest; run cluster first")
-    if digests.get("dupes.json") != digest(dupes):
-        raise TrancheFatal("dupes.json does not match the recorded digest; run cluster first")
-    prs = load_prs()
-    judgments = current_judgments(prs)
-    batches = merge_batches(dupes, judgments, prs, digests["dupes.json"])
-    parks = park_state(dupes, judgments, prs)
-    atomic_json(OUT_DIR / "batches.json", batches)
-    atomic_json(OUT_DIR / "parked.json", parked_payload(parks, prs, judgments, digests["dupes.json"]))
-    append_batch_plan(batches)
-    if parks:
-        append_park_section(parks, prs)
-    print(f"{len(batches['batches'])} batches of ≤ {batches['batch_size']} PRs "
-          f"({batches['security_batches']} security-first, {batches['same_change_groups']} "
-          f"same-change groups, {batches['excluded_review_prs']} review-group PRs excluded, "
-          f"{batches['parked_prs']} parked)")
-    print(f"wrote {OUT_DIR}/batches.json, {OUT_DIR}/parked.json")
-
-
-def append_batch_plan(batches) -> None:
-    """Append the suggested batch plan to the published tranches.md."""
-    path = OUT_DIR / "tranches.md"
-    if not path.exists():
-        return  # cluster owns the report; batches only append its plan section.
-    lines = ["", "# Suggested pre-release batches (issue #4)", "",
-             f"A batch is **{batches['batch_size']} PRs merged together as one tranche**. Jev determines",
-             "the composition: model-consistent same_change groups are atomic — their PRs combine into",
-             "ONE pull request inside the batch. Batches are disjoint (every PR is in at most one",
-             "batch); review groups are excluded on purpose. Ordered security-first, then",
-             "risk band and evidenced head idle time. Model-suggested, never verified safe to merge.", "",
-             f"Batches: {len(batches['batches'])} · security-first batches: "
-             f"{batches['security_batches']} · same-change groups: "
-             f"{batches['same_change_groups']} · review-group PRs excluded: "
-             f"{batches['excluded_review_prs']}.", ""]
-    if batches["batches"]:
-        lines += ["| Batch | Size | Security | Avg risk | Groups | Members |",
-                  "|---|---|---|---|---|---|"]
-        for batch in batches["batches"]:
-            members = " ".join(f"#{n}" for n in batch["members"])
-            risk = "unknown" if batch["average_risk"] is None else f"{batch['average_risk']:.1f}"
-            lines.append(f"| {batch['id']} | {batch['count']} | "
-                         f"{batch['security_members'] or '—'} | {risk} | "
-                         f"{batch['same_change_groups'] or '—'} | {members} |")
-        lines += ["", "## Reviewer agent prompts", "",
-                  "Copy-paste a prompt into an agent to start a thorough, methodical review that",
-                  "produces one unified proposal + merge plan for the batch.", ""]
-        for batch in batches["batches"]:
-            lines += [f"### {batch['id']}", "", "```", batch["review_prompt"], "```", ""]
-    text = "\n".join(lines).rstrip("\n") + "\n"
-    with path.open("a", encoding="utf-8") as stream:
-        stream.write(text)
-
-
-def append_park_section(parks, prs) -> None:
-    """Append the park record (issue #8) to the published tranches.md.
-    Batches append; cluster owns the file."""
-    path = OUT_DIR / "tranches.md"
-    if not path.exists():
-        return
-    lines = ["", "# Parked before batching (issue #8)", "",
-             f"{len(parks)} PRs are parked: drafts, PRs without finished form, PRs without a",
-             "current judgment, and same_change groups holding for a parked member. Park is a",
-             "**hold with a named unblock path, never a close** — re-entry is automatic when the",
-             "reason clears and the next refresh re-packs. No batch lists a parked PR.",
-             "",
-             f"Reasons: draft {sum('draft' in r for r in parks.values())} · "
-             f"finished_form {sum('finished_form' in r for r in parks.values())} · "
-             f"unjudged_or_stale {sum('unjudged_or_stale' in r for r in parks.values())} · "
-             f"same_change_hold {sum('same_change_hold' in r for r in parks.values())}.", "",
-             "| PR | Reasons | Unblocked by |", "|---|---|---|"]
-    for n, reasons in sorted(parks.items()):
-        unblock = " ".join(PARK_UNBLOCK[reason] for reason in reasons)
-        lines.append(f"| #{n} | {', '.join(reasons)} | {unblock} |")
-    lines += ["", "Parked does not remove a security-flagged PR from the security meta-category;",
-              "it only removes it from merge batches. Full record: out/parked.json.", ""]
-    text = "\n".join(lines).rstrip("\n") + "\n"
-    with path.open("a", encoding="utf-8") as stream:
-        stream.write(text)
-
-
-def report_binding(prs, judgments, verdicts):
-    return digest({"version": BINDING_VERSION, "repo": REPO,
-                   "sources": {n: {"source": pr["source_digest"],
-                                   "evidence": pr["evidence_digest"],
-                                   "references": pr["ref_digest"]}
-                               for n, pr in prs.items()},
-                   "judgments": judgments, "pairs": verdicts,
-                   "questions": [judge_questions(), pair_questions()], "model": MODEL})
-
-
-def cmd_cluster(args) -> None:
-    prs = load_prs()
-    allow_unbound = getattr(args, "allow_unbound", False)
-    judgments = current_judgments(prs, allow_unbound=allow_unbound)
-    verdicts = current_pairs(prs, judgments, allow_unbound=allow_unbound)
-    OUT_DIR.mkdir(parents=True, exist_ok=True)
-    dupe_groups, review_groups = duplicate_groups(verdicts)
-    in_group = {n for g in dupe_groups for n in g} | {n for g in review_groups for n in g["members"]}
-    uncertain_pairs = [{"a": v["a"], "b": v["b"], "p_same": p_same(v),
-                        "similarity": v.get("similarity"), "verdict": v.get("verdict"),
-                        "classification": pair_classification(v)}
-                       for v in verdicts if pair_classification(v) in
-                       ("uncertain", "contradictory", "malformed")]
-    uncertain_pairs.sort(key=lambda v: -(v["p_same"] if v["p_same"] is not None else -1))
-
-    clusters = {}
-    tranches = defaultdict(list)
-    security_review = []
-    follow_up, escalate = [], []
-    for n, j in sorted(judgments.items()):
-        risk = metric(j, "risk")
-        band = "unknown" if risk is None else ("low" if risk <= 1.5 else ("core" if risk <= 2.5 else "danger"))
-        cat = category(j)
-        item = {"number": n, "title": prs[n]["title"], "author": prs[n]["author"],
-                "risk": risk, "finished_form": metric(j, "finished_form"),
-                "is_fix": metric(j, "is_fix", "noul"), "review_effort": metric(j, "review_effort"),
-                "security_flag": metric(j, "security_flag", "noul"), "freshness": j["freshness"],
-                "superseded_by": None, "source_digest": prs[n]["source_digest"],
-                "evidence_digest": prs[n]["evidence_digest"],
-                "head_sha": prs[n]["head_sha"], "url": prs[n]["url"]}
-        clusters.setdefault(cat, {}).setdefault(band, []).append(item)
-        if review_candidate(prs[n], j, in_group):
-            tranches[cat].append(item)
-        if security_priority(j):
-            security_review.append(item)
-        finished = metric(j, "finished_form")
-        if finished is not None and finished <= 1 and n not in in_group:
-            follow_up.append(n)
-        if escalated(j):
-            escalate.append(n)
-    # Issue #3: the security meta-category is a first-class output key, ordered
-    # before every category when consumers read clusters.json.
-    security_review.sort(key=lambda it: (-(it["security_flag"]
-                         if it["security_flag"] is not None else -1), it["number"]))
-    clusters_payload = {"security-review": security_review, **clusters}
-    tokens = Counter()
-    for record in [*judgments.values(), *verdicts]:
-        for field in ("input_tokens", "output_tokens"):
-            value = record.get("usage", {}).get(field)
-            if type(value) is int and value >= 0:
-                tokens[field] += value
-
-    dupes = {"confirmed_groups": dupe_groups, "review_groups": review_groups,
-             "uncertain_pairs": uncertain_pairs,
-             "meaning": "Model-consistent candidate groups, not verified duplicates. No survivor selected."}
-    summary = {
-        "format_version": 2, "repo": REPO, "prs_in_corpus": len(prs), "judged": len(judgments),
-        "unjudged_or_stale": len(prs) - len(judgments),
-        "unbound_judgments": sum(j["freshness"] == "unbound" for j in judgments.values()),
-        "allow_unbound": allow_unbound, "report_binding": report_binding(prs, judgments, verdicts),
-        "dupe_groups": len(dupe_groups), "review_groups": len(review_groups),
-        "uncertain_pairs": len(uncertain_pairs), "prs_in_dupe_groups": len(in_group),
-        "superseded": 0, "ready_tranches": len(tranches),
-        "ready_prs": sum(map(len, tranches.values())),
-        "recommendation_kind": "review-candidates", "needs_author_followup": len(follow_up),
-        "escalate_review": len(escalate), "security_priority": len(security_review),
-        "unknown_risk_or_security": sum(metric(j, "risk") is None or metric(j, "security_flag", "noul") is None
-                                        for j in judgments.values()),
-        "tokens": {"input": tokens["input_tokens"], "output": tokens["output_tokens"]},
-        "output_digests": {"clusters.json": digest(clusters_payload), "dupes.json": digest(dupes)},
-    }
-    # Issue #3: the security meta-category ships with top priority — its own key
-    # inside clusters.json, sorted probability-first, before any category output.
-    atomic_json(OUT_DIR / "clusters.json", clusters_payload)
-    atomic_json(OUT_DIR / "dupes.json", dupes)
-    lines = [
-        "# Tranche — PR review candidates", "",
-        f"Corpus: {len(prs)} observed open PRs; {len(judgments)} matching judgments; "
-        f"{summary['unjudged_or_stale']} unjudged/stale; {summary['unbound_judgments']} unbound legacy judgments.",
-        f"Review candidates: {summary['ready_prs']}. Model-consistent groups: {len(dupe_groups)}. "
-        f"Groups needing relationship review: {len(review_groups)}. "
-        f"Security-priority items: {summary['security_priority']} (meta-category, reviewed first).", "",
-        "Evidence: titles and shortened descriptions (1200 characters per PR; 400 per pair). "
-        "Diffstat is unknown unless captured input supplies it. Patches, CI, reproductions, "
-        "fix coverage and security have not been verified. Model scores are suggestions, "
-        "not calibrated guarantees or approval to merge/close. Pagination records an observation, not a point-in-time GitHub snapshot.", "",
-    ]
-    if allow_unbound:
-        lines += ["LEGACY INSPECTION: unbound judgments cannot establish freshness or enter review-candidate tranches.", ""]
-    def cell(value):
-        return str(value).replace("|", "\\|").replace("\n", " ")
-    def candidate_row(it):
-        return (f"| [#{it['number']}]({it['url']}) | {cell(it['title'][:80])} | {cell(it['author'])} | "
-                f"{it['finished_form']:.1f} | {it['review_effort']:.1f} | {it['is_fix']:.2f} |")
-    CANDIDATE_TABLE = ("| PR | Title | Author | Model finished | Model effort | Model fix |\n"
-                       "|---|---|---|---|---|---|")
-    if security_review:
-        # Issue #3: security ranks above every category in the report.
-        lines += ["## Security review — top priority (meta-category)", "",
-                  "These PRs touch credentials, remote code execution, sudo/permissions, network",
-                  "exposure or crypto material (model probability ≥ "
-                  f"{SECURITY_PRIORITY}). Review before any category batch.", "",
-                  CANDIDATE_TABLE, *[candidate_row(it) for it in security_review], ""]
-    for cat, candidates in sorted(tranches.items(), key=lambda t: -len(t[1])):
-        lines += [f"## Review candidates: {cat} — {len(candidates)} PRs", "", CANDIDATE_TABLE,
-                  *[candidate_row(it) for it in candidates]]
-        lines.append("")
-    for label, groups in (("Model-consistent candidate groups — verify fix coverage; no survivor selected", dupe_groups),
-                          ("Candidate groups needing relationship review", review_groups)):
-        if groups:
-            lines += [f"## {label}", ""]
-            for group in groups:
-                members = group if isinstance(group, list) else group["members"]
-                lines.append("- " + ", ".join(f"#{n}" for n in members))
-                if isinstance(group, dict):
-                    for field in ("conflicting_pairs", "uncertain_pairs", "missing_pairs"):
-                        if group[field]:
-                            lines.append(f"  - {field}: {json.dumps(group[field])}")
-                    if group["unbound_evidence"]:
-                        lines.append("  - Unbound legacy evidence; revisions cannot be checked.")
-            lines.append("")
-    if uncertain_pairs:
-        lines += ["## Uncertain pairs — human comparison needed", ""]
-        for pair in uncertain_pairs:
-            lines.append(f"- #{pair['a']} ↔ #{pair['b']}: P(same)={pair['p_same']}; "
-                         f"verdict={pair['verdict']}; {pair['classification']}")
-        lines.append("")
-    for label, numbers in (("Escalate for risk/security review", escalate),
-                           ("Possible author follow-up — verify before requesting changes", follow_up)):
-        if numbers:
-            lines += [f"## {label}", "", *[f"- #{n} {cell(prs[n]['title'])}" for n in numbers], ""]
-    (OUT_DIR / "tranches.md").write_text("\n".join(lines), encoding="utf-8")
-    # Commit the report manifest last. The renderer rejects mixed generations.
-    atomic_json(OUT_DIR / "summary.json", summary)
-    print(json.dumps(summary, indent=1))
-    print(f"\nwrote {OUT_DIR}/clusters.json dupes.json tranches.md summary.json")
-
-
-def cmd_refresh(args) -> None:
-    """Deterministic incremental refresh: the documented one-command pipeline.
-
-    Runs the same steps in the same order every time and reuses everything the
-    caches can still support, so the work is proportional to what actually
-    changed since the last pass rather than to the corpus size.
-    """
-    steps = [step for step in ("fetch", "judge", "dupes", "cluster", "batches", "page")
-             if not (step == "page" and args.no_page)]
-    before = None
-    summary_path = OUT_DIR / "summary.json"
-    if summary_path.exists():
-        try:
-            before = json.loads(summary_path.read_text())
-        except json.JSONDecodeError:
-            before = None
-    batches_path = OUT_DIR / "batches.json"
-    before_batches = None
-    if batches_path.exists():
-        try:
-            before_batches = json.loads(batches_path.read_text())
-        except json.JSONDecodeError:
-            before_batches = None
-
-    if args.dry_run:
-        prs = load_prs()
-        judgments = current_judgments(prs)
-        pending = outstanding_pairs(prs, judgments)
-        print(f"refresh plan ({' -> '.join(steps)}), no changes written:")
-        print(f"  judged now          {len(judgments)}/{len(prs)} captured PRs")
-        print(f"  pair verdicts to re-run  {len(pending)} of "
-              f"{len(candidate_pairs(prs, judgments, ref_index(prs)))} candidates")
-        if "fetch" in steps:
-            print("  fetch               would re-read open-PR membership from GitHub")
-        return
-
-    print(f"refresh: {' -> '.join(steps)}")
-    for step in steps:
-        if step == "fetch":
-            cmd_fetch(argparse.Namespace(transport="gh"))
-        elif step == "judge":
-            cmd_judge(argparse.Namespace(resume=True, limit=None))
-        elif step == "dupes":
-            cmd_dupes(argparse.Namespace(max_pairs=args.max_pairs))
-        elif step == "cluster":
-            cmd_cluster(argparse.Namespace(allow_unbound=False))
-        elif step == "batches":
-            cmd_batches(argparse.Namespace())
-        elif step == "page":
-            render_page()
-
-    after = json.loads(summary_path.read_text()) if summary_path.exists() else {}
-    after_batches = json.loads(batches_path.read_text()) if batches_path.exists() else {}
-    print("\nrefresh complete")
-    for key in ("prs_in_corpus", "judged", "dupe_groups", "review_groups",
-                "uncertain_pairs", "ready_prs", "escalate_review", "security_priority"):
-        old, new = (before or {}).get(key), after.get(key)
-        marker = "" if old == new else f"   (was {old})"
-        print(f"  {key:<22} {new}{marker}")
-    old, new = (before_batches or {}).get("parked_prs"), after_batches.get("parked_prs")
-    marker = "" if old == new else f"   (was {old})"
-    print(f"  {'parked_prs':<22} {new}{marker}")
-
-
-def render_page() -> None:
-    """Render docs/index.html through gen_page.py, refusing inconsistent inputs."""
-    result = subprocess.run([sys.executable, str(ROOT / "gen_page.py")],
-                            capture_output=True, text=True)
-    sys.stdout.write(result.stdout)
-    if result.returncode:
-        sys.stderr.write(result.stderr)
-        raise TrancheFatal("page rendering failed; out/ inputs were not rewritten")
-
-
-def main() -> None:
-    # Imported here, not at module scope: `evidence` imports tranche, and the
-    # pipeline must stay importable without pulling the evidence service in.
-    # Under __main__ the same module object is `__main__`, so importing `tranche`
-    # here would create a second copy of this module's state; importing from
-    # `tranche` when it is already `__main__` avoids that by construction.
-    import evidence
-
-    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
-    sub = ap.add_subparsers(dest="cmd", required=True)
-    fetch = sub.add_parser("fetch", help="refresh observed open-PR membership from GitHub")
-    fetch.add_argument("--transport", choices=("gh", "urllib", "curl"), default="gh",
-                       help="gh (authenticated via the gh CLI, default), curl or urllib")
-    j = sub.add_parser("judge", help="Jev judgment pass over PRs")
-    j.add_argument("--limit", type=int, default=None, help="judge only the N newest unjudged PRs")
-    j.add_argument("--resume", action="store_true", help="reuse judgments bound to unchanged input/questions/model")
-    d = sub.add_parser("dupes", help="compare candidate pairs with Jev")
-    d.add_argument("--max-pairs", type=int, default=300)
-    cluster = sub.add_parser("cluster", help="build candidate groups and review reports offline")
-    cluster.add_argument("--allow-unbound", action="store_true", help="inspect legacy judgments with freshness warnings; no legacy review tranches")
-    sub.add_parser("batches", help="classify review candidates into cumulative pre-release batches (issue #4)")
-    refresh = sub.add_parser("refresh", help="deterministic incremental refresh: fetch → judge → dupes → cluster → batches → page")
-    refresh.add_argument("--max-pairs", type=int, default=400,
-                         help="cap model pair comparisons this pass (default 400)")
-    refresh.add_argument("--no-page", action="store_true", help="skip rendering docs/index.html")
-    refresh.add_argument("--dry-run", action="store_true", help="report what would change without writing")
-    a = sub.add_parser("all", help="judge --resume, dupes, cluster, batches")
-    a.add_argument("--limit", type=int, default=None)
-    a.add_argument("--resume", action="store_true", help="accepted for compatibility; all always resumes")
-    a.add_argument("--max-pairs", type=int, default=300)
-    evidence.add_parser(sub)
-    args = ap.parse_args()
-    if getattr(args, "limit", None) is not None and args.limit <= 0:
-        ap.error("--limit must be positive")
-    if getattr(args, "max_pairs", 0) < 0:
-        ap.error("--max-pairs must be nonnegative")
-    if args.cmd == "evidence":
-        # Evidence is a separate, read-only service; its exit codes are its own.
-        raise SystemExit(evidence.dispatch(args))
-    if args.cmd == "fetch":
-        cmd_fetch(args)
-    elif args.cmd == "judge":
-        cmd_judge(args)
-    elif args.cmd == "dupes":
-        cmd_dupes(args)
-    elif args.cmd == "cluster":
-        cmd_cluster(args)
-    elif args.cmd == "batches":
-        cmd_batches(args)
-    elif args.cmd == "refresh":
-        cmd_refresh(args)
-    elif args.cmd == "all":
-        args.resume = True
-        cmd_judge(args)
-        cmd_dupes(args)
-        cmd_cluster(args)
-        cmd_batches(args)
-
-
-if __name__ == "__main__":
-    main()