diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a43b5e9..864d276 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,8 +27,11 @@ jobs: pre-release-gate: name: Pre-release Gate runs-on: ubuntu-latest + outputs: + prerelease: ${{ steps.release_ref.outputs.prerelease }} steps: - name: Verify release ref + id: release_ref shell: bash run: | set -euo pipefail @@ -36,6 +39,11 @@ jobs: echo "::error::Release workflow requires a semver tag like v0.1.3; got ${RELEASE_TAG}." exit 1 fi + if [[ "${RELEASE_TAG}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+- ]]; then + echo "prerelease=true" >> "$GITHUB_OUTPUT" + else + echo "prerelease=false" >> "$GITHUB_OUTPUT" + fi if [[ "${GITHUB_REF_TYPE}" != "tag" && -z "${{ inputs.tag }}" ]]; then echo "::error::Manual release runs from a branch must provide the tag input." exit 1 @@ -66,10 +74,10 @@ jobs: run: cargo fmt --all -- --check - name: Run clippy - run: cargo clippy --all-targets -- -D warnings + run: cargo clippy --all-features --all-targets -- -D warnings - name: Run tests - run: cargo test --all-targets + run: cargo test --all-features --all-targets - name: Build release binary run: cargo build --release @@ -81,7 +89,7 @@ jobs: - name: Verify generated man pages run: | - cargo run --bin gen-man -- /tmp/keito-man + cargo run --features dev-tools --bin gen-man -- /tmp/keito-man test -s /tmp/keito-man/keito.1 test -s /tmp/keito-man/keito-auth-login.1 test -s /tmp/keito-man/keito-time-stop.1 @@ -102,7 +110,7 @@ jobs: - target: aarch64-apple-darwin os: macos-latest - target: x86_64-apple-darwin - os: macos-latest + os: macos-15-intel - target: x86_64-unknown-linux-gnu os: ubuntu-latest - target: x86_64-pc-windows-msvc @@ -131,20 +139,44 @@ jobs: restore-keys: | ${{ runner.os }}-${{ matrix.target }}-cargo-release-build- - - name: Build - run: cargo build --release --target ${{ matrix.target }} + # The companion is finalized first. Any future signing/notarization must + # finish here, before its bytes are anchored in the main executable. + - name: Build final native guard + run: cargo build --locked --release --target ${{ matrix.target }} --bin keito-capture-guard + + - name: Build release-bound core and manifest + run: | + set -euo pipefail + suffix="" + if [[ "${{ runner.os }}" == "Windows" ]]; then suffix=".exe"; fi + release_dir="target/${{ matrix.target }}/release" + guard_hash=$(sha256sum "$release_dir/keito-capture-guard$suffix" | awk '{print $1}') + KEITO_RELEASE_GUARD_SHA256="$guard_hash" cargo build --locked --release --target ${{ matrix.target }} --bin keito + core_hash=$(sha256sum "$release_dir/keito$suffix" | awk '{print $1}') + printf '{"manifest_contract":1,"version":"%s","target":"%s","guard_contract":2,"files":{"keito%s":"%s","keito-capture-guard%s":"%s"}}\n' \ + "${RELEASE_TAG#v}" "${{ matrix.target }}" "$suffix" "$core_hash" "$suffix" "$guard_hash" > "$release_dir/capture-runtime-manifest.json" - name: Package Unix if: runner.os != 'Windows' run: | cd "target/${{ matrix.target }}/release" - tar czf "${GITHUB_WORKSPACE}/keito-${{ matrix.target }}.tar.gz" keito + tar czf "${GITHUB_WORKSPACE}/keito-${{ matrix.target }}.tar.gz" keito keito-capture-guard capture-runtime-manifest.json - name: Package Windows if: runner.os == 'Windows' run: | cd "target/${{ matrix.target }}/release" - 7z a "${GITHUB_WORKSPACE}/keito-${{ matrix.target }}.zip" keito.exe + 7z a "${GITHUB_WORKSPACE}/keito-${{ matrix.target }}.zip" keito.exe keito-capture-guard.exe capture-runtime-manifest.json + + - name: Qualify fresh packaged Unix pair + if: runner.os != 'Windows' + run: | + set -euo pipefail + qualification_root=$(mktemp -d) + qualification_root=$(cd "$qualification_root" && pwd -P) + mkdir "$qualification_root/extracted" + tar -xzf "keito-${{ matrix.target }}.tar.gz" -C "$qualification_root/extracted" + KEITO_TEST_REAL_PROFILE_HOME="$HOME" scripts/qualify-capture-artifact.sh "$qualification_root/extracted" "$qualification_root" - name: Upload packaged asset uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -155,7 +187,7 @@ jobs: create-release: name: Create GitHub Release - needs: build-assets + needs: [pre-release-gate, build-assets] runs-on: ubuntu-latest steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 @@ -182,6 +214,9 @@ jobs: exit 1 fi + - name: Checksum release archives + run: cd dist && sha256sum keito-*.tar.gz keito-*.zip > SHA256SUMS + - name: Publish GitHub release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -190,21 +225,28 @@ jobs: set -euo pipefail ls -la dist + release_options=(--prerelease=false) + if [[ "${{ needs.pre-release-gate.outputs.prerelease }}" == "true" ]]; then + release_options=(--prerelease --latest=false) + fi + if gh release view "$RELEASE_TAG" > /dev/null 2>&1; then gh release edit "$RELEASE_TAG" \ --title "$RELEASE_TAG" \ - --notes-file release_notes.md + --notes-file release_notes.md "${release_options[@]}" gh release upload "$RELEASE_TAG" dist/* --clobber else gh release create "$RELEASE_TAG" \ --title "$RELEASE_TAG" \ --notes-file release_notes.md \ + "${release_options[@]}" \ dist/* fi homebrew: name: Publish Homebrew Formula - needs: create-release + needs: [pre-release-gate, create-release] + if: needs.pre-release-gate.outputs.prerelease != 'true' runs-on: ubuntu-latest steps: - name: Update Homebrew tap @@ -258,11 +300,12 @@ jobs: end def install - bin.install "keito" + bin.install "keito", "keito-capture-guard", "capture-runtime-manifest.json" end test do assert_match "keito #{version}", shell_output("#{bin}/keito --version") + assert_match '"guard_contract":2', shell_output("#{bin}/keito skill runtime --json") end end FORMULA @@ -280,7 +323,8 @@ jobs: scoop: name: Trigger Scoop Manifest Update - needs: create-release + needs: [pre-release-gate, create-release] + if: needs.pre-release-gate.outputs.prerelease != 'true' runs-on: ubuntu-latest steps: # Requires osodevops/scoop-bucket to define an update-keito-manifest handler. @@ -301,11 +345,16 @@ jobs: - name: Check release jobs shell: bash run: | + distribution_ok=false + if [[ "${{ needs.pre-release-gate.outputs.prerelease }}" == "true" ]]; then + if [[ "${{ needs.homebrew.result }}" == "skipped" && "${{ needs.scoop.result }}" == "skipped" ]]; then distribution_ok=true; fi + elif [[ "${{ needs.homebrew.result }}" == "success" && "${{ needs.scoop.result }}" == "success" ]]; then + distribution_ok=true + fi if [ "${{ needs.pre-release-gate.result }}" != "success" ] || \ [ "${{ needs.build-assets.result }}" != "success" ] || \ [ "${{ needs.create-release.result }}" != "success" ] || \ - [ "${{ needs.homebrew.result }}" != "success" ] || \ - [ "${{ needs.scoop.result }}" != "success" ]; then + [ "$distribution_ok" != "true" ]; then echo "One or more release jobs failed" exit 1 fi diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 12c5ba0..b2bec4f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -48,7 +48,7 @@ jobs: key: ${{ runner.os }}-cargo-clippy-${{ hashFiles('**/Cargo.lock') }} restore-keys: | ${{ runner.os }}-cargo-clippy- - - run: cargo clippy --all-targets -- -D warnings + - run: cargo clippy --all-features --all-targets -- -D warnings - run: cargo check --all-targets test: @@ -73,7 +73,49 @@ jobs: key: ${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.lock') }} restore-keys: | ${{ runner.os }}-cargo-test- - - run: cargo test --all-targets + - name: Prepare locked dependencies before the offline macOS test boundary + if: runner.os == 'macOS' + run: cargo fetch --locked + - name: Run macOS tests inside the proved service/network boundary + if: runner.os == 'macOS' + run: KEITO_TEST_REAL_PROFILE_HOME="$HOME" tests/run-macos-isolated.sh + - name: Run Linux tests with verified source-fixture runtime pairs + if: runner.os == 'Linux' + run: | + python3 -I -S -B tests/support/test_paired_test_runner.py + python3 -I -S -B tests/support/run_paired_tests.py "$(rustup which cargo)" "$(rustup which rustc)" + - run: cargo test --all-features --all-targets + if: runner.os == 'Windows' + - name: Verify normal numeric capture with an owned source-fixture pair + if: runner.os == 'Linux' + shell: bash + run: | + qa_root=$(mktemp -d /tmp/keito-source-usage.XXXXXX) + chmod 700 "$qa_root" + mkdir -m 700 "$qa_root/finite-tmp" + export TMPDIR="$qa_root/finite-tmp" + export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" + cargo_bin=$(rustup which cargo) + rustc_bin=$(rustup which rustc) + python3 -I -S -B tests/support/test_source_qa_protocol.py + python3 -I -S -B tests/support/test_source_qa_protocol_review_regressions.py + python3 -I -S -B tests/support/test_source_owner_finalizer.py + python3 -I -S -B tests/support/test_source_owner_finalizer_review_regressions.py + python3 -I -S -B tests/support/test_runtime_children_finite.py + python3 -I -S -B tests/support/test_guarded_failure_diagnostic.py + python3 -I -S -B tests/support/test_source_clock_domain.py + python3 -I -S -B tests/support/test_source_qa_build_owner.py + PYTHONDONTWRITEBYTECODE=1 python3 tests/support/test_source_qa_contract.py "$qa_root" + PYTHONDONTWRITEBYTECODE=1 python3 tests/support/source_qa_manifest.py collect "$PWD" "$qa_root" + qa_result=0 + PYTHONDONTWRITEBYTECODE=1 python3 tests/support/run_guarded_usage_qa.py \ + "$qa_root" "$cargo_bin" "$rustc_bin" || qa_result=$? + complete_result=0 + PYTHONDONTWRITEBYTECODE=1 python3 tests/support/source_qa_manifest.py verify-complete \ + "$PWD" "$qa_root" || complete_result=$? + printf 'original_exit=%s\nsource_complete_exit=%s\n' "$qa_result" "$complete_result" > "$qa_root/source-qa-outer-result.txt" + if [ "$qa_result" -ne 0 ]; then exit "$qa_result"; fi + exit "$complete_result" release-smoke: name: Release Smoke @@ -101,7 +143,7 @@ jobs: ./target/release/keito --help > /dev/null - name: Verify generated man pages run: | - cargo run --bin gen-man -- /tmp/keito-man + cargo run --features dev-tools --bin gen-man -- /tmp/keito-man test -s /tmp/keito-man/keito.1 test -s /tmp/keito-man/keito-auth-login.1 test -s /tmp/keito-man/keito-time-stop.1 diff --git a/.gitignore b/.gitignore index e0f15b6..da01a24 100644 --- a/.gitignore +++ b/.gitignore @@ -3,9 +3,14 @@ /tapes/* !/tapes/ !/tapes/*.tape -/scripts +/scripts/* +!/scripts/qualify-capture-artifact.sh *.swp *.swo .DS_Store .env recordings/time-start-stop.gif + +# Developer-only Python QA must never become source or an installed payload. +__pycache__/ +*.py[cod] diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e3c40c..6435f0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/). +## [0.2.0-rc.1] - 2026-11-19 + +Opt-in prerelease candidate; stable update channels remain unchanged. Supported client/platform combinations and live capture require the corresponding final-artifact qualification and release notes. + +### Added + +- Add opt-in metadata-only coding-agent capture with exact native turn identities, integer seconds, private SQLite durability, explicit repository consent, frozen canonical revisions and server-review-first delivery. +- Add capture setup/status/preview/sync, pause/resume/disable controls, bounded foreground worker, and explicit macOS launchd worker installation/status/removal with integration-owned rollback-safe settings. +- Add real SQLite/process concurrency, privacy, retry, authentication-binding, repository-boundary, transport and supervisor acceptance checks. +- Add live authentication diagnostics and selected-agent uninstall while leaving harness trust decisions to the user. + +### Changed + +- Install only explicitly selected adapters in scripts; interactive installation presents a target picker and authentication no longer defaults to installing both tools. +- Bundle thin lifecycle adapters that discard prose and transcript data, preserve unrelated host configuration and use native prompt/turn identities instead of the legacy list-then-create logging path. +- Distinguish credentials configured, authentication verified, trust unknown and delivery unverified. Structural configuration alone never reports ready. + +### Security + +- Patch inherited QUIC/TLS trust dependencies to the fixed quinn-proto, rustls, rustls-webpki and webpki-roots releases reported by the current security audit. +- Parse legacy YAML/JSON mapping hints with a maintained deserializer and explicit depth/event/alias budgets; no include or filesystem-expansion features are enabled. + +### Compatibility and qualification + +- Existing manual timer/log/session-record commands retain their legacy contracts. Automatic capture requires the canonical API and workspace eligibility and never falls back to legacy ordinary writes. +- New captures remain nonbillable pending authorized review. Usage/cost capture is explicitly unavailable until qualified numeric evidence exists. +- Native capture/launchd qualification targets macOS; release/artifact availability is separate from verified harness trust, lifecycle coverage, live delivery and invoice acceptance. + ## [0.1.9] - 2026-09-01 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 0e78b82..d231ccd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,6 +20,17 @@ dependencies = [ "libc", ] +[[package]] +name = "annotate-snippets" +version = "0.12.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176" +dependencies = [ + "anstyle", + "memchr", + "unicode-width", +] + [[package]] name = "anstream" version = "1.0.0" @@ -56,7 +67,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -67,14 +78,20 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" + +[[package]] +name = "arraydeque" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" [[package]] name = "assert-json-diff" @@ -125,6 +142,15 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bstr" version = "1.12.1" @@ -176,6 +202,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + [[package]] name = "chrono" version = "0.4.45" @@ -221,7 +258,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -252,7 +289,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -267,12 +304,42 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[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.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "deadpool" version = "0.12.3" @@ -309,6 +376,17 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + [[package]] name = "dirs" version = "6.0.0" @@ -327,7 +405,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -338,7 +416,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -347,6 +425,29 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "encoding_rs_io" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fba3fe847045ecff794b9c138293a80db914678c453ad63fbf0c6a9eb6e00b22" +dependencies = [ + "encoding_rs", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -360,9 +461,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.4.1" @@ -396,6 +509,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -461,7 +580,7 @@ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -508,29 +627,28 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.3.4" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi 5.3.0", + "r-efi", + "rand_core", "wasip2", + "wasip3", "wasm-bindgen", ] [[package]] -name = "getrandom" -version = "0.4.2" +name = "granit-parser" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "05f05586d4d4df3d47123207826c40b252728b438a1a07bad3c01ee6bea401df" dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", - "wasip2", - "wasip3", + "arraydeque", + "smallvec", ] [[package]] @@ -558,7 +676,7 @@ version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ - "foldhash", + "foldhash 0.1.5", ] [[package]] @@ -566,6 +684,18 @@ name = "hashbrown" version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.0", +] [[package]] name = "heck" @@ -624,6 +754,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.9.0" @@ -872,19 +1011,24 @@ dependencies = [ [[package]] name = "keito-cli" -version = "0.1.9" +version = "0.2.0-rc.1" dependencies = [ "assert_cmd", + "base64", "chrono", "clap", "clap_mangen", "colored", "dialoguer", "dirs", + "libc", "predicates", "reqwest", + "rusqlite", "serde", + "serde-saphyr", "serde_json", + "sha2", "tabled", "tempfile", "thiserror", @@ -907,9 +1051,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.186" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libredox" @@ -920,6 +1064,17 @@ dependencies = [ "libc", ] +[[package]] +name = "libsqlite3-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -970,6 +1125,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "normalize-line-endings" version = "0.3.0" @@ -1059,6 +1220,12 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "potential_utf" version = "0.1.5" @@ -1068,15 +1235,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - [[package]] name = "predicates" version = "3.1.4" @@ -1114,29 +1272,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ "proc-macro2", - "syn", -] - -[[package]] -name = "proc-macro-error-attr2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "proc-macro-error2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" -dependencies = [ - "proc-macro-error-attr2", - "proc-macro2", - "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -1170,14 +1306,15 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.15" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", - "getrandom 0.3.4", + "getrandom 0.4.2", "lru-slab", "rand", + "rand_pcg", "ring", "rustc-hash", "rustls", @@ -1191,16 +1328,16 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.14" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -1212,12 +1349,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - [[package]] name = "r-efi" version = "6.0.0" @@ -1226,31 +1357,28 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.9.4" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "rand_chacha", + "chacha20", + "getrandom 0.4.2", "rand_core", ] [[package]] -name = "rand_chacha" -version = "0.9.0" +name = "rand_core" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core", -] +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] -name = "rand_core" -version = "0.9.5" +name = "rand_pcg" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" dependencies = [ - "getrandom 0.3.4", + "rand_core", ] [[package]] @@ -1360,6 +1488,30 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + [[package]] name = "rustc-hash" version = "2.1.2" @@ -1368,22 +1520,22 @@ checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "rustls" -version = "0.23.40" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -1405,9 +1557,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -1448,6 +1600,20 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-saphyr" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe" +dependencies = [ + "annotate-snippets", + "encoding_rs_io", + "granit-parser", + "num-traits", + "serde_core", + "smallvec", +] + [[package]] name = "serde_core" version = "1.0.228" @@ -1465,7 +1631,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -1502,6 +1668,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shell-words" version = "1.1.1" @@ -1524,6 +1701,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" @@ -1543,7 +1726,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36bd8e29bf08189a005b2df1df99823aa0861cabe9044e5f31ed54ca292ee618" +dependencies = [ + "cc", + "rsqlite-vfs", ] [[package]] @@ -1575,6 +1768,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -1592,14 +1796,14 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] name = "tabled" -version = "0.21.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5dc662e6da844ad6e428ad16b57967c9d33c82e16bb1c258326c0c078605dff" +checksum = "2d2596a104db1900b943f97d793a6c99addca918c4525c999f751a0f17d472eb" dependencies = [ "papergrid", "tabled_derive", @@ -1608,15 +1812,14 @@ dependencies = [ [[package]] name = "tabled_derive" -version = "0.11.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ea5d1b13ca6cff1f9231ffd62f15eefd72543dab5e468735f1a456728a02846" +checksum = "7dca1937322a1e892b1a65f6a6736183bb0a29d3b4234d1d53bc436dff9beb76" dependencies = [ "heck", - "proc-macro-error2", "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -1629,7 +1832,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -1649,22 +1852,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -1694,9 +1897,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.52.3" +version = "1.53.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" dependencies = [ "bytes", "libc", @@ -1717,7 +1920,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -1852,6 +2055,12 @@ 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.24" @@ -1900,6 +2109,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "wait-timeout" version = "0.2.1" @@ -1984,7 +2199,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 2.0.117", "wasm-bindgen-shared", ] @@ -2053,9 +2268,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "1.0.7" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -2081,7 +2296,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -2092,7 +2307,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] @@ -2125,16 +2340,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", + "windows-targets", ] [[package]] @@ -2152,31 +2358,14 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", + "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]] @@ -2185,96 +2374,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[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_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[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_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[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_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[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_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winnow" version = "1.0.2" @@ -2340,7 +2481,7 @@ dependencies = [ "heck", "indexmap", "prettyplease", - "syn", + "syn 2.0.117", "wasm-metadata", "wit-bindgen-core", "wit-component", @@ -2356,7 +2497,7 @@ dependencies = [ "prettyplease", "proc-macro2", "quote", - "syn", + "syn 2.0.117", "wit-bindgen-core", "wit-bindgen-rust", ] @@ -2423,30 +2564,10 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", "synstructure", ] -[[package]] -name = "zerocopy" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "zerofrom" version = "0.1.7" @@ -2464,7 +2585,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", "synstructure", ] @@ -2504,7 +2625,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.117", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 80b0d94..743c447 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "keito-cli" -version = "0.1.9" +version = "0.2.0-rc.1" edition = "2021" +default-run = "keito" description = "AI agent time tracking CLI for Keito: capture billable human and agent work for client billing, agency projects, and AI-native services" license = "MIT" repository = "https://github.com/osodevops/keito-cli" @@ -18,24 +19,74 @@ path = "src/lib.rs" name = "keito" path = "src/main.rs" +[[bin]] +name = "keito-capture-guard" +path = "src/bin/keito-capture-guard.rs" + [[bin]] name = "gen-man" path = "src/bin/gen-man.rs" +required-features = ["dev-tools"] + +[[bin]] +name = "qualify-capture" +path = "src/bin/qualify-capture.rs" +required-features = ["dev-tools"] + +[[bin]] +name = "check-service-boundary" +path = "src/bin/check-service-boundary.rs" +required-features = ["dev-tools"] + +[[bin]] +name = "codex-inert-source-only" +path = "tests/fixtures/codex_native_origin.rs" +required-features = ["dev-tools"] + +[[bin]] +name = "claude-inert-source-only" +path = "tests/fixtures/claude_native_origin.rs" +required-features = ["dev-tools"] + +[features] +dev-tools = [] +# Diagnostic-only; never publish a capture-profile artifact. +capture-profile = [] + +[[example]] +name = "source-qa-keeper" +path = "examples/source_qa_keeper.rs" +required-features = ["dev-tools"] + +[[example]] +name = "registry-api-actor" +path = "examples/registry_api_actor.rs" +required-features = ["dev-tools"] + +[[example]] +name = "real-client-qa" +path = "examples/real_client_qa.rs" +required-features = ["dev-tools"] [dependencies] +base64 = "0.22.1" clap = { version = "4", features = ["derive", "env", "string"] } reqwest = { version = "0.12", features = ["json", "rustls-tls"], default-features = false } -tokio = { version = "1", features = ["full"] } +tokio = { version = "1.53.3", features = ["full"] } serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1.1" -tabled = "0.21" +tabled = "0.22" chrono = { version = "0.4", features = ["serde"] } dirs = "6" thiserror = "2" colored = "3" dialoguer = "0.12" clap_mangen = "0.3" +rusqlite = { version = "0.41.1", features = ["bundled"] } +sha2 = "0.11.1" +libc = "0.2.191" +serde-saphyr = { version = "2.1.1", default-features = false, features = ["deserialize"] } [dev-dependencies] assert_cmd = "2" @@ -44,6 +95,7 @@ wiremock = "0.6" tempfile = "3" [profile.release] +opt-level = "z" strip = true lto = true codegen-units = 1 diff --git a/README.md b/README.md index f6a2c43..85dc517 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ brew install osodevops/tap/keito ### GitHub Releases -Download the latest binary from [Releases](https://github.com/osodevops/keito-cli/releases) for your platform (macOS, Linux, Windows). +Download the latest archive from [Releases](https://github.com/osodevops/keito-cli/releases) for your platform (macOS, Linux, Windows). On macOS/Linux, keep `keito`, `keito-capture-guard`, and `capture-runtime-manifest.json` together. Verify the archive against `SHA256SUMS`, then run `keito skill runtime --json` to check the release-bound pair before installing capture. Windows supports manual CLI commands; native capture is unqualified. ### Build from Source @@ -52,7 +52,7 @@ cargo build --release # binary at target/release/keito ``` -Requires Rust 1.75+. +Requires a current stable Rust toolchain. Source and `cargo install keito-cli --bin keito --bin keito-capture-guard` builds support manual commands; native capture requires the official release pair whose finalized guard hash is embedded by the release workflow. No local manifest can substitute for that release anchor. ## Setup @@ -118,20 +118,22 @@ Exit codes tell you exactly what happened — no need to parse error messages. S The Keito Agent Skill ships with this CLI. It brings Keito to the places where agents already work by installing lifecycle hooks for Claude Code and OpenAI -Codex CLI, then recording one `source=agent` time entry when a tracked coding -session ends. +Codex CLI. The capture runtime records exact observed turn intervals in a +private local queue and sends canonical pending-review evidence. An authorized +reviewer must explicitly approve any client charge. See [capture setup and +qualification](docs/capture.md); new capture availability depends on server eligibility. ### Requirements - Claude Code and/or Codex CLI -- Git, Bash, and `jq` +- Git, Bash, and the official paired `keito` / `keito-capture-guard` release - Keito credentials via `keito auth login` or `KEITO_API_KEY` + `KEITO_ACCOUNT_ID` - macOS/Linux: `./setup` can install the CLI through Homebrew or release tarballs if `keito` is not already on `PATH` - Windows: install the binary from [Releases](https://github.com/osodevops/keito-cli/releases) first, then run - the skill commands from Git Bash or WSL where `bash` and `jq` are available + manual timer commands; automatic capture and supervision require platform qualification ### Ask Your Agent to Install Keito @@ -163,8 +165,8 @@ cd ~/.keito/keito-cli `./setup` installs the CLI if needed, installs the bundled `keito-time-track` skill, and configures hooks for Claude Code, Codex, or both. In an interactive -terminal it asks which host to configure. In non-interactive runs it defaults -to both. +terminal it asks which host to configure. Non-interactive runs require an explicit +`--host claude`, `--host codex`, or `--host both`. Target one host explicitly when needed: @@ -178,7 +180,7 @@ If the CLI is already installed, this equivalent command uses the bundled skill without the source checkout: ```sh -keito skill install +keito skill install --agent claude-code --agent codex ``` Choose one target when needed: @@ -245,18 +247,26 @@ created by `/track-time-keito`. - `./setup` is the gstack-style source-checkout installer. It keeps a stable checkout at `~/.keito/keito-cli`, installs the CLI if needed, then calls - `keito skill install --source bundled`. + `keito skill install --source bundled --agent `. - `keito skill install` materializes the bundled `keito-time-track` skill and copies it into agent home directories: `~/.claude/skills/keito-time-track` for Claude Code and `~/.codex/skills/keito-time-track` for Codex. - The hook installers merge lifecycle hooks into `~/.claude/settings.json` and - `~/.codex/hooks.json` using `jq`. + `~/.codex/hooks.json` using the native Rust installer. Trust remains a + separate harness decision; an installed adapter is not a verified delivery. - `/track-time-keito` verifies auth, asks for the Keito client/project/task for the current repo, and writes `.keito/config.yml`. -- On agent session start, the hook records local session state. On session end, - the hook logs one Keito time entry with `source=agent` and metadata such as - repo path, branch, commit, and agent type. +- Prompt/Stop hooks checkpoint each supported turn through the deterministic + CLI core. They discard prompts, assistant prose, transcripts, code and raw + local paths before persistence. A supervised worker sends frozen revisions; + retrying never increases their duration. Repository config is only a hint; + local consent is stored separately, and new captures remain nonbillable + pending review. Timing consent is metadata-only. Separate `capture usage + enable` consent can admit partial request observations from an approved native + harness and exact active source; provider expenditure remains unknown. See + [numeric usage consent](docs/capture.md#separate-numeric-usage-consent) for the + supported-version and qualification limits. ### Distribution Model @@ -273,7 +283,7 @@ Audit-first external install remains available: ```sh npx --yes skills@1.5.6 add osodevops/keito-skill -g -a codex -a claude-code -s keito-time-track -y --copy -keito skill install --skip-skills-add +keito skill install --skip-skills-add --agent claude-code --agent codex ``` ## Features @@ -393,16 +403,47 @@ $ keito time list --limit 2 git clone https://github.com/osodevops/keito-cli.git cd keito-cli cargo build --release -cargo test --all-targets ``` +For tests, use the platform runners below. A plain source build intentionally +cannot provide verified capture ownership. + +```sh +# Linux: compile and verify source-fixture CLI/guard pairs, then run all targets. +python3 -I -S -B tests/support/run_paired_tests.py "$(rustup which cargo)" "$(rustup which rustc)" +# macOS: use the protected runner described below. +# Windows: manual CLI tests; native capture remains unsupported. +cargo test --all-features --all-targets +``` + +The Unix pair runner uses the existing opt2 source-fixture build settings so +executable hashing fits the unchanged capture deadlines. Each capture test +executable receives its own manifest and the actual compiled guard digest; +tests of missing or unqualified release pairs retain their unpaired binaries. +These fixtures do not qualify a release or a real agent client. + ### Generate Man Pages ```sh -cargo run --bin gen-man +cargo run --features dev-tools --bin gen-man man ./man/keito.1 ``` ## License [MIT](LICENSE) + +### Protected macOS tests + +Prepare locked dependencies with `cargo fetch --locked`, then run macOS CLI tests +with `KEITO_TEST_REAL_PROFILE_HOME="$HOME" tests/run-macos-isolated.sh`. +CI performs this explicit preparation before the offline boundary, so cache hits +are an optimization rather than a prerequisite. +The runner proves one inherited kernel policy using owned native marker and alias +executables plus an allowed control, then permits loopback fixtures while denying +execution of the real service utility. Doctor and transport assertions remain active. +Their test command builders require a source/hash-bound owned proof receipt and +recheck denial with an inert marker before spawning the CLI; plain unprotected +macOS test runs fail before a service observation can execute. No production +supervisor override or test bypass flag is exposed. Profile access is limited to +before/after hashes of the three configuration anchors. diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..df288bb --- /dev/null +++ b/build.rs @@ -0,0 +1,17 @@ +fn main() { + println!("cargo:rerun-if-env-changed=KEITO_RELEASE_GUARD_SHA256"); + println!( + "cargo:rustc-env=KEITO_BUILD_TARGET={}", + std::env::var("TARGET").expect("Cargo target") + ); + if let Ok(hash) = std::env::var("KEITO_RELEASE_GUARD_SHA256") { + assert!( + hash.len() == 64 + && hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "invalid final guard release hash" + ); + println!("cargo:rustc-env=KEITO_RELEASE_GUARD_SHA256={hash}"); + } +} diff --git a/dist-workspace.toml b/dist-workspace.toml index 2eee701..7dc0404 100644 --- a/dist-workspace.toml +++ b/dist-workspace.toml @@ -1,6 +1,9 @@ [workspace] members = ["cargo:."] +# Production capture uses .github/workflows/release.yml: finalize the guard, +# embed its hash into keito, then package both plus the manifest. cargo-dist +# output without that pairing is intentionally manual-CLI-only. [dist] cargo-dist-version = "0.30.2" allow-dirty = ["ci"] diff --git a/docs/agent-guide.md b/docs/agent-guide.md index e823e72..b87ab94 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -41,7 +41,7 @@ Exit code `0` = ready. Exit code `1` = fix credentials. Install the packaged Keito skill into Claude Code and Codex: ```sh -keito skill install +keito skill install --agent claude-code --agent codex ``` Install one host only when needed: @@ -56,7 +56,7 @@ For source-checkout installs, use the gstack-style setup entrypoint: ```sh git clone --single-branch --depth 1 https://github.com/osodevops/keito-cli.git ~/.keito/keito-cli cd ~/.keito/keito-cli -./setup +./setup --host both ``` From each client repository, invoke the skill once: @@ -77,6 +77,9 @@ keito skill doctor keito skill status --json ``` +For private automatic capture, follow [capture setup and qualification](capture.md). +The repository hint is not consent, and elapsed activity is not permission to bill. + ## Discovery ### List Projects diff --git a/docs/capture.md b/docs/capture.md new file mode 100644 index 0000000..4868fce --- /dev/null +++ b/docs/capture.md @@ -0,0 +1,256 @@ +# Private coding-agent capture + +Capture records observed agent turn duration for review under your existing Keito identity. +It does not measure human effort, CPU time, verified delivery or permission to charge a client. +Numeric usage is disabled by default and requires separate device-local consent. +Qualified request observations remain partial; provider expenditure is unknown, +and missing counters are never reported as zero. + +This implementation requires the canonical agent-session API and workspace eligibility. +A released CLI, installed hook or successful local test does not prove the server is enabled +or your harness has been qualified. The initial qualification targets are Claude Code +2.1.319 and Codex CLI 0.167.0 on macOS; real lifecycle/trust/delivery qualification must be +recorded for the exact installed artifacts before calling them supported. + +## Install selected adapters + +Install the reviewed CLI release, then select only the adapters you use: + +```sh +keito skill install --agent claude-code --agent codex +keito skill doctor --live --json +``` + +Scripted installation requires explicit targets. Interactive installation offers a target +picker. Authentication never silently installs both adapters. The CLI uses its bundled +skill by default. Configuration merging uses the native Rust installer and the verified +Keito/core guard release pair; Bash and Git support the adapter scripts. It preserves +unrelated hooks, settings and plugins. If integration-owned legacy registrations require +migration, review them and rerun the selected installation with `--confirm-migration`. + +Review new or changed Codex hooks through the harness's normal `/hooks` trust flow and +check that lifecycle hooks are enabled. Keito never writes trust decisions or bypasses +managed settings. Doctor distinguishes configured credentials from verified live +authentication and a matching current owner/workspace/API-origin binding. Historical +delivery from another binding is not current delivery proof. Unknown trust or delivery never counts as ready. + +## Approve a repository + +From an intended project repository, use `/track-time-keito` to select an accessible +existing client/project/task, preview the mapping and accept the metadata-only policy. +The wizard writes a local mapping hint before requesting device-local consent. It never +creates clients or projects as an installation side effect. + +For explicit scripted consent: + +```sh +keito capture setup --agent claude-code --agent codex \ + --project PROJECT_ID --task TASK_ID --confirm +``` + +The runtime verifies current authentication and the selected project/task before storing +approval outside the repository. A cloned `.keito/config.yml` cannot authorize collection. Legacy YAML and JSON hints +use the same minimized mapping identity; ambiguous duplicate keys, malformed documents +and over-budget depth/alias input are refused without quoting the source. The parser has +no filesystem include or environment expansion feature enabled. +Changed mapping/policy or Git remote identity holds evidence until renewed approval. Linked +worktrees use the Git common repository identity; nested repositories remain separate. +A repeated identical setup preserves the binding and its pause state. Adding another +selected harness preserves the existing canonical session revision stream. A real mapping +or remote change holds prior queued evidence for review; an already-started native session +will not silently move to the new binding or restart at revision one. + +## Automatic delivery on macOS + +Save credentials with `keito auth login` first. The worker never copies an environment API +key into service settings. From the approved repository, explicitly install its supervisor: + +```sh +keito capture setup --agent claude-code --agent codex \ + --project PROJECT_ID --task TASK_ID --confirm --install-worker +keito capture worker-status --json +``` + +This opt-in creates only an integration-owned launch agent for this repository. Its +operational settings necessarily contain the local executable, working directory and queue +paths; these remain on your device and are separate from billing evidence. No key is stored +in the launch agent. Existing unrelated launch agents are preserved. Binary changes make +the service stale; its expected-runtime digest also refuses delivery after replacement. +Explicitly repeat installation with the reviewed updated runtime. + +Launchd starts and restarts the worker. Settings installed, service loaded, process running and delivery +verified are separate states. Failed or unavailable launchd observations are unknown, +not proof of service absence; uninstall keeps settings until absence is positively verified. Real restart/kill/recovery checks remain part of artifact +qualification. To stop/remove only this repository's worker service: + +```sh +keito capture worker-uninstall --repo +# If the repository moved or was removed, discover its opaque owned worker ID: +keito capture worker-status --all --json +keito capture worker-uninstall --worker-id WORKER_ID +``` + +For a separately supervised foreground worker, or supported development environments: + +```sh +keito capture worker --interval-seconds 5 +``` + +The worker performs network I/O; hooks do not. An explicit sync is also a recovery trigger: + +```sh +keito capture sync --json +``` + +A detached hook child is not the sole delivery mechanism. On unsupported platforms use +manual CLI time commands until native capture and supervision are qualified. + +## Inspect and control + +```sh +keito capture status --json +keito capture preview --session ORIGINAL_HARNESS_SESSION_ID --json +keito capture pause --repo +keito capture resume --repo +keito capture disable --repo +keito capture disable-all +``` + +Pause excludes its interval and holds queued uploads. Resume preserves earned time and +requires an unchanged approved binding. Disable revokes local consent; re-enabling requires +explicit setup again. None of these commands rewrites submitted accounting records. Revoking global or +harness consent abandons any unmeasured active interval as incomplete; reapproval +cannot resurrect the clock or count time while capture was disabled. Observing a disabled +or changed repository hint or remote also persists revocation; restoring its previous digest +requires explicit setup again. A refused Stop prevents later duplicate or pause/resume +commands from supplying a later completion time. + +Prompt opens a supported turn and Stop checkpoints it. Session starts/resumes do not erase +previous completed intervals. Native Claude `prompt_id` and Codex `turn_id` identify turns; +missing identity is refused instead of falling back to another directory session. Interrupts, +missing boundaries and detected clock/reboot discontinuity produce incomplete evidence rather +than fabricated elapsed time. A short first turn remains exact; inter-turn idle is excluded. + +Local storage is a private SQLite transaction ledger with full synchronization, a 100 MiB +ceiling and no silent eviction of unsent evidence. Frozen request bodies are limited to +16 KiB and 100 segments. Worker maintenance expires acknowledged request payloads after +seven days, including idle and consent-held queues; +minimized session/consent state remains for replay integrity until the bounded store is +explicitly managed. A full or damaged queue pauses capture with a recovery error. If SQLite refuses a +boundary (for example lock contention), separate bounded, private failure markers +record only hashed identities, timestamps and safe reasons. Publication never waits on +the authority lock; each marker has a unique immutable name and is synchronized before +acknowledgement. Clock transitions acquire SQLite before a bounded 25 ms authority lock, +then recheck refusal state; no network runs under that lock. The missed boundary is explicitly refused, +not described as saved. Status exposes storage_paused and the failure reason. +After fixing storage, explicitly run `keito capture recover --confirm`; it marks unfinished +intervals incomplete and never reconstructs missing seconds. Because markers contain no +customer or session identity, potentially affected unacknowledged complete revisions are +conservatively held across the local queue with `REFUSED_BOUNDARY_REVIEW_REQUIRED`. +Their frozen bytes remain unchanged, and recovery or reapproval cannot release them. +Recovery clears only the exact marker snapshot it reconciled; a concurrent new refusal +remains paused and requires another explicit recovery. + +Installed hooks publish a private, content-free invocation flag before starting the CLI. +The guard alone holds its file lock and removes the exact flag only after a fixed-byte +acknowledgement from a durable core result. Startup stalls, watchdog termination, missing +acknowledgements and abandoned preparations therefore remain visible to the next core +operation. Any pending invocation blocks delivery; an abandoned one pauses collection and +holds potentially affected frozen complete evidence for review. Explicit recovery cannot +clear a live invocation. The flag contains no native session identity, hook JSON or paths. +This protects failures after the guard first creates durable local state; it cannot observe +a guard that never reaches its first filesystem instruction. + +Capture state defaults to the effective OS user's configuration directory, independently +of hook `HOME`, `XDG_CONFIG_HOME` and repository input. An explicit `KEITO_CAPTURE_HOME` +is an operator or supervisor setting and must name the same private ledger for both guard +and core. Invocation directories require owned, private permissions and paths without +symlink components. + +## Separate numeric usage consent + +Metadata-only timing consent never authorizes transcript reading. From the approved +repository, inspect or disable one namespace independently: + +```sh +keito capture usage status --repo --agent codex --json +keito capture usage disable --repo --agent codex --json +``` + +Explicit enable requires the current verified release pair, managed hook registration, +a canonical owned HOME, and the actual native harness image. The supported parser +versions are Claude Code 2.1.319 and Codex CLI 0.167.0. Supply owned canonical paths: + +```sh +keito capture usage enable --repo --agent codex \ + --profile-home /absolute/approved/home \ + --harness-executable /absolute/codex-launcher \ + --native-executable /absolute/codex-native --confirm +``` + +Use `--agent claude-code` for Claude. A native launcher may omit +`--native-executable`; a JavaScript launcher must identify its native image separately. +Enable performs bounded image qualification, one exact-native `--version` probe and +full managed-install inspection. Functional paths stay in a private device profile +record. SQLite consent and billing evidence contain no source paths. Status and +disable do not inspect harness profiles or transcripts; disable remains available +when a profile or release pair needs repair. + +A normal guarded hook checks persisted consent inside its SQLite transaction before +loading a profile, inspecting origin metadata or opening a source file. It requires +an exact supported version, unchanged approved installation/profile/runtime, a live +guard invocation and a coherent same-user native-image ancestor within at most eight +hops. It inspects PID, start time, parent and image metadata, without reading process +arguments, environment or enumerating processes. PATH, hook JSON, HOME and a version +argument alone cannot grant this authority. These cooperative checks do not establish +provider attestation or protection against a malicious process running as the same OS user. +Darwin retains the documented kernel path-to-image race. + +The next qualified Prompt establishes an identifier-only historical exclusion baseline +and opaque source identity. Provisional historical request identifiers remain excluded +when later finalized. Stop/SessionEnd cannot repair a missing baseline, and a replaced +source requires another qualified Prompt. Symlinks, FIFOs, hardlinks, directories, +wrong sessions/paths/versions and changed sources remain unavailable. Pauses, +revocation, reapproval, refused boundaries and native gaps require a fresh baseline. +Profile, registration, runtime or native image changes require explicit reapproval. +A late lease failure rolls back new numeric finalization while preserving legitimate +timing and previous frozen evidence. Numeric disable affects only that namespace; +metadata timing consent remains separate. + +Only minimized request identifiers, optional model/provenance and nullable counters +can enter usage evidence. Observations remain `PARTIAL`; they do not establish full +session coverage, streaming finality, transcript lag or provider expenditure. The +owned inert source-fixture tests exercise the normal command route; real pinned-harness +trust/lifecycle qualification, final release timing and demonstrations remain separate +required records. No usage observation automatically creates a charge or expense. + +Canonical request data contains harness/session identifiers, versioned mapping, +absolute lifecycle instants, exact integer seconds, completeness and either qualified +partial usage or explicit unavailability. It contains no prompts, assistant prose, +transcript, source code, tool arguments, raw branches, full repository paths or API keys. +Metadata-only capture does not read transcript files. Known credential/path patterns +are refused in identifiers; this is not a claim to detect every possible secret. + +## Recover without changing accounting evidence + +The worker checks local consent and whether any delivery is due before making even an +authentication request. It then rechecks authenticated owner, workspace and API origin +before delivery. A credential switch cannot transfer queued work to another person. +The server rechecks access on every revision and replay. Disabled/unavailable API, expired +authentication, network failure, rate limits and temporary server errors retain the original +payload. Retry-After and bounded backoff apply. A revision conflict or rejected payload is +held for inspection; no fallback ordinary time entry is created. + +Use status and exact-session preview to inspect evidence. Never edit the database to bypass +a hold, delete unsent evidence to conceal a conflict, or enable legacy automatic logging as +a retry workaround. Review the original mapping and canonical server state with a workspace +administrator. Existing ordinary `time session-record` remains available for its legacy +manual/custom-metadata use; the new adapters never use its list-then-create strategy. + +## Review before charging + +Accepted capture evidence is nonbillable pending scoped review. An authorized reviewer +confirms the exact revision, safe notes and explicit charging decision. Time, token usage, +estimated provider cost and client charges remain separate. Approved sources retain their +financial snapshot; later evidence needs a reviewable amendment. End demonstrations at an +unsent draft/preview. Capturing activity never sends an invoice or charges a customer. diff --git a/docs/native-capture-runtime.md b/docs/native-capture-runtime.md new file mode 100644 index 0000000..4640ade --- /dev/null +++ b/docs/native-capture-runtime.md @@ -0,0 +1,207 @@ +# Native capture runtime contract + +Capture uses the Rust `keito-capture-guard` companion and the Rust CLI. No Python interpreter or development tests are installed in the skill payload. + +The release workflow finalizes the guard first, embeds its exact SHA-256 into `keito`, and packages both executables with a versioned manifest containing both file hashes. The ordinary archive checksums and Homebrew checksum authenticate the distribution. An unsigned adjacent manifest alone grants no release identity. Source builds support manual commands; they do not manufacture a capture release anchor. `keito skill runtime --json` performs read-only pair verification. + +Managed commands pin absolute core and guard paths plus `KEITO_CAPTURE_CORE_SHA256`, the installer-verified core hash. The guardian verifies the core through no-follow descriptors before executing it. The main CLI checks its compiled guard anchor and installed manifest whenever an invocation nonce is present. Replacement of a core, guard, or manifest refuses capture and retains the invocation flag. Doctor never executes the registered runtime to decide whether it is configured. + +## Publication and acknowledgement + +The guard uses effective-user passwd HOME unless the operator explicitly supplies `KEITO_CAPTURE_HOME`; raw stdin, working directory and inherited HOME never choose capture storage. Capture directories are private, and descriptor traversal refuses symlinks and foreign-owned ancestors. + +Each invocation creates a cryptographically random, content-free `.preparing` file, takes its guardian-only lock, writes the fixed pending bytes, and flushes the file and directory. Preparation occurs outside the bounded publication lock: holding that lock over the initial macOS filesystem flushes exceeded the existing 25 ms contention budget in a controlled test. Rename to `.pending` and the subsequent directory flush occur under the publication lock. The core starts only after both are durable. Zero-length and partial `.preparing` files are recognizable uncertainty markers. A lock timeout retains the durable preparation and launches no core. Invocation-cap exhaustion publishes a minimized unique global refusal without evicting existing evidence. + +The guardian never reads, parses or spools hook stdin. It passes stdin unchanged and exposes a private ACK pipe. Cleanup requires exactly `KEITO_CAPTURE_DURABLE_V1\n`, pipe EOF, child exit zero, completion within the internal deadline, and an unchanged private marker: bytes, length, owner, mode, link count, type, device and inode. A same-inode content edit is retained. Timeout, missing execution, extra ACK bytes, nonzero exit and interrupted preparation retain uncertainty. Only the owned, unreaped child's process group can be signalled. + +The internal deadline remains 600 ms, with outer adapter TERM/KILL at 650/675 ms and a one-second host timeout. The parallel marker visibility gate remains 500 ms; the actual release artifact p95 target remains below 100 ms. Development correctness results do not qualify cold release latency. + +## Executable descriptor lifecycle + +macOS refused native Mach-O execution through `/dev/fd/N` with a CLOEXEC descriptor (`EBADF`), an inherited read descriptor (`EACCES`), and an inherited O_EXEC descriptor (`EACCES`). These failed qualification attempts are preserved. Apple's XNU syscall catalog has no public fexecve/execveat entry, and its devfs descriptor support modifies execute bits according to descriptor flags. The explicit Darwin implementation executes the fixed managed pathname after checking its device, inode and type immediately before exec. Linux uses the verified descriptor path. Neither platform silently switches launch methods on failure. + +The narrow descriptor contract permits exactly standard I/O, private ACK descriptor 3, and one read-only, verified executable-image descriptor across kernel exec. All other inherited descriptors are closed. + +The main executable starts synchronously, before CLI parsing or constructing Tokio. It marks the image descriptor CLOEXEC, obtains its installed path through macOS `F_GETPATH` or Linux `/proc/self/fd`, checks both that path and `current_exe` device/inode against the descriptor, and closes it on both success and error. Only the verified original path is retained for subsequent release-pair checks. The heavy runtime inherits no image descriptor. Darwin pathname selection has a residual check-to-exec race against a malicious process running as the same OS user; it does not provide fd-only execution or immutable image sealing. + +These checks detect accidental replacement and stale installations. They do not establish security against an adversary running as the same OS user: that user can rewrite the adapter, replace environment assignments, or modify an owned executable inode in the hash-to-exec interval. Darwin also has the explicitly described final pathname-check-to-exec interval. No immutable-file or same-user tamper-resistance claim is made. + +Windows and other unqualified capture platforms retain manual CLI commands and report capture as unsupported. + +## Development evidence continuity + +The abandoned production Python guard/installer/mapping implementation and Python-pin Doctor tests were archived in the dated task evidence before removal. The old Python adapter wrapper is no longer an active cargo test or installed payload. Its native replacements cover installer/mapping ownership and recovery in Rust module tests; protocol, exact ACK, timeout, concurrent publication and capacity faults are covered by `tests/native_capture_guard.rs`; compiled-anchor and file identity qualification is covered by `tests/native_runtime_pair.rs`. Successful CLI installation must also be qualified using the actual paired release artifact, because source-build refusal tests cannot establish that behavior. + +Primary operating-system evidence: [Apple XNU descriptor support](https://github.com/apple-oss-distributions/xnu/blob/main/bsd/miscfs/devfs/devfs_fdesc_support.c), [Apple syscall catalog](https://github.com/apple-oss-distributions/xnu/blob/main/bsd/kern/syscalls.master), and the local macOS execve(2) manual. The task record retains fetched source hashes and the platform's exact failing probe results. + +## Reproducible paired-artifact qualification + +After the guard-first/anchored-core build, extract the normal release archive into a fresh directory under a private run-owned root. Before executing either extracted binary, run: + +```sh +KEITO_TEST_REAL_PROFILE_HOME=/absolute/original/profile \ + scripts/qualify-capture-artifact.sh /private/run-root/extracted /private/run-root +``` + +The development-only Rust driver is excluded from default installation. Its first artifact execution is the actual frozen dispatch/guard/core Prompt path, with private HOME, capture state, harness roots, config roots and PATH. It records the first result before assertions, verifies the actual core's exact private ACK on valid input, no ACK on malformed input, and no accepted boundary for replaced core/guard/manifest fixtures. It then measures 100 ordinary Prompt samples, with Stop boundaries between samples. The profile is read only to compare the three global configuration digests before/after; no profile restoration is attempted. Failed evidence remains in the printed run directory. The normal Unix release workflow runs this profile against the packaged/extracted artifact before upload. + +Guard flushes use POSIX `fsync`, with bounded EINTR retry, in the original file/directory order. Rust `File::sync_all` maps to Apple's stronger `F_FULLFSYNC`, which introduced drive-wide flush latency in the first native candidate. Neither the guard nor SQLite claims power-loss durability stronger than the existing fsync/SQLite contract. No SQLite durability policy was changed. + +The hook entry point performs one synchronous poll of its deterministic persistence operation and fails closed if that operation unexpectedly needs asynchronous work. It does not construct Tokio's general command worker pool. Authentication, sync and worker commands retain the normal asynchronous runtime. No updater or network operation runs before hook persistence. + +The tampered-guard fixture invokes the actual qualified core against the changed guard file to prove its entry refusal. It does not claim that an unexecutable, corrupted guardian can start and publish uncertainty. The checked profile also opens an image descriptor, replaces the core pathname with an identical-byte file of a different inode, then invokes the actual core: startup must refuse before accepting the boundary. On macOS, the already-built qualification driver and its descendants run under an OS sandbox denying network; other hosts record when that facility is unavailable. + +The first b43a5ca extracted-artifact probe failed at 866.572 ms with a retained +pending flag and no accepted session. That immutable baseline is retained. Later +pair/bootstrap and exact-ACK diagnostics were unqualified observations. The +qualification fixture now uses private symlinks to the caller's same selected Git +and explicit OS bash/sleep, recording paths and hashes instead of adding fresh +shell wrappers or choosing a faster Git implementation. A fresh reviewed source +and artifact still require a new quiet-host first probe. + +The missing/non-executable/symlinked-core regression exercises both the bundled +dispatcher and actual plugin command, with direct-guard controls. Dispatch delegates +core refusals to the available guard so publication precedes refusal. A guard that +cannot start remains a separate pre-instruction limitation; no corrupted-guardian +startup durability claim follows from the core-refusal tests. + + +## Locked dependency preparation and output compatibility + +The macOS CI job fetches locked dependencies before applying the offline test +boundary. A cache hit is optional. Local callers likewise run `cargo fetch --locked` +before `tests/run-macos-isolated.sh`; product tests retain inherited service-exec +and network denial. + +The cold-cache regression was reproduced as a setup-gate failure with an empty +private Cargo cache. Locked public dependency preparation then populated that +cache, and an offline checker compilation check succeeded. Both stages denied access to the +operator HOME and denied real service execution after owned native marker/alias +and allowed controls. This is dependency-preparation evidence, not capture +latency qualification. + +The source now requires Tokio 1.53.3 or later and locks that fixed release, locks +anyhow 1.0.103, and uses tabled 0.22/derive 0.12 to remove the unmaintained +proc-macro-error2 build dependency. Seven retained synthetic human-table outputs +cover typed tables, multiline/truncated notes, rounded borders, headers, fallback +and empty results; the migration preserves their exact output strings. These +source changes require a new reviewed build and first-artifact qualification. +The earlier 1e234ee paired build remains unexecuted evidence, not a qualified +artifact for the updated dependency set. + +## Hosted CI follow-up and platform verification + +A live Permit retains its verified read-only, close-on-exec marker descriptor +through clones, transaction validation and acknowledgement. This pins the inode +allocation after unlink, preventing a recycled device/inode pair from authorizing +a different marker. Snapshot/dead-marker probes still close immediately, releasing +any probe flock; the retained live descriptor does not own the guardian's lock. +This does not extend the documented same-user tamper or marker unlink/CAS guarantee. + +Emergency refusal publication alone now uses POSIX `fsync` for the marker and then +the renamed marker's parent directory, preserving write/flush/rename/flush order +and error propagation. Apple's stronger drive-wide `F_FULLFSYNC` from Rust +`File::sync_all` exceeded the existing contention budget. SQLite's 500 ms busy +policy and synchronous setting, the 700 ms core test assertion, and all guardian +and adapter deadlines remain unchanged. This is the existing POSIX durability +contract, not a power-loss or unconditional filesystem-latency guarantee. The +contention test records event, emergency publication and total elapsed time even +when the unchanged assertion fails. + +Windows automatic capture explicitly refuses before credentials, network, Store +or profile work; ordinary manual CLI/API/output and clap discovery remain covered. +Unix-only imports and resource fields are partitioned rather than warning-suppressed. +The platform test inventory is deliberate: + +- `capture_store`: 36 POSIX-authority cases on Unix; six pure identifier/Git/mapping + parser cases remain cross-platform. +- `capture::usage_qualification_tests`: 21 Unix native reader/SQLite ledger + qualification cases, moved intact to the private library test child in + `tests/unit/capture_usage_qualification.rs`. The old integration target and + exported synthetic usage capability are removed. This private `cfg(test)` + seam cannot enable numeric capture in default or dev-tools production builds; + normal guarded command acceptance remains a separate requirement. +- `capture_transport`: 11 native consent/queued-store cases on Unix. +- Parser tests moved from the removed integration target to the private + `capture_usage::parser_tests` library child in `tests/unit/capture_usage_parser.rs`. + All 29 names/assertions remain: 27 pure decoder cases are cross-platform and two + POSIX path/descriptor safety cases are Unix-only. Unix fixtures still invoke + the real bounded readers and additionally compare pure decoder results. Pure + decoder identity carries no path, file authority, consent or normal enablement. +- Mixed entry/supervisor suites partition native operations individually, retaining + help, selection, and applicable doctor checks. `capture_unsupported` adds a + Windows public-command matrix for unsupported diagnostics, no API requests, + no stdout/ACK/readiness and unchanged private state/profile bytes. + +Use `--lib capture_usage::parser_tests` for focused parser selection inside the +protected test environment. The old `--test capture_usage_parser` target no longer +exists; the full all-features/all-targets suite discovers the library cases. +Actual Windows hosted execution remains necessary; local source partitioning is +not a passing Windows runtime result. These changes also require fresh independent +review and a new paired-artifact qualification. The retained 689 source's FIRST +and p95 observations qualify only that earlier source/artifact slice. + + +## Separate numeric admission and source-only verification + +`capture usage enable/status/disable --repo --agent ` manages separate +path-free persisted consent. Enable alone performs managed-install inspection, +bounded streaming native image hashing (512 MiB maximum), and one bounded native +version probe. A private 0600 functional profile contains device paths; it is not +billing evidence. Hooks perform metadata freshness checks instead of repeating +image hashes, version commands or installer inspection. + +The normal guarded factory reads current persisted consent inside the transaction +before functional profile, origin or source operations. A sealed actual runtime +verifier result and live invocation Permit are required. The supported native image +must occur in a coherent same-user ancestry chain of at most eight observations; +PID/start/parent/image changes, unavailable metadata and wrong images fail closed. +No process arguments/environment, broad process discovery or provider attestation +are involved. Darwin's cooperative path-to-image limitation remains explicit. + +A qualified Prompt binds an opaque source identity and historical request-ID baseline. +Terminals require that baseline and check source identity before reading bytes. +Read-only profile/image/source descriptors and coherent origin snapshots remain alive +through commit. Freshness is checked before reading and at finalization. A numeric-only +savepoint rolls back uncertain new queue/body/session writes after a late failure, +then persists the measured timing and previously accepted ledger without rewriting +prior frozen bodies. Status reasons are a closed local allowlist; the outbound usage +schema has not gained arbitrary diagnostic fields. + +The normal-route developer QA uses a guard-first anchored opt2 dev pair, explicit +private HOME/config/harness/capture/state/PATH, owned inert Rust native fixtures and +actual `isolation::checked` before product Command construction. Two namespaces +exercise explicit normal consent and managed guarded Prompt/Stop; the 38-case negative +matrix covers stale profile/native/registration/generation, unsafe/replaced source, +missing/wrong paths, revoke/pause and a wrong native image within an entirely owned +bounded ancestor chain. Exclusive observations retain each first outcome. Python +orchestration remains developer-only and is excluded from the installed 21-file payload. +The macOS full suite runs it inside the existing proved inherited policy, without a +nested sandbox; Linux CI runs the same source-only runner after its native suite. +The Linux runner uses explicit private checked operands and environment; it makes +no kernel service/network-denial claim. Neither source route invokes a real +harness, service or network operation. Windows retains the 17-command unsupported capture matrix and manual CLI coverage. + +This source-only QA does not qualify an actual provider/harness, a default release +candidate, first quiet-host behavior or the unchanged p95 below 100 ms target. Those +records require the exact separately reviewed final source/artifact and authorized +real harness qualification. Partial counters and UNKNOWN provider expenditure never +authorize automatic charging. + + +The reusable source runner requires an exclusive bounded outer source manifest. +The outer harness collects tracked, untracked nonignored and deliberately deleted +membership through read-only Git with hooks/fsmonitor/global config disabled. +Inside the macOS boundary, verification reads only the approved manifest and owned +no-follow source files; it never follows the checkout's linked common Git metadata. +Raw manifest, collector and complete source-set hashes are bound in the receipts. +Deleted source paths must remain absent. Outer completeness verification runs after +both successful and failed execution and preserves the original failure status. + +Metadata, compiler, fixture and source-QA subprocesses use tracked direct handles. +A PID/PGID, launch interval and opaque nonce are recorded before normal waiting. +Timeout, cancellation and receipt exceptions finalize only that owned unreaped +child group with bounded TERM/KILL and confirmed wait. The inert Unix contract +batch is a mandatory separate CI phase; it supplies no runtime approval capability. +These developer controls do not claim general supervision of malicious children, +unobservable hard kills, escaped groups or processes discovered by enumeration. diff --git a/docs/pr-evidence/group-registry-r33-20261110.json b/docs/pr-evidence/group-registry-r33-20261110.json new file mode 100644 index 0000000..9e9ae05 --- /dev/null +++ b/docs/pr-evidence/group-registry-r33-20261110.json @@ -0,0 +1,74 @@ +{ + "schema_version": 1, + "scope": "developer same-session opaque-group registry, finite local public API acceptance on macOS", + "source_commit": "257f5c0cf30d2151428c397cead27f6aeacb39de", + "verdict": "APPROVE_COMPONENT_SOURCE_AND_INDEPENDENT_FINITE_PUBLIC_API_OS", + "required_new_findings": [], + "review_artifact_sha256": { + "review.md": "99c10110375c4e04d489a03ace72f6469443068396ab04d5553f544b24f6d5b9", + "verdict.json": "f749559f0f8c997b28334ca7aabfc225f9068bec505783f6743c7a72d4d25e4d", + "completion-audit.json": "236f65efe18401053385ba851ff872e6e1175e1bcdb1671fa1bd5c0d1778af31", + "independent-raw-verification.json": "d4f492c513a7f7ef1badac02a5e90031c9b05d54f9f6f6ef22f62629474127aa" + }, + "executed": { + "independent_cases": 4, + "firsts_each": 1, + "retries": 0, + "clean_two": "CLEAN; two retained group proofs, successful actual waits and keeper EOF under reduced common end", + "publication_fault": "actual exclusive collision after slot insertion; failed owner retained both slots and applicable waits; timely QA physical EOF did not become clean group proof", + "edge_fault": "invalid repeat start retained both original workloads; failed owner and actual waits remained distinct from QA physical EOF", + "expired_bound": "expected sticky refusal; direct waits known at FIRST, QA EOF unknown; late natural N-marked EOF in FINAL never upgraded FIRST" + }, + "resources": { + "tool_processes": 4, + "controllers": 4, + "keepers": 8, + "workloads": 7, + "all_actual_direct_waits_collected": true, + "orphan_members_reaped_by_controller": false, + "global_process_absence_claimed": false + }, + "prior_outcomes": { + "R32_first": "NOT_ACCEPTED_UNEXPECTED_FIRST; controller1 before evidence; original reason unrecorded, never healed", + "root_diagnostics": "two distinct pre-repair diagnostic successors identify ENV_KEYS then sole known CF encoding extra; diagnostic only, not independent acceptance", + "R31": "source-only group registry approval", + "R30": "finite keeper-interface comparison, bypasses parent APIs", + "R29": "eight historical empty0644 sinks remain nonconforming and unchanged" + }, + "parent_checks": { + "at_source_257": "three pure tests, selected dev examples build/Clippy-Dwarnings and fmt check pass", + "earlier_17_and_90": "prior scoped checks only; no exact257 rerun claim", + "full_default_and_hosted_CI": "not qualified by this record" + }, + "environment": { + "operator_credentials_or_environment_values_copied": false, + "macos_scalar": "explicit UID-derived zero script/region encoding metadata; exact value and closed platform key set required", + "unknown_extra_keys": "refused", + "original_auth_proxy_profile_paths": "unchanged kernel denial", + "zero_OS_home_reads_claimed": false, + "running_OS_syscalls_traced": false + }, + "limits": { + "output_eof_proven": false, + "raw_ESRCH_or_exact_syscall_order_independently_instrumented": false, + "whole_Scope_accepted": false, + "normal_reusable_command_settlement_accepted": false, + "cooperative_setsid_core_accepted": false, + "native_chain_Bash_Python_manager_integration_accepted": false, + "nested_LIVE_receipt_faults_accepted": false, + "default_FIRST_strict_p95_qualified": false, + "BOTH_real_full_numeric_P0B_qualified": false, + "images_platform_financial_browser_recovery_release_qualified": false + }, + "remaining_required": [ + "real cooperative core and opaque leaves inside its session", + "normal command completion and explicit stdin/output draining plus observed EOF", + "real manager/native/chain/Bash/guardian handles retained before receipts and forwarding", + "distinct nested LIVE control/start-receipt/result-write faults", + "short product deadline integration without increasing allowances", + "default paired artifact FIRST and strict p95<100ms", + "full numeric P0-B for both pinned real harnesses", + "remaining platform, recovery, rehearsals and guarded release gates" + ], + "publication_or_production_action": false +} diff --git a/docs/pr-evidence/ownership-protocol-20261109.json b/docs/pr-evidence/ownership-protocol-20261109.json new file mode 100644 index 0000000..8827514 --- /dev/null +++ b/docs/pr-evidence/ownership-protocol-20261109.json @@ -0,0 +1,60 @@ +{ + "schema_version": 1, + "scope": "Developer-QA protocol component; process cleanup integration remains open", + "component_commit": "6c5d1b0b6e2cd6f14091095a87a1da5a6dcfa17f", + "prior_component": "b2ac4ae2dd43640239009957b33b66da013dbd6e", + "published_base": "76acc97771d2f98a05914216330469c3ba23ffe8", + "parent_first_red": { + "original_r13_python": "2pass/8fail", + "original_r13_rust": "2pass/4fail", + "original_unchanged_r17_reviewer_cases": "1pass/3fail", + "expanded_r17": "31methods; failures9 including subtests; errors1 from unnormalized shutdown OSError" + }, + "parent_current_python": { + "main": 34, + "preserved_reviewer_cases": 4 + }, + "reused_rust_checks": { + "source_commit": "b2ac4ae2dd43640239009957b33b66da013dbd6e", + "rust_units_passed": 18, + "unrelated_filtered": 153, + "default_all_targets_check": "PASS", + "all_feature_all_targets_clippy_warnings_denied": "PASS", + "relevant_rust_source_and_vector_blobs_unchanged_at_reviewed_commit": true, + "exact_new_head_full_ci_claim": false + }, + "independent_review": { + "id": "protocol-r18-independent-source-and-socket-only", + "verdict": "APPROVE", + "scope": "Developer-QA protocol component ONLY", + "blocking_findings": [], + "first_attempt_tests": { + "checked_in_main": 34, + "preserved_r17_cases": 4, + "new_independent_methods": 10 + }, + "retries": 0, + "report_sha256": "108495c5228a1306fbf3079d2accb0be6646a11a353e52e20fd678ad6ba06fd1", + "verdict_sha256": "37ab57ba50e0f125661a774361dfe0e3ef6bc1945cf4ed2597b3ca1ffbbae40b" + }, + "reviewer_packaging_limit": "First own-file mode assertion found0644 files inside0700 directory; only own evidence permissions corrected to0600, bytes/assertions/results unchanged, no test reruns.", + "first_failures_retained": true, + "execution_scope": "Finite Unix sockets and fake managers only; no in-suite child actors, threads, signals, profiles or provider requests.", + "installed_python_runtime": false, + "production_behavior_changed_by_protocol_component": false, + "CLIProxyCLI_changed": false, + "whole_process_cleanup_qualified": false, + "real_harness_numeric_p0b_qualified": false, + "release_qualified": false, + "open_gates": [ + "cooperative controlled source owners and actual old-runner/native/guardian/core integration", + "GroupLease/opaque Git/sysctl/BOTH version probes/Python tools", + "actual direct waits, reserved-group absence, terminal EOF and cancellation before wait", + "actual nested LIVE start/result receipt faults", + "default release FIRST/p95 and full source-pair/broader CI", + "BOTH actual Claude2.1.319/Codex0.167.0 current Mac FULL numeric P0-B", + "provider/auth budget, clean install, image/manifest/runtime/worker/browser", + "canonical API/PostgreSQL/financial invariants", + "two rehearsals, guarded release and pilot availability" + ] +} diff --git a/docs/pr-evidence/protocol-prefill-20261109.json b/docs/pr-evidence/protocol-prefill-20261109.json new file mode 100644 index 0000000..f049cc4 --- /dev/null +++ b/docs/pr-evidence/protocol-prefill-20261109.json @@ -0,0 +1,54 @@ +{ + "schema_version": 1, + "failed_head": "c88107d407955e9b1a42d325bfc8003e8539f963", + "failed_run": 42625955203, + "failed_job": 129190288575, + "cause": "Budget unit test blocks while filling a Unix socket with100small writes before any reader polls. Hosted Linux test remained active until6hour cancellation; CI Complete failed its prerequisite.", + "repair_commit": "5096ae851b5a02cafc9723993c1d1665b1df1549", + "repair_scope": "Test transport only; no runtime protocol/installed payload/product deadline change", + "fixture_changes": [ + "Batch exactly100identical frames in one bounded write", + "Constrain sender buffer to8192bytes", + "Bound test peer socket reads/writes at1second", + "Retain all original budget assertions; additionally drain/assert all100frames within bounded per-poll work" + ], + "verification": { + "rust_protocol_tests": 18, + "passed": 18, + "unrelated_filtered": 153, + "default_all_target_check": "PASS", + "all_feature_all_target_clippy_warnings_denied": "PASS", + "crate_wide_format": "PASS", + "diff_check": "PASS", + "constrained_linux_transport": { + "original": "WouldBlock at frame22 within250ms", + "batched": "all100frames received", + "scope": "standalone std-only transport reproduction; NOT wholeLinuxcrate or runtimequalification" + } + }, + "retained_first_outcomes": [ + "macOS constrained original test still passed; no localMacREDclaimed", + "firstLinuxcontainer compiled but execution denied bynoexec tmpfs; no productfailure", + "explicitexec tmpfs successor defaultLinuxsocket accommodated100smallwrites; failedexpected-REDcheck, originalnonreproductionpreserved", + "constrained8192Linuxsender original timedout; batchpassed" + ], + "open_gates": [ + "freshhostedLinuxCI", + "priorintermittentmacOSpluginrefusalcauseremainsunresolved", + "fullcooperativeprocessownershipandGroupLease", + "defaultartifactFIRST/p95", + "fullnumericBOTHactualharnesses", + "appworkers/financial/browser/rehearsal/guardedrelease/pilot" + ], + "logs_sha256": { + "cli-c881-ubuntu-cancelled.log": "3391eccc46b297a8b8618d65604e3cbdcc35d74f866aaba3bad64e237e9b11d4", + "cli-c881-socket-constrained-first.log": "1e3d5526ea76a86e4d71c5d997a5dca81acb7247fdb53e7b834a4aacd8668986", + "cli-c881-linux-transport-first.log": "de9930189277740da2c9e1c8d3065e956adc8a5f435ac35ad37abeb96a8f58fd", + "cli-c881-linux-transport-v2.log": "f20fed3ad90ea3a5f53d341acbfbb39c6455f37aaecc2d995b35ec3cca07afdb", + "cli-c881-linux-transport-v3-constrained.log": "2da355cf9c7fcda6f2acce0100563b94c2ba162dce88f1dc52d0fce4dedbae07", + "protocol-rust-c881-prefill-fix.log": "9cc707b72ba0aa0890ece45479410e2bb7795121445abf76deae7022e543b7b3", + "protocol-clippy-c881-prefill-fix.log": "f94a9d36030fadddfb0adc22d640ba575f9d73dd0ab7849ee86f03c57c2600cc", + "protocol-default-check-c881-prefill-fix.log": "77d182cea7d90bb2ad95d4e8069ed7cc70a0aa023d1824486edbc256d2d65225", + "cli-c881-prefill-format.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + } +} diff --git a/docs/pr-evidence/status-revocation-20261109.json b/docs/pr-evidence/status-revocation-20261109.json new file mode 100644 index 0000000..ea9faa9 --- /dev/null +++ b/docs/pr-evidence/status-revocation-20261109.json @@ -0,0 +1,75 @@ +{ + "schema_version": 1, + "scope": "repository-consent observation before numeric usage status", + "product_commit": "6c0735252c1a212cc4a43a6b8f8eb5a70e9c9342", + "base_commit": "76276a2782af884329348d737b27956b556caf0c", + "production_runtime": "Rust; no installed Python dependency introduced", + "parent_developer_acceptance": { + "baseline": { + "tests": 5, + "passed": 5 + }, + "red": { + "tests": 6, + "passed": 5, + "failed": 1, + "regressionCasesFailed": 6, + "setupFailure": false + }, + "green": { + "tests": 6, + "passed": 6, + "regressionCasesPassed": 6 + }, + "factory_units": { + "tests": 8, + "passed": 8, + "filteredUnrelated": 145 + }, + "rustfmt": "PASS", + "diff_check": "PASS" + }, + "evidence_sha256": { + "status-boundary-build-first.log": "96286a5ba7c4fb731a10bcef9e4b0e23827f6e6d9d9fbce1ec64a28c07f028d7", + "status-boundary-build-fetch.log": "577ff53395da2ed0b726ea3d91aee0a0c25dcf8a98f099ea3ac7d3a80fd350a5", + "status-baseline-first.log": "cc474c8adc2614b8c8f3c809faa047d48fe7169de8cd3ea7d197eab907697c86", + "status-red-first.log": "6d91ef19732590788285c16b25e0dfc6ddd7ff3aa119d1910065088334cd6d84", + "status-green-first.log": "4e0ac3a3c1446538dcf89a4de06e6266cda00ab8f1184eb660a8ee74018d28f6", + "status-factory-units-first.log": "f5f0fa02fbfc850c279e200eabfc532b9be4255666fb1566a3a4dc8858c2645b", + "status-factory-units-corrected-filter.log": "02cdbc51819dadc6ceed90fce0e7a60ebb6284eae299956b7b46d31889109cf6" + }, + "setup_limits": [ + "First offline boundary build missed cached tabled dependency; public locked fetch/build successor succeeded.", + "First factory unit filter selected zero tests; not accepted as evidence; corrected exact module filter ran8." + ], + "independent_review": { + "review_id": "status-r15-independent-source-only", + "verdict": "APPROVE", + "scope": "status-revocation source delta only", + "executed_by_reviewer": false, + "blocking_findings": [], + "report_sha256": "78508577daac6ae40dc07568bda31958b147bd14cdb2956d75c8d7214ed1c6d7", + "verdict_sha256": "1069c8f06057345f6cd61f7e9bd454ff0a5b38346518eb7ab0eb2fe254c8db28" + }, + "isolation": { + "synthetic_private_fixtures": true, + "normal_profile_access": false, + "proxy_routing_changed": false, + "actual_service_utility_executed": false, + "real_harness_model_requests": 0, + "automatic_fixture_cleanup": true, + "owned_test_handles_waited": true + }, + "unresolved": [ + "OWNERSHIP-R13-01 whole-group settlement", + "OWNERSHIP-R13-02 sticky protocol failure", + "independent runtime and exact release artifact qualification", + "actual app and both worker image runtime gates", + "full numeric qualification of Claude Code2.1.319 AND Codex0.167.0", + "recovery and rehearsals", + "guarded delivery and intended-audience availability" + ], + "release_qualified": false, + "production_enabled": false, + "attribution": "Fresh parent developer test execution; independent reviewer performed source inspection only. Historical artifact results are not reused as current execution proof." +} diff --git a/docs/source-qa-build-bootstrap.md b/docs/source-qa-build-bootstrap.md new file mode 100644 index 0000000..0115f87 --- /dev/null +++ b/docs/source-qa-build-bootstrap.md @@ -0,0 +1,73 @@ +# Developer compiler bootstrap draft + +This Python standard-library owner is developer QA only. It is not installed or +called by Keito's Rust CLI, guard, hooks or adapters. The source-reviewed Rust +keeper cannot own its own first compiler before being built. This draft supplies +that separate bootstrap path; no process actor or compiler has run through it. + +Run only pinned system Python with `-I -S -B` under the proven inherited kernel +boundary and an explicit private spec. The spec binds canonical Cargo and owner +source hashes, exact argv/cwd, private HOME/harness/state/TMP/target roots, a +closed offline environment and one finite lifetime. Missing environment/policy +markers refuse before actors. The marker is a refusal guard, not proof of kernel +policy. Actual direct/alias denial checks and source/copy hashes belong to the +coordinator's future build receipt, never normal profile contents. + +A forked sibling keeper reserves its own live PID as PGID. Parent alone owns the +returned keeper PID and Cargo Popen handle before receipts. Catchable cancellation +is blocked across spawn/handle assignment; the compiler child restores the +original signal mask before exec. Keeper ignores owner-group INT/TERM and reacts +to its control lifeline. No parent cached-group query or signal exists. Command +ancestry is unchanged by this sibling; opaque tools that escape groups/sessions +are outside a group-absence proof. + +PARK is intent until the bounded control drain. Complete rejected lines poison +proof but permit bounded failure-only draining; partial/budget yield permits no +group work. Fatal unknown transport stops group authority, leaving FAILED/unknown. +Parking-loss fallback is a one-time action against the keeper's own still-reserved +member group, including itself, with no GONE/proof. Expiry reserves final1.8s +INSIDE the granted lifetime. TERM grace starts once. This single-command bootstrap +supports ONE immutable CLEAN deadline; later requests are refused, not silently +accepted only in the parent. It is not the Rust component's decreasing-bound API +or a complete Scope implementation. + +Normal Cargo leader completion is not group absence. After CLEAN, source-bound +GONE, actual direct waits, RELEASE/write EOF, successful keeper exit and empty +terminal EOF are required before the proof deadline. A nonzero compiler exit is +still a failed command even if its resource cleanup settles. Failure never +rehabilitates proof. Available direct waits continue to be collected after a +failed proof deadline within the ORIGINAL lifetime, without new signals or a new +proof budget. FIRST is exclusive and precedes later wait-only facts; FINAL and a +bounded fact-only stdout fallback preserve failures/unknowns if receipts fail. +Unknown handles, lost helper authority, late observations and missing receipts +must block acceptance; a dead owner's direct waits cannot be reconstructed. + +The current checks are pure fake transport/kernel/wait/policy tests only. No +fork, Popen, signal/group actor, Cargo invocation or real harness has used this +owner. Independent source review and bounded bootstrap OS acceptance remain +required. The proposed Rust actor driver also remains uncompiled text. Parent +GroupLease runtime acceptance, Scope/core/native/Bash/Python integrations, LIVE +receipt faults and full BOTH-harness numeric P0-B/default artifact timing/images +and workers/financial/browser/recovery/rehearsals/release remain open. + +Catchable cancellation now records a non-throwing latch. Normal checkpoints stop +new admission; finalization keeps collecting known waits and attempting every +owned close and fact publication. A secondary failure cannot skip another stage. +Only the last handler handoff is masked, after bounded wait/close work; each +handler restore is guarded. FINAL is an immutable pre-handoff snapshot with +handler and mask restoration explicitly pending. The last bounded fact packet +follows the actual unmask attempt; it reports mask uncertainty and the first or +secondary HANDOFF_UNMASK reason on failure, including late catchable INT. Only +successful handler and mask restoration reports handoff_complete. No handoff +retry or receipt overwrite can turn failure into success. FIRST's +pre-fallback fact snapshot is retained separately from late waits and is included +in fact fallbacks even when FIRST cannot be published. Secondary-error lists are +copied into snapshots so later cleanup cannot mutate cutpoint evidence. + +Every guarded terminal stage normalizes a caught KeyboardInterrupt to the fixed +cancellation latch and CANCELLED before rebuilding fallback facts, while keeping +any earlier first reason and the stage failure. If both fact sinks fail, no +complete final report is claimed. Admission checkpoints after handler installation +and inside the first masked fork section prevent an already-accepted cancellation +from creating a keeper; a handle returned before cancellation remains owned and +must still be waited. Masking alone is not an admission check. diff --git a/docs/source-qa-group-draft.md b/docs/source-qa-group-draft.md new file mode 100644 index 0000000..c7a9901 --- /dev/null +++ b/docs/source-qa-group-draft.md @@ -0,0 +1,99 @@ +# Reserved group implementation draft + +This developer component is not connected to product hooks, the guard, the core, +native fixtures or Python tools. Its state machines now live in the shared +`process_ownership` Unix library module, with developer compatibility reexports. +Default library builds compile that shared source; real product call sites and +guard roles are not wired yet. The keeper example is never installed. Its +state/socket checks are not process acceptance. + +The lease is only for an opaque command in the current session. A guardian core +still calls `setsid()` and must instead be a cooperative source owner whose own +opaque children receive leases inside that session. The parent never queries or +signals a cached PGID. The live sibling keeper alone operates on its own +PID-reserved group. It stays a member until the original prepared command joins, +parks outside it, and reports GONE only after ESRCH. Absence irreversibly disables +all subsequent group queries/signals. Direct waits remain separate facts. + +Call `spawn_keeper`, register the returned object locally, then call `await_ready` +and `start`. No READY read occurs before the caller receives the keeper handle. +`start` consumes the original prepared Command once, preserving its executable, +arguments, environment, descriptors and existing pre-exec checks; its appended +join callback cannot return to a caller for reuse. The developer +[group registry](source-qa-scope.md) now retains these objects before publishing +registration and coordinates one batch cleanup. Receipt forwarding, cooperative +core edges and output-pipe ownership remain unintegrated. + +The legacy lifetime reserves its final 1.8 seconds for failure cleanup. The +explicit `HookShort` lease policy instead reserves 50ms, retains 15ms TERM grace +and caps setup at 20ms. Its exact optional keeper tag is `hook-short-v1`; absent +tag retains legacy behavior and every other tag is refused. These are fixed +policies inside the inherited deadline, not caller-supplied extensions. The +batch registry remains legacy and actual product wiring is pending. Expiry +starts cleanup at that earlier trigger, without extending the immutable hard end. +Cleanup advances incrementally, receiving deadline reductions before each step. +TERM grace starts once. Every group syscall checks the current absolute end. +A receive result distinguishes a frame, WouldBlock quiescence, EOF and a read +budget yield. A read-budget yield or the eight-frame turn cap skips group work; +already-buffered reductions are consumed on a later bounded turn first. Failure +cleanup continues to consume canonical CLEAN minimum bounds without clearing its +first fault, restarting grace or reopening normal control/proof. The actual +keeper_main turn function is shared with fake-transport regressions, so tests +exercise these dispatch decisions rather than separate model methods. + +PARK parsing records only one pending intent. The membership change, its +failure-only self-group fallback and PARKED response occur only after the same +bounded drain has applied readable minimum bounds. Read/frame-budget yields and +partial controls retain intent without group work; a fatal transport stop clears +it without executing it. Duplicate pending PARK is a control failure. A timely +ordinary PARK retains its original response, and a failed PARKED write still +enters bounded failure cleanup after the membership change. + +A rejected complete line has a known consumed boundary. It poisons proof but +continues the bounded failure-only drain, so a valid shorter CLEAN behind it is +applied before group work. WouldBlock with a partial frame yields instead of +claiming the queue empty. Fatal reads, wire overflow, an unterminated frame limit +or truncated EOF leave no trustworthy drain boundary: the keeper permanently +disables group operations and exits failed. Even a later valid frame cannot +restore that authority. Physical cleanup may then remain unknown; no GONE or +clean proof may be issued, and caller registry/wait reporting must retain that +failure. This is a conservative authority stop, not evidence of group absence. + +The same decreasing end covers GONE, RELEASE and empty EOF. RELEASE plus write EOF +seals the last shared bound; a later smaller request is explicitly refused with +GROUP_BOUND_SEALED, rather than silently shortening only the parent. That terminal +seal is not permission to restart a deadline or perform another group operation. + +If the original owner group disappeared before PARK, the keeper has a failure-only +last action against its own still-reserved group: SIGKILL includes the keeper. +This cannot emit GONE or provide a clean proof, and cannot give a dead parent +wait facts. No parent-side cached group operation or replacement parking actor is +introduced. Its finite keeper-interface topology now has independent OS +acceptance; that comparison deliberately bypasses the parent lease API. + +`poll_cleanup` always attempts both outstanding direct waits, even on a prior +fault, clock failure or expired proof deadline. `report` retains the first safe +reason, up to eight distinct secondary reasons, actual returned statuses and +remaining unknowns. A later valid frame or wait cannot rehabilitate proof. Failure +closes still-owned stdin and the control writer; the keeper then makes its +bounded failure cleanup attempt. Transferred stdin/stdout/stderr must have a +caller-scoped cancellation/drain/EOF owner; keeper EOF is not output EOF. +Drop is only a bounded failure fallback. The group registry retains failed slots +and reports until its caller completes explicit finish and inspects the facts. +Direct lease users still own those retention/reporting responsibilities. + +The parent accepts exactly one GONE in Cleaning. Pre-READY cancellation still +requires the actual matching READY before GONE. Duplicate terminals, wrong-phase +frames, partial trailing bytes, missing EOF and failed waits cannot form proof. +Opaque tools that change groups/sessions or daemonize are outside group absence; +this does not prove an arbitrary subtree absent or reap non-child orphans. + +The original R19 source at 263b918 remains immutable for the recorded actor RED. Current +regressions use the actual settlement/session methods with fake clocks, wait +handles and syscalls plus finite socketpairs. A separate independent finite OS +comparison passed both CLEAN controls, reproduced original263's expiry failure +and verified the candidate's timely physical cancellation with FAILED protocol. +It does not establish parent GroupLease or registry API runtime acceptance, raw +ESRCH instrumentation, orphan reaping or default latency. Full Scope/core/native/Python integration, real nested LIVE receipt +failures, default release FIRST/p95, BOTH real full numeric harnesses, images and +workers, financial/browser tests, rehearsals and guarded release remain gates. diff --git a/docs/source-qa-ownership.md b/docs/source-qa-ownership.md new file mode 100644 index 0000000..bd53eca --- /dev/null +++ b/docs/source-qa-ownership.md @@ -0,0 +1,120 @@ +# Developer QA ownership repair + +The `dev-tools` Rust protocol and matching Python QA protocol carry only bounded +cancellation and process-ledger metadata. They grant no capture, profile, usage, +authentication or runtime-pair authority. Neither module is installed in the +21-file Rust/thin-shell skill payload. The developer API now reexports the single +Unix implementation in `process_ownership`; that shared implementation compiles +in default library builds. Product call sites and the guard still need wiring. +Compilation alone is not default-artifact ownership or runtime acceptance. + +The protocol requires a valid terminal followed by EOF. A nonce, identity, schema, +state, I/O, forwarding or budget fault permanently fails that endpoint and its +owner; later valid frames cannot restore clean settlement. Cancellation closes +admission separately from resource cleanup. REGISTER/WAITED facts alone never +authorize signalling another process or prove a reserved group is absent. + +Metadata limits apply across an operation's shared send/receive/forwarding budget: +256 bytes per frame including newline, 1024 pending bytes, 4096 registrations, +16384 frames and 4 MiB total metadata. Each poll makes at most eight read attempts +and parses at most 32 frames. Reason codes contain no offending input. + +Containing-owner failure also prevents clean terminal emission from every other +admitted endpoint. Root forwarding uses the same closed metadata ledger even +without an upstream socket; unfinished registrations prevent successful finish. +Each receive, local forward and actual send counts toward its operation budget. + +The manager interface currently returns an untimed boolean. A first proof polled +at or after the shared cleanup deadline is rejected, including a `True` returned +late. A previously accepted manager proof is cached and is not polled again or +given a fresh deadline. A manager must close its own admission permanently before +reporting success. These rules are tested with finite objects, not process actors. + +This is a component repair. It is not yet connected to the process-owning runners, +native fixtures, guardian or core. The Python `SourceOwner` requires explicit +manager cleanup APIs; the existing `OwnedChildren` does not yet implement them. +Do not attach it to the old runner or infer cleanup from `manager.active == None`. + +The Python owner now latches ordinary operation exceptions before cleanup and +terminal emission. Manager begin/poll/schema errors retain pending collection +within the same end; collected facts after a callback fault are cached separately +from clean proof. Failed close/finalization cannot replace the original operation +exception. Seven retained regressions plus the existing protocol/socket tests +pass (45 total). R35 independently approved this finalizer prerequisite with +53 passing methods, including eight additional reviewer cases. Those eight +cases are now checked in and called by Linux and Mac CI. This does not implement +the real multi-slot process manager or establish nested LIVE receipt acceptance; +R34-06 remains partial and open. + +The shared Rust lease now has two closed cleanup policies. The legacy adapter +keeps its 1.8-second reserve; `HookShort` reserves 50ms, with 15ms TERM grace and +a 20ms handshake cap, inside the inherited hard end. Its optional keeper tag is +exactly `hook-short-v1`, never a numeric timeout supplied by a caller. Failed +parent control also caps local observation without clearing the first fault or +claiming a wire acknowledgement. At source `1ed602e`, 84 shared Rust state/socket +tests, default all-target checking, all-feature Clippy and formatting pass. +R37 independently approved extraction, policy plumbing and test promotion as +source prerequisites, with no required findings. Real product integration remains open. +The existing batch registry still uses the legacy policy. None of these checks +establishes an installed guard/core path, short-policy process acceptance or +default latency. + +Ordinary verified command owners now select the closed `CommandProbe` policy. +READY and PARK share the remaining original owner operation end (hard end minus +50ms); they receive no new relative interval. The command-owner local bound +remains one second, cleanup remains 50ms and TERM grace remains 15ms. Capture +hooks retain `HookShort` and its 20ms setup cap. The public QA-owned image +constructor refuses `CommandProbe`; only the crate-private verified-image path +selects its fixed `command-probe-v1` keeper tag. This does not extend a hook cap, +change latency acceptance or prove actual cold startup and cleanup. + +The one-second statement describes the constructor/owner lifetime. Installation +and explicit usage approval have earlier pair verification outside that owner +when unattached, so it is not a whole-command guarantee. The developer opaque +gateway tightens its supplied Scope before its own pair/image verification; +subsequent calls retain that original minimum. Stronger whole-command ownership +would require acquiring and reusing one owner before those earlier caller steps. + +The shared Unix `Scope` now retains individual command slots and can settle one +without closing the containing owner. It consumes the original prepared Command, +returns pending keeper ownership, and progresses READY/PARK while bounded pipe +reads and writes continue. Global cancellation broadcasts every retained slot's +intent before polling waits; a failed slot or operation cannot restore clean +completion. Direct waits, keeper terminal EOF, group absence and output read-zero +EOF remain separate facts. Completed slots and their identities are not recycled. + +Transient input and each output are capped at 1MiB; admitted buffer capacities +total at most 4MiB per Scope. Each pipe turn performs at most one 4096-byte I/O +attempt, and a Scope turn visits at most eight slots in rotation. WouldBlock, +interruption, a closed local descriptor or child exit never substitutes for +observed output EOF. Overflow retains the first fault while bounded draining +continues. Raw output has no Debug/Serialize implementation and stays outside +metadata reports. Result retrieval is single-use and requires timely resource +proof. Full retained reports are explicit snapshots outside the hot poll path. + +At source `ff34067`, 98 shared state/socket/fake-stream tests, default all-target +checking, all-feature Clippy and formatting pass. The retained migration baseline +has 93 passes and one behavioral failure for containing admission being closed; +an earlier test-only type error is recorded separately. R38 independently found +two required corrections: retained input capacity was undercharged, and the last +finish-clock error did not propagate a zero cleanup bound. Their retained +regressions produced 99 passes and three behavioral failures. Source `a6b89ac` +passes all 102 focused tests, default all-target checking, all-feature Clippy and +formatting after correcting both paths; independent repair review is pending. +Input now charges its reserved Vec capacity, including unused space, and rejects +oversized reservations before spawn. Output allocation must fit its charged +capacity too. A final clock error broadcasts irreversible zero bounds before +marking finished; later clock recovery cannot reopen that observation interval. +The actual finish envelope is shared with clock-injected regressions, including +pending resources, accepted historical slots, earlier faults and an empty owner. +The only current Scope image entrypoint requires a QA-owned +0700 image. Sealed official images, cooperative core edges, signal/bootstrap +integration and actual product/probe/Python-manager call sites remain pending. +These tests do not execute the real command/guard chain or qualify its timing. + +The remaining integration must preserve the guardian's actual `setsid`, imageFD, +ACK and timing boundaries; give controlled source processes cooperative owners; +and reserve same-session groups around opaque child commands. Group absence and +actual direct waits are separate requirements. Full ownership acceptance, live +nested receipt faults, default release latency, actual harness usage and billing +qualification remain open. Socket-only unit tests establish none of those gates. diff --git a/docs/source-qa-scope.md b/docs/source-qa-scope.md new file mode 100644 index 0000000..f55c342 --- /dev/null +++ b/docs/source-qa-scope.md @@ -0,0 +1,104 @@ +# Developer ownership registry + +The direct native `skill install` operation now has a separate, closed +four-second containing lifetime, restricted by any earlier inherited end and +measured from the original pre-parse entry clock. This deliberately replaces +the old one-second whole-install restriction; it is not a production latency +SLA. Ordinary commands retain their original one-second entry restriction. +Nested auth-offered installation cannot upgrade its ordinary parent, and a +partial attachment cannot fall back to a fresh standalone installer. +Library-supplied owners are additionally restricted once at the start of the +installer preflight; a more generous caller cannot grant a longer installation. +Any earlier entry or caller restriction still wins. + +Both selected version probes share one original one-second preflight deadline, +including that preflight's pair preparation. Each retained slot and its actual +group lease receives that same tighter end. Every version result, physical +resource fact and forwarded registration wait must be settled before the +preflight runner is consumed. Only then may materialization and per-target +publication begin. The containing owner remains live, retaining every slot and +ledger through publication and final terminal handling. Its checks surround +blocking filesystem work; they cannot preempt a filesystem syscall. + +Publication checks cancellation and the original operation end, including +immediately before the config switch after its temporary file has been +fsynced. Existing journals, recovery, compare-and-swap and fsyncs remain. +This is not a transaction across both targets: a later target failure preserves +an already published first target. Recovery may complete safety work after a +deadline, but cannot make that failed operation successful. A later terminal +also requires a fresh clock, rather than a cached clean finish. + +The nonquiet install summary preserves unknown trust/authentication/readiness +and marks capture/worker diagnostics as `NOT_CHECKED_AFTER_INSTALL`; it does +not launch another process cohort. Run a separate explicit doctor/status for +those checks. External `npx` download ownership remains an open qualification +concern; bundled-only checks do not certify that path. HookShort/Legacy policy, +the hook timing limits and all outer acceptance limits are unchanged. + +These are implementation contracts pending acceptance, not claims that the +four-second install, real harnesses, cold FIRST or p95 have passed. The retained +instrumented failure and all earlier failed first attempts remain failed. + +`source_qa_scope::GroupRegistry` is the first integration layer above the reserved +group lease. It is compiled only for Unix developer tools and is not installed +with the CLI or capture payload. It currently manages opaque same-session group +edges. Cooperative core edges, pipe draining/EOF and upstream terminal reporting +still require integration. + +The registry reserves bounded slot capacity before starting a keeper. It stores +the returned lease before invoking the registration publisher. An unsuccessful +publisher cannot discard that slot or reopen admission. Original I/O errors are +returned to the caller; safe sticky stage codes and bounded secondary codes stay +in reports. Slot IDs are bound to their registry and cannot target another one. + +`spawn_group`, `await_ready` and consuming `start` preserve the existing lease +protocol. `begin_cleanup` closes admission and broadcasts the same minimum +absolute CLOCK_MONOTONIC end to every retained slot before any polling or waiting. +One failed begin does not skip a sibling. Polling attempts all slots, including +after a previous error. Both failed and successful slots remain in the registry +for explicit reports; a known direct wait never replaces a missing group proof. + +`finish` uses that same end and a fresh completion clock. It never grants a new +per-slot cleanup allowance, never rehabilitates late observations, and records a +deadline or clock failure even when earlier group facts were already complete. +After finish, a request to reduce the sealed bound is refused in sticky report +state without another group operation. Drop is a failure fallback, not the normal +completion API. A failed lease also caps its local retention deadline to the +registry end so dropping several failed slots cannot multiply the allowance. + +Reports contain each retained group's known direct-handle PID/status facts and +unknowns, separately from the aggregate flags. Those PIDs are metadata, not +permission to query or signal a cached group. Only the keeper retains that +authority. The registry never queries or signals a PID/group itself. + +This is a group batch finalizer, not yet a complete command/output runner. It +does not provide output-pipe access or claim output EOF: `output_eof_proven` is +always false. Do not use it to attest an opaque guardian core across `setsid()`; +that core must remain a cooperative owner with leases inside its own session. +There is no capture/profile/auth approval constructor or upstream SETTLED API. + +The first normal-only integration baseline reproduced six behavioral failures; +the repaired source passed 90 selected state/socket tests, including the original +eight registry cases and seven additional controls. The independent finite OS +comparison of the existing keeper interface remains scoped to that interface: +it bypasses parent GroupLease/registry APIs. + +The separate R33 review at `257f5c0` accepted four finite public API cases on +macOS: two-group clean completion, actual registration-receipt collision, +invalid repeated start, and expired-bound failure retention. The last case +observed late natural expiry and does not prove timely cancellation. All actual +direct waits completed; QA lifeline EOF is not product output EOF. The original +R32 early failure remains unaccepted and its missing reason is not reconstructed. + +The private actor and helper explicitly supply UID-derived zero encoding +metadata on macOS. The actor validates this exact value and its closed platform +environment; arbitrary extra keys remain refused. No operator environment value +or credential is copied. This developer QA correction is not installed capture +runtime qualification. See the [scoped evidence](pr-evidence/group-registry-r33-20261110.json). + +Nested LIVE receipt faults, cooperative core, +native/chain/Bash/Python-manager integration, default FIRST/p95 and BOTH real full +numeric harnesses remain required. Product timing limits, profile isolation, +CLIProxyCLI and production behavior are unchanged. The current 1.8-second group +cleanup reserve still requires integration with the shorter product deadlines; +passing these finite cases does not authorize increasing those deadlines. diff --git a/examples/real_client_qa.rs b/examples/real_client_qa.rs new file mode 100644 index 0000000..fc6de4a --- /dev/null +++ b/examples/real_client_qa.rs @@ -0,0 +1,8 @@ +//! Offline native discovery only. Never starts a model session or signs in. +fn main() -> std::process::ExitCode { + #[cfg(unix)] + let passed = keito_cli::real_client_qa::run_offline(); + #[cfg(not(unix))] + let passed = false; + std::process::ExitCode::from(if passed { 0 } else { 1 }) +} diff --git a/examples/registry_api_actor.rs b/examples/registry_api_actor.rs new file mode 100644 index 0000000..b74e968 --- /dev/null +++ b/examples/registry_api_actor.rs @@ -0,0 +1,1049 @@ +//! Developer-only finite PUBLIC GroupRegistry API actor. Never installed. +//! Authored source, not runtime acceptance. Only the reserved keeper has group +//! authority. Lifeline EOF is QA metadata, never product output EOF. +#[cfg(unix)] +mod unix { + use keito_cli::{ + source_qa_protocol::SharedOwner, + source_qa_scope::{GroupRegistry, RegistryReport, SlotId}, + }; + use serde_json::{json, Value}; + use sha2::{Digest, Sha256}; + use std::{ + fs::{self, File, OpenOptions}, + io::{self, Read, Write}, + os::{ + fd::AsRawFd, + unix::{ + fs::{MetadataExt, OpenOptionsExt}, + net::UnixStream, + process::{CommandExt, ExitStatusExt}, + }, + }, + path::{Path, PathBuf}, + process::{Command, Stdio}, + time::Duration, + }; + type R = Result; + const NS: u64 = 1_000_000_000; + const CASES: [&str; 4] = [ + "api-clean-two", + "api-publication-fault", + "api-edge-fault", + "api-expired-bound", + ]; + #[derive(Clone, Copy)] + enum EntryStage { + Arguments, + PrivateRole, + Images, + Binding, + Canary, + EventOpen, + ControllerGroup, + Clock, + Run, + FiniteRole, + } + impl EntryStage { + fn label(self) -> &'static str { + match self { + Self::Arguments => "ARGUMENTS", + Self::PrivateRole => "PRIVATE_ROLE", + Self::Images => "IMAGES", + Self::Binding => "BINDING", + Self::Canary => "CANARY", + Self::EventOpen => "EVENT_OPEN", + Self::ControllerGroup => "CONTROLLER_GROUP", + Self::Clock => "CLOCK", + Self::Run => "RUN", + Self::FiniteRole => "FINITE_ROLE", + } + } + } + fn entry_failure(stage: EntryStage, reason: &str) -> Value { + // No argv, path, environment value or arbitrary error text can enter + // this early packet. Unknown reasons remain unknown, not a diagnosis. + let safe = match reason { + "ARGS" + | "PRIVATE_ENV" + | "ENV_KEYS" + | "ENV_KEYS_CF_TEXT_ENCODING" + | "PLATFORM_ENV" + | "POLICY_PREREQUISITE" + | "PATH" + | "MODE" + | "SELF" + | "IMAGE_PATH" + | "BINDING" + | "BINDING_SCHEMA" + | "BINDING_MISMATCH" + | "HASH_OPEN" + | "HASH_META" + | "HASH_READ" + | "HASH_LIMIT" + | "HASH_DRIFT" + | "CANARY" + | "EVENT_OPEN" + | "CONTROLLER_GROUP" + | "CLOCK" + | "FIRST_FAILED" + | "LEADER_ARGS" + | "ROLE_FD" + | "ROLE_FD_BLOCKING" + | "FORK" => reason, + _ => "UNCLASSIFIED", + }; + json!({"actor_failure":true,"entry_phase":stage.label(),"reason":safe, + "resource_admission_may_have_started":matches!(stage,EntryStage::Run|EntryStage::FiniteRole), + "runtime_qualification":false}) + } + fn clock() -> R { + let mut t = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, t.as_mut_ptr()) } != 0 { + return Err("CLOCK"); + } + let t = unsafe { t.assume_init() }; + (t.tv_sec as u64) + .checked_mul(NS) + .and_then(|n| n.checked_add(t.tv_nsec as u64)) + .ok_or("CLOCK") + } + fn nap() { + std::thread::sleep(Duration::from_millis(1)); + } + fn hex(s: &str, n: usize) -> bool { + s.len() == n + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + } + fn owned(p: &Path, root: &Path, dir: bool) -> R<()> { + if !p.is_absolute() || !p.starts_with(root) || p.canonicalize().ok().as_deref() != Some(p) { + return Err("PATH"); + } + let m = fs::symlink_metadata(p).map_err(|_| "PATH")?; + if m.file_type().is_symlink() + || m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != 0o700 + || (dir && !m.is_dir()) + || (!dir && (!m.is_file() || m.nlink() != 1)) + { + return Err("MODE"); + } + Ok(()) + } + fn digest(p: &Path) -> R { + let mut f = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(p) + .map_err(|_| "HASH_OPEN")?; + let before = f.metadata().map_err(|_| "HASH_META")?; + if !before.is_file() || before.nlink() != 1 || before.len() > 128 * 1024 * 1024 { + return Err("HASH_META"); + } + let mut h = Sha256::new(); + let mut b = [0u8; 65536]; + let mut total = 0; + loop { + let n = f.read(&mut b).map_err(|_| "HASH_READ")?; + if n == 0 { + break; + } + total += n; + if total > 128 * 1024 * 1024 { + return Err("HASH_LIMIT"); + } + h.update(&b[..n]); + } + let after = f.metadata().map_err(|_| "HASH_META")?; + if before.dev() != after.dev() + || before.ino() != after.ino() + || before.len() != after.len() + || before.mtime() != after.mtime() + || before.mtime_nsec() != after.mtime_nsec() + { + return Err("HASH_DRIFT"); + } + Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect()) + } + fn exclusive(path: &Path, value: &Value) -> R<()> { + let mut f = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(path) + .map_err(|_| "RESULT_EXCLUSIVE")?; + let b = serde_json::to_vec_pretty(&value).map_err(|_| "RESULT_JSON")?; + f.write_all(&b) + .and_then(|_| f.write_all(b"\n")) + .and_then(|_| f.flush()) + .map_err(|_| "RESULT_WRITE")?; + if unsafe { libc::fsync(f.as_raw_fd()) } != 0 { + return Err("RESULT_FSYNC"); + } + Ok(()) + } + // Retain the caller's immutable cutpoint by reference. Durable means the + // exclusive writer completed write+flush+fsync, never merely create succeeded. + struct Publication { + durable: bool, + fallback_emitted: bool, + errors: Vec<&'static str>, + } + fn publish_snapshot( + snapshot: &Value, + phase: &'static str, + mut write: W, + mut fallback: F, + ) -> Publication + where + W: FnMut(&Value) -> R<()>, + F: FnMut(&Value) -> R<()>, + { + let mut receipt = Publication { + durable: false, + fallback_emitted: false, + errors: vec![], + }; + match write(snapshot) { + Ok(()) => receipt.durable = true, + Err(reason) => { + receipt.errors.push(reason); + let packet = json!({"publication":phase,"publication_fault":reason,"case_pass":false,"snapshot":snapshot}); + match fallback(&packet) { + Ok(()) => receipt.fallback_emitted = true, + Err(reason) => receipt.errors.push(reason), + } + } + } + receipt + } + fn emit_fact_fallback(value: &Value) -> R<()> { + let mut bytes = serde_json::to_vec(value).map_err(|_| "FACT_JSON")?; + if bytes.len() > 16384 { + return Err("FACT_LIMIT"); + } + bytes.push(b'\n'); + // The reviewed outer invocation binds stdout/stderr to private regular + // files. A failed sink never skips natural containment/wait collection. + let out = std::io::stdout(); + let result = { + let mut sink = out.lock(); + sink.write_all(&bytes).and_then(|()| sink.flush()) + }; + if result.is_ok() { + return Ok(()); + } + let err = std::io::stderr(); + let mut sink = err.lock(); + sink.write_all(&bytes) + .and_then(|()| sink.flush()) + .map_err(|_| "FACT_OUTPUT") + } + // Required values are validated first. macOS also gets one explicit + // UID-derived encoding value, preventing CF's home-file fallback. + // Unknown names/values never emit; additional keys still refuse. + fn environment_key_refusal( + keys: impl Iterator, + macos: bool, + ) -> Option<&'static str> { + let mut count = 0usize; + let mut cf_text_encoding = false; + for key in keys { + count = count.saturating_add(1); + cf_text_encoding |= key == std::ffi::OsStr::new("__CF_USER_TEXT_ENCODING"); + } + if (!macos && count == 10 && !cf_text_encoding) + || (macos && count == 11 && cf_text_encoding) + { + None + } else if count == 11 && cf_text_encoding { + Some("ENV_KEYS_CF_TEXT_ENCODING") + } else { + Some("ENV_KEYS") + } + } + #[cfg(any(target_os = "macos", test))] + fn platform_encoding_value(uid: u32) -> String { + format!("0x{uid:X}:0:0") + } + #[cfg(any(target_os = "macos", test))] + fn platform_encoding_is_exact(value: Option<&std::ffi::OsStr>, uid: u32) -> bool { + value == Some(std::ffi::OsStr::new(&platform_encoding_value(uid))) + } + fn private_role(root: &Path) -> R<()> { + if std::env::var("KEITO_ACTOR_POLICY_CONFIRMED").as_deref() + != Ok("source-registry-api-only") + { + return Err("POLICY_PREREQUISITE"); + } + owned(root, root, true)?; + for n in [ + "home", + "home/.codex", + "home/.claude", + "home/capture", + "home/config", + "home/state", + "home/AppData", + "tmp", + "bin", + ] { + owned(&root.join(n), root, true)?; + } + // This refusal flag supplements, but does not prove, the inherited policy. + for (key, relative) in [ + ("HOME", "home"), + ("CODEX_HOME", "home/.codex"), + ("CLAUDE_CONFIG_DIR", "home/.claude"), + ("KEITO_CAPTURE_HOME", "home/capture"), + ("XDG_CONFIG_HOME", "home/config"), + ("XDG_STATE_HOME", "home/state"), + ("APPDATA", "home/AppData"), + ("TMPDIR", "tmp"), + ("PATH", "bin"), + ] { + if std::env::var_os(key).map(PathBuf::from).as_ref() != Some(&root.join(relative)) { + return Err("PRIVATE_ENV"); + } + } + #[cfg(target_os = "macos")] + if !platform_encoding_is_exact( + std::env::var_os("__CF_USER_TEXT_ENCODING").as_deref(), + unsafe { libc::getuid() }, + ) { + return Err("PLATFORM_ENV"); + } + if let Some(reason) = environment_key_refusal( + std::env::vars_os().map(|(key, _)| key), + cfg!(target_os = "macos"), + ) { + return Err(reason); + } + Ok(()) + } + fn unix_nonblocking_fd(fd: i32) -> R<()> { + let mut kind: libc::c_int = 0; + let mut n = std::mem::size_of_val(&kind) as libc::socklen_t; + if unsafe { + libc::getsockopt( + fd, + libc::SOL_SOCKET, + libc::SO_TYPE, + (&mut kind as *mut libc::c_int).cast(), + &mut n, + ) + } != 0 + || kind != libc::SOCK_STREAM + { + return Err("ROLE_FD"); + } + let mut address = std::mem::MaybeUninit::::zeroed(); + let mut length = std::mem::size_of::() as libc::socklen_t; + if unsafe { libc::getsockname(fd, address.as_mut_ptr().cast(), &mut length) } != 0 + || unsafe { address.assume_init() }.ss_family as i32 != libc::AF_UNIX + { + return Err("ROLE_FD"); + } + let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; + if flags < 0 || flags & libc::O_NONBLOCK == 0 { + return Err("ROLE_FD_BLOCKING"); + } + Ok(()) + } + + // The post-fork member uses only libc, no allocation/runtime/destructors. + fn finite_leader(args: &[String]) -> R<()> { + if args.len() != 5 || !matches!(args[1].as_str(), "0" | "1") { + return Err("LEADER_ARGS"); + } + let root = PathBuf::from(&args[0]); + private_role(&root)?; + if std::env::current_exe().map_err(|_| "SELF")? != root.join("bin/actor") { + return Err("SELF"); + } + let ready = args[2].parse::().map_err(|_| "LEADER_ARGS")?; + let live = args[3].parse::().map_err(|_| "LEADER_ARGS")?; + let safety = args[4].parse::().map_err(|_| "LEADER_ARGS")?; + let at = clock()?; + if !(4..=1024).contains(&ready) + || !(4..=1024).contains(&live) + || ready == live + || safety <= at + || safety - at > 5 * NS + { + return Err("LEADER_ARGS"); + } + unix_nonblocking_fd(ready)?; + unix_nonblocking_fd(live)?; + let child = unsafe { libc::fork() }; + if child < 0 { + return Err("FORK"); + } + if child == 0 { + unsafe { + if libc::signal(libc::SIGTERM, libc::SIG_IGN) == libc::SIG_ERR { + libc::_exit(91); + } + if libc::write(ready, b"R".as_ptr().cast(), 1) != 1 { + libc::_exit(92); + } + libc::close(ready); + let delay = libc::timespec { + tv_sec: 0, + tv_nsec: 1_000_000, + }; + for _ in 0..6000 { + let mut t = std::mem::MaybeUninit::::uninit(); + if libc::clock_gettime(libc::CLOCK_MONOTONIC, t.as_mut_ptr()) != 0 { + let _ = libc::write(live, b"F".as_ptr().cast(), 1); + libc::_exit(93); + } + let t = t.assume_init(); + if (t.tv_sec as u64) * NS + t.tv_nsec as u64 >= safety { + break; + } + libc::nanosleep(&delay, std::ptr::null_mut()); + } + let _ = libc::write(live, b"N".as_ptr().cast(), 1); + libc::close(live); + libc::_exit(0); + } + } + unsafe { + libc::close(ready); + libc::close(live); + } + Ok(()) // Member is an orphan, never reported as reaped by this controller. + } + + fn registry_facts(report: &RegistryReport) -> Value { + json!({"first_fault":report.first_fault.map(|e|e.0), + "secondary_faults":report.secondary_faults.iter().map(|e|e.0).collect::>(), + "admission_closed":report.admission_closed,"retained_slots":report.retained_slots, + "cleanup_end":report.cleanup_end,"all_group_proofs":report.all_group_proofs, + "all_direct_waits_known":report.all_direct_waits_known, + "finish_called":report.finish_called,"output_eof_proven":report.output_eof_proven, + "groups":report.groups.iter().map(|g|json!({"slot":g.slot,"proof":g.group_proof, + "keeper_pid":g.facts.keeper_pid,"workload_pid":g.facts.workload_pid, + "first_fault":g.facts.first_fault,"secondary_faults":g.facts.secondary_faults, + "workload_spawned":g.facts.workload_spawned, + "keeper_wait":g.facts.keeper_status.map(|s|json!({"code":s.code(),"signal":s.signal(),"success":s.success()})), + "workload_wait":g.facts.workload_status.map(|s|json!({"code":s.code(),"signal":s.signal(),"success":s.success()})), + "group_absent":g.facts.group_absent,"release_sent":g.facts.release_sent, + "terminal_eof":g.facts.terminal_eof})).collect::>()}) + } + + struct Observation { + ready: UnixStream, + live: UnixStream, + ready_at: Option, + eof_at: Option, + natural: bool, + marker_checked: bool, + } + impl Observation { + fn poll(&mut self) -> R<()> { + if self.ready_at.is_none() { + let mut b = [0u8; 2]; + match self.ready.read(&mut b) { + Ok(1) if b[0] == b'R' => self.ready_at = Some(clock()?), + Ok(0) => return Err("READY_EOF"), + Ok(_) => return Err("READY_SCHEMA"), + Err(e) + if matches!( + e.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted + ) => {} + Err(_) => return Err("READY_READ"), + } + } + if self.eof_at.is_none() { + let mut b = [0u8; 2]; + match self.live.read(&mut b) { + Ok(0) => self.eof_at = Some(clock()?), + Ok(1) if b[0] == b'N' => self.natural = true, + Ok(1) if b[0] == b'F' => return Err("MEMBER_CLOCK"), + Ok(_) => return Err("LIVE_SCHEMA"), + Err(e) + if matches!( + e.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted + ) => {} + Err(_) => return Err("LIVE_READ"), + } + } + Ok(()) + } + fn facts(&self) -> Value { + json!({"ready_at":self.ready_at,"lifeline_eof_at":self.eof_at, + "natural_expiry_marker":self.natural,"original_preexec_preserved":self.marker_checked, + "orphan_member_reaped":false,"product_output_eof":false}) + } + } + + struct Run { + registry: GroupRegistry, + observations: Vec, + log: File, + events: usize, + hard: u64, + safety: u64, + first: Option<&'static str>, + secondary: Vec<&'static str>, + } + impl Run { + fn fail(&mut self, why: &'static str) { + if self.first.is_none() { + self.first = Some(why); + } else if self.first != Some(why) + && self.secondary.len() < 8 + && !self.secondary.contains(&why) + { + self.secondary.push(why); + } + } + fn event(&mut self, tag: &'static str, value: Value) -> R<()> { + self.events += 1; + if self.events > 64 { + return Err("EVENT_LIMIT"); + } + let b = serde_json::to_vec(&json!({"event":tag,"at":clock().ok(),"fact":value})) + .map_err(|_| "EVENT_JSON")?; + self.log + .write_all(&b) + .and_then(|_| self.log.write_all(b"\n")) + .and_then(|_| self.log.flush()) + .and_then(|_| self.log.sync_all()) + .map_err(|_| "EVENT_WRITE") + } + fn poll_observations(&mut self) -> R<()> { + let mut first = None; + for observation in &mut self.observations { + if let Err(e) = observation.poll() { + first.get_or_insert(e); + } + } + first.map_or(Ok(()), Err) + } + fn facts(&self) -> Value { + json!({"first_fault":self.first,"secondary_faults":self.secondary, + "registry":registry_facts(&self.registry.report()), + "observations":self.observations.iter().map(Observation::facts).collect::>(), + "hard_end":self.hard,"fixed_member_safety_end":self.safety, + "controller_group_signals_or_queries":false,"raw_esrch_instrumented":false}) + } + fn spawn(&mut self, root: &Path, keeper: &Path, index: usize) -> io::Result { + self.registry.spawn_group(root, keeper, |id, report| { + if id.index() != index || report.workload_spawned || report.keeper_pid == 0 { + return Err(io::Error::other("PUBLISHER_NOT_RETAINED")); + } + // A real exclusive write: slot1 deliberately collides only in the + // fixed publication-fault case. Registry must retain its actual Child. + let mut f = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(root.join(format!("registration-{index}.json")))?; + let bytes = + serde_json::to_vec(&json!({"slot":id.index(),"keeper_pid":report.keeper_pid}))?; + f.write_all(&bytes)?; + f.flush()?; + f.sync_all() + }) + } + fn start(&mut self, root: &Path, image: &Path, id: &SlotId, index: usize) -> R<()> { + let (ready_r, ready_w) = UnixStream::pair().map_err(|_| "PAIR")?; + let (live_r, live_w) = UnixStream::pair().map_err(|_| "PAIR")?; + for s in [&ready_r, &ready_w, &live_r, &live_w] { + s.set_nonblocking(true).map_err(|_| "NONBLOCK")?; + } + let marker_path = root.join(format!("preexec-{index}.txt")); + let marker = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(&marker_path) + .map_err(|_| "MARKER_OPEN")?; + let (rf, lf, mf) = (ready_w.as_raw_fd(), live_w.as_raw_fd(), marker.as_raw_fd()); + if [rf, lf, mf].iter().any(|f| !(4..=1024).contains(f)) { + return Err("FD"); + } + let mut command = Command::new(image); + command + .env_clear() + .current_dir(root) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .env("KEITO_ACTOR_POLICY_CONFIRMED", "source-registry-api-only") + .env("HOME", root.join("home")) + .env("CODEX_HOME", root.join("home/.codex")) + .env("CLAUDE_CONFIG_DIR", root.join("home/.claude")) + .env("KEITO_CAPTURE_HOME", root.join("home/capture")) + .env("XDG_CONFIG_HOME", root.join("home/config")) + .env("XDG_STATE_HOME", root.join("home/state")) + .env("APPDATA", root.join("home/AppData")) + .env("TMPDIR", root.join("tmp")) + .env("PATH", root.join("bin")) + .args([ + "--finite-leader".to_owned(), + root.to_string_lossy().into_owned(), + index.to_string(), + rf.to_string(), + lf.to_string(), + self.safety.to_string(), + ]); + #[cfg(target_os = "macos")] + command.env( + "__CF_USER_TEXT_ENCODING", + platform_encoding_value(unsafe { libc::getuid() }), + ); + unsafe { + command.pre_exec(move || { + if libc::write(mf, b"P".as_ptr().cast(), 1) != 1 + || libc::fsync(mf) != 0 + || libc::fcntl(rf, libc::F_SETFD, 0) < 0 + || libc::fcntl(lf, libc::F_SETFD, 0) < 0 + { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + // Retain observation endpoints BEFORE consuming the original Command. + self.observations.push(Observation { + ready: ready_r, + live: live_r, + ready_at: None, + eof_at: None, + natural: false, + marker_checked: false, + }); + let result = self.registry.start(id, command); + drop(ready_w); + drop(live_w); + drop(marker); + result.map_err(|_| "START")?; + if fs::read(marker_path).map_err(|_| "MARKER_READ")? != b"P" { + return Err("PREEXEC_LOST"); + } + self.observations[index].marker_checked = true; + Ok(()) + } + fn ready(&mut self, end: u64) -> R<()> { + loop { + self.poll_observations()?; + if self + .observations + .iter() + .any(|v| v.eof_at.is_some() || v.natural) + { + return Err("NOT_LIVE"); + } + if clock()? >= end { + return Err("SETUP_BOUND"); + } + if self.observations.iter().all(|v| v.ready_at.is_some()) { + return Ok(()); + } + nap(); + } + } + fn fallback(&mut self) { + // Same existing bound, no new cleanup/proof allowance. Late facts never + // replace FIRST. Only already-owned leases may collect actual waits. + self.registry.begin_cleanup(self.hard); + for _ in 0..6000 { + self.registry.poll_cleanup(); + if let Err(e) = self.poll_observations() { + self.fail(e); + } + if self.registry.report().all_direct_waits_known + && self.observations.iter().all(|v| v.eof_at.is_some()) + { + break; + } + if clock().is_ok_and(|at| at >= self.safety + 500_000_000) { + break; + } + nap(); + } + // Required explicit finalization even for setup/receipt failure. + self.registry.finish(); + } + } + + fn binding(root: &Path, image: &Path, keeper: &Path) -> R { + let path = root.join("binding.json"); + let m = fs::symlink_metadata(&path).map_err(|_| "BINDING")?; + if !m.is_file() + || m.file_type().is_symlink() + || m.nlink() != 1 + || m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != 0o600 + || m.len() > 65536 + { + return Err("BINDING"); + } + let b: Value = serde_json::from_slice(&fs::read(path).map_err(|_| "BINDING")?) + .map_err(|_| "BINDING")?; + let keys = [ + "source_commit", + "actor_sha256", + "keeper_sha256", + "source_manifest_sha256", + "actor_source_sha256", + ]; + if b.as_object() + .is_none_or(|o| o.len() != keys.len() || o.keys().any(|k| !keys.contains(&k.as_str()))) + { + return Err("BINDING_SCHEMA"); + } + if !b["source_commit"].as_str().is_some_and(|s| hex(s, 40)) + || ["source_manifest_sha256", "actor_source_sha256"] + .iter() + .any(|k| !b[*k].as_str().is_some_and(|s| hex(s, 64))) + || b["actor_sha256"].as_str() != Some(digest(image)?.as_str()) + || b["keeper_sha256"].as_str() != Some(digest(keeper)?.as_str()) + { + return Err("BINDING_MISMATCH"); + } + Ok(b) + } + + fn controller(args: &[String], stage: &mut EntryStage) -> R<()> { + *stage = EntryStage::Arguments; + if args.len() != 3 || !CASES.contains(&args[1].as_str()) { + return Err("ARGS"); + } + let root = PathBuf::from(&args[0]); + *stage = EntryStage::PrivateRole; + private_role(&root)?; + *stage = EntryStage::Images; + let image = std::env::current_exe().map_err(|_| "SELF")?; + let keeper = root.join("bin/keeper"); + if image != root.join("bin/actor") || Path::new(&args[2]) != keeper { + return Err("IMAGE_PATH"); + } + owned(&image, &root, false)?; + owned(&keeper, &root, false)?; + *stage = EntryStage::Binding; + let bound = binding(&root, &image, &keeper)?; + let scenario = args[1].as_str(); + *stage = EntryStage::Canary; + if scenario == "api-publication-fault" + && fs::read(root.join("registration-1.json")).map_err(|_| "CANARY")? != b"CANARY\n" + { + return Err("CANARY"); + } + *stage = EntryStage::EventOpen; + let log = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(root.join("events.jsonl")) + .map_err(|_| "EVENT_OPEN")?; + *stage = EntryStage::ControllerGroup; + if unsafe { libc::getpid() } == unsafe { libc::getsid(0) } + || unsafe { libc::setpgid(0, 0) } != 0 + { + return Err("CONTROLLER_GROUP"); + } + *stage = EntryStage::Clock; + let start = clock()?; + let hard = start + 3 * NS; + let safety = start + 4 * NS; + let mut run = Run { + registry: GroupRegistry::new(SharedOwner::default(), hard), + observations: Vec::with_capacity(2), + log, + events: 0, + hard, + safety, + first: None, + secondary: Vec::new(), + }; + *stage = EntryStage::Run; + let outcome = (|| -> R { + let a = run.spawn(&root, &keeper, 0).map_err(|_| "SPAWN_0")?; + run.registry.await_ready(&a).map_err(|_| "READY_0")?; + run.start(&root, &image, &a, 0)?; + run.ready(start + 400_000_000)?; + let live = run.facts(); + run.event("SLOT_ZERO_LIVE_BEFORE_SECOND_ADMISSION", live)?; + let b = run.spawn(&root, &keeper, 1); + if scenario == "api-publication-fault" { + if b.as_ref() + .err() + .is_none_or(|e| e.kind() != io::ErrorKind::AlreadyExists) + { + return Err("EXPECTED_RECEIPT_COLLISION"); + } + } else { + let b = b.map_err(|_| "SPAWN_1")?; + run.registry.await_ready(&b).map_err(|_| "READY_1")?; + run.start(&root, &image, &b, 1)?; + run.ready(start + 400_000_000)?; + } + let live = run.facts(); + run.event("AFTER_SECOND_ADMISSION", live)?; + if scenario == "api-edge-fault" { + let mut refused = Command::new(&image); + refused + .arg("--refuse-extra-start") + .env_clear() + .current_dir(&root) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + if run.registry.start(&a, refused).is_ok() { + return Err("REPEAT_START_ACCEPTED"); + } + } + if matches!(scenario, "api-edge-fault" | "api-publication-fault") { + let mut publisher_called = false; + let attempt = run.registry.spawn_group(&root, &keeper, |_, _| { + publisher_called = true; + Ok(()) + }); + if attempt.is_ok() || publisher_called || run.registry.report().retained_slots != 2 + { + return Err("ADMISSION_REOPENED"); + } + } + let requested = if scenario == "api-expired-bound" { + clock()?.saturating_sub(1) + } else { + (clock()? + 600_000_000).min(hard) + }; + run.registry.begin_cleanup(requested); + if scenario == "api-clean-two" { + run.registry.begin_cleanup(requested - 50_000_000); + run.registry.begin_cleanup(requested + 50_000_000); + if run.registry.report().cleanup_end != Some(requested - 50_000_000) { + return Err("BOUND_EXTENDED"); + } + } + let action_end = run.registry.report().cleanup_end.ok_or("NO_CLEANUP_END")?; + let before = run.facts(); + run.event( + "BEFORE_FINISH", + json!({"requested_end":requested,"actual_end":action_end,"facts":before}), + )?; + let report = run.registry.finish(); + run.poll_observations()?; + let at = clock()?; + if report.retained_slots != 2 + || !report.admission_closed + || !report.finish_called + || report.output_eof_proven + { + return Err("REGISTRY_FACTS"); + } + if scenario == "api-expired-bound" { + if report.first_fault.is_none() || action_end > requested { + return Err("EXPIRED_HEALED"); + } + return Ok( + json!({"case_pass":true,"expected_bound_refusal":true,"protocol_outcome":"FAILED", + "physical_cancel_before_bound":null,"clean_proof":false,"cutpoint_at":at}), + ); + } + // finish may precede scheduler delivery of the QA lifeline EOF. This is + // observation only under the SAME end, never another proof allowance. + while run.observations.iter().any(|v| v.eof_at.is_none()) && clock()? < action_end { + run.poll_observations()?; + nap(); + } + let at = clock()?; + if at >= action_end + || !report.all_direct_waits_known + || run + .observations + .iter() + .any(|v| v.eof_at.is_none_or(|t| t >= action_end) || v.natural) + { + return Err("PHYSICAL_OR_WAIT_UNPROVEN"); + } + if scenario == "api-clean-two" { + if report.first_fault.is_some() + || !report.all_group_proofs + || report.groups.iter().any(|g| { + !g.facts.keeper_status.is_some_and(|s| s.success()) + || !g.facts.workload_status.is_some_and(|s| s.success()) + || !g.facts.terminal_eof + }) + { + return Err("CLEAN_UNPROVEN"); + } + } else if report.first_fault.is_none() { + return Err("FAILED_OWNER_HEALED"); + } + Ok( + json!({"case_pass":true,"protocol_outcome":if scenario=="api-clean-two" {"CLEAN"} else {"FAILED"}, + "physical_cancel_before_bound":true,"clean_proof":scenario=="api-clean-two","cutpoint_at":at}), + ) + })(); + if let Err(e) = &outcome { + run.fail(e); + } + let first = json!({"scenario":scenario,"binding":bound,"result":outcome.as_ref().ok(),"facts":run.facts()}); + let first_receipt = publish_snapshot( + &first, + "FIRST", + |v| exclusive(&root.join("FIRST.json"), v), + emit_fact_fallback, + ); + for e in &first_receipt.errors { + run.fail(e); + } + run.fallback(); + if !run.registry.report().all_direct_waits_known + || run.observations.iter().any(|o| o.eof_at.is_none()) + { + run.fail("LATE_UNKNOWN_HANDLES"); + } + let drift = digest(&image).ok().as_deref() == bound["actor_sha256"].as_str() + && digest(&keeper).ok().as_deref() == bound["keeper_sha256"].as_str(); + if !drift { + run.fail("IMAGE_DRIFT"); + } + let canary = scenario != "api-publication-fault" + || fs::read(root.join("registration-1.json")).ok().as_deref() == Some(b"CANARY\n"); + if !canary { + run.fail("CANARY_DRIFT"); + } + let final_snapshot = json!({"case_pass":outcome.is_ok()&&run.first.is_none(),"cutpoint":&first, + "first_preserved":first_receipt.durable,"first_fallback_emitted":first_receipt.fallback_emitted, + "image_drift_free":drift,"collision_canary_unchanged":canary,"facts":run.facts(), + "late_facts_never_upgrade_first":true}); + let final_receipt = publish_snapshot( + &final_snapshot, + "FINAL", + |v| exclusive(&root.join("FINAL.json"), v), + emit_fact_fallback, + ); + for e in &final_receipt.errors { + run.fail(e); + } + if outcome.is_ok() && run.first.is_none() && final_receipt.durable { + Ok(()) + } else { + Err("FIRST_FAILED") + } + } + + pub fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let mut stage = EntryStage::Arguments; + let result = if args.first().is_some_and(|s| s == "--finite-leader") { + stage = EntryStage::FiniteRole; + finite_leader(&args[1..]) + } else { + controller(&args, &mut stage) + }; + if let Err(reason) = result { + // Existing private output sinks and bounded fallback, never a new + // path write or proof. A failed diagnostic cannot change exit1. + let _ = emit_fact_fallback(&entry_failure(stage, reason)); + std::process::exit(1); + } + } + + #[cfg(test)] + mod entry_diagnostic_tests { + use super::*; + + #[test] + fn preflight_diagnostic_has_no_arbitrary_text_or_resource_proof() { + for text in ["/private/secret", "TOKEN_VALUE", "ENV_KEYS\nsecret", ""] { + let packet = entry_failure(EntryStage::PrivateRole, text); + assert_eq!(packet["reason"], "UNCLASSIFIED"); + assert_eq!(packet["entry_phase"], "PRIVATE_ROLE"); + assert_eq!(packet["resource_admission_may_have_started"], false); + assert_eq!(packet["runtime_qualification"], false); + assert_eq!(packet.as_object().unwrap().len(), 5); + } + let packet = entry_failure(EntryStage::PrivateRole, "ENV_KEYS"); + assert_eq!(packet["reason"], "ENV_KEYS"); + assert!(serde_json::to_vec(&packet).unwrap().len() < 256); + assert_eq!( + entry_failure(EntryStage::Run, "FIRST_FAILED") + ["resource_admission_may_have_started"], + true + ); + } + + #[test] + fn platform_key_requires_explicit_platform_layout_and_unknown_extras_stay_opaque() { + let ten: Vec<_> = (0..10) + .map(|i| std::ffi::OsString::from(format!("SYNTHETIC_{i}"))) + .collect(); + assert_eq!( + environment_key_refusal(ten.clone().into_iter(), false), + None + ); + assert_eq!( + environment_key_refusal(ten.clone().into_iter(), true), + Some("ENV_KEYS") + ); + let mut known = ten.clone(); + known.push("__CF_USER_TEXT_ENCODING".into()); + assert_eq!( + environment_key_refusal(known.clone().into_iter(), false), + Some("ENV_KEYS_CF_TEXT_ENCODING") + ); + assert_eq!( + environment_key_refusal(known.clone().into_iter(), true), + None + ); + let mut unknown = ten; + unknown.push("UNPRINTED_EXTRA_NAME".into()); + assert_eq!( + environment_key_refusal(unknown.into_iter(), true), + Some("ENV_KEYS") + ); + known.push("ANOTHER_UNPRINTED_NAME".into()); + assert_eq!( + environment_key_refusal(known.into_iter(), true), + Some("ENV_KEYS") + ); + } + + #[test] + fn encoding_value_cannot_select_another_uid_or_nonzero_encoding() { + let exact = platform_encoding_value(501); + assert!(platform_encoding_is_exact( + Some(std::ffi::OsStr::new(&exact)), + 501 + )); + for value in [ + None, + Some("0x0:0:0"), + Some("0x1F5:1:0"), + Some("0x1F5:0:1"), + Some("/private/secret"), + ] { + assert!(!platform_encoding_is_exact( + value.map(std::ffi::OsStr::new), + 501 + )); + } + } + } +} + +#[cfg(unix)] +fn main() { + unix::main(); +} +#[cfg(not(unix))] +fn main() { + std::process::exit(1); +} diff --git a/examples/source_qa_keeper.rs b/examples/source_qa_keeper.rs new file mode 100644 index 0000000..3c0f819 --- /dev/null +++ b/examples/source_qa_keeper.rs @@ -0,0 +1,12 @@ +//! Developer QA sibling group keeper. Never installed or launched by default. +#[cfg(unix)] +fn main() { + if keito_cli::source_qa_group::keeper_main(std::env::args_os().skip(1)).is_err() { + // No argv/path or OS error may enter this helper's output. + std::process::exit(1); + } +} +#[cfg(not(unix))] +fn main() { + std::process::exit(1); +} diff --git a/scripts/qualify-capture-artifact.sh b/scripts/qualify-capture-artifact.sh new file mode 100755 index 0000000..3a969b4 --- /dev/null +++ b/scripts/qualify-capture-artifact.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Development/release verification only. The driver preflights every mutation +# command; this wrapper hashes exactly the three operator config anchors. +set -euo pipefail +repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) +profile=${KEITO_TEST_REAL_PROFILE_HOME:?Set the original profile for digest-only verification} +[ "$#" -eq 2 ] || { echo 'Usage: qualify-capture-artifact.sh ' >&2; exit 2; } +fingerprint() { + local relative file + for relative in .codex/hooks.json .codex/config.toml .claude/settings.json; do + file="$profile/$relative" + [ ! -L "$file" ] || return 1 + if [ -f "$file" ]; then shasum -a 256 < "$file"; elif [ ! -e "$file" ]; then printf '%s\n' MISSING; else return 1; fi + done +} +before=$(fingerprint) +readonly profile before +verify() { + local result=$? after + after=$(fingerprint) || result=98 + if [ "$after" != "$before" ]; then + echo 'Operator profile changed during artifact verification; preserve evidence and stop.' >&2 + result=98 + fi + exit "$result" +} +trap verify EXIT +cd "$repo" +CARGO_TARGET_DIR="$repo/target" cargo build --locked --features dev-tools --bin qualify-capture +driver="$repo/target/debug/qualify-capture" +if [ -x /usr/bin/sandbox-exec ]; then + KEITO_QUALIFICATION_NETWORK_DENY=macos-sandbox-exec /usr/bin/sandbox-exec -p '(version 1) (allow default) (deny network*)' "$driver" "$1" "$2" +else + KEITO_QUALIFICATION_NETWORK_DENY=unavailable "$driver" "$1" "$2" +fi diff --git a/setup b/setup index 97021c0..02ea066 100755 --- a/setup +++ b/setup @@ -57,6 +57,11 @@ case "$TEAM_MODE" in *) echo "Unknown --team value: $TEAM_MODE" >&2; exit 1 ;; esac +if [ "$HOST" = "auto" ] && [ ! -t 0 ]; then + echo "Scripted setup requires --host claude, --host codex, or --host both; nothing installed." >&2 + exit 2 +fi + script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) if ! command -v keito >/dev/null 2>&1; then @@ -76,20 +81,20 @@ if [ "$HOST" = "auto" ] && [ -t 0 ]; then echo " 2) Claude Code only" echo " 3) Codex only" echo "" - printf "Choice [1/2/3] (default: 1): " + printf "Choice [1/2/3]: " read -r choice - case "${choice:-1}" in + case "$choice" in + 1) HOST="both" ;; 2) HOST="claude" ;; 3) HOST="codex" ;; - *) HOST="both" ;; + *) echo "Choose an explicit target; nothing configured." >&2; exit 2 ;; esac -elif [ "$HOST" = "auto" ]; then - HOST="both" fi args=(skill install --source bundled) case "$HOST" in both) + args+=(--agent claude-code --agent codex) ;; claude) args+=(--agent claude-code) diff --git a/skills/keito-time-track/SKILL.md b/skills/keito-time-track/SKILL.md index 65fe684..d7a514b 100644 --- a/skills/keito-time-track/SKILL.md +++ b/skills/keito-time-track/SKILL.md @@ -1,68 +1,138 @@ --- name: keito-time-track description: > - Track billable AI coding-session time to Keito through the Keito CLI. Use - when the user asks to set up repository time tracking, install or configure - the Keito skill, log agent work, check tracking status, pause or resume - tracking, disable tracking, or review today's source=agent time entries. + Set up explicit repository consent and inspect metadata-only coding-agent + activity through the Keito CLI. Use when the user asks to install capture, + map a repository, check queued activity, pause or resume capture, disable + capture, or review agent time. Activity needs authorized review before billing. --- # Keito Time Track -You are helping the user manage Keito time tracking for coding sessions in -this repository. Time entries are created automatically by installed lifecycle -hooks when a session ends. Do not create time entries directly from the skill -body. +The CLI owns deterministic capture, the local consent ledger, exact observed +turn intervals and durable delivery. The skill selects and configures it. +Never measure time or create time/expense records from a model response. -## Commands +## Setup -When the user asks to set up Keito tracking for the current repo, or invokes -this skill directly with `/track-time-keito` or `/keito-time-track:keito-time-track`, run: +Confirm which supported adapters the user wants: `claude-code`, `codex`, or both. +Scripted installation always names targets. If the user already selected them, +continue without asking again. For example, for both: ```bash -if ! command -v keito >/dev/null 2>&1; then scripts/install-cli.sh; fi -keito skill install --skip-skills-add -scripts/setup-wizard.sh +keito skill install --agent claude-code --agent codex +scripts/setup-wizard.sh --agent claude-code --agent codex --install-worker ``` -If `keito auth status` reports unauthenticated, stop before setup and tell the -user to run `keito auth login`. Do not ask for or print API keys. - -When the user asks for tracking status, run: +The native Rust CLI and its verified matching `keito-capture-guard` must be installed. +Capture, installer and mapping setup have no production Python runtime dependency. +The CLI must expose `keito capture --help`. If it does not, install a qualified +CLI release before proceeding. `scripts/install-cli.sh` installs the public CLI; +it does not establish capture support or harness qualification. Authentication +belongs to `keito auth login`; never request or print API keys. + +The explicit `--install-worker` option requests a local macOS background +uploader; the picker previews it before confirmation. Without that option setup +only approves local queuing, so do not claim automatic delivery. The CLI owns +service setup and must report its actual running/verified state. + +The setup picker uses existing accessible clients, projects and project tasks. +It delegates mapping publication and recovery to native `capture setup --client + --project --task --write-hint --confirm` in the +canonical Git root; it never shells back into the CLI from an installer service. +It previews metadata-only collection and requires explicit mapping consent on +this device. A repository-carried `.keito/config.yml` is only a hint; it cannot +approve capture, choose a billing rate or authorize historical import. Failed setup restores the previous hint. After an +interruption, run setup recovery and inspect `keito capture status` before +explicit reapproval; core consent may have committed even when the wrapper +failed. Recovery must not replay that operation automatically. + +## Inspect and control ```bash scripts/status.sh -``` - -When the user asks to pause or resume tracking for the current session, run: - -```bash +keito capture preview --session --json +keito capture sync scripts/pause-resume.sh pause scripts/pause-resume.sh resume -``` - -When the user asks to disable tracking for this repository, run: - -```bash scripts/disable.sh ``` -When the user asks what was logged today, run: +Pause, resume and disable target the approved current repository, including +unsent work; they do not rewrite previously submitted accounting evidence. +Use CLI status/preview for actionable holds and errors. Never open transcripts +or raw hook inputs for diagnostics. Never manufacture a successful delivery from +configured hook files or treat unknown usage as zero. + +For adapter removal, explicitly select only the unwanted target: ```bash -keito --json time list --today --source agent +installers/uninstall.sh --agent codex ``` -Summarise the returned entries by duration, project, task, and notes. - -## Rules - -- Never read or expose Keito API keys. Authentication belongs to the Keito CLI. -- Never write `.keito/config.yml` by hand. Use `scripts/setup-wizard.sh`. -- Treat `.keito/config.yml` as repository-specific. Do not reuse a config from - another client or project. -- Never create a time entry from the skill body. The session-end hook owns - duration measurement and writes exactly one entry per session. -- If the Keito CLI is missing, run `scripts/install-cli.sh`. -- If the Keito CLI is unauthenticated, tell the user to run `keito auth login` - or set `KEITO_API_KEY` and `KEITO_ACCOUNT_ID`. +Removal preserves unrelated/ambiguous commands and refuses to delete modified +skill payloads. Immutable hidden adapter generations remain for safe rollback; +installation never replaces an executable referenced by an existing hook. It does not delete capture evidence or restore previously disabled +legacy plugins automatically. + +## Plugin qualification + +Claude plugin registrations do not snapshot the running executable version. +They use `KEITO_HARNESS_VERSION` when explicitly provided, otherwise `unknown`. +Unknown means unqualified: never report a plugin as ready or live-delivery +verified from installed files. The direct installer records the selected +observed version. The native guard/core pair is configured by managed direct +installation; a plugin-only installation does not establish that pair and +remains unqualified. All routes still need real trust/dispatch qualification. +These scripts do not run a version-discovery subprocess on every hook. + +## Measure and review agent work + +Use captured runs as audit evidence. Lead project/task summaries with explicitly +reviewed outcomes and available usage; a completed capture or approved time entry +does not prove a deliverable was accepted. Project tasks may be billing categories. +Review outcomes in the application's Agent work view when that qualified feature +is enabled. Do not invent a CLI outcome command or mark success from model prose. + +Keep the observation window and summed observed run durations separate. Ten +concurrent two-hour runs can mean a two-hour window and twenty summed run-hours; +neither measures human labor or active compute. Log human steering and review +separately. Missing usage is unknown, partial tokens are not complete expenditure, +and tokens are not a productivity score. Keep model/cache semantics and provenance. + +An outcome judgment is revision-bound and separate from an agreed client charge. +Neither duration nor usage automatically authorizes billing. Preserve existing +review/pricing permissions and exact captured evidence. Demos must label synthetic +data and show concurrent runs, explicit outcome review and unknown usage/costs; +an animation or seeded expense is not proof of automatic capture. + +A request to update measurement code, processes or skills does not authorize marketing-site copy, visuals or public positioning. Keep controlled product demos separate; public claims need observed usage evidence and an explicit website request. + +## Capture and privacy contract + +- `SessionStart` preserves session identity; `UserPromptSubmit` opens a turn; + `Stop` checkpoints it; interruption/failure/finalization retain incomplete + evidence. A session may have many completed turns. +- Hooks invoke the paired native Rust guard/core locally, with the unchanged + one-second fail-open ceiling. A content-free durable prelaunch marker precedes + core startup; only exact durable acknowledgement, successful exit and pipe EOF + permit cleanup. The guard performs no network or SQLite work. Core SQLite + durability precedes acknowledgement; workers handle + network I/O and frozen retries separately. +- Default capture never uploads prompts, assistant prose, transcripts, source + code, full local paths, branch names or Git diffs. The raw harness JSON is + transient stdin to the allowlisting CLI and is never logged by these scripts. +- Observed agent duration is not human labour, CPU time, vendor expenditure or + permission to charge. New evidence remains nonbillable pending review. +- A separately qualified numeric parser may read the exact active-session file + locally after current consent and baseline checks. It discards prompts, prose, + code and tool arguments; only allowlisted counters/identifiers/provenance can + persist. Paused/revoked terminal events do not read transcripts. No arbitrary + history scans, backfill, model summaries or transcript uploads are authorized. +- Numeric usage and cost claims require separately qualified versioned evidence. + These adapters alone establish no automatic usage or actual-cost claim. +- Installation cannot grant host trust, mapping consent, rate authority or live + delivery verification. Codex uses `features.hooks`; follow its normal trust + review and never bypass it. Changed hook hashes require renewed host review. +- Legacy plugin/direct-hook duplicates need an explicit migration confirmation. + Do not silently run old financial hooks alongside the new implementation. diff --git a/skills/keito-time-track/assets/claude.md-block.md b/skills/keito-time-track/assets/claude.md-block.md index 216d635..685ee3d 100644 --- a/skills/keito-time-track/assets/claude.md-block.md +++ b/skills/keito-time-track/assets/claude.md-block.md @@ -1,5 +1,8 @@ -## Keito Time Tracking +## Keito coding-agent capture -This repository is configured for Keito agent time tracking. Use -`/track-time-keito status` to check whether tracking is enabled, and -`/track-time-keito pause` before doing one-off unbillable work in this repo. +Capture is optional until this device's user explicitly approves the repository +mapping through `keito capture setup`. Use `keito capture status --json` for +consent, queue and delivery state, and `keito capture pause --repo` before work +that should not be collected. A checked-in config is only a mapping hint. +Never send prompts, responses, transcripts, code or full paths to Keito, and +never use model judgement to log duration or create a client charge. diff --git a/skills/keito-time-track/assets/config.example.yml b/skills/keito-time-track/assets/config.example.yml index 9efb1c8..e26e968 100644 --- a/skills/keito-time-track/assets/config.example.yml +++ b/skills/keito-time-track/assets/config.example.yml @@ -1,18 +1,10 @@ +# Legacy mapping hint only. This file cannot approve capture on another device. +# Use `keito capture setup` to validate and explicitly approve the mapping. version: 1 workspace_id: co_example client_id: cli_example -client_name: "Example Client" project_id: prj_example -project_name: "Example Project" task_id: tsk_development -task_name: "Development" agent_tracking: - enabled: true - source: agent - draft: true - min_duration_seconds: 60 - max_duration_seconds: 28800 - redact_notes: false -metadata: - integration: keito_skill - cost_centre: engineering + enabled: false + redact_notes: true diff --git a/skills/keito-time-track/hooks/claude-plugin.json b/skills/keito-time-track/hooks/claude-plugin.json new file mode 100644 index 0000000..6b9dc9e --- /dev/null +++ b/skills/keito-time-track/hooks/claude-plugin.json @@ -0,0 +1,59 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/keito-time-track/hooks/dispatch.sh\" --agent claude-code --event session-start", + "timeout": 1 + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/keito-time-track/hooks/dispatch.sh\" --agent claude-code --event prompt", + "timeout": 1 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/keito-time-track/hooks/dispatch.sh\" --agent claude-code --event stop", + "timeout": 1 + } + ] + } + ], + "StopFailure": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/keito-time-track/hooks/dispatch.sh\" --agent claude-code --event interrupt", + "timeout": 1 + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/keito-time-track/hooks/dispatch.sh\" --agent claude-code --event session-end", + "timeout": 1 + } + ] + } + ] + } +} diff --git a/skills/keito-time-track/hooks/dispatch.sh b/skills/keito-time-track/hooks/dispatch.sh new file mode 100755 index 0000000..2b2d4fc --- /dev/null +++ b/skills/keito-time-track/hooks/dispatch.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Hooks only hand transient stdin to the local deterministic capture core. +# Never log, inspect transcripts, infer identity, or perform network writes here. +set -u +agent=${KEITO_AGENT_TYPE:-} +version=${KEITO_HARNESS_VERSION:-unknown} +event="" +while [ "$#" -gt 0 ]; do + [ "$#" -ge 2 ] || exit 0 + case "$1" in + --agent) agent=$2 ;; + --event) event=$2 ;; + --harness-version) version=$2 ;; + *) exit 0 ;; + esac + shift 2 +done +case "$agent" in claude-code|codex) ;; *) exit 0 ;; esac +case "$event" in session-start|prompt|stop|interrupt|session-end) ;; *) exit 0 ;; esac +[[ "$version" =~ ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ ]] || exit 0 +[[ "$version" != *..* ]] || exit 0 +keito_cmd=${KEITO_CLI_BIN:-keito} +guard_cmd=${KEITO_CAPTURE_GUARD_BIN:-} +case "$keito_cmd" in /*) ;; *) exit 0 ;; esac +case "$guard_cmd" in /*) ;; *) exit 0 ;; esac +# Core refusal belongs to the native guard, after durable publication. +[ -f "$guard_cmd" ] && [ -x "$guard_cmd" ] && [ ! -L "$guard_cmd" ] || exit 0 +# Preserve the directly owned PID across shell -> native dispatch. There are +# no background timer processes. Exec refusal stays silent and fail-open; attached +# ownership sees EOF without terminal and cannot accept capture proof. +shopt -s execfail +exec "$guard_cmd" --internal-dispatch-v2 --core "$keito_cmd" --agent "$agent" --event "$event" --harness-version "$version" <&0 >/dev/null 2>&1 +exit 0 diff --git a/skills/keito-time-track/hooks/interrupt.sh b/skills/keito-time-track/hooks/interrupt.sh new file mode 100755 index 0000000..3010ce0 --- /dev/null +++ b/skills/keito-time-track/hooks/interrupt.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) || exit 0 +exec bash "$script_dir/dispatch.sh" --event interrupt "$@" diff --git a/skills/keito-time-track/hooks/lib/config.sh b/skills/keito-time-track/hooks/lib/config.sh deleted file mode 100644 index 46f2c18..0000000 --- a/skills/keito-time-track/hooks/lib/config.sh +++ /dev/null @@ -1,175 +0,0 @@ -#!/usr/bin/env bash - -keito_require_jq() { - command -v jq >/dev/null 2>&1 -} - -keito_json_get() { - local payload="$1" - local filter="$2" - printf '%s' "$payload" | jq -r "$filter" 2>/dev/null -} - -keito_json_get_string() { - local value - value=$(keito_json_get "$1" "$2 // empty") - [ "$value" != "null" ] && printf '%s\n' "$value" -} - -keito_safe_filename() { - printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_' -} - -keito_session_id_from_payload() { - local payload="$1" - local cwd="$2" - local raw - raw=$(keito_json_get_string "$payload" '.session_id // .sessionId // .conversation_id // .conversationId // .transcript_path') - if [ -n "$raw" ]; then - printf '%s\n' "$raw" - return 0 - fi - - if command -v shasum >/dev/null 2>&1; then - printf '%s\n' "$cwd" | shasum | awk '{print "session_" $1}' - else - printf 'session_%s\n' "$(date -u +%s)" - fi -} - -keito_find_config() { - local dir="$1" - [ -n "$dir" ] || dir="$PWD" - dir=$(cd "$dir" 2>/dev/null && pwd -P) || return 1 - - local git_root="" - git_root=$(git -C "$dir" rev-parse --show-toplevel 2>/dev/null || true) - - while [ -n "$dir" ] && [ "$dir" != "/" ]; do - if [ -f "$dir/.keito/config.yml" ]; then - printf '%s\n' "$dir/.keito/config.yml" - return 0 - fi - if [ -n "$git_root" ] && [ "$dir" = "$git_root" ]; then - break - fi - dir=$(dirname "$dir") - done - - return 1 -} - -keito_yaml_unquote() { - sed -e 's/^[[:space:]]*//' \ - -e 's/[[:space:]]*$//' \ - -e 's/^"//' \ - -e 's/"$//' \ - -e "s/^'//" \ - -e "s/'$//" -} - -keito_yaml_get_fallback() { - local file="$1" - local path="$2" - local default="$3" - - local section key value - if [[ "$path" == *.* ]]; then - section=${path%%.*} - key=${path#*.} - value=$(awk -v section="$section" -v key="$key" ' - $0 ~ "^[[:space:]]*" section ":" { in_section=1; next } - in_section && $0 ~ "^[^[:space:]]" { in_section=0 } - in_section && $0 ~ "^[[:space:]]+" key ":" { - sub("^[[:space:]]+" key ":[[:space:]]*", "") - sub("[[:space:]]+#.*$", "") - print - exit - } - ' "$file") - else - value=$(awk -v key="$path" ' - $0 ~ "^" key ":" { - sub("^" key ":[[:space:]]*", "") - sub("[[:space:]]+#.*$", "") - print - exit - } - ' "$file") - fi - - if [ -n "$value" ]; then - printf '%s\n' "$value" | keito_yaml_unquote - else - printf '%s\n' "$default" - fi -} - -keito_yaml_get() { - local file="$1" - local path="$2" - local default="${3:-}" - - if command -v yq >/dev/null 2>&1; then - local value - value=$(yq -r ".$path // \"\"" "$file" 2>/dev/null || true) - if [ -n "$value" ] && [ "$value" != "null" ]; then - printf '%s\n' "$value" - return 0 - fi - fi - - keito_yaml_get_fallback "$file" "$path" "$default" -} - -keito_yaml_metadata_json() { - local file="$1" - - if command -v yq >/dev/null 2>&1; then - local json - json=$(yq -o=json '.metadata // {}' "$file" 2>/dev/null || true) - if printf '%s' "$json" | jq -e 'type == "object"' >/dev/null 2>&1; then - printf '%s\n' "$json" - return 0 - fi - fi - - local json key value - json='{}' - while IFS='=' read -r key value; do - [ -n "$key" ] || continue - json=$(printf '%s' "$json" | jq --arg key "$key" --arg value "$value" '. + {($key): $value}') - done < <(awk ' - /^metadata:/ { in_section=1; next } - in_section && /^[^[:space:]]/ { in_section=0 } - in_section && /^[[:space:]]+[A-Za-z0-9_-]+:/ { - line=$0 - sub(/^[[:space:]]+/, "", line) - split(line, parts, ":") - key=parts[1] - sub(/^[^:]+:[[:space:]]*/, "", line) - sub(/[[:space:]]+#.*$/, "", line) - gsub(/^"|"$/, "", line) - gsub(/^'\''|'\''$/, "", line) - print key "=" line - } - ' "$file") - - printf '%s\n' "$json" -} - -keito_latest_state_for_cwd() { - local cwd="$1" - local state_dir - state_dir=$(keito_state_dir) - [ -d "$state_dir" ] || return 1 - - local candidate - candidate=$(find "$state_dir" -type f -name '*.json' -print 2>/dev/null | while read -r file; do - if [ "$(jq -r '.cwd // empty' "$file" 2>/dev/null)" = "$cwd" ]; then - printf '%s\n' "$file" - fi - done | xargs ls -t 2>/dev/null | head -n 1) - - [ -n "$candidate" ] && printf '%s\n' "$candidate" -} diff --git a/skills/keito-time-track/hooks/lib/duration.sh b/skills/keito-time-track/hooks/lib/duration.sh deleted file mode 100644 index 1e121e7..0000000 --- a/skills/keito-time-track/hooks/lib/duration.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash - -keito_now_epoch() { - date -u +%s -} - -keito_now_iso() { - date -u +'%Y-%m-%dT%H:%M:%SZ' -} - -keito_git_rev() { - git -C "$1" rev-parse --short HEAD 2>/dev/null || true -} - -keito_git_branch() { - git -C "$1" branch --show-current 2>/dev/null || true -} - -keito_trim_notes() { - awk 'BEGIN { max = 1500 } { text = text $0 "\n" } END { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", text); print substr(text, 1, max) }' -} - -keito_notes_from_transcript() { - local transcript="$1" - [ -f "$transcript" ] || return 1 - - jq -r ' - select((.role // .message.role // empty) == "assistant") - | (.content // .message.content // .message.text // empty) - | if type == "array" then map(.text // empty) | join(" ") else . end - ' "$transcript" 2>/dev/null | tail -n 1 -} - -keito_extract_notes() { - local payload="$1" - local transcript="$2" - local cwd="$3" - local redact="$4" - - if [ "$redact" = "true" ]; then - printf '[redacted]\n' - return 0 - fi - - local notes - notes=$(printf '%s' "$payload" | jq -r '.last_assistant_message // .summary // .message.content // empty' 2>/dev/null | keito_trim_notes) - if [ -z "$notes" ] && [ -n "$transcript" ]; then - notes=$(keito_notes_from_transcript "$transcript" | keito_trim_notes) - fi - if [ -z "$notes" ]; then - notes="Agent coding session in $(basename "$cwd")" - fi - - printf '%s\n' "$notes" -} diff --git a/skills/keito-time-track/hooks/lib/log.sh b/skills/keito-time-track/hooks/lib/log.sh deleted file mode 100644 index 54c4863..0000000 --- a/skills/keito-time-track/hooks/lib/log.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash - -keito_skill_home() { - printf '%s\n' "${KEITO_SKILL_HOME:-$HOME/.keito/skill}" -} - -keito_state_dir() { - printf '%s\n' "$(keito_skill_home)/sessions" -} - -keito_log_file() { - printf '%s\n' "$(keito_skill_home)/skill.log" -} - -keito_rotate_log_if_needed() { - local file="$1" - [ -f "$file" ] || return 0 - - local size - size=$(wc -c < "$file" 2>/dev/null || printf '0') - if [ "${size:-0}" -gt 10485760 ]; then - mv "$file" "$file.1" 2>/dev/null || true - fi -} - -keito_log() { - local level="$1" - shift - local home log_file - home=$(keito_skill_home) - log_file=$(keito_log_file) - - mkdir -p "$home" "$(keito_state_dir)" 2>/dev/null || true - keito_rotate_log_if_needed "$log_file" - printf '%s [%s] %s\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "$level" "$*" >> "$log_file" 2>/dev/null || true -} diff --git a/skills/keito-time-track/hooks/prompt.sh b/skills/keito-time-track/hooks/prompt.sh new file mode 100755 index 0000000..968ccf6 --- /dev/null +++ b/skills/keito-time-track/hooks/prompt.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) || exit 0 +exec bash "$script_dir/dispatch.sh" --event prompt "$@" diff --git a/skills/keito-time-track/hooks/session-end.sh b/skills/keito-time-track/hooks/session-end.sh index 52eba03..586c639 100755 --- a/skills/keito-time-track/hooks/session-end.sh +++ b/skills/keito-time-track/hooks/session-end.sh @@ -1,163 +1,4 @@ #!/usr/bin/env bash -set -u - -script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) -# shellcheck source=hooks/lib/log.sh -. "$script_dir/lib/log.sh" -# shellcheck source=hooks/lib/config.sh -. "$script_dir/lib/config.sh" -# shellcheck source=hooks/lib/duration.sh -. "$script_dir/lib/duration.sh" - -payload=$(cat || true) - -if ! keito_require_jq; then - keito_log WARN "jq is not installed; skipping session end" - exit 0 -fi - -cwd=$(keito_json_get_string "$payload" '.cwd // .workspace.current_dir // .workspace_root // .repository_root') -[ -n "$cwd" ] || cwd="$PWD" -cwd=$(cd "$cwd" 2>/dev/null && pwd -P) || exit 0 - -session_id=$(keito_session_id_from_payload "$payload" "$cwd") -safe_session_id=$(keito_safe_filename "$session_id") -state_file="$(keito_state_dir)/$safe_session_id.json" -if [ ! -f "$state_file" ]; then - state_file=$(keito_latest_state_for_cwd "$cwd" 2>/dev/null || true) -fi -[ -f "$state_file" ] || exit 0 - -stored_session_id=$(jq -r '.session_id // empty' "$state_file") -[ -n "$stored_session_id" ] && session_id="$stored_session_id" - -paused=$(jq -r '.paused // false' "$state_file") -if [ "$paused" = "true" ]; then - keito_log INFO "skipped paused session session_id=$session_id" - rm -f "$state_file" - exit 0 -fi - -started_at=$(jq -r '.started_at // empty' "$state_file") -started_epoch=$(jq -r '.started_epoch // empty' "$state_file") -config_path=$(jq -r '.config_path // empty' "$state_file") -[ -f "$config_path" ] || config_path=$(keito_find_config "$cwd" 2>/dev/null || true) - -if [ ! -f "$config_path" ]; then - keito_log WARN "missing config for session session_id=$session_id cwd=$cwd" - exit 0 -fi - -enabled=$(keito_yaml_get "$config_path" "agent_tracking.enabled" "true") -if [ "$enabled" = "false" ]; then - keito_log INFO "skipped disabled config session_id=$session_id" - rm -f "$state_file" - exit 0 -fi - -now_epoch=$(keito_now_epoch) -if [ -z "$started_epoch" ] || ! [[ "$started_epoch" =~ ^[0-9]+$ ]]; then - started_epoch=$now_epoch -fi -duration_seconds=$(( now_epoch - started_epoch )) -[ "$duration_seconds" -lt 0 ] && duration_seconds=0 - -min_duration=$(keito_yaml_get "$config_path" "agent_tracking.min_duration_seconds" "60") -[[ "$min_duration" =~ ^[0-9]+$ ]] || min_duration=60 -if [ "$duration_seconds" -lt "$min_duration" ]; then - keito_log INFO "skipped short session session_id=$session_id duration=${duration_seconds}s min=${min_duration}s" - rm -f "$state_file" - exit 0 -fi - -max_duration=$(keito_yaml_get "$config_path" "agent_tracking.max_duration_seconds" "28800") -[[ "$max_duration" =~ ^[0-9]+$ ]] || max_duration=28800 -duration_capped=false -original_duration_seconds=$duration_seconds -if [ "$duration_seconds" -gt "$max_duration" ]; then - duration_seconds=$max_duration - duration_capped=true -fi - -workspace_id=$(keito_yaml_get "$config_path" "workspace_id" "") -project_id=$(keito_yaml_get "$config_path" "project_id" "") -task_id=$(keito_yaml_get "$config_path" "task_id" "") -source=$(keito_yaml_get "$config_path" "agent_tracking.source" "agent") -case "$source" in - web|cli|api|agent) ;; - *) source="agent" ;; -esac - -if [ -z "$project_id" ] || [ -z "$task_id" ]; then - keito_log WARN "missing project_id or task_id in $config_path; preserving state session_id=$session_id" - exit 0 -fi - -redact_notes=$(keito_yaml_get "$config_path" "agent_tracking.redact_notes" "false") -transcript=$(keito_json_get_string "$payload" '.transcript_path // .transcriptPath // empty') -notes=$(keito_extract_notes "$payload" "$transcript" "$cwd" "$redact_notes") -ended_at=$(keito_now_iso) -agent_id=${KEITO_AGENT_ID:-} -[ -n "$agent_id" ] || agent_id=$(keito_json_get_string "$payload" '.agent_id // .agent.id // empty') -agent_type=${KEITO_AGENT_TYPE:-} -[ -n "$agent_type" ] || agent_type=$(jq -r '.agent_type // "unknown"' "$state_file") -git_rev=$(jq -r '.git_rev // empty' "$state_file") -git_branch=$(jq -r '.git_branch // empty' "$state_file") -draft=$(keito_yaml_get "$config_path" "agent_tracking.draft" "true") -base_metadata=$(keito_yaml_metadata_json "$config_path") - -metadata=$(jq -c -n \ - --argjson base "$base_metadata" \ - --arg skill "keito-time-track" \ - --arg session_id "$session_id" \ - --arg agent_id "$agent_id" \ - --arg agent_type "$agent_type" \ - --arg git_rev "$git_rev" \ - --arg git_branch "$git_branch" \ - --arg cwd "$cwd" \ - --arg config_path "$config_path" \ - --argjson duration_seconds "$duration_seconds" \ - --argjson original_duration_seconds "$original_duration_seconds" \ - --argjson duration_capped "$duration_capped" \ - --argjson draft "$draft" \ - '$base + { - skill: $skill, - session_id: $session_id, - agent_id: $agent_id, - agent_type: $agent_type, - git_rev: $git_rev, - git_branch: $git_branch, - cwd: $cwd, - config_path: $config_path, - duration_seconds: $duration_seconds, - original_duration_seconds: $original_duration_seconds, - duration_capped: $duration_capped, - draft: $draft - }') - -keito_cmd=${KEITO_CLI_BIN:-keito} -cmd=("$keito_cmd" --json) -if [ -n "$workspace_id" ]; then - cmd+=(--workspace "$workspace_id") -fi -cmd+=(time session-record) -cmd+=(--project "$project_id") -cmd+=(--task "$task_id") -cmd+=(--session-id "$session_id") -cmd+=(--duration-seconds "$duration_seconds") -if [ -n "$started_at" ]; then - cmd+=(--started-at "$started_at") -fi -cmd+=(--ended-at "$ended_at") -cmd+=(--source "$source") -cmd+=(--metadata "$metadata") -cmd+=(--notes "$notes") - -if "${cmd[@]}" >> "$(keito_log_file)" 2>&1; then - keito_log INFO "logged session session_id=$session_id duration=${duration_seconds}s source=$source" - rm -f "$state_file" -else - keito_log ERROR "failed to log session session_id=$session_id; state preserved at $state_file" -fi - -exit 0 +# Legacy path: older Stop registrations invoke session-end.sh. +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) || exit 0 +exec bash "$script_dir/dispatch.sh" --event stop "$@" diff --git a/skills/keito-time-track/hooks/session-finalize.sh b/skills/keito-time-track/hooks/session-finalize.sh new file mode 100755 index 0000000..2805e62 --- /dev/null +++ b/skills/keito-time-track/hooks/session-finalize.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) || exit 0 +exec bash "$script_dir/dispatch.sh" --event session-end "$@" diff --git a/skills/keito-time-track/hooks/session-start.sh b/skills/keito-time-track/hooks/session-start.sh index 90232ef..fa6e944 100755 --- a/skills/keito-time-track/hooks/session-start.sh +++ b/skills/keito-time-track/hooks/session-start.sh @@ -1,67 +1,3 @@ #!/usr/bin/env bash -set -u - -script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) -# shellcheck source=hooks/lib/log.sh -. "$script_dir/lib/log.sh" -# shellcheck source=hooks/lib/config.sh -. "$script_dir/lib/config.sh" -# shellcheck source=hooks/lib/duration.sh -. "$script_dir/lib/duration.sh" - -payload=$(cat || true) - -if ! keito_require_jq; then - keito_log WARN "jq is not installed; skipping session start" - exit 0 -fi - -cwd=$(keito_json_get_string "$payload" '.cwd // .workspace.current_dir // .workspace_root // .repository_root') -[ -n "$cwd" ] || cwd="$PWD" -cwd=$(cd "$cwd" 2>/dev/null && pwd -P) || exit 0 - -config_path=$(keito_find_config "$cwd" 2>/dev/null || true) -[ -n "$config_path" ] || exit 0 - -enabled=$(keito_yaml_get "$config_path" "agent_tracking.enabled" "true") -if [ "$enabled" = "false" ]; then - exit 0 -fi - -session_id=$(keito_session_id_from_payload "$payload" "$cwd") -safe_session_id=$(keito_safe_filename "$session_id") -state_dir=$(keito_state_dir) -state_file="$state_dir/$safe_session_id.json" -mkdir -p "$state_dir" || exit 0 - -started_at=$(keito_now_iso) -started_epoch=$(keito_now_epoch) -agent_type=${KEITO_AGENT_TYPE:-} -if [ -z "$agent_type" ]; then - agent_type=$(keito_json_get_string "$payload" '.agent_type // .agent.name // .agent // empty') -fi -[ -n "$agent_type" ] || agent_type="unknown" - -jq -n \ - --arg session_id "$session_id" \ - --arg started_at "$started_at" \ - --argjson started_epoch "$started_epoch" \ - --arg cwd "$cwd" \ - --arg config_path "$config_path" \ - --arg git_rev "$(keito_git_rev "$cwd")" \ - --arg git_branch "$(keito_git_branch "$cwd")" \ - --arg agent_type "$agent_type" \ - '{ - session_id: $session_id, - started_at: $started_at, - started_epoch: $started_epoch, - cwd: $cwd, - config_path: $config_path, - git_rev: $git_rev, - git_branch: $git_branch, - agent_type: $agent_type, - paused: false - }' > "$state_file.tmp" 2>/dev/null && mv "$state_file.tmp" "$state_file" - -keito_log INFO "started session session_id=$session_id cwd=$cwd config=$config_path" -exit 0 +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) || exit 0 +exec bash "$script_dir/dispatch.sh" --event session-start "$@" diff --git a/skills/keito-time-track/hooks/stop.sh b/skills/keito-time-track/hooks/stop.sh new file mode 100755 index 0000000..74bd833 --- /dev/null +++ b/skills/keito-time-track/hooks/stop.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) || exit 0 +exec bash "$script_dir/dispatch.sh" --event stop "$@" diff --git a/skills/keito-time-track/installers/install-claude-code.sh b/skills/keito-time-track/installers/install-claude-code.sh index e9e214b..4548a6f 100755 --- a/skills/keito-time-track/installers/install-claude-code.sh +++ b/skills/keito-time-track/installers/install-claude-code.sh @@ -1,71 +1,4 @@ #!/usr/bin/env bash +# Native CLI owns installation, preservation and recovery. set -euo pipefail - -if ! command -v jq >/dev/null 2>&1; then - echo "jq is required to merge Claude Code hook settings." >&2 - exit 1 -fi - -source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) -dest="$HOME/.claude/skills/keito-time-track" -settings="$HOME/.claude/settings.json" -keito_bin=${KEITO_CLI_BIN:-} -[ -n "$keito_bin" ] || keito_bin=$(command -v keito 2>/dev/null || true) - -shell_quote() { - printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")" -} - -mkdir -p "$(dirname "$dest")" "$(dirname "$settings")" -dest_dir=$(cd "$(dirname "$dest")" && pwd -P) -dest_physical="$dest_dir/$(basename "$dest")" -if [ "$source_dir" != "$dest_physical" ]; then - rm -rf "$dest" - cp -R "$source_dir" "$dest" -fi - -[ -f "$settings" ] || printf '{}\n' > "$settings" -keito_env="" -if [ -n "$keito_bin" ]; then - keito_env="KEITO_CLI_BIN=$(shell_quote "$keito_bin") " -fi -start_cmd="${keito_env}KEITO_AGENT_TYPE=claude-code $(shell_quote "$dest/hooks/session-start.sh")" -end_cmd="${keito_env}KEITO_AGENT_TYPE=claude-code $(shell_quote "$dest/hooks/session-end.sh")" - -jq \ - --arg start "$start_cmd" \ - --arg end "$end_cmd" \ - --arg start_script "$dest/hooks/session-start.sh" \ - --arg end_script "$dest/hooks/session-end.sh" \ - ' - .hooks = (.hooks // {}) | - .hooks.SessionStart = ( - (.hooks.SessionStart // []) - | map(select( - (.hooks // [] | map(.command // "") | any(. == $start or contains($start_script))) - | not - )) - + [{ - matcher: "*", - hooks: [{ type: "command", command: $start }] - }] - ) | - .hooks.Stop = ( - (.hooks.Stop // []) - | map(select( - (.hooks // [] | map(.command // "") | any(. == $end or contains($end_script))) - | not - )) - + [{ - hooks: [{ type: "command", command: $end, timeout: 30 }] - }] - ) - ' "$settings" > "$settings.tmp" -mv "$settings.tmp" "$settings" - -chmod +x "$dest/hooks/session-start.sh" "$dest/hooks/session-end.sh" "$dest/scripts/"*.sh - -echo "Installed Keito Time Track skill for Claude Code:" -echo " $dest" -echo "Updated hooks:" -echo " $settings" +exec "${KEITO_CLI_BIN:-keito}" skill install --agent claude-code "$@" diff --git a/skills/keito-time-track/installers/install-codex.sh b/skills/keito-time-track/installers/install-codex.sh index 4ee08d0..2ccfad8 100755 --- a/skills/keito-time-track/installers/install-codex.sh +++ b/skills/keito-time-track/installers/install-codex.sh @@ -1,71 +1,4 @@ #!/usr/bin/env bash +# Native CLI owns installation, preservation and recovery. set -euo pipefail - -if ! command -v jq >/dev/null 2>&1; then - echo "jq is required to merge Codex hook settings." >&2 - exit 1 -fi - -source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) -dest="$HOME/.codex/skills/keito-time-track" -hooks="$HOME/.codex/hooks.json" -keito_bin=${KEITO_CLI_BIN:-} -[ -n "$keito_bin" ] || keito_bin=$(command -v keito 2>/dev/null || true) - -shell_quote() { - printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")" -} - -mkdir -p "$(dirname "$dest")" "$(dirname "$hooks")" -dest_dir=$(cd "$(dirname "$dest")" && pwd -P) -dest_physical="$dest_dir/$(basename "$dest")" -if [ "$source_dir" != "$dest_physical" ]; then - rm -rf "$dest" - cp -R "$source_dir" "$dest" -fi - -[ -f "$hooks" ] || printf '{}\n' > "$hooks" -keito_env="" -if [ -n "$keito_bin" ]; then - keito_env="KEITO_CLI_BIN=$(shell_quote "$keito_bin") " -fi -start_cmd="${keito_env}KEITO_AGENT_TYPE=codex $(shell_quote "$dest/hooks/session-start.sh")" -end_cmd="${keito_env}KEITO_AGENT_TYPE=codex $(shell_quote "$dest/hooks/session-end.sh")" - -jq \ - --arg start "$start_cmd" \ - --arg end "$end_cmd" \ - --arg start_script "$dest/hooks/session-start.sh" \ - --arg end_script "$dest/hooks/session-end.sh" \ - ' - .hooks = (.hooks // {}) | - .hooks.SessionStart = ( - (.hooks.SessionStart // []) - | map(select( - (.hooks // [] | map(.command // "") | any(. == $start or contains($start_script))) - | not - )) - + [{ - matcher: "startup|resume", - hooks: [{ type: "command", command: $start }] - }] - ) | - .hooks.Stop = ( - (.hooks.Stop // []) - | map(select( - (.hooks // [] | map(.command // "") | any(. == $end or contains($end_script))) - | not - )) - + [{ - hooks: [{ type: "command", command: $end, timeout: 30 }] - }] - ) - ' "$hooks" > "$hooks.tmp" -mv "$hooks.tmp" "$hooks" - -chmod +x "$dest/hooks/session-start.sh" "$dest/hooks/session-end.sh" "$dest/scripts/"*.sh - -echo "Installed Keito Time Track skill for Codex:" -echo " $dest" -echo "Updated hooks:" -echo " $hooks" +exec "${KEITO_CLI_BIN:-keito}" skill install --agent codex "$@" diff --git a/skills/keito-time-track/installers/install.sh b/skills/keito-time-track/installers/install.sh new file mode 100755 index 0000000..88b1934 --- /dev/null +++ b/skills/keito-time-track/installers/install.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# Native CLI owns installation, preservation and recovery. +set -euo pipefail +exec "${KEITO_CLI_BIN:-keito}" skill install "$@" diff --git a/skills/keito-time-track/installers/uninstall.sh b/skills/keito-time-track/installers/uninstall.sh new file mode 100755 index 0000000..eec4490 --- /dev/null +++ b/skills/keito-time-track/installers/uninstall.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# Native CLI owns installation, preservation and recovery. +set -euo pipefail +exec "${KEITO_CLI_BIN:-keito}" skill uninstall "$@" diff --git a/skills/keito-time-track/scripts/disable.sh b/skills/keito-time-track/scripts/disable.sh index 12f3135..0318f03 100755 --- a/skills/keito-time-track/scripts/disable.sh +++ b/skills/keito-time-track/scripts/disable.sh @@ -1,41 +1,3 @@ #!/usr/bin/env bash set -euo pipefail - -script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) -# shellcheck disable=SC1091 -# shellcheck source=../hooks/lib/log.sh -. "$script_dir/../hooks/lib/log.sh" -# shellcheck disable=SC1091 -# shellcheck source=../hooks/lib/config.sh -. "$script_dir/../hooks/lib/config.sh" - -cwd=$(pwd -P) -config_path=$(keito_find_config "$cwd" 2>/dev/null || true) - -if [ -z "$config_path" ] || [ ! -f "$config_path" ]; then - echo "Keito tracking is already untracked for $cwd." - exit 0 -fi - -echo "Keito tracking config found:" -echo " $config_path" -printf 'Disable tracking for this repo by moving this config aside? [y/N] ' -read -r answer - -case "$answer" in - y|Y|yes|YES) ;; - *) - echo "Disable cancelled; no changes written." - exit 0 - ;; -esac - -disabled_path="$config_path.disabled" -if [ -e "$disabled_path" ]; then - disabled_path="$config_path.disabled.$(date -u +%Y%m%dT%H%M%SZ)" -fi - -mv "$config_path" "$disabled_path" -keito_log INFO "disabled repo tracking config=$config_path disabled_path=$disabled_path" -echo "Disabled Keito tracking for this repo." -echo "Moved config to: $disabled_path" +exec "${KEITO_CLI_BIN:-keito}" capture disable --repo "$@" diff --git a/skills/keito-time-track/scripts/install-cli.sh b/skills/keito-time-track/scripts/install-cli.sh index 78390ce..4294a6f 100755 --- a/skills/keito-time-track/scripts/install-cli.sh +++ b/skills/keito-time-track/scripts/install-cli.sh @@ -2,12 +2,17 @@ set -euo pipefail if command -v keito >/dev/null 2>&1; then - echo "Keito CLI is already installed: $(command -v keito)" - exit 0 + if keito skill runtime --json >/dev/null 2>&1; then + echo "Keito native runtime pair is already installed: $(command -v keito)" + exit 0 + fi + echo "The existing Keito installation is unqualified for capture; install the official paired release." >&2 + exit 1 fi if command -v brew >/dev/null 2>&1; then brew install osodevops/tap/keito + keito skill runtime --json >/dev/null exit 0 fi @@ -39,21 +44,30 @@ cleanup() { } trap cleanup EXIT -url="https://github.com/osodevops/keito-cli/releases/latest/download/$asset" +base="https://github.com/osodevops/keito-cli/releases/latest/download" archive="$tmp_dir/$asset" -curl -fsSL "$url" -o "$archive" +curl -fsSL "$base/$asset" -o "$archive" +curl -fsSL "$base/SHA256SUMS" -o "$tmp_dir/SHA256SUMS" +expected=$(awk -v name="$asset" '$2 == name { print $1 }' "$tmp_dir/SHA256SUMS") +[[ "$expected" =~ ^[0-9a-f]{64}$ ]] || { echo "Release checksum missing or ambiguous." >&2; exit 1; } +if command -v shasum >/dev/null 2>&1; then actual=$(shasum -a 256 "$archive" | awk '{print $1}'); else actual=$(sha256sum "$archive" | awk '{print $1}'); fi +[ "$actual" = "$expected" ] || { echo "Release archive checksum mismatch." >&2; exit 1; } +# Accept exactly the expected flat release layout, before extracting anything. +entries=$(tar -tzf "$archive") +[ "$(printf '%s\n' "$entries" | LC_ALL=C sort)" = "$(printf '%s\n' capture-runtime-manifest.json keito keito-capture-guard | LC_ALL=C sort)" ] || { echo "Unexpected release archive layout." >&2; exit 1; } tar -xzf "$archive" -C "$tmp_dir" - -keito_bin=$(find "$tmp_dir" -type f -name keito | head -n 1) -if [ -z "$keito_bin" ]; then - echo "Downloaded Keito CLI archive did not contain a keito binary." >&2 - exit 1 -fi - +for name in keito keito-capture-guard capture-runtime-manifest.json; do + [ -f "$tmp_dir/$name" ] && [ ! -L "$tmp_dir/$name" ] || exit 1 +done +"$tmp_dir/keito" skill runtime --json >/dev/null install_dir="${KEITO_INSTALL_DIR:-$HOME/.local/bin}" mkdir -p "$install_dir" -cp "$keito_bin" "$install_dir/keito" -chmod +x "$install_dir/keito" +for name in keito keito-capture-guard capture-runtime-manifest.json; do + [ ! -L "$install_dir/$name" ] || { echo "Refusing existing symlink destination." >&2; exit 1; } + install -m 644 "$tmp_dir/$name" "$install_dir/$name" +done +chmod 755 "$install_dir/keito" "$install_dir/keito-capture-guard" +"$install_dir/keito" skill runtime --json >/dev/null echo "Installed Keito CLI to $install_dir/keito" case ":$PATH:" in diff --git a/skills/keito-time-track/scripts/pause-resume.sh b/skills/keito-time-track/scripts/pause-resume.sh index 61fc9aa..519e3b1 100755 --- a/skills/keito-time-track/scripts/pause-resume.sh +++ b/skills/keito-time-track/scripts/pause-resume.sh @@ -1,36 +1,5 @@ #!/usr/bin/env bash set -euo pipefail - -usage() { - echo "Usage: pause-resume.sh pause|resume" >&2 -} - -action="${1:-}" -case "$action" in - pause|resume) ;; - *) usage; exit 1 ;; -esac - -script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) -# shellcheck disable=SC1091 -# shellcheck source=../hooks/lib/log.sh -. "$script_dir/../hooks/lib/log.sh" -# shellcheck disable=SC1091 -# shellcheck source=../hooks/lib/config.sh -. "$script_dir/../hooks/lib/config.sh" - -cwd=$(pwd -P) -state_file=$(keito_latest_state_for_cwd "$cwd" 2>/dev/null || true) -if [ -z "$state_file" ] || [ ! -f "$state_file" ]; then - echo "No active Keito-tracked session state found for $cwd." - exit 1 -fi - -paused=false -[ "$action" = "pause" ] && paused=true - -jq --argjson paused "$paused" '.paused = $paused' "$state_file" > "$state_file.tmp" -mv "$state_file.tmp" "$state_file" - -keito_log INFO "$action session state_file=$state_file" -echo "Keito tracking ${action}d for this session." +case "${1:-}" in pause|resume) action=$1 ;; *) echo 'Usage: pause-resume.sh pause|resume' >&2; exit 1 ;; esac +shift +exec "${KEITO_CLI_BIN:-keito}" capture "$action" --repo "$@" diff --git a/skills/keito-time-track/scripts/setup-wizard.sh b/skills/keito-time-track/scripts/setup-wizard.sh index 9816529..f8c41cf 100755 --- a/skills/keito-time-track/scripts/setup-wizard.sh +++ b/skills/keito-time-track/scripts/setup-wizard.sh @@ -1,212 +1,80 @@ #!/usr/bin/env bash +# Selection is a user workflow; consent and mapping validation belong to the CLI. set -euo pipefail - -repo_root=$(pwd -P) -config_path="$repo_root/.keito/config.yml" keito_cmd=${KEITO_CLI_BIN:-keito} - -json_field() { - local json=$1 - local filter=$2 - local label=$3 - local value - - if ! value=$(printf '%s' "$json" | jq -er "$filter // empty"); then - echo "Keito CLI did not return $label." >&2 - exit 1 +agents=() +worker=() +while [ "$#" -gt 0 ]; do + if [ "$1" = '--install-worker' ]; then + worker=(--install-worker) + shift + continue fi - - printf '%s\n' "$value" -} - -if ! command -v jq >/dev/null 2>&1; then - echo "jq is required. Install jq and rerun /track-time-keito." >&2 - exit 1 -fi - -if [ -n "${KEITO_CLI_BIN:-}" ]; then - if [ ! -x "$keito_cmd" ]; then - echo "Keito CLI path is not executable: $keito_cmd" >&2 + if [ "$1" != '--agent' ] || [ "$#" -lt 2 ]; then + echo 'Usage: setup-wizard.sh --agent claude-code|codex [--agent claude-code|codex] [--install-worker]' >&2 exit 1 fi -elif ! command -v "$keito_cmd" >/dev/null 2>&1; then - echo "Keito CLI is required. Install it, then run: keito auth login" >&2 - exit 1 -fi - -auth_json=$("$keito_cmd" --json auth status 2>/dev/null || printf '{"authenticated":false}') -authenticated=$(printf '%s' "$auth_json" | jq -r '.authenticated // false') -api_key_valid=$(printf '%s' "$auth_json" | jq -r '.api_key_valid // true') -if [ "$authenticated" != "true" ] || [ "$api_key_valid" != "true" ]; then - echo "Keito CLI is not authenticated. Run: keito auth login" >&2 + case "$2" in claude-code|codex) agents+=(--agent "$2") ;; *) echo 'Select a supported adapter explicitly.' >&2; exit 1 ;; esac + shift 2 +done +if [ "${#agents[@]}" -eq 0 ]; then + echo 'Select the adapters explicitly: setup-wizard.sh --agent claude-code --agent codex' >&2 exit 1 fi - -workspace_id=$(printf '%s' "$auth_json" | jq -r '.account_id // .workspace_id // empty') - -echo "Keito time tracking setup for $(basename "$repo_root")" -echo - -clients_json=$("$keito_cmd" --json clients list) -client_count=$(printf '%s' "$clients_json" | jq 'length') - -echo "Select a client:" -if [ "$client_count" -gt 0 ]; then - printf '%s' "$clients_json" | jq -r 'to_entries[] | "\(.key + 1)) \(.value.name) - \(.value.id)"' -fi -printf '%s) + Create new client\n' "$((client_count + 1))" -printf 'Client number: ' -read -r client_choice -if ! [[ "$client_choice" =~ ^[0-9]+$ ]] || [ "$client_choice" -lt 1 ] || [ "$client_choice" -gt $((client_count + 1)) ]; then - echo "Invalid client selection." >&2 +command -v jq >/dev/null 2>&1 || { echo 'jq is required for the setup picker.' >&2; exit 1; } +"$keito_cmd" capture --help >/dev/null 2>&1 || { echo 'Update Keito CLI to a version with capture support.' >&2; exit 1; } +auth_json=$("$keito_cmd" --json auth status) +if ! jq -e '.authenticated == true and .api_key_valid == true' >/dev/null <<< "$auth_json"; then + echo 'Verify authentication with keito auth login before setting up capture.' >&2 exit 1 fi - -if [ "$client_choice" -eq $((client_count + 1)) ]; then - printf 'Client name: ' - read -r client_name - if [ -z "$client_name" ]; then - echo "Client name is required." >&2 - exit 1 +repo_root=$(git rev-parse --show-toplevel) || { echo "Run setup from the intended Git repository." >&2; exit 1; } +repo_root=$(cd "$repo_root" && pwd -P) +workspace_id=$(jq -er '.account_id // .workspace_id // empty' <<< "$auth_json") +select_id() { + local data=$1 label=$2 choice count + count=$(jq -er 'if type == "array" then length else error("Expected a list") end' <<< "$data") + if [ "$count" -eq 0 ]; then + echo "No available $label. Add an existing authorized $label in Keito, then retry." >&2 + return 1 fi - client_json=$("$keito_cmd" --json clients create "$client_name") - client_id=$(json_field "$client_json" '.id' 'created client id') - client_name=$(json_field "$client_json" '.name' 'created client name') -else - client_index=$((client_choice - 1)) - client_id=$(json_field "$clients_json" ".[$client_index].id" 'selected client id') - client_name=$(json_field "$clients_json" ".[$client_index].name" 'selected client name') -fi - -echo -projects_json=$("$keito_cmd" --json projects list --client "$client_id") -project_count=$(printf '%s' "$projects_json" | jq 'length') - -echo "Select a project for $client_name:" -if [ "$project_count" -gt 0 ]; then - printf '%s' "$projects_json" | jq -r ' - to_entries[] - | "\(.key + 1)) \(.value.name) \((.value.code // "") | if . == "" then "" else "[" + . + "]" end) - \(.value.id)" - ' -fi -printf '%s) + Create new project\n' "$((project_count + 1))" -printf 'Project number: ' -read -r project_choice -if ! [[ "$project_choice" =~ ^[0-9]+$ ]] || [ "$project_choice" -lt 1 ] || [ "$project_choice" -gt $((project_count + 1)) ]; then - echo "Invalid project selection." >&2 - exit 1 -fi - -if [ "$project_choice" -eq $((project_count + 1)) ]; then - printf 'Project name [%s]: ' "$(basename "$repo_root")" - read -r project_name - [ -n "$project_name" ] || project_name=$(basename "$repo_root") - project_json=$("$keito_cmd" --json projects create "$project_name" --client "$client_id") - project_id=$(json_field "$project_json" '.id' 'created project id') - project_name=$(json_field "$project_json" '.name' 'created project name') + echo "Select an existing $label:" >&2 + jq -r 'to_entries[] | "\(.key + 1)) \(.value.name) - \(.value.id)"' <<< "$data" >&2 + printf '%s number: ' "$label" >&2 + read -r choice + [[ "$choice" =~ ^[0-9]{1,6}$ ]] || { echo 'Invalid selection.' >&2; return 1; } + choice=$((10#$choice)) + if [ "$choice" -lt 1 ] || [ "$choice" -gt "$count" ]; then + echo 'Invalid selection.' >&2 + return 1 + fi + jq -er --argjson index "$((choice - 1))" '.[$index].id | select(type == "string" and length > 0)' <<< "$data" +} +clients=$("$keito_cmd" --json --workspace "$workspace_id" clients list) +client_id=$(select_id "$clients" client) +projects=$("$keito_cmd" --json --workspace "$workspace_id" projects list --client "$client_id") +project_id=$(select_id "$projects" project) +tasks=$("$keito_cmd" --json --workspace "$workspace_id" projects tasks "$project_id") +task_id=$(select_id "$tasks" task) +echo "Review mapping: workspace $workspace_id; client $client_id; project $project_id; task $task_id." +echo 'Capture sends allowlisted identities and observed interval metadata. Numeric usage is unavailable in this candidate.' +echo 'Prompts, responses, transcripts, code, full paths and branch names are not uploaded.' +echo 'Activity remains pending review and nonbillable. Existing repository config is only a mapping hint.' +if [ "${#worker[@]}" -gt 0 ]; then + echo 'This setup also requests a local background uploader service for this user.' else - project_index=$((project_choice - 1)) - project_id=$(json_field "$projects_json" ".[$project_index].id" 'selected project id') - project_name=$(json_field "$projects_json" ".[$project_index].name" 'selected project name') + echo 'This setup approves local queuing only; automatic delivery requires explicit --install-worker setup.' fi - -tasks_json=$("$keito_cmd" --json projects tasks) -task_count=$(printf '%s' "$tasks_json" | jq 'length') -if [ "$task_count" -eq 0 ]; then - echo "No Keito tasks were returned. Add a default task in Keito, then rerun this wizard." >&2 - exit 1 -fi - -echo -echo "Select a task:" -printf '%s' "$tasks_json" | jq -r 'to_entries[] | "\(.key + 1)) \(.value.name) - \(.value.id)"' -default_task=$(printf '%s' "$tasks_json" | jq -r ' - to_entries[] - | select((.value.name | ascii_downcase) == "development") - | .key + 1 -' | head -n 1) -[ -n "$default_task" ] || default_task=1 -printf 'Task number [%s]: ' "$default_task" -read -r task_choice -[ -n "$task_choice" ] || task_choice=$default_task -if ! [[ "$task_choice" =~ ^[0-9]+$ ]] || [ "$task_choice" -lt 1 ] || [ "$task_choice" -gt "$task_count" ]; then - echo "Invalid task selection." >&2 - exit 1 +if [ -e "$repo_root/.keito/config.yml" ] || [ -L "$repo_root/.keito/config.yml" ]; then + echo 'An existing mapping hint will be replaced for setup; failure restores it. Inspect status after interruption.' fi -task_index=$((task_choice - 1)) -task_id=$(json_field "$tasks_json" ".[$task_index].id" 'selected task id') -task_name=$(json_field "$tasks_json" ".[$task_index].name" 'selected task name') -client_name_yaml=$(jq -Rn --arg value "$client_name" '$value') -project_name_yaml=$(jq -Rn --arg value "$project_name" '$value') -task_name_yaml=$(jq -Rn --arg value "$task_name" '$value') - -echo -printf 'Enable agent time tracking for this repo? [Y/n] ' -read -r enabled_answer -enabled_answer=${enabled_answer:-Y} -case "$enabled_answer" in - y|Y|yes|YES) enabled=true ;; - *) enabled=false ;; -esac - -echo -if [ -f "$config_path" ]; then - echo "Existing Keito repo config will be replaced:" - echo " $config_path" - echo +printf 'Approve this repository mapping and metadata-only capture on this device? [y/N] ' +read -r confirm +case "$confirm" in y|Y|yes|YES) ;; *) echo 'Setup cancelled; no mapping approved.'; exit 0 ;; esac +if [ "${#worker[@]}" -gt 0 ]; then + agents+=(--install-worker) fi -echo "Review this repo-specific Keito config:" -echo " Path: $config_path" -echo " Workspace: ${workspace_id:-default}" -echo " Client: $client_name ($client_id)" -echo " Project: $project_name ($project_id)" -echo " Task: $task_name ($task_id)" -echo " Source: agent" -echo " Draft metadata: true" -echo " Min duration: 60s" -echo " Max duration: 28800s" -printf 'Write this config for this repo only? [y/N] ' -read -r confirm_answer -case "$confirm_answer" in - y|Y|yes|YES) ;; - *) - echo "Setup cancelled; no changes written." - exit 0 - ;; -esac - -mkdir -p "$repo_root/.keito" -config_tmp=$(mktemp "$repo_root/.keito/config.yml.tmp.XXXXXX") -cleanup_config_tmp() { - rm -f "$config_tmp" -} -trap cleanup_config_tmp EXIT - -cat > "$config_tmp" </dev/null || true) -keito_cmd=${KEITO_CLI_BIN:-keito} - -if [ -z "$config_path" ]; then - echo "Keito tracking: untracked" - echo "No .keito/config.yml found at or above $cwd" - exit 0 -fi - -echo "Keito tracking: configured" -echo "Current directory: $cwd" -echo "Config: $config_path" -workspace_id=$(keito_yaml_get "$config_path" "workspace_id" "") -client_id=$(keito_yaml_get "$config_path" "client_id" "") -client_name=$(keito_yaml_get "$config_path" "client_name" "$client_id") -project_id=$(keito_yaml_get "$config_path" "project_id" "") -project_name=$(keito_yaml_get "$config_path" "project_name" "$project_id") -task_id=$(keito_yaml_get "$config_path" "task_id" "") -task_name=$(keito_yaml_get "$config_path" "task_name" "$task_id") -echo "Workspace: ${workspace_id:-default}" -echo "Client: $client_name ($client_id)" -echo "Project: $project_name ($project_id)" -echo "Task: $task_name ($task_id)" -echo "Enabled: $(keito_yaml_get "$config_path" "agent_tracking.enabled" "true")" -echo "Source: $(keito_yaml_get "$config_path" "agent_tracking.source" "agent")" -echo "Draft metadata: $(keito_yaml_get "$config_path" "agent_tracking.draft" "true")" -echo "Min duration: $(keito_yaml_get "$config_path" "agent_tracking.min_duration_seconds" "60")s" -echo "Max duration: $(keito_yaml_get "$config_path" "agent_tracking.max_duration_seconds" "28800")s" - -state_file=$(keito_latest_state_for_cwd "$cwd" 2>/dev/null || true) -if [ -n "$state_file" ] && [ -f "$state_file" ]; then - started_epoch=$(jq -r '.started_epoch // empty' "$state_file") - session_id=$(jq -r '.session_id // empty' "$state_file") - paused=$(jq -r '.paused // false' "$state_file") - now=$(date -u +%s) - elapsed=0 - if [[ "$started_epoch" =~ ^[0-9]+$ ]]; then - elapsed=$((now - started_epoch)) - fi - echo "Current session: $session_id (${elapsed}s elapsed, paused=$paused)" -else - echo "Current session: none recorded" -fi - -last_error=$(grep ' \[ERROR\] ' "$(keito_log_file)" 2>/dev/null | tail -n 1 || true) -if [ -n "$last_error" ]; then - echo "Last hook error: $last_error" -else - echo "Last hook error: none" -fi - -if [ -n "${KEITO_CLI_BIN:-}" ] || command -v "$keito_cmd" >/dev/null 2>&1; then - echo - echo "Today's agent entries:" - "$keito_cmd" --json time list --today --source agent --limit 20 2>/dev/null || echo "Unable to query Keito CLI." -fi +exec "${KEITO_CLI_BIN:-keito}" capture status "$@" diff --git a/src/adapter_files.rs b/src/adapter_files.rs new file mode 100644 index 0000000..3a4de13 --- /dev/null +++ b/src/adapter_files.rs @@ -0,0 +1,1034 @@ +//! Descriptor-relative, no-follow filesystem operations for adapter publication. +//! Errors intentionally omit local paths and file contents. +#![cfg(unix)] +use crate::error::AppError; +use sha2::{Digest, Sha256}; +use std::ffi::{CStr, CString, OsString}; +use std::fs::{File, Metadata}; +use std::io::{Read, Write}; +use std::os::fd::{AsRawFd, FromRawFd}; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +pub(crate) fn failure() -> AppError { + AppError::Config("Local adapter files need review; inspect capture status and retained recovery metadata before retrying.".into()) +} +pub(crate) fn conflict() -> AppError { + AppError::Conflict("An external edit was preserved. Inspect capture status and retained recovery metadata before retrying.".into()) +} +pub(crate) fn digest(bytes: impl AsRef<[u8]>) -> String { + Sha256::digest(bytes.as_ref()) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} +pub(crate) fn hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} +pub(crate) fn identifier(value: &str, limit: usize) -> bool { + !value.is_empty() + && value.len() <= limit + && value.as_bytes()[0].is_ascii_alphanumeric() + && value + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"_.:-".contains(&c)) + && !value.contains("..") +} +fn name(value: &str) -> Result { + if value.is_empty() || value == "." || value == ".." || value.contains('/') { + return Err(failure()); + } + CString::new(value).map_err(|_| failure()) +} +pub(crate) fn nonce() -> Result { + let mut bytes = [0u8; 32]; + File::open("/dev/urandom") + .and_then(|mut f| f.read_exact(&mut bytes)) + .map_err(|_| failure())?; + Ok(digest(bytes)) +} +#[derive(Clone)] +pub(crate) struct Dir { + file: Arc, + pub(crate) path: PathBuf, + parent: Option<(Box, String)>, +} +impl Dir { + pub(crate) fn anchor(path: &Path) -> Result { + let path = path.canonicalize().map_err(|_| failure())?; + let c = CString::new(path.as_os_str().as_bytes()).map_err(|_| failure())?; + // SAFETY: c is NUL terminated; returned descriptor is uniquely owned. + let fd = unsafe { + libc::open( + c.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(failure()); + } + let result = Self { + file: Arc::new(unsafe { File::from_raw_fd(fd) }), + path, + parent: None, + }; + result.check_owner()?; + Ok(result) + } + fn check_owner(&self) -> Result<(), AppError> { + let m = self.file.metadata().map_err(|_| failure())?; + if !m.is_dir() || m.uid() != unsafe { libc::geteuid() } { + return Err(failure()); + } + Ok(()) + } + pub(crate) fn verify(&self) -> Result<(), AppError> { + self.check_owner()?; + if let Some((parent, child)) = &self.parent { + parent.verify()?; + let expected = self.file.metadata().map_err(|_| failure())?; + let child = name(child)?; + let mut actual = std::mem::MaybeUninit::::uninit(); + // The parent and expected child are already held by descriptors. + // Inspect the current entry without following links or opening a + // disposable descriptor just to stat it. Every ancestor remains + // checked on every call; this is still a snapshot, not a path lock. + if unsafe { + libc::fstatat( + parent.file.as_raw_fd(), + child.as_ptr(), + actual.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { + return Err(failure()); + } + // SAFETY: successful fstatat initialized the complete stat value. + let actual = unsafe { actual.assume_init() }; + if actual.st_mode & libc::S_IFMT != libc::S_IFDIR + || actual.st_uid != unsafe { libc::geteuid() } + { + return Err(failure()); + } + // stat field widths differ between supported Unix platforms. + #[allow(clippy::unnecessary_cast)] + let same_identity = + expected.dev() == actual.st_dev as u64 && expected.ino() == actual.st_ino as u64; + if !same_identity { + return Err(conflict()); + } + } else { + let m = std::fs::symlink_metadata(&self.path).map_err(|_| failure())?; + let own = self.file.metadata().map_err(|_| failure())?; + if !m.is_dir() || m.dev() != own.dev() || m.ino() != own.ino() { + return Err(conflict()); + } + } + Ok(()) + } + fn open_directory(&self, child: &str) -> Result { + #[cfg(test)] + directory_verification_tests::directory_opened(); + let c = name(child)?; + let fd = unsafe { + libc::openat( + self.file.as_raw_fd(), + c.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(failure()); + } + let dir = Self { + file: Arc::new(unsafe { File::from_raw_fd(fd) }), + path: self.path.join(child), + parent: Some((Box::new(self.clone()), child.into())), + }; + dir.check_owner()?; + Ok(dir) + } + pub(crate) fn child(&self, child: &str, create: bool) -> Result { + self.verify()?; + let c = name(child)?; + if create + && unsafe { libc::mkdirat(self.file.as_raw_fd(), c.as_ptr(), 0o700) } != 0 + && std::io::Error::last_os_error().kind() != std::io::ErrorKind::AlreadyExists + { + return Err(failure()); + } + let result = self.open_directory(child)?; + if create { + self.sync()?; + } + Ok(result) + } + pub(crate) fn exists(&self, child: &str) -> Result { + let c = name(child)?; + let mut m = std::mem::MaybeUninit::::uninit(); + if unsafe { + libc::fstatat( + self.file.as_raw_fd(), + c.as_ptr(), + m.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } == 0 + { + return Ok(true); + } + if std::io::Error::last_os_error().kind() == std::io::ErrorKind::NotFound { + Ok(false) + } else { + Err(failure()) + } + } + pub(crate) fn open(&self, child: &str) -> Result { + let c = name(child)?; + let fd = unsafe { + libc::openat( + self.file.as_raw_fd(), + c.as_ptr(), + libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(failure()); + } + let f = unsafe { File::from_raw_fd(fd) }; + let m = f.metadata().map_err(|_| failure())?; + if !m.is_file() || m.uid() != unsafe { libc::geteuid() } || m.nlink() != 1 { + return Err(failure()); + } + Ok(f) + } + pub(crate) fn read(&self, child: &str, max: usize) -> Result>, AppError> { + if !self.exists(child)? { + return Ok(None); + } + let f = self.open(child)?; + if f.metadata().map_err(|_| failure())?.len() > max as u64 { + return Err(failure()); + } + let mut bytes = Vec::new(); + f.take(max as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| failure())?; + if bytes.len() > max { + return Err(failure()); + } + Ok(Some(bytes)) + } + pub(crate) fn lock(&self, child: &str) -> Result { + self.verify()?; + let c = name(child)?; + let fd = unsafe { + libc::openat( + self.file.as_raw_fd(), + c.as_ptr(), + libc::O_WRONLY + | libc::O_CREAT + | libc::O_NOFOLLOW + | libc::O_NONBLOCK + | libc::O_CLOEXEC, + 0o600, + ) + }; + if fd < 0 { + return Err(failure()); + } + let f = unsafe { File::from_raw_fd(fd) }; + let m = f.metadata().map_err(|_| failure())?; + if !m.is_file() || m.uid() != unsafe { libc::geteuid() } || m.nlink() != 1 { + return Err(failure()); + } + if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { + return Err(AppError::Conflict( + "Another local adapter operation is active. Wait, then inspect capture status." + .into(), + )); + } + Ok(f) + } + pub(crate) fn sync(&self) -> Result<(), AppError> { + installer_phase_event(20); + let result = self.file.sync_all(); + installer_phase_event(if result.is_ok() { 21 } else { 22 }); + result.map_err(|_| failure())?; + checkpoint("adapter-directory-fsynced"); + Ok(()) + } + pub(crate) fn atomic( + &self, + child: &str, + bytes: &[u8], + mode: u32, + expected: Option>, + phase: &str, + ) -> Result<(), AppError> { + self.atomic_checked(child, bytes, mode, expected, phase, &mut || Ok(())) + } + pub(crate) fn atomic_checked( + &self, + child: &str, + bytes: &[u8], + mode: u32, + expected: Option>, + phase: &str, + check: &mut impl FnMut() -> Result<(), AppError>, + ) -> Result<(), AppError> { + match phase { + "install-payload-file-fsynced" => installer_phase_event(50), + "install-journal-fsynced" => installer_phase_event(52), + "install-config-fsynced" => installer_phase_event(53), + _ => {} + } + self.verify()?; + let temp = format!(".keito-publish-{}", nonce()?); + let c = name(&temp)?; + let fd = unsafe { + libc::openat( + self.file.as_raw_fd(), + c.as_ptr(), + libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, + mode, + ) + }; + if fd < 0 { + return Err(failure()); + } + let result = (|| { + let mut f = unsafe { File::from_raw_fd(fd) }; + f.set_permissions(std::fs::Permissions::from_mode(mode)) + .map_err(|_| failure())?; + f.write_all(bytes) + .and_then(|_| { + installer_phase_event(10); + let result = f.sync_all(); + installer_phase_event(if result.is_ok() { 11 } else { 12 }); + result + }) + .map_err(|_| failure())?; + checkpoint(phase); + publication_fault(phase)?; + self.verify()?; + if let Some(expected) = expected { + if self.read(child, 32 * 1024 * 1024)?.as_deref() != expected { + return Err(conflict()); + } + } + check()?; + // rename flushes every affected directory before returning. No + // namespace change here requires another flush of that same state. + self.rename(&temp, self, child) + })(); + if self.exists(&temp).unwrap_or(false) { + let _ = self.unlink(&temp, false); + } + result + } + pub(crate) fn rename(&self, child: &str, dest: &Self, target: &str) -> Result<(), AppError> { + self.verify()?; + dest.verify()?; + let a = name(child)?; + let b = name(target)?; + if unsafe { + libc::renameat( + self.file.as_raw_fd(), + a.as_ptr(), + dest.file.as_raw_fd(), + b.as_ptr(), + ) + } != 0 + { + return Err(failure()); + } + checkpoint("adapter-entry-renamed"); + self.sync()?; + // Atomic replacement passes the identical anchored directory handle. + // Distinct handles conservatively keep both flushes, even for aliases. + if !Arc::ptr_eq(&self.file, &dest.file) { + dest.sync()?; + } + Ok(()) + } + pub(crate) fn unlink(&self, child: &str, directory: bool) -> Result<(), AppError> { + self.verify()?; + let c = name(child)?; + if unsafe { + libc::unlinkat( + self.file.as_raw_fd(), + c.as_ptr(), + if directory { libc::AT_REMOVEDIR } else { 0 }, + ) + } != 0 + { + return Err(failure()); + } + self.sync() + } + pub(crate) fn entries(&self) -> Result, AppError> { + // openat "." gives an independent directory cursor; dup would share it. + let fd = unsafe { + libc::openat( + self.file.as_raw_fd(), + c".".as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(failure()); + } + let stream = unsafe { libc::fdopendir(fd) }; + if stream.is_null() { + unsafe { libc::close(fd) }; + return Err(failure()); + } + let mut out = Vec::new(); + let result = loop { + set_errno(0); + let item = unsafe { libc::readdir(stream) }; + if item.is_null() { + break if errno() == 0 { Ok(()) } else { Err(failure()) }; + } + let raw = unsafe { CStr::from_ptr((*item).d_name.as_ptr()) }.to_bytes(); + if raw == b"." || raw == b".." { + continue; + } + if out.len() >= 4096 { + break Err(failure()); + } + match OsString::from_vec(raw.to_vec()).into_string() { + Ok(s) => out.push(s), + Err(_) => break Err(failure()), + } + }; + unsafe { libc::closedir(stream) }; + result?; + out.sort(); + Ok(out) + } + pub(crate) fn remove_tree(&self, child: &str) -> Result<(), AppError> { + self.remove_tree_checked(child, &mut || Ok(())) + } + pub(crate) fn remove_tree_checked( + &self, + child: &str, + check: &mut impl FnMut() -> Result<(), AppError>, + ) -> Result<(), AppError> { + check()?; + let dir = self.child(child, false)?; + check()?; + for entry in dir.entries()? { + check()?; + if dir.child(&entry, false).is_ok() { + dir.remove_tree_checked(&entry, check)?; + } else { + check()?; + let _ = dir.open(&entry)?; + check()?; + dir.unlink(&entry, false)?; + check()?; + } + } + check()?; + self.unlink(child, true)?; + check() + } + pub(crate) fn metadata(&self) -> Result { + self.file.metadata().map_err(|_| failure()) + } +} +#[cfg(target_os = "macos")] +fn set_errno(value: i32) { + unsafe { + *libc::__error() = value; + } +} +#[cfg(target_os = "macos")] +fn errno() -> i32 { + unsafe { *libc::__error() } +} +#[cfg(not(target_os = "macos"))] +fn set_errno(value: i32) { + unsafe { + *libc::__errno_location() = value; + } +} +#[cfg(not(target_os = "macos"))] +fn errno() -> i32 { + unsafe { *libc::__errno_location() } +} +#[cfg(not(test))] +pub(crate) fn checkpoint(_: &str) {} +#[cfg(test)] +type PhaseHook = Box; +#[cfg(test)] +thread_local! {static HOOK: std::cell::RefCell> = std::cell::RefCell::new(None);} +#[cfg(test)] +pub(crate) fn checkpoint(phase: &str) { + HOOK.with(|h| { + if let Some(f) = h.borrow().as_ref() { + f(phase); + } + }) +} +#[cfg(test)] +pub(crate) fn set_hook(hook: Option) { + HOOK.with(|h| *h.borrow_mut() = hook); +} + +#[cfg(not(test))] +fn publication_fault(_: &str) -> Result<(), AppError> { + Ok(()) +} +#[cfg(test)] +thread_local! {static FAILURE_PHASE: std::cell::RefCell> = const { std::cell::RefCell::new(None) };} +#[cfg(test)] +fn publication_fault(phase: &str) -> Result<(), AppError> { + FAILURE_PHASE.with(|p| { + if p.borrow().as_deref() == Some(phase) { + Err(failure()) + } else { + Ok(()) + } + }) +} +#[cfg(test)] +pub(crate) fn set_publication_fault(phase: Option<&str>) { + FAILURE_PHASE.with(|p| *p.borrow_mut() = phase.map(str::to_owned)); +} + +#[cfg(test)] +mod directory_verification_tests { + use super::*; + use std::cell::Cell; + + thread_local! { + static DIRECTORY_OPENS: Cell = const { Cell::new(0) }; + } + pub(super) fn directory_opened() { + DIRECTORY_OPENS.with(|count| count.set(count.get() + 1)); + } + + #[test] + fn directory_verify_uses_existing_descriptors_for_every_ancestor() { + let root = tempfile::tempdir().unwrap(); + let anchor = Dir::anchor(root.path()).unwrap(); + let parent = anchor.child("parent", true).unwrap(); + let leaf = parent.child("leaf", true).unwrap(); + let before = DIRECTORY_OPENS.with(Cell::get); + leaf.verify().unwrap(); + assert_eq!( + DIRECTORY_OPENS.with(Cell::get), + before, + "verification must not open disposable descriptors for held ancestors" + ); + assert!(leaf.path.is_dir()); + } + + #[test] + fn directory_verify_refuses_real_directory_replacement() { + let root = tempfile::tempdir().unwrap(); + let anchor = Dir::anchor(root.path()).unwrap(); + let leaf = anchor.child("leaf", true).unwrap(); + std::fs::rename(root.path().join("leaf"), root.path().join("retained")).unwrap(); + std::fs::create_dir(root.path().join("leaf")).unwrap(); + assert!(leaf.verify().is_err()); + assert!(leaf + .atomic("blocked", b"new", 0o600, Some(None), "test") + .is_err()); + assert!(!root.path().join("leaf/blocked").exists()); + assert!(!root.path().join("retained/blocked").exists()); + } + + #[test] + fn directory_verify_refuses_symlink_even_to_the_held_directory() { + let root = tempfile::tempdir().unwrap(); + let anchor = Dir::anchor(root.path()).unwrap(); + let leaf = anchor.child("leaf", true).unwrap(); + std::fs::rename(root.path().join("leaf"), root.path().join("retained")).unwrap(); + std::os::unix::fs::symlink(root.path().join("retained"), root.path().join("leaf")).unwrap(); + assert!(leaf.verify().is_err()); + assert!(leaf + .atomic("blocked", b"new", 0o600, Some(None), "test") + .is_err()); + assert!(!root.path().join("retained/blocked").exists()); + } + + #[test] + fn directory_verify_refuses_replaced_ancestor_and_root() { + for replace_root in [false, true] { + let root = tempfile::tempdir().unwrap(); + let base = root.path().join("base"); + std::fs::create_dir(&base).unwrap(); + let anchor = Dir::anchor(&base).unwrap(); + let parent = anchor.child("parent", true).unwrap(); + let leaf = parent.child("leaf", true).unwrap(); + let target = if replace_root { + base + } else { + parent.path.clone() + }; + std::fs::rename(&target, target.with_extension("retained")).unwrap(); + std::fs::create_dir(&target).unwrap(); + assert!(leaf.verify().is_err()); + assert!(leaf + .atomic("blocked", b"new", 0o600, Some(None), "test") + .is_err()); + assert!(!leaf.path.join("blocked").exists()); + } + } +} + +#[cfg(test)] +mod installer_flush_tests { + use super::*; + use std::{cell::RefCell, rc::Rc}; + + struct Observe(Rc>>); + impl Observe { + fn start() -> Self { + let events = Rc::new(RefCell::new(Vec::new())); + let copy = Rc::clone(&events); + set_hook(Some(Box::new(move |phase| { + copy.borrow_mut().push(phase.to_owned()); + }))); + Self(events) + } + fn events(&self) -> Vec { + self.0.borrow().clone() + } + } + impl Drop for Observe { + fn drop(&mut self) { + set_hook(None); + } + } + + #[test] + fn recovery_owner_already_refused_preserves_the_entire_tree() { + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let target = dir.child("stage", true).unwrap(); + std::fs::write(target.path.join("a"), b"a").unwrap(); + let result = dir.remove_tree_checked("stage", &mut || { + Err(AppError::Conflict("Original recovery owner refusal".into())) + }); + assert!( + matches!(result, Err(AppError::Conflict(message)) if message == "Original recovery owner refusal") + ); + assert_eq!(target.read("a", 16).unwrap().unwrap(), b"a"); + assert!(root.path().join("stage").is_dir()); + } + #[test] + fn recovery_owner_refusal_after_first_deletion_preserves_remaining_files() { + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let target = dir.child("stage", true).unwrap(); + std::fs::write(target.path.join("a"), b"a").unwrap(); + std::fs::write(target.path.join("b"), b"b").unwrap(); + let result = dir.remove_tree_checked("stage", &mut || { + if target.path.join("a").exists() { + Ok(()) + } else { + Err(AppError::Conflict("Original recovery owner refusal".into())) + } + }); + assert!( + matches!(result, Err(AppError::Conflict(message)) if message == "Original recovery owner refusal") + ); + assert!(!target.path.join("a").exists()); + assert_eq!(target.read("b", 16).unwrap().unwrap(), b"b"); + assert!(root.path().join("stage").is_dir()); + } + #[test] + fn installer_flush_atomic_syncs_file_then_renamed_directory_once() { + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let observe = Observe::start(); + dir.atomic("payload", b"new", 0o600, Some(None), "payload-file-fsynced") + .unwrap(); + assert_eq!( + observe.events(), + [ + "payload-file-fsynced", + "adapter-entry-renamed", + "adapter-directory-fsynced" + ] + ); + assert_eq!(dir.read("payload", 16).unwrap().unwrap(), b"new"); + } + + #[test] + fn installer_flush_cross_directory_rename_flushes_both_parents() { + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let destination = dir.child("destination", true).unwrap(); + std::fs::write(root.path().join("payload"), b"new").unwrap(); + let observe = Observe::start(); + dir.rename("payload", &destination, "payload").unwrap(); + assert_eq!( + observe.events(), + [ + "adapter-entry-renamed", + "adapter-directory-fsynced", + "adapter-directory-fsynced" + ] + ); + assert!(!dir.exists("payload").unwrap()); + assert_eq!(destination.read("payload", 16).unwrap().unwrap(), b"new"); + } + + #[test] + fn installer_flush_distinct_handles_remain_conservative() { + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let second = Dir::anchor(root.path()).unwrap(); + std::fs::write(root.path().join("old"), b"new").unwrap(); + let observe = Observe::start(); + dir.rename("old", &second, "new").unwrap(); + assert_eq!( + observe.events(), + [ + "adapter-entry-renamed", + "adapter-directory-fsynced", + "adapter-directory-fsynced" + ] + ); + } + + #[test] + fn installer_flush_guard_refusal_never_switches_existing_file() { + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + std::fs::write(root.path().join("payload"), b"old").unwrap(); + let observe = Observe::start(); + assert!(dir + .atomic_checked( + "payload", + b"new", + 0o600, + Some(Some(b"old")), + "payload-file-fsynced", + &mut || Err(failure()) + ) + .is_err()); + assert_eq!( + observe.events(), + ["payload-file-fsynced", "adapter-directory-fsynced"] + ); + assert_eq!(dir.read("payload", 16).unwrap().unwrap(), b"old"); + assert_eq!(dir.entries().unwrap(), ["payload"]); + } + + #[test] + fn installer_flush_cas_refusal_preserves_foreign_bytes() { + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + std::fs::write(root.path().join("payload"), b"foreign").unwrap(); + let observe = Observe::start(); + assert!(dir + .atomic( + "payload", + b"new", + 0o600, + Some(Some(b"old")), + "payload-file-fsynced" + ) + .is_err()); + assert_eq!( + observe.events(), + ["payload-file-fsynced", "adapter-directory-fsynced"] + ); + assert_eq!(dir.read("payload", 16).unwrap().unwrap(), b"foreign"); + assert_eq!(dir.entries().unwrap(), ["payload"]); + } +} + +// Compiled out of default releases. No path/content is accepted by this API. +#[cfg(not(feature = "dev-tools"))] +#[inline(always)] +pub(crate) fn installer_phase_event(_: u8) {} +#[cfg(feature = "dev-tools")] +pub(crate) fn installer_phase_event(code: u8) { + installer_phase_trace::emit(code); +} +#[cfg(feature = "dev-tools")] +pub(crate) mod installer_phase_trace { + use std::{cell::RefCell, io}; + pub(super) const MAX_FRAMES: u32 = 2048; + struct State { + fd: i32, + sequence: u32, + failed: bool, + } + thread_local! { + static STATE: RefCell> = const { RefCell::new(None) }; + } + pub(crate) struct Guard { + fd: i32, + flags: i32, + enabled: bool, + finished: bool, + } + pub(crate) fn with_trace( + initialize: impl FnOnce() -> io::Result, + run: impl FnOnce() -> Result, + ) -> Result { + // Observation setup cannot decide whether the actual installer runs. + let mut guard = initialize().ok(); + let result = run(); + if let Some(guard) = guard.as_mut() { + guard.finish(result.is_ok()); + } + result + } + impl Guard { + pub(crate) fn begin(enabled: bool) -> io::Result { + if !enabled { + return Ok(Self { + fd: -1, + flags: 0, + enabled: false, + finished: false, + }); + } + Self::begin_fd(libc::STDOUT_FILENO) + } + fn begin_fd(fd: i32) -> io::Result { + if STATE.with(|s| s.borrow().is_some()) { + return Err(io::Error::other("QA_PHASE_TRACE_ACTIVE")); + } + let mut info = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstat(fd, info.as_mut_ptr()) } != 0 { + return Err(io::Error::other("QA_PHASE_TRACE_FD")); + } + if unsafe { info.assume_init() }.st_mode & libc::S_IFMT != libc::S_IFIFO { + return Err(io::Error::other("QA_PHASE_TRACE_PIPE")); + } + let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; + if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 + { + return Err(io::Error::other("QA_PHASE_TRACE_FLAGS")); + } + STATE.with(|s| { + *s.borrow_mut() = Some(State { + fd, + sequence: 0, + failed: false, + }) + }); + emit(1); + Ok(Self { + fd, + flags, + enabled: true, + finished: false, + }) + } + pub(crate) fn finish(&mut self, success: bool) { + if self.enabled && !self.finished { + emit(if success { 2 } else { 3 }); + self.finished = true; + } + } + } + impl Drop for Guard { + fn drop(&mut self) { + if self.enabled { + if !self.finished { + emit(4); + } + STATE.with(|s| *s.borrow_mut() = None); + unsafe { + libc::fcntl(self.fd, libc::F_SETFL, self.flags); + } + } + } + } + pub(super) fn emit(code: u8) { + STATE.with(|cell| { + let mut state = cell.borrow_mut(); + let Some(state) = state.as_mut() else { + return; + }; + if state.failed { + return; + } + if state.sequence >= MAX_FRAMES + || !matches!(code, 1..=4 | 10..=12 | 20..=22 | 30..=32 | 40..=41 | 50 | 52..=53) + { + state.failed = true; + return; + } + let Ok(at) = crate::process_ownership::scope::monotonic_now() else { + state.failed = true; + return; + }; + let mut frame = [0u8; 24]; + frame[..4].copy_from_slice(b"KIP1"); + frame[4] = code; + frame[8..12].copy_from_slice(&state.sequence.to_le_bytes()); + frame[16..24].copy_from_slice(&at.to_le_bytes()); + // One nonblocking write; no retry, formatting, path or content. + let count = unsafe { libc::write(state.fd, frame.as_ptr().cast(), frame.len()) }; + if count == frame.len() as isize { + state.sequence += 1; + } else { + state.failed = true; + } + }); + } + #[cfg(test)] + mod tests { + use super::*; + use std::{ + fs::File, + io::Read, + os::fd::{AsRawFd, FromRawFd}, + }; + fn pipe() -> (File, File) { + let mut fds = [-1; 2]; + assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0); + for fd in fds { + assert_eq!( + unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) }, + 0 + ); + } + unsafe { (File::from_raw_fd(fds[0]), File::from_raw_fd(fds[1])) } + } + #[test] + fn installer_phase_trace_init_failure_preserves_handler_success() { + let called = std::cell::Cell::new(0); + let result = with_trace( + || Guard::begin_fd(-1), + || { + called.set(called.get() + 1); + Ok("original installer success") + }, + ); + assert_eq!(called.get(), 1, "trace setup may not bypass the installer"); + assert_eq!(result.unwrap(), "original installer success"); + assert!(STATE.with(|state| state.borrow().is_none())); + } + #[test] + fn installer_phase_trace_init_failure_preserves_original_handler_error() { + let called = std::cell::Cell::new(0); + let result: Result<(), crate::error::AppError> = with_trace( + || Guard::begin_fd(-1), + || { + called.set(called.get() + 1); + Err(crate::error::AppError::Conflict( + "original installer failure".into(), + )) + }, + ); + assert_eq!(called.get(), 1, "trace setup may not bypass the installer"); + assert!( + matches!(result, Err(crate::error::AppError::Conflict(message)) + if message == "original installer failure") + ); + assert!(STATE.with(|state| state.borrow().is_none())); + } + #[test] + fn installer_phase_trace_actual_atomic_write_is_fixed_metadata() { + let (mut reader, writer) = pipe(); + let root = tempfile::tempdir().unwrap(); + let dir = crate::adapter_files::Dir::anchor(root.path()).unwrap(); + let mut guard = Guard::begin_fd(writer.as_raw_fd()).unwrap(); + dir.atomic( + "PRIVATE_PATH_CANARY", + b"PRIVATE_BODY_CANARY", + 0o600, + Some(None), + "test-flush", + ) + .unwrap(); + guard.finish(true); + drop(guard); + drop(writer); + let mut bytes = Vec::new(); + reader.read_to_end(&mut bytes).unwrap(); + assert!( + !bytes.is_empty(), + "actual filesystem progress must be emitted" + ); + assert_eq!(bytes.len() % 24, 0); + let codes: Vec<_> = bytes + .as_chunks::<24>() + .0 + .iter() + .enumerate() + .map(|(i, frame)| { + assert_eq!(&frame[..4], b"KIP1"); + assert_eq!( + u32::from_le_bytes(frame[8..12].try_into().unwrap()), + i as u32 + ); + assert_eq!(&frame[5..8], &[0; 3]); + assert_eq!(&frame[12..16], &[0; 4]); + assert!(u64::from_le_bytes(frame[16..24].try_into().unwrap()) > 0); + frame[4] + }) + .collect(); + assert_eq!(codes, [1, 10, 11, 20, 21, 2]); + assert!(!bytes.windows(8).any(|w| w == b"PRIVATE_")); + assert_eq!( + std::fs::read(root.path().join("PRIVATE_PATH_CANARY")).unwrap(), + b"PRIVATE_BODY_CANARY" + ); + } + #[test] + fn installer_phase_trace_full_pipe_failure_is_sticky_and_nonblocking() { + let (reader, writer) = pipe(); + let mut guard = Guard::begin_fd(writer.as_raw_fd()).unwrap(); + let block = [0u8; 24]; + loop { + let n = + unsafe { libc::write(writer.as_raw_fd(), block.as_ptr().cast(), block.len()) }; + if n < 0 { + assert_eq!(io::Error::last_os_error().kind(), io::ErrorKind::WouldBlock); + break; + } + assert!(n > 0); + } + emit(20); + assert!(STATE.with(|s| s.borrow().as_ref().unwrap().failed)); + let sequence = STATE.with(|s| s.borrow().as_ref().unwrap().sequence); + emit(21); + guard.finish(false); + assert_eq!( + STATE.with(|s| s.borrow().as_ref().unwrap().sequence), + sequence + ); + drop(guard); + drop(writer); + drop(reader); + } + #[test] + fn installer_phase_trace_frame_cap_never_wraps_or_resumes() { + let (reader, writer) = pipe(); + let mut guard = Guard::begin_fd(writer.as_raw_fd()).unwrap(); + STATE.with(|s| s.borrow_mut().as_mut().unwrap().sequence = MAX_FRAMES); + emit(20); + assert!(STATE.with(|s| s.borrow().as_ref().unwrap().failed)); + emit(21); + guard.finish(true); + assert_eq!( + STATE.with(|s| s.borrow().as_ref().unwrap().sequence), + MAX_FRAMES + ); + drop(guard); + drop(writer); + drop(reader); + } + } +} diff --git a/src/bin/check-service-boundary.rs b/src/bin/check-service-boundary.rs new file mode 100644 index 0000000..06dab80 --- /dev/null +++ b/src/bin/check-service-boundary.rs @@ -0,0 +1,199 @@ +//! Development-only, single inherited macOS execution/network boundary. +#[cfg(target_os = "macos")] +#[path = "../../tests/support/mutation_environment.rs"] +mod isolation; +#[cfg(target_os = "macos")] +mod boundary { + use serde_json::json; + use sha2::{Digest, Sha256}; + use std::{ + collections::BTreeSet, + fs, + io::{Read, Write}, + net::{TcpListener, TcpStream}, + os::unix::fs::{symlink, MetadataExt, PermissionsExt}, + path::{Path, PathBuf}, + process::Command, + time::Duration, + }; + fn hash(path: &Path) -> String { + Sha256::digest(fs::read(path).unwrap()) + .iter() + .map(|v| format!("{v:02x}")) + .collect() + } + fn root(path: &Path) -> PathBuf { + let root = path.canonicalize().unwrap(); + let m = fs::metadata(&root).unwrap(); + assert!(m.is_dir() && m.uid() == unsafe { libc::geteuid() } && m.mode() & 0o777 == 0o700); + root + } + fn command(program: &Path, base: &Path, core: &Path) -> Command { + let home = base.join("home"); + let capture = home.join("capture"); + let c = + super::isolation::checked(base, base, Some(&home), Some(&capture), Some(core)).unwrap(); + assert_eq!(c.core, core); + let mut cmd = Command::new(program); + cmd.env_clear() + .current_dir(base) + .env("HOME", &c.home) + .env("CODEX_HOME", c.home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", c.home.join(".claude")) + .env("KEITO_CAPTURE_HOME", &c.capture) + .env("XDG_CONFIG_HOME", c.home.join("config")) + .env("APPDATA", c.home.join("AppData")) + .env("PATH", base.join("empty-bin")) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null"); + cmd + } + pub fn run() { + let args: Vec<_> = std::env::args_os().skip(1).collect(); + assert_eq!(args.len(), 2); + let mode = args[0].to_str().unwrap(); + let base = root(Path::new(&args[1])); + if mode == "marker" { + fs::write(base.join("native.marker"), b"owned-marker").unwrap(); + return; + } + if mode == "loopback" { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let worker = std::thread::spawn(move || { + let (mut peer, _) = listener.accept().unwrap(); + peer.write_all(b"ok").unwrap(); + }); + let mut client = TcpStream::connect_timeout(&address, Duration::from_secs(1)).unwrap(); + client + .set_read_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let mut bytes = [0; 2]; + client.read_exact(&mut bytes).unwrap(); + assert_eq!(&bytes, b"ok"); + worker.join().unwrap(); + fs::write(base.join("loopback.marker"), b"loopback-only").unwrap(); + return; + } + if mode == "prepare" { + fs::create_dir(base.join("home")).unwrap(); + fs::create_dir(base.join("home/capture")).unwrap(); + fs::set_permissions(base.join("home/capture"), fs::Permissions::from_mode(0o700)) + .unwrap(); + for name in ["blocked-native-marker", "allowed-native-marker"] { + fs::copy(std::env::current_exe().unwrap(), base.join(name)).unwrap(); + fs::set_permissions(base.join(name), fs::Permissions::from_mode(0o700)).unwrap(); + } + fs::create_dir(base.join("allowed")).unwrap(); + fs::set_permissions(base.join("allowed"), fs::Permissions::from_mode(0o700)).unwrap(); + symlink( + base.join("blocked-native-marker"), + base.join("blocked-alias"), + ) + .unwrap(); + fs::copy(std::env::current_exe().unwrap(), base.join("owned-checker")).unwrap(); + fs::set_permissions( + base.join("owned-checker"), + fs::Permissions::from_mode(0o700), + ) + .unwrap(); + let mut denied = BTreeSet::new(); + for path in [ + PathBuf::from("/bin/launchctl"), + PathBuf::from("/usr/bin/launchctl"), + base.join("blocked-native-marker"), + base.join("blocked-alias"), + ] { + denied.insert(path.clone()); + if let Ok(p) = path.canonicalize() { + denied.insert(p); + } + } + let literals = denied + .iter() + .map(|p| { + format!( + "(literal \"{}\")", + p.to_string_lossy() + .replace('\\', "\\\\") + .replace('"', "\\\"") + ) + }) + .collect::>() + .join(" "); + let policy=format!("(version 1)\n(allow default)\n(deny process-exec {literals})\n(deny network*)\n(allow network-bind (local ip \"localhost:*\"))\n(allow network-inbound (local ip \"localhost:*\"))\n(allow network-outbound (remote ip \"localhost:*\"))\n"); + fs::write(base.join("boundary.sb"), policy).unwrap(); + fs::set_permissions(base.join("boundary.sb"), fs::Permissions::from_mode(0o600)) + .unwrap(); + return; + } + assert_eq!(mode, "verify"); + let blocked = base.join("blocked-native-marker"); + let allowed = base.join("allowed-native-marker"); + let marker = base.join("native.marker"); + let denied = command(&blocked, &base, &blocked) + .arg("marker") + .arg(&base) + .output(); + let alias = base.join("blocked-alias"); + assert_eq!(alias.canonicalize().unwrap(), blocked); + let denied_alias = command(&alias, &base, &blocked) + .arg("marker") + .arg(&base) + .output(); + let allowed_marker = base.join("allowed/native.marker"); + let control = command(&allowed, &base, &allowed) + .arg("marker") + .arg(base.join("allowed")) + .output() + .unwrap(); + let checker = base.join("owned-checker"); + let loopback = command(&checker, &base, &checker) + .arg("loopback") + .arg(&base) + .output() + .unwrap(); + let permission_denied = |result: &std::io::Result| { + result + .as_ref() + .is_err_and(|e| e.kind() == std::io::ErrorKind::PermissionDenied) + }; + let passed = permission_denied(&denied) + && permission_denied(&denied_alias) + && !marker.exists() + && control.status.success() + && allowed_marker.is_file() + && loopback.status.success() + && base.join("loopback.marker").is_file(); + let result = json!({"schema":1,"passed":passed,"denied_errno":denied.as_ref().err().and_then(std::io::Error::raw_os_error),"alias_errno":denied_alias.as_ref().err().and_then(std::io::Error::raw_os_error),"control_status":control.status.code(),"loopback_status":loopback.status.code(),"actual_service_utility_executed":false,"actual_service_negative_probe":false,"policy_sha256":hash(&base.join("boundary.sb")),"checker_sha256":hash(&checker),"blocked_sha256":hash(&blocked),"checker_source_sha256":Sha256::digest(include_bytes!("check-service-boundary.rs")).iter().map(|v|format!("{v:02x}")).collect::(),"helper_source_sha256":Sha256::digest(include_bytes!("../../tests/support/service_boundary.rs")).iter().map(|v|format!("{v:02x}")).collect::()}); + fs::write( + base.join("proof-result.json"), + serde_json::to_vec_pretty(&result).unwrap(), + ) + .unwrap(); + assert!( + passed, + "single inherited service/network policy proof failed; inspect fixed result codes" + ); + fs::write( + base.join("service-boundary-receipt.json"), + serde_json::to_vec_pretty(&result).unwrap(), + ) + .unwrap(); + fs::set_permissions( + base.join("service-boundary-receipt.json"), + fs::Permissions::from_mode(0o600), + ) + .unwrap(); + println!("{}", serde_json::to_string_pretty(&result).unwrap()); + } +} +fn main() { + #[cfg(target_os = "macos")] + boundary::run(); + #[cfg(not(target_os = "macos"))] + { + eprintln!("The macOS test boundary is unavailable on this platform"); + std::process::exit(1); + } +} diff --git a/src/bin/keito-capture-guard.rs b/src/bin/keito-capture-guard.rs new file mode 100644 index 0000000..b4b5e09 --- /dev/null +++ b/src/bin/keito-capture-guard.rs @@ -0,0 +1,54 @@ +#[path = "../native_capture_guard.rs"] +mod native_capture_guard; +// Shared Scope's diagnostic calls use this binary's independent numeric TLS. +// Guard roles never begin a handler record, so these calls collect nothing. +#[cfg(all(unix, feature = "capture-profile"))] +#[path = "../capture_profile.rs"] +#[allow(dead_code)] +mod capture_profile; +#[cfg(unix)] +#[path = "../process_ownership/mod.rs"] +#[allow(dead_code)] // Core-only APIs share this source; the guard links only its roles. +pub mod process_ownership; +fn main() { + #[cfg(unix)] + { + let args: Vec<_> = std::env::args_os().skip(1).collect(); + if args + .first() + .is_some_and(|a| a == process_ownership::image::KEEPER_ROLE) + { + let fields = &args[1..]; + let result = (|| { + if !matches!(fields.len(), 6 | 7) { + return Err(()); + } + let control = fields[0] + .to_str() + .and_then(|s| s.parse::().ok()) + .filter(|fd| (4..=1024).contains(fd)) + .ok_or(())?; + process_ownership::image::bootstrap_keeper_image(control).map_err(|_| ())?; + process_ownership::group::keeper_main(fields.iter()).map_err(|_| ()) + })(); + if result.is_err() { + std::process::exit(1); + } + return; + } + } + #[cfg(unix)] + { + // Every installed role is owned on this entry thread before it can + // create a Child. Private keeper startup remains its closed role above. + let args: Vec<_> = std::env::args_os().skip(1).collect(); + let role = args.first().and_then(|a| a.to_str()); + let dispatch = role == Some(process_ownership::image::DISPATCH_ROLE); + let fields = if dispatch { &args[1..] } else { &args[..] }; + // Dispatch and guardian share one durable prelaunch entry. No image + // hash/verification or child admission precedes marker publication. + let _ = native_capture_guard::run(fields); + // Installed hooks remain silent/fail-open; a failed/absent ownership + // terminal and retained durable marker independently forbid time proof. + } +} diff --git a/src/bin/qualify-capture.rs b/src/bin/qualify-capture.rs new file mode 100644 index 0000000..c161afa --- /dev/null +++ b/src/bin/qualify-capture.rs @@ -0,0 +1,830 @@ +//! Development-only paired-artifact acceptance. No harness, credentials, +//! network service, installed profile or real CLI fallback is used. +#[cfg(unix)] +#[path = "../../tests/support/mutation_environment.rs"] +mod isolation; +#[cfg(unix)] +mod qualification { + use keito_cli::{ + capture::{self, Binding, Store}, + process_ownership::{io::IoPlan, scope::Scope}, + }; + use serde_json::{json, Value}; + use std::{ + fs, + io::{Read, Write}, + os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::{ + fs::{MetadataExt, PermissionsExt}, + process::{CommandExt, ExitStatusExt}, + }, + }, + path::{Path, PathBuf}, + process::{Command, Stdio}, + time::{Duration, Instant}, + }; + const PENDING: &[u8] = b"KEITO_CAPTURE_PENDING_V1\n"; + #[derive(serde::Serialize)] + struct Observation { + elapsed_ms: f64, + success: bool, + exit_code: Option, + stdout_bytes: usize, + stderr_bytes: usize, + spawn_error: Option, + flags: usize, + } + const ACK: &[u8] = b"KEITO_CAPTURE_DURABLE_V1\n"; + const STDERR_LIMIT: usize = 64 * 1024; + fn direct_clock() -> std::io::Result { + let mut clock = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, clock.as_mut_ptr()) } != 0 { + return Err(std::io::Error::last_os_error()); + } + let clock = unsafe { clock.assume_init() }; + u64::try_from(clock.tv_sec) + .ok() + .and_then(|s| s.checked_mul(1_000_000_000)) + .and_then(|s| s.checked_add(clock.tv_nsec as u64)) + .ok_or_else(|| std::io::Error::other("qualifier clock overflow")) + } + fn direct_sync_marker(marker: &fs::File) -> std::io::Result<()> { + // Match native_capture_guard::sync: POSIX fsync, not Apple's + // F_FULLFSYNC used by Rust File::sync_all. Never refresh leaf/parent ends. + let started = Instant::now(); + loop { + if unsafe { libc::fsync(marker.as_raw_fd()) } == 0 { + return Ok(()); + } + let error = std::io::Error::last_os_error(); + if error.kind() != std::io::ErrorKind::Interrupted + || started.elapsed() >= Duration::from_millis(25) + { + return Err(error); + } + } + } + fn direct_admission_fresh(at: u64, leaf_end: u64) -> bool { + // The public cooperative API has the parent ceiling; preserve the + // guard's earlier leaf admission reserve at both caller and exec edge. + at < leaf_end.saturating_sub(50_000_000) + } + fn direct_close_inventory(image_fd: i32, inventory_fd: i32, fds: &[i32]) -> Vec { + assert!((5..=1024).contains(&image_fd)); + fds.iter() + .copied() + .filter(|fd| *fd >= 4 && *fd != inventory_fd && *fd != image_fd) + .collect() + } + fn direct_pipe() -> (fs::File, OwnedFd) { + let mut pipe = [-1; 2]; + assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0); + let reader = unsafe { fs::File::from_raw_fd(pipe[0]) }; + let writer = unsafe { OwnedFd::from_raw_fd(pipe[1]) }; + for fd in [reader.as_raw_fd(), writer.as_raw_fd()] { + assert_eq!( + unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) }, + 0 + ); + } + assert_eq!( + unsafe { libc::fcntl(reader.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }, + 0 + ); + (reader, writer) + } + fn direct_read( + reader: &mut fs::File, + bytes: &mut Vec, + eof: &mut bool, + limit: usize, + ) -> std::io::Result<()> { + if *eof { + return Ok(()); + } + // One bounded read per owner-pump turn. One extra byte detects excess. + let mut part = [0u8; 256]; + let remaining = (limit + 1).saturating_sub(bytes.len()).min(part.len()); + if remaining == 0 { + return Err(std::io::Error::other("qualifier output limit")); + } + match reader.read(&mut part[..remaining]) { + Ok(0) => *eof = true, + Ok(n) => bytes.extend_from_slice(&part[..n]), + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted + ) => {} + Err(e) => return Err(e), + } + if bytes.len() > limit { + return Err(std::io::Error::other("qualifier output limit")); + } + Ok(()) + } + struct Case { + root: PathBuf, + home: PathBuf, + capture: PathBuf, + core: PathBuf, + guard: PathBuf, + bin: PathBuf, + repo: PathBuf, + core_hash: String, + } + impl Case { + fn new(source: &Path, run: &Path, name: &str) -> Self { + let root = run.join(name); + fs::create_dir(&root).unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let home = root.join("home"); + fs::create_dir(&home).unwrap(); + let capture = home.join("capture"); + fs::create_dir(&capture).unwrap(); + fs::set_permissions(&capture, fs::Permissions::from_mode(0o700)).unwrap(); + let artifact = root.join("artifact"); + fs::create_dir(&artifact).unwrap(); + for name in [ + "keito", + "keito-capture-guard", + "capture-runtime-manifest.json", + ] { + let from = source.join(name); + let m = fs::symlink_metadata(&from).unwrap(); + assert!(m.is_file() && !m.file_type().is_symlink()); + fs::copy(from, artifact.join(name)).unwrap(); + } + let core = artifact.join("keito"); + let guard = artifact.join("keito-capture-guard"); + let manifest: Value = serde_json::from_slice( + &fs::read(artifact.join("capture-runtime-manifest.json")).unwrap(), + ) + .unwrap(); + let core_hash = manifest["files"]["keito"].as_str().unwrap().to_owned(); + assert_eq!(core_hash.len(), 64); + let bin = root.join("bin"); + fs::create_dir(&bin).unwrap(); + fs::write(bin.join("keito"), "#!/bin/sh\nexit 89\n").unwrap(); + fs::set_permissions(bin.join("keito"), fs::Permissions::from_mode(0o700)).unwrap(); + fs::write( + root.join("dispatch.sh"), + include_str!("../../skills/keito-time-track/hooks/dispatch.sh"), + ) + .unwrap(); + fs::set_permissions(root.join("dispatch.sh"), fs::Permissions::from_mode(0o700)) + .unwrap(); + let repo = root.join("repo"); + fs::create_dir(&repo).unwrap(); + let result = Self { + root, + home, + capture, + core, + guard, + bin, + repo, + core_hash, + }; + // Preserve the caller's real executable selection; private PATH + // aliases remove fixture wrapper overhead without choosing a + // different/faster Git implementation than the installed hook. + let selected_git = std::env::var_os("PATH") + .and_then(|paths| { + std::env::split_paths(&paths) + .map(|p| p.join("git")) + .find(|p| { + fs::metadata(p).is_ok_and(|m| m.is_file() && m.mode() & 0o111 != 0) + }) + }) + .expect( + "Caller Git is unavailable; fixture setup failed before artifact execution", + ); + let platform_git = selected_git.canonicalize().unwrap(); + let mut tools = serde_json::Map::new(); + for (name, path) in [ + ("git", platform_git), + ("sleep", PathBuf::from("/bin/sleep")), + ("bash", PathBuf::from("/bin/bash")), + ] { + let path = path.canonicalize().unwrap(); + let metadata = fs::metadata(&path).unwrap(); + assert!( + metadata.is_file() + && metadata.mode() & 0o111 != 0 + && metadata.mode() & 0o022 == 0 + && (metadata.uid() == 0 || metadata.uid() == unsafe { libc::geteuid() }) + ); + std::os::unix::fs::symlink(&path, result.bin.join(name)).unwrap(); + tools.insert( + name.into(), + json!({"path":path,"sha256":capture::hash(fs::read(&path).unwrap()), + "selection":if name=="git" {"caller_PATH"} else {"explicit_OS_utility"}}), + ); + } + tools.insert("selected_git_path".into(), json!(selected_git)); + fs::write( + result.root.join("platform-tools.json"), + serde_json::to_vec_pretty(&tools).unwrap(), + ) + .unwrap(); + let template = result.root.join("git-template"); + fs::create_dir(&template).unwrap(); + let mut git = result.command(&result.bin.join("git")); + assert!(git + .arg("-C") + .arg(&result.repo) + .arg("init") + .arg(format!("--template={}", template.display())) + .output() + .unwrap() + .status + .success()); + let common = result.repo.join(".git").canonicalize().unwrap(); + let mut store = Store::open(&result.capture).unwrap(); + store + .approve(Binding { + repository_key: capture::hash(common.to_string_lossy().as_bytes()), + remote_hash: capture::hash(""), + hint_hash: capture::hash("no-mapping-hint"), + id: String::new(), + version: 0, + workspace_id: "co_synthetic".into(), + owner_id: "synthetic_owner".into(), + origin_hash: capture::hash("synthetic_origin"), + project_id: "synthetic_project".into(), + task_id: "synthetic_task".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }) + .unwrap(); + result + } + fn use_guarded_pair(&mut self, guarded: &Self) { + // The unchanged first probe already exercised this exact image pair + // through the cold guard entry. Direct-ACK is a protocol fixture, + // not a second cold keeper-start test on a never-dispatched guard. + // Keep this case's fresh HOME/capture/repository and pending marker. + assert_eq!(self.root.parent(), guarded.root.parent()); + assert_eq!(self.core_hash, guarded.core_hash); + self.core = guarded.core.clone(); + self.guard = guarded.guard.clone(); + } + fn command(&self, program: &Path) -> Command { + let checked = super::isolation::checked( + self.root.parent().unwrap(), + &self.root, + Some(&self.home), + Some(&self.capture), + Some(&self.core), + ) + .expect("non-isolated artifact command refused"); + assert_eq!(checked.core, self.core); + let mut cmd = Command::new(program); + cmd.env_clear() + .current_dir(&self.repo) + .env("HOME", &checked.home) + .env("CODEX_HOME", checked.home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", checked.home.join(".claude")) + .env("KEITO_CAPTURE_HOME", &checked.capture) + .env("XDG_CONFIG_HOME", checked.home.join("config")) + .env("APPDATA", checked.home.join("AppData")) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("PATH", &self.bin) + .env("KEITO_CAPTURE_CORE_SHA256", &self.core_hash); + cmd + } + fn input(&self, session: &str) -> Vec { + serde_json::to_vec(&json!({"cwd":self.repo,"session_id":session,"turn_id":format!("turn_{session}"),"prompt":"PRIVATE_QUALIFICATION_CANARY"})).unwrap() + } + fn flags(&self) -> usize { + fs::read_dir(self.capture.join("capture-invocations")) + .map(|v| v.count()) + .unwrap_or(0) + } + fn observe_guard(&self, event: &str, input: &[u8]) -> Observation { + let mut cmd = self.command(Path::new("/bin/bash")); + cmd.env("KEITO_CLI_BIN", &self.core) + .env("KEITO_CAPTURE_GUARD_BIN", &self.guard) + .arg(self.root.join("dispatch.sh")) + .args([ + "--agent", + "codex", + "--event", + event, + "--harness-version", + "0.167.0", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let start = Instant::now(); + let mut child = match cmd.spawn() { + Ok(child) => child, + Err(error) => { + return Observation { + elapsed_ms: start.elapsed().as_secs_f64() * 1000.0, + success: false, + exit_code: None, + stdout_bytes: 0, + stderr_bytes: 0, + spawn_error: error.raw_os_error(), + flags: self.flags(), + } + } + }; + let _ = child.stdin.take().unwrap().write_all(input); + let output = child.wait_with_output().unwrap(); + let elapsed = start.elapsed(); + Observation { + elapsed_ms: elapsed.as_secs_f64() * 1000.0, + success: output.status.success(), + exit_code: output.status.code(), + stdout_bytes: output.stdout.len(), + stderr_bytes: output.stderr.len(), + spawn_error: None, + flags: self.flags(), + } + } + fn assert_guard(observation: &Observation) { + assert!( + observation.success + && observation.stdout_bytes == 0 + && observation.stderr_bytes == 0 + && observation.spawn_error.is_none(), + "artifact dispatch execution failed" + ); + assert!( + observation.elapsed_ms < 1000.0, + "artifact host deadline: {}ms", + observation.elapsed_ms + ); + } + fn guard(&self, event: &str, input: &[u8]) -> Duration { + let observation = self.observe_guard(event, input); + Self::assert_guard(&observation); + Duration::from_secs_f64(observation.elapsed_ms / 1000.0) + } + fn assert_private_state(&self) { + fn visit(path: &Path) { + for entry in fs::read_dir(path).unwrap() { + let path = entry.unwrap().path(); + let metadata = fs::symlink_metadata(&path).unwrap(); + assert!(!metadata.file_type().is_symlink()); + if metadata.is_dir() { + visit(&path); + } else { + let bytes = fs::read(path).unwrap(); + assert!( + !bytes + .windows(b"PRIVATE_QUALIFICATION_CANARY".len()) + .any(|v| v == b"PRIVATE_QUALIFICATION_CANARY"), + "raw hook canary persisted in capture state" + ); + } + } + } + visit(&self.capture); + } + fn direct_ack(&self, input: &[u8], nonce: &str) -> Vec { + self.direct_ack_replacement(input, nonce, false) + } + fn direct_ack_replacement( + &self, + input: &[u8], + nonce: &str, + replace_after_image_open: bool, + ) -> Vec { + let origin = direct_clock().unwrap(); + let leaf_end = origin.checked_add(500_000_000).unwrap(); + let parent_end = origin.checked_add(600_000_000).unwrap(); + let flags = self.capture.join("capture-invocations"); + fs::create_dir_all(&flags).unwrap(); + fs::set_permissions(&flags, fs::Permissions::from_mode(0o700)).unwrap(); + let path = flags.join(format!("{nonce}.pending")); + let mut marker = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .unwrap(); + marker + .set_permissions(fs::Permissions::from_mode(0o600)) + .unwrap(); + marker.write_all(PENDING).unwrap(); + direct_sync_marker(&marker).unwrap(); + assert_eq!( + unsafe { libc::flock(marker.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + let original_image = fs::File::open(&self.core).unwrap(); + // Owner attachment is fixed at4. Bootstrap requires image5..1024. + let image_fd = + unsafe { libc::fcntl(original_image.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 5) }; + assert!((5..=1024).contains(&image_fd)); + let image = unsafe { fs::File::from_raw_fd(image_fd) }; + drop(original_image); + if replace_after_image_open { + let replacement = self.root.join("replacement-core"); + fs::copy(&self.core, &replacement).unwrap(); + fs::rename(replacement, &self.core).unwrap(); + } + let (mut reader, writer) = direct_pipe(); + // Scope's fault path intentionally withholds take_result output. + // Retain stderr independently for the existing privacy assertion; + // stdin/stdout and the internal stderr pipe remain Scope-owned. + let (mut error_reader, error_writer) = direct_pipe(); + let write_fd = writer.as_raw_fd(); + let error_fd = error_writer.as_raw_fd(); + let inventory = unsafe { libc::opendir(c"/dev/fd".as_ptr()) }; + assert!(!inventory.is_null()); + let own_inventory = unsafe { libc::dirfd(inventory) }; + let mut descriptors = Vec::new(); + loop { + let entry = unsafe { libc::readdir(inventory) }; + if entry.is_null() { + break; + } + let name = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) }; + if let Some(fd) = name.to_str().ok().and_then(|v| v.parse::().ok()) { + descriptors.push(fd); + } + } + let inherited = direct_close_inventory(image_fd, own_inventory, &descriptors); + unsafe { + libc::closedir(inventory); + } + let mut cmd = self.command(&self.core); + cmd.env("KEITO_CAPTURE_INVOCATION_NONCE", nonce) + .env("KEITO_CAPTURE_ACK_FD", "3") + .env("KEITO_CAPTURE_IMAGE_FD", image_fd.to_string()) + .env("KEITO_CAPTURE_LEAF_END_NS", leaf_end.to_string()) + .args([ + "capture", + "hook", + "--agent", + "codex", + "--event", + "prompt", + "--harness-version", + "0.167.0", + ]); + unsafe { + cmd.pre_exec(move || { + if !direct_admission_fresh(direct_clock()?, leaf_end) { + return Err(std::io::Error::from_raw_os_error(libc::ETIMEDOUT)); + } + if libc::setsid() < 0 + || libc::dup2(write_fd, 3) < 0 + || libc::dup2(error_fd, 2) < 0 + { + return Err(std::io::Error::last_os_error()); + } + if libc::fcntl(3, libc::F_SETFD, 0) < 0 + || libc::fcntl(image_fd, libc::F_SETFD, 0) < 0 + { + return Err(std::io::Error::last_os_error()); + } + for fd in &inherited { + libc::close(*fd); + } + // Scope appends its owner4 callback AFTER this callback. + // Its freshly allocated attachment descriptors were not in + // our earlier inventory; no private owner tuple is forged. + Ok(()) + }); + } + let mut scope = Scope::local_entry(parent_end).unwrap(); + assert!(direct_admission_fresh(direct_clock().unwrap(), leaf_end)); + let child = scope + .start_cooperative_with_io(cmd, IoPlan::new(input.to_vec(), 4096, 4096).unwrap()) + .unwrap(); + drop(writer); + drop(error_writer); + let mut ack = Vec::with_capacity(ACK.len() + 1); + let mut stderr = Vec::new(); + let (mut eof, mut error_eof) = (false, false); + let mut read_fault = false; + let mut observed_before_parent = false; + loop { + scope.poll(); + read_fault |= direct_read(&mut reader, &mut ack, &mut eof, ACK.len()).is_err(); + read_fault |= + direct_read(&mut error_reader, &mut stderr, &mut error_eof, STDERR_LIMIT) + .is_err(); + let report = scope.report(); + let slot = report.slots.first().unwrap(); + // Negative bootstrap/FAILED peers need not provide a clean + // terminal. Independently retain original wait and pipe facts. + let fresh = direct_clock().unwrap(); + if slot.waits_known + && slot.io.complete() + && eof + && error_eof + && (scope.slot_complete(&child) || scope.failed()) + && fresh < parent_end + { + observed_before_parent = true; + break; + } + if fresh >= parent_end { + break; + } + std::thread::sleep(Duration::from_millis(1)); + } + let output = if scope.slot_complete(&child) { + Some(scope.take_result(&child).unwrap()) + } else { + None + }; + let report = scope.finish(); + let slot = report.slots.first().unwrap(); + fs::write( + self.root.join("direct-ack-probe.json"), + serde_json::to_vec_pretty(&json!({ + "ack_bytes":ack.len(), "ack_eof":eof, "stderr_eof":error_eof, + "observed_before_parent":observed_before_parent, + "stderr_bytes":stderr.len(), "read_fault":read_fault, + "waits_known":slot.waits_known, "exit_code":slot.status.and_then(|s|s.code()), + "signal":slot.status.and_then(|s|s.signal()), "terminal_eof":slot.terminal_eof, + "stdin_closed":slot.io.stdin_closed, "stdout_eof":slot.io.stdout_eof, + "scope_stderr_eof":slot.io.stderr_eof, "io_fault":slot.io.first_fault, + "slot_fault":slot.first_fault, "scope_fault":report.first_fault.map(|e|e.0), + "whole_clean":report.clean, "all_resources":report.all_resources, + "leaf_end_ns":leaf_end, "parent_end_ns":parent_end, + "finality_limit":"negative refusal proves only independently observed facts; no clean-terminal or descendant proof is synthesized" + })).unwrap(), + ).unwrap(); + assert!( + !read_fault && eof && error_eof && observed_before_parent, + "direct ACK/stderr stream not boundedly settled" + ); + assert!( + slot.waits_known && slot.status.is_some() && slot.io.complete(), + "original child wait/stdio finality unknown" + ); + assert!(!String::from_utf8_lossy(&stderr).contains("PRIVATE_QUALIFICATION_CANARY")); + if !ack.is_empty() { + assert!( + slot.io.first_fault.is_none(), + "ACK with direct core stdio fault" + ); + assert!( + report.clean && slot.terminal_eof, + "ACK without cooperative settlement" + ); + let output = output + .as_ref() + .expect("ACK without retained command result"); + assert!(output.status.success()); + assert!(output.output.stdout.is_empty() && output.output.stderr.is_empty()); + } + drop(image); + drop(marker); + ack + } + } + pub fn run() { + let args: Vec<_> = std::env::args_os().skip(1).collect(); + assert_eq!( + args.len(), + 2, + "qualify-capture " + ); + let source = PathBuf::from(&args[0]).canonicalize().unwrap(); + let owner = PathBuf::from(&args[1]).canonicalize().unwrap(); + let meta = fs::symlink_metadata(&owner).unwrap(); + assert!( + meta.is_dir() + && meta.uid() == unsafe { libc::geteuid() } + && meta.mode() & 0o777 == 0o700 + && source.starts_with(&owner), + "source/run root must be isolated and run-owned" + ); + let mut random = [0u8; 16]; + assert_eq!( + unsafe { libc::getentropy(random.as_mut_ptr().cast(), random.len()) }, + 0 + ); + let nonce: String = random.iter().map(|b| format!("{b:02x}")).collect(); + let run = owner.join(format!("paired-qualification-{nonce}")); + fs::create_dir(&run).unwrap(); + fs::set_permissions(&run, fs::Permissions::from_mode(0o700)).unwrap(); + eprintln!("Preserved qualification evidence: {}", run.display()); + // FIRST execution of the extracted/copied pair. No version/help/runtime + // warm-up is permitted before this qualified actual hook invocation. + let positive = Case::new(&source, &run, "first"); + let first_observation = positive.observe_guard("prompt", &positive.input("cold")); + fs::write( + run.join("first-probe.json"), + serde_json::to_vec_pretty(&first_observation).unwrap(), + ) + .unwrap(); + Case::assert_guard(&first_observation); + let first = Duration::from_secs_f64(first_observation.elapsed_ms / 1000.0); + assert_eq!( + positive.flags(), + 0, + "first real core failed exact durable ACK/exit0" + ); + assert_eq!( + Store::open(&positive.capture) + .unwrap() + .status() + .unwrap() + .unfinished, + 1 + ); + positive.assert_private_state(); + positive.guard("stop", &positive.input("cold")); + assert_eq!(positive.flags(), 0); + let mut ack = Case::new(&source, &run, "exact-ack"); + ack.use_guarded_pair(&positive); + assert_eq!( + ack.direct_ack(&ack.input("ack"), &capture::hash("qualified_ack")), + b"KEITO_CAPTURE_DURABLE_V1\n" + ); + ack.assert_private_state(); + let malformed = Case::new(&source, &run, "malformed"); + assert!(malformed + .direct_ack( + b"{PRIVATE_QUALIFICATION_CANARY", + &capture::hash("malformed") + ) + .is_empty()); + assert_eq!(malformed.flags(), 1); + assert_eq!( + Store::open(&malformed.capture) + .unwrap() + .status() + .unwrap() + .unfinished, + 0 + ); + malformed.assert_private_state(); + for changed in ["core", "guard", "manifest"] { + let case = Case::new(&source, &run, &format!("changed-{changed}")); + match changed { + "core" => fs::write(&case.core, b"replaced inert core fixture").unwrap(), + "guard" => fs::write(&case.guard, b"replaced inert guard fixture").unwrap(), + _ => fs::write( + case.core + .parent() + .unwrap() + .join("capture-runtime-manifest.json"), + b"{}", + ) + .unwrap(), + } + if changed == "core" { + case.guard("prompt", &case.input("changed")); + } else { + assert!(case + .direct_ack(&case.input("changed"), &capture::hash(changed)) + .is_empty()); + } + case.assert_private_state(); + assert_eq!(case.flags(), 1); + assert_eq!( + Store::open(&case.capture) + .unwrap() + .status() + .unwrap() + .unfinished, + 0, + "changed pair accepted a boundary" + ); + } + let replaced = Case::new(&source, &run, "replaced-after-image-open"); + assert!(replaced + .direct_ack_replacement( + &replaced.input("replaced"), + &capture::hash("replaced_image"), + true + ) + .is_empty()); + assert_eq!(replaced.flags(), 1); + assert_eq!( + Store::open(&replaced.capture) + .unwrap() + .status() + .unwrap() + .unfinished, + 0 + ); + replaced.assert_private_state(); + let mut milliseconds = Vec::new(); + for n in 0..100 { + let session = format!("latency_{n}"); + milliseconds.push( + positive + .guard("prompt", &positive.input(&session)) + .as_secs_f64() + * 1000.0, + ); + positive.guard("stop", &positive.input(&session)); + assert_eq!(positive.flags(), 0); + } + positive.assert_private_state(); + milliseconds.sort_by(f64::total_cmp); + let p95 = milliseconds[94]; + let result = json!({"first_ms":first.as_secs_f64()*1000.0,"p95_ms":p95,"samples":100,"first_host_deadline_passed":first Case { + let root = PathBuf::from(cohort).join(name); + Case { + home: root.join("home"), + capture: root.join("home/capture"), + core: root.join("artifact/keito"), + guard: root.join("artifact/keito-capture-guard"), + bin: root.join("bin"), + repo: root.join("repo"), + core_hash: hash.into(), + root, + } + } + #[test] + fn direct_ack_reuses_only_guarded_pair_and_preserves_fresh_case_state() { + let guarded = isolated_case("/owned/cohort", "first", "same_core"); + let mut ack = isolated_case("/owned/cohort", "exact-ack", "same_core"); + let state = ( + ack.root.clone(), + ack.home.clone(), + ack.capture.clone(), + ack.repo.clone(), + ack.bin.clone(), + ); + ack.use_guarded_pair(&guarded); + assert_eq!(ack.core, guarded.core); + assert_eq!(ack.guard, guarded.guard); + assert_eq!((ack.root, ack.home, ack.capture, ack.repo, ack.bin), state); + } + #[test] + fn direct_ack_rejects_pair_from_another_cohort_or_core_identity() { + let guarded = isolated_case("/owned/cohort", "first", "same_core"); + let mut wrong_hash = isolated_case("/owned/cohort", "exact-ack", "different_core"); + assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe( + || wrong_hash.use_guarded_pair(&guarded) + )) + .is_err()); + let mut foreign = isolated_case("/foreign/cohort", "exact-ack", "same_core"); + assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe( + || foreign.use_guarded_pair(&guarded) + )) + .is_err()); + } + #[test] + fn leaf_admission_reserve_uses_the_original_absolute_bound() { + assert!(direct_admission_fresh(449_999_999, 500_000_000)); + assert!(!direct_admission_fresh(450_000_000, 500_000_000)); + assert!(!direct_admission_fresh(500_000_000, 500_000_000)); + assert!(!direct_admission_fresh(0, 1)); + } + } +} +fn main() { + #[cfg(unix)] + qualification::run(); + #[cfg(not(unix))] + { + eprintln!("Native capture artifact qualification is unsupported on this platform"); + std::process::exit(1); + } +} diff --git a/src/capture.rs b/src/capture.rs new file mode 100644 index 0000000..0c3d7a2 --- /dev/null +++ b/src/capture.rs @@ -0,0 +1,4254 @@ +//! Metadata-only durable capture. Raw hook JSON is never a storage type. +use crate::capture_authority::AuthorityGuard; +use crate::capture_invocations::{self, Permit}; +use crate::capture_usage::{ + read_active_session, read_active_session_excluding_request_ids, + read_active_session_request_ids, ApprovedActiveSession, Harness, +}; +use crate::capture_usage_ledger::UsageLedger; +use crate::cli::capture::CaptureEvent; +use crate::error::AppError; +use chrono::{DateTime, SecondsFormat}; +use rusqlite::{params, Connection, OptionalExtension, Transaction}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::fs::{self, OpenOptions}; +use std::io::Read; +use std::path::{Path, PathBuf}; +#[cfg(unix)] +use std::process::Command; +#[cfg(feature = "dev-tools")] +use std::time::Duration; + +pub const MAX_EVENT_BYTES: usize = 1024 * 1024; +pub const MAX_BODY_BYTES: usize = 16 * 1024; +const MAX_QUEUE_BYTES: i64 = 100 * 1024 * 1024; +const MAX_INTERVAL_SECONDS: i64 = 24 * 60 * 60; +const POLICY: &str = "METADATA_ONLY_OBSERVED_TURNS_V1"; + +fn storage_error(_: impl std::fmt::Display) -> AppError { + AppError::Config("Capture storage unavailable; inspect disk space and permissions. Evidence was not discarded.".into()) +} +pub fn hash(value: impl AsRef<[u8]>) -> String { + Sha256::digest(value.as_ref()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} +pub fn identifier(value: &str) -> Result<(), AppError> { + if value.is_empty() + || !value + .as_bytes() + .first() + .is_some_and(u8::is_ascii_alphanumeric) + || value.contains("..") + || value.len() > 128 + || !value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_.:-".contains(&b)) + || [ + "kto_", + "sk-", + "sk_", + "AKIA", + "ghp_", + "gho_", + "github_pat_", + "xoxb-", + "xoxp-", + ] + .iter() + .any(|p| value.starts_with(p)) + { + return Err(AppError::InvalidInput( + "Capture identifier rejected; use an opaque identifier without paths or credentials" + .into(), + )); + } + Ok(()) +} +pub fn version_identifier(value: &str) -> Result<(), AppError> { + identifier(value) +} + +fn timestamp(seconds: i64) -> Result { + DateTime::from_timestamp(seconds, 0) + .map(|d| d.to_rfc3339_opts(SecondsFormat::Secs, true)) + .ok_or_else(|| AppError::InvalidInput("Invalid capture clock".into())) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Clock { + pub wall: i64, + pub monotonic: i64, + pub boot: String, +} +#[cfg(target_os = "macos")] +fn native_boot_identity_from( + read: impl FnOnce(&mut libc::timeval, &mut usize) -> i32, +) -> Option { + let mut value = libc::timeval { + tv_sec: 0, + tv_usec: 0, + }; + let mut length = std::mem::size_of::(); + if read(&mut value, &mut length) != 0 + || length != std::mem::size_of::() + || value.tv_sec <= 0 + || !(0..1_000_000).contains(&value.tv_usec) + { + return None; + } + // Never hash ABI padding, localized dates or environment-controlled text. + // A pre-upgrade active clock deliberately differs and closes incomplete. + Some(hash(format!( + "macos-kern-boottime-v1:{}:{}", + value.tv_sec, value.tv_usec + ))) +} +#[cfg(target_os = "macos")] +fn native_boot_identity() -> Option { + native_boot_identity_from(|value, length| { + let mut mib = [libc::CTL_KERN, libc::KERN_BOOTTIME]; + // Fixed read-only MIB and exact initialized output ABI. NULL newp and + // zero newlen prohibit a write; no subprocess, cache or fallback. + unsafe { + libc::sysctl( + mib.as_mut_ptr(), + mib.len() as libc::c_uint, + (value as *mut libc::timeval).cast(), + length, + std::ptr::null_mut(), + 0, + ) + } + }) +} +impl Clock { + #[cfg(unix)] + pub fn now() -> Result { + let mut owner = crate::capture_command_owner::CommandOwner::standalone()?; + let result = Self::now_with(&mut owner); + owner.finish(result) + } + #[cfg(unix)] + pub(crate) fn now_with( + runner: &mut impl crate::process_ownership::probes::LeafRunner, + ) -> Result { + // Retain the explicit containing runner API. macOS boot metadata is + // now a direct read; repository commands still use the same owner. + let _ = runner; + let mut time = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // CLOCK_MONOTONIC is system-wide across hook processes, unlike Instant. + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut time) } != 0 { + return Err(AppError::Config( + "Monotonic clock unavailable; capture paused".into(), + )); + } + #[cfg(target_os = "macos")] + let boot = native_boot_identity(); + #[cfg(not(target_os = "macos"))] + let boot = { fs::read("/proc/sys/kernel/random/boot_id").ok().map(hash) }; + Ok(Self { + wall: chrono::Utc::now().timestamp(), + monotonic: time.tv_sec, + boot: boot.ok_or_else(|| { + AppError::Config("Boot identity unavailable; capture paused".into()) + })?, + }) + } + #[cfg(not(unix))] + pub fn now() -> Result { + Err(AppError::Config( + "Capture timing is not qualified on this platform".into(), + )) + } + fn elapsed(&self, end: &Self) -> Option { + let wall = end.wall.checked_sub(self.wall)?; + let mono = end.monotonic.checked_sub(self.monotonic)?; + (self.boot == end.boot + && (0..=MAX_INTERVAL_SECONDS).contains(&wall) + && (0..=MAX_INTERVAL_SECONDS).contains(&mono) + && (wall - mono).abs() <= 2) + .then_some(wall) + } +} + +#[derive(Clone, Debug)] +pub struct Repository { + pub key: String, + pub remote_hash: String, + pub hint_hash: String, + pub linked_without_hint: bool, + pub disabled: bool, +} +#[cfg(unix)] +fn repository_command(directory: &Path, args: &[&str]) -> Command { + let mut command = Command::new("git"); + command.arg("-C").arg(directory).args(args); + command +} +#[cfg(unix)] +fn repository_ownership_error(_: std::io::Error) -> AppError { + AppError::Config("Repository command ownership unavailable; capture paused".into()) +} +#[cfg(unix)] +fn repository_text( + result: crate::process_ownership::scope::CommandResult, + empty_no_match: bool, +) -> Result { + crate::process_ownership::probes::text(result, empty_no_match) + .map_err(|_| AppError::Config("Capture requires an identifiable Git repository".into())) +} +#[cfg(unix)] +fn git_with( + runner: &mut impl crate::process_ownership::probes::LeafRunner, + directory: &Path, + args: &[&str], + empty_no_match: bool, +) -> Result { + let command = repository_command(directory, args); + let result = runner + .output( + command, + if empty_no_match { 1024 * 1024 } else { 8192 }, + 8192, + ) + .map_err(repository_ownership_error)?; + repository_text(result, empty_no_match) +} +impl Repository { + pub fn matches_binding(&self, binding: &Binding) -> bool { + !self.disabled + && self.remote_hash == binding.remote_hash + && (self.linked_without_hint || self.hint_hash == binding.hint_hash) + } + pub fn resolve(directory: &Path) -> Result { + #[cfg(unix)] + { + let mut owner = crate::capture_command_owner::CommandOwner::standalone()?; + let result = Self::resolve_with(directory, &mut owner); + owner.finish(result) + } + #[cfg(not(unix))] + { + let _ = directory; + Err(AppError::Config("Automatic capture is unsupported on this platform; manual time commands remain available".into())) + } + } + #[cfg(unix)] + pub(crate) fn resolve_with( + directory: &Path, + runner: &mut impl crate::process_ownership::probes::LeafRunner, + ) -> Result { + let root_args = &["rev-parse", "--show-toplevel"]; + let common_args = &["rev-parse", "--path-format=absolute", "--git-common-dir"]; + let identity_args = &[ + "rev-parse", + "--path-format=absolute", + "--show-toplevel", + "--git-common-dir", + ]; + let remotes_args = &["config", "--get-regexp", "^remote\\..*\\.url$"]; + let cohort = runner + .repository_outputs([ + repository_command(directory, identity_args), + repository_command(directory, remotes_args), + ]) + .transpose() + .map_err(repository_ownership_error)?; + let (root, common, remotes) = match cohort { + Some([identity, remotes]) => { + let identity = crate::process_ownership::probes::text_untrimmed(identity, false) + .map_err(|_| { + AppError::Config("Capture requires an identifiable Git repository".into()) + })?; + let remotes = repository_text(remotes, true)?; + let framed = identity.strip_suffix('\n').unwrap_or(&identity); + let mut lines = framed.split('\n'); + let root = lines.next().unwrap_or_default(); + let common = lines.next().ok_or_else(|| { + AppError::Config("Capture requires an identifiable Git repository".into()) + })?; + let (root, common) = if lines.next().is_some() { + // Git does not quote these paths, even with --sq. Never + // guess a newline-containing pathname's field boundary. + // Read the original two commands under the SAME owner/end. + ( + git_with(runner, directory, root_args, false)?, + git_with(runner, directory, common_args, false)?, + ) + } else if root.is_empty() + || common.is_empty() + || root.len() >= 8192 + || common.len() >= 8192 + { + return Err(AppError::Config( + "Capture requires an identifiable Git repository".into(), + )); + } else { + // Match the legacy classifier for EACH scalar; approval + // and hooks must select the same mapping/disabled policy. + let root = root.trim(); + let common = common.trim(); + if root.is_empty() || common.is_empty() { + return Err(AppError::Config( + "Capture requires an identifiable Git repository".into(), + )); + } + (root.to_owned(), common.to_owned()) + }; + ( + PathBuf::from(root).canonicalize().map_err(storage_error)?, + PathBuf::from(common) + .canonicalize() + .map_err(storage_error)?, + remotes, + ) + } + None => { + let root = PathBuf::from(git_with(runner, directory, root_args, false)?) + .canonicalize() + .map_err(storage_error)?; + let common = PathBuf::from(git_with(runner, directory, common_args, false)?) + .canonicalize() + .map_err(storage_error)?; + ( + root, + common, + git_with(runner, directory, remotes_args, true)?, + ) + } + }; + // All remotes participate in consent; adding/replacing one invalidates it. + // Raw remotes may contain credentials. Only their digest is ever retained. + let mut remotes: Vec<_> = remotes.lines().collect(); + remotes.sort_unstable(); + let key = hash(common.to_string_lossy().as_bytes()); + let remote_hash = hash(remotes.join("\n")); + let hint_path = root.join(".keito/config.yml"); + let mut disabled = false; + let hint_hash = if hint_path.exists() { + if fs::symlink_metadata(&hint_path) + .map_err(storage_error)? + .file_type() + .is_symlink() + { + return Err(AppError::Config( + "Repository mapping hint cannot be a symlink".into(), + )); + } + let file = fs::File::open(&hint_path).map_err(storage_error)?; + let mut bytes = Vec::new(); + file.take(64 * 1024 + 1) + .read_to_end(&mut bytes) + .map_err(storage_error)?; + if bytes.len() > 64 * 1024 { + return Err(AppError::Config("Repository mapping hint too large".into())); + } + // Hash only mapping/policy fields, never persist the original YAML. + let mut budget = serde_saphyr::Budget::default(); + budget.max_depth = 16; + budget.max_events = 4096; + budget.max_nodes = 2048; + budget.max_documents = 1; + budget.max_aliases = 64; + budget.max_anchors = 16; + budget.max_recorded_anchor_events = 4096; + budget.max_recorded_anchor_bytes = 64 * 1024; + budget.max_total_scalar_bytes = 64 * 1024; + let mut options = serde_saphyr::Options::default(); + options.budget = Some(budget); + options.alias_limits.max_total_replayed_events = 4096; + options.alias_limits.max_replay_stack_depth = 16; + options.alias_limits.max_alias_expansions_per_anchor = 64; + let yaml: serde_json::Value = serde_saphyr::from_slice_with_options(&bytes, options) + .map_err(|_| { + AppError::Config("Invalid or over-budget repository mapping hint".into()) + })?; + disabled = yaml + .get("agent_tracking") + .and_then(|v| v.get("enabled")) + .and_then(|v| v.as_bool()) + == Some(false); + let fields = [ + "workspace_id", + "client_id", + "project_id", + "task_id", + "agent_tracking", + ]; + let allowlisted: Vec<_> = fields.iter().map(|k| (k, yaml.get(*k).cloned())).collect(); + hash(serde_json::to_vec(&allowlisted).map_err(storage_error)?) + } else { + hash(b"no-mapping-hint") + }; + let linked_without_hint = root.join(".git").is_file() && !hint_path.exists(); + Ok(Self { + key, + remote_hash, + hint_hash, + linked_without_hint, + disabled, + }) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Binding { + pub repository_key: String, + #[serde(default)] + pub remote_hash: String, + pub hint_hash: String, + pub id: String, + pub version: i64, + pub workspace_id: String, + pub owner_id: String, + pub origin_hash: String, + pub project_id: String, + pub task_id: String, + pub agents: Vec, + pub paused: bool, + pub revoked: bool, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Segment { + pub segment_key: String, + pub started_at: String, + pub ended_at: String, + pub duration_seconds: i64, + pub completeness: String, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +struct ActiveTurn { + key: String, + clock: Option, + part: usize, +} +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct NumericAuthority { + profile_id: String, + profile_digest: String, + epoch: u64, + #[serde(default)] + source_identity: Option, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Session { + pub id: String, + pub source_session_id: String, + pub source_namespace: String, + pub harness_version: String, + pub binding: Binding, + pub started_at: i64, + pub observed_through: i64, + active: Option, + pub segments: Vec, + queued_segments: usize, + generation: i64, + pub revision: i64, + pub lifecycle: String, + last_turn: Option, + seen_turns: std::collections::BTreeSet, + queued_lifecycle: String, + pub needs_attention: bool, + #[serde(default)] + pub canonical_server_id: Option, + #[serde(default)] + usage_ledger: UsageLedger, + #[serde(default)] + numeric_authority: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CapturePayload { + pub schema_version: u8, + pub source_namespace: String, + pub source_session_id: String, + pub revision: i64, + pub expected_revision: i64, + pub harness_version: String, + pub repository_binding_id: String, + pub binding_version: i64, + pub project_id: String, + pub task_id: String, + pub work_kind: String, + pub lifecycle: String, + pub started_at: String, + pub observed_through: String, + pub measurement_method: String, + pub segments: Vec, + pub usage: serde_json::Value, +} +fn canonical_session_key(binding: &Binding, source: &str, session_id: &str) -> String { + hash(format!( + "{}\0{}\0{}\0{}\0{}", + binding.origin_hash, binding.workspace_id, binding.owner_id, source, session_id + )) +} +impl Session { + fn begin( + binding: &Binding, + source: &str, + session_id: &str, + version: &str, + clock: &Clock, + ) -> Self { + Self { + id: canonical_session_key(binding, source, session_id), + source_session_id: session_id.into(), + source_namespace: source.into(), + binding: binding.clone(), + harness_version: version.into(), + started_at: clock.wall, + observed_through: clock.wall, + active: None, + segments: vec![], + queued_segments: 0, + generation: 0, + revision: 0, + lifecycle: "ACTIVE".into(), + last_turn: None, + seen_turns: Default::default(), + queued_lifecycle: "ACTIVE".into(), + needs_attention: false, + canonical_server_id: None, + usage_ledger: UsageLedger::default(), + numeric_authority: None, + } + } + fn close(&mut self, clock: &Clock, complete: bool) -> Result<(), AppError> { + if let Some(mut active) = self.active.take() { + if let Some(start) = active.clock.take() { + let elapsed = start.elapsed(clock).filter(|_| complete); + let seconds = elapsed.unwrap_or(0); + let end = if elapsed.is_some() { + clock.wall + } else { + start.wall + }; + self.segments.push(Segment { + segment_key: hash(format!("{}-{}", active.key, active.part)), + started_at: timestamp(start.wall)?, + ended_at: timestamp(end)?, + duration_seconds: seconds, + completeness: if elapsed.is_some() { + "COMPLETE" + } else { + self.needs_attention = true; + "INCOMPLETE" + } + .into(), + }); + } + self.seen_turns.insert(active.key.clone()); + if !complete { + self.needs_attention = true; + } + self.last_turn = Some(active.key); + } + self.observed_through = self.observed_through.max(clock.wall); + Ok(()) + } + fn abandon_native_resume(&mut self, clock: &Clock) -> Result<(), AppError> { + let paused = self + .active + .as_ref() + .filter(|active| active.clock.is_none()) + .map(|active| (active.key.clone(), active.part, self.observed_through)); + self.close(clock, false)?; + if let Some((turn, part, anchor)) = paused { + // The pause boundary is known; the resumed continuation was never + // measured. Preserve a zero-second incomplete marker for reviewers. + self.segments.push(Segment { + segment_key: hash(format!("{turn}-{part}")), + started_at: timestamp(anchor)?, + ended_at: timestamp(anchor)?, + duration_seconds: 0, + completeness: "INCOMPLETE".into(), + }); + } + Ok(()) + } + fn abandon_active(&mut self) -> Result<(), AppError> { + let clock = self + .active + .as_ref() + .and_then(|turn| turn.clock.clone()) + .unwrap_or(Clock { + wall: self.observed_through, + monotonic: 0, + boot: "UNOBSERVED_BOUNDARY".into(), + }); + self.close(&clock, false) + } + fn payload(&self, segments: Vec, revision: i64) -> Result { + Ok(CapturePayload { + schema_version: 1, + source_namespace: self.source_namespace.clone(), + source_session_id: self.source_session_id.clone(), + revision, + expected_revision: revision - 1, + harness_version: self.harness_version.clone(), + repository_binding_id: self.binding.id.clone(), + binding_version: self.binding.version, + project_id: self.binding.project_id.clone(), + task_id: self.binding.task_id.clone(), + work_kind: "HUMAN_ASSISTED_AGENT_ACTIVITY".into(), + lifecycle: self.lifecycle.clone(), + started_at: timestamp(self.started_at)?, + observed_through: timestamp(self.observed_through)?, + measurement_method: "OBSERVED_TURN_INTERVALS_V1".into(), + segments, + usage: serde_json::json!({"status":"UNAVAILABLE","reason":"NO_QUALIFIED_USAGE_EVIDENCE","models":[]}), + }) + } +} + +/// Private transient input. It is never serialized, logged or stored. Ordinary +/// production callers cannot construct a synthetic qualification capability. +struct UsageSource<'a> { + resolved_home: &'a Path, + exact_hook_path: &'a Path, + qualified_source: &'a str, + qualified_native_session: &'a str, +} +#[cfg(unix)] +struct NormalHookInput<'a> { + path: Option<&'a Path>, + runtime: Option<&'a crate::capture_runtime_pair::HookRuntime>, +} +#[cfg(not(unix))] +type NormalHookInput<'a> = std::marker::PhantomData<&'a ()>; + +#[cfg(unix)] +struct NormalFactoryArgs<'a, 'r> { + connection: &'a Connection, + directory: &'a Path, + invocation: Option<&'a Permit>, + binding: &'a Binding, + source: &'a str, + source_id: &'a str, + version: &'a str, + event: CaptureEvent, + input: NormalHookInput<'r>, +} +#[cfg(unix)] +struct EventFinalization<'a> { + id: &'a str, + binding: &'a Binding, + source_id: &'a str, + was_refused: bool, + time_only: Option<&'a Session>, +} +#[cfg(unix)] +struct NormalFactory<'r> { + policy: Option, + runtime: Option<&'r crate::capture_runtime_pair::HookRuntime>, + approved: Option, + profile: Option, + origin: Option, + source_lease: Option, + reason: Option<&'static str>, + invalidate: bool, +} +#[cfg(unix)] +impl NormalFactory<'_> { + fn fail(&mut self, session: &mut Session, reason: &'static str) { + self.reason = Some(reason); + self.invalidate |= matches!( + reason, + "PROFILE_CHANGED" + | "HARNESS_CHANGED" + | "REGISTRATION_CHANGED" + | "RUNTIME_CHANGED" + | "UNSUPPORTED_HARNESS_VERSION" + ); + session.usage_ledger.require_baseline(); + if self.invalidate { + session.numeric_authority = None; + } else if let Some(authority) = &mut session.numeric_authority { + authority.source_identity = None; + } + } + fn observe( + &mut self, + session: &mut Session, + event: CaptureEvent, + source: &str, + version: &str, + source_id: &str, + ) { + if self.policy.is_none() { + return; + } + if let Some(reason) = self.reason { + self.fail(session, reason); + return; + } + if let Err(reason) = self.valid() { + self.fail(session, reason); + return; + } + let Some(approved) = self.approved.as_ref() else { + return; + }; + if event == CaptureEvent::Prompt { + match crate::capture_usage::read_request_ids_leased(approved) { + Ok((baseline, lease)) + if baseline.source_session_id == source_id + && baseline.harness_version == version + && baseline.limitations.is_empty() + && baseline.source_adapter + == if source == "claude-code" { + "CLAUDE_JSONL_2_1_319_V1" + } else { + "CODEX_ROLLOUT_0_167_0_V1" + } => + { + let Some(identity) = lease.identity() else { + self.fail(session, "SOURCE_CHANGED"); + return; + }; + let same_source = session + .numeric_authority + .as_ref() + .and_then(|authority| authority.source_identity.as_ref()) + == Some(&identity); + if !same_source && session.usage_ledger.baseline_ready() { + session.usage_ledger.require_baseline(); + } + if !session.usage_ledger.baseline_ready() + && !session.usage_ledger.establish_baseline(baseline.record_ids) + { + self.fail(session, "SOURCE_PARSE_UNAVAILABLE"); + return; + } + if let Some(authority) = &mut session.numeric_authority { + authority.source_identity = Some(identity); + } + self.source_lease = Some(lease); + self.reason = Some("OBSERVED_REQUEST_RECORDS"); + } + _ => self.fail(session, "SOURCE_PARSE_UNAVAILABLE"), + } + } else if matches!(event, CaptureEvent::Stop | CaptureEvent::SessionEnd) { + let Some(identity) = session + .numeric_authority + .as_ref() + .and_then(|authority| authority.source_identity.as_deref()) + else { + self.fail(session, "MISSING_QUALIFIED_PROMPT"); + return; + }; + match crate::capture_usage::read_requests_leased( + approved, + &session.usage_ledger.excluded_request_ids, + identity, + ) { + Ok((evidence, lease)) => { + session + .usage_ledger + .observe(evidence, source, version, source_id); + self.source_lease = Some(lease); + self.reason = Some("OBSERVED_REQUEST_RECORDS"); + } + Err(crate::capture_usage::UsageReadError::SourceChanged) => { + self.fail(session, "SOURCE_CHANGED") + } + Err(_) => self.fail(session, "SOURCE_PARSE_UNAVAILABLE"), + } + } + } + fn validate_current( + &self, + connection: &Connection, + binding: &Binding, + ) -> Result, AppError> { + // An invalidating failure has already discarded this boundary's new + // numeric state. Its own transactional revocation is expected; do not + // replace the specific local failure reason with "disabled" afterward. + if self.invalidate { + return Ok(Ok(())); + } + if let Some(policy) = &self.policy { + if !Store::policy_current(connection, binding, policy)? { + return Ok(Err("NUMERIC_CAPTURE_DISABLED")); + } + } + Ok(self.valid()) + } + fn valid(&self) -> Result<(), &'static str> { + if let (Some(profile), Some(runtime)) = (&self.profile, self.runtime) { + profile.validate(runtime.identity())?; + } + if self.origin.as_ref().is_some_and(|origin| !origin.valid()) { + return Err("HARNESS_ORIGIN_UNAVAILABLE"); + } + if self + .source_lease + .as_ref() + .is_some_and(|lease| !lease.valid()) + { + return Err("SOURCE_CHANGED"); + } + Ok(()) + } +} + +pub struct Signal<'a> { + pub source: &'a str, + pub resumed: bool, + pub source_id: &'a str, + pub turn_id: Option<&'a str>, + pub version: &'a str, + pub event: CaptureEvent, + pub clock: &'a Clock, +} + +struct CaptureTransaction<'a> { + inner: Transaction<'a>, + _authority: AuthorityGuard, + notification: Option, + directory: PathBuf, + invocation: Option, + #[cfg(feature = "dev-tools")] + admitted_at: std::time::Instant, + #[cfg(feature = "dev-tools")] + timing: &'a AdmissionTiming, +} +impl<'a> std::ops::Deref for CaptureTransaction<'a> { + type Target = Transaction<'a>; + fn deref(&self) -> &Self::Target { + &self.inner + } +} +impl CaptureTransaction<'_> { + fn failure(&self) -> Result, AppError> { + Ok(read_failure_markers(&self.directory)? + .into_iter() + .next() + .map(|(_, failure)| failure)) + } + fn ensure_no_new_refusal(&self, was_refused: bool) -> Result<(), AppError> { + if !was_refused && self.failure()?.is_some() { + return Err(AppError::Config( + "Capture authority changed during this boundary; collection remains paused".into(), + )); + } + Ok(()) + } + fn commit(self) -> Result<(), AppError> { + let Self { + inner, + _authority, + notification, + directory, + invocation, + #[cfg(feature = "dev-tools")] + admitted_at, + #[cfg(feature = "dev-tools")] + timing, + } = self; + if let Some(invocation) = invocation { + crate::capture_profile_measure!(PermitValidation, invocation.validate(&directory))?; + } + #[cfg(feature = "dev-tools")] + let commit_started = { + // Includes authority acquisition and every fresh check before commit. + // This receipt describes only transactions reaching commit admission. + timing + .transaction_before_commit + .set(Some(admitted_at.elapsed())); + std::time::Instant::now() + }; + let committed = crate::capture_profile_measure!(Commit, inner.commit()); + #[cfg(feature = "dev-tools")] + timing.commit.set(Some(commit_started.elapsed())); + committed.map_err(storage_error)?; + drop(_authority); + if let Some(notification) = notification { + notification.released_after_authority(); + } + Ok(()) + } +} +/// Developer-only passive phase observations; no identifiers, paths or payloads. +#[cfg(feature = "dev-tools")] +#[derive(Clone, Debug, Default)] +pub struct AdmissionTiming { + pub permit_validation: Option, + pub sqlite_begin: Option, + pub sqlite_error: Option, + pub authority: Option, + /// After successful BEGIN through final permit validation, before COMMIT. + /// None means no commit-admission receipt, not a zero-duration transaction. + pub transaction_before_commit: std::cell::Cell>, + /// The original COMMIT call, including its failure/rollback path if any. + pub commit: std::cell::Cell>, +} + +pub struct Store { + #[cfg(feature = "dev-tools")] + last_admission_timing: Option, + connection: Connection, + notification: Option, + directory: PathBuf, + invocation: Option, +} +#[derive(Debug, Serialize)] +pub struct QueueState { + pub source_session_id: String, + pub revision: i64, + pub state: String, + pub reason: Option, + pub attempts: i64, + pub retry_at: i64, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CaptureFailure { + pub reason: String, + pub boundary_id: String, + pub observed_at: i64, + #[cfg(feature = "dev-tools")] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub probe: Option, +} +// Source-fixture diagnosis only. The default installed marker schema remains +// unchanged. No path, error body, command, native identity or payload can enter. +#[cfg(feature = "dev-tools")] +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HookFailurePhase { + Input, + Parse, + Repository, + Store, + Permit, + Clock, + Event, +} +#[cfg(feature = "dev-tools")] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HookOwnerFault { + GroupDeadline, + GroupLifetime, + OperationDeadline, + ProofDeadline, + CleanupDeadline, + Clock, + Other, +} +#[cfg(all(feature = "dev-tools", any(unix, test)))] +impl HookOwnerFault { + pub(crate) fn from_static(reason: &'static str) -> Self { + match reason { + "GROUP_DEADLINE" => Self::GroupDeadline, + "GROUP_LIFETIME" => Self::GroupLifetime, + "SCOPE_OPERATION_DEADLINE" | "SCOPE_SETUP_DEADLINE" => Self::OperationDeadline, + "SCOPE_PROOF_DEADLINE" => Self::ProofDeadline, + "SCOPE_CLEANUP_DEADLINE" => Self::CleanupDeadline, + "SCOPE_CLOCK" | "GROUP_CLOCK" => Self::Clock, + _ => Self::Other, + } + } +} +#[cfg(feature = "dev-tools")] +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HookReadyEdge { + BeforeReceive, + AfterReceive, + ParkBeforeReceive, + ParkAfterReceive, +} +#[cfg(feature = "dev-tools")] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HookGroupState { + AwaitReady, + Ready, + Joined, + Parked, + Cleaning, + Gone, + Released, + Failed, + Other, +} +#[cfg(feature = "dev-tools")] +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HookSetupProbe { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fault_state: Option, + pub ready_window_ns: Option, + pub pre_spawn_offset_ns: Option, + pub spawn_return_offset_ns: Option, + pub first_ready_poll_offset_ns: Option, + pub deadline_offset_ns: Option, + pub ready_frame_observed: bool, + pub ready_eof_observed: bool, + pub deadline_edge: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub park_end_offset_ns: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub workload_spawn_return_offset_ns: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub first_park_poll_offset_ns: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub park_frame_observed: Option, +} +#[cfg(feature = "dev-tools")] +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HookFailureProbe { + pub phase: HookFailurePhase, + pub owner_fault: Option, + pub setup: Option, +} +#[derive(Debug, Serialize)] +pub struct Status { + pub policy: &'static str, + pub pending: i64, + pub held: i64, + pub needs_attention: i64, + pub delivery_verified: bool, + pub trusted: &'static str, + pub bindings: Vec, + pub unfinished: i64, + pub queue: Vec, + pub queue_truncated: bool, + pub storage_paused: bool, + pub storage_reason: Option, + pub capture_failure: Option, + pub pending_invocations: usize, +} +#[derive(Clone, Debug)] +pub struct Queued { + pub id: i64, + pub body: String, + pub hash: String, + pub attempts: i64, + pub session_id: String, + pub revision: i64, + pub canonical_server_id: Option, +} +impl Store { + pub fn open(directory: &Path) -> Result { + if directory.exists() + && fs::symlink_metadata(directory) + .map_err(storage_error)? + .file_type() + .is_symlink() + { + return Err(AppError::Config( + "Capture storage cannot be a symlink".into(), + )); + } + fs::create_dir_all(directory).map_err(storage_error)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(directory, fs::Permissions::from_mode(0o700)) + .map_err(storage_error)?; + } + let path = directory.join("capture.sqlite3"); + if path.exists() + && fs::symlink_metadata(&path) + .map_err(storage_error)? + .file_type() + .is_symlink() + { + return Err(AppError::Config( + "Capture database cannot be a symlink".into(), + )); + } + if !path.exists() { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + match options.open(&path) { + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(storage_error(e)), + } + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).map_err(storage_error)?; + } + let mut connection = Connection::open(&path).map_err(storage_error)?; + let notification = crate::capture_busy::ReleaseNotifier::for_database(&path); + let busy_notification = notification.clone(); + let origin = std::time::Instant::now(); + let mut admission_budget = crate::capture_busy::BusyBudget::default(); + connection + .busy_handler(Some(move |count| { + admission_budget.retry_hinted( + count, + || std::time::Instant::now().checked_duration_since(origin), + |delay, hints_allowed| match &busy_notification { + Some(notification) if hints_allowed => notification.wait(delay), + _ => { + std::thread::sleep(delay); + false + } + }, + ) + })) + .map_err(storage_error)?; + connection.execute_batch("PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA max_page_count=25600; + CREATE TABLE IF NOT EXISTS bindings (repo_key TEXT PRIMARY KEY, data TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, binding_id TEXT NOT NULL, source_id TEXT NOT NULL, data TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS outbox (id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, revision INTEGER NOT NULL, body TEXT NOT NULL, + payload_hash TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, + retry_at INTEGER NOT NULL DEFAULT 0, claimed_until INTEGER NOT NULL DEFAULT 0, reason TEXT, + acknowledged_at INTEGER, UNIQUE(session_id,revision)); + CREATE TABLE IF NOT EXISTS usage_consents (binding_id TEXT NOT NULL, namespace TEXT NOT NULL, data TEXT NOT NULL, + PRIMARY KEY(binding_id,namespace));").map_err(storage_error)?; + Ok(Self { + connection, + notification, + directory: directory.to_owned(), + invocation: None, + #[cfg(feature = "dev-tools")] + last_admission_timing: None, + }) + } + #[cfg(feature = "dev-tools")] + #[doc(hidden)] + pub fn last_admission_timing(&self) -> Option<&AdmissionTiming> { + self.last_admission_timing.as_ref() + } + + pub fn hook_invocation(&mut self, nonce: &str) -> Result<(), AppError> { + self.invocation = Some(Permit::new(&self.directory, nonce)?); + Ok(()) + } + pub fn acknowledge_hook(&self, fd: i32) -> Result<(), AppError> { + self.invocation + .as_ref() + .ok_or_else(|| storage_error("missing invocation"))? + .acknowledge(&self.directory, fd) + } + pub fn invocations_pending(&self) -> Result { + Ok(!capture_invocations::snapshot(&self.directory)?.is_empty()) + } + fn transaction(&mut self) -> Result, AppError> { + self.transaction_for_event(false) + } + fn transaction_for_event(&mut self, event: bool) -> Result, AppError> { + #[cfg(feature = "dev-tools")] + let permit_started = { + self.last_admission_timing = Some(AdmissionTiming::default()); + std::time::Instant::now() + }; + let directory = self.directory.clone(); + let invocation = if event { self.invocation.clone() } else { None }; + if let Some(permit) = &invocation { + crate::capture_profile_measure!(PermitValidation, permit.validate(&directory))?; + } + #[cfg(feature = "dev-tools")] + let sqlite_started = { + self.last_admission_timing + .as_mut() + .unwrap() + .permit_validation = Some(permit_started.elapsed()); + std::time::Instant::now() + }; + #[cfg(all(unix, feature = "capture-profile"))] + let profile_sqlite_begin = + crate::capture_profile::Span::start(crate::capture_profile::Phase::SqliteBegin); + let admission = self + .connection + .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate); + #[cfg(all(unix, feature = "capture-profile"))] + drop(profile_sqlite_begin); + #[cfg(feature = "dev-tools")] + { + let timing = self.last_admission_timing.as_mut().unwrap(); + timing.sqlite_begin = Some(sqlite_started.elapsed()); + timing.sqlite_error = admission + .as_ref() + .err() + .and_then(rusqlite::Error::sqlite_error_code); + } + let inner = admission.map_err(storage_error)?; + #[cfg(feature = "dev-tools")] + let admitted_at = std::time::Instant::now(); + #[cfg(feature = "dev-tools")] + let authority_started = std::time::Instant::now(); + let authority = crate::capture_profile_measure!( + AuthorityAcquire, + AuthorityGuard::acquire(&directory, true) + ); + #[cfg(feature = "dev-tools")] + { + self.last_admission_timing.as_mut().unwrap().authority = + Some(authority_started.elapsed()); + } + let authority = authority?; + if let Some(permit) = &invocation { + crate::capture_profile_measure!(PermitValidation, permit.validate(&directory))?; + } + let tx = CaptureTransaction { + inner, + _authority: authority, + notification: self.notification.clone(), + directory, + invocation, + #[cfg(feature = "dev-tools")] + admitted_at, + #[cfg(feature = "dev-tools")] + timing: self.last_admission_timing.as_ref().unwrap(), + }; + let markers = capture_invocations::snapshot(&tx.directory)?; + for marker in markers.iter().filter(|m| !m.live) { + let boundary = hash(format!("INVOCATION\0{}", marker.nonce)); + if !read_failure_markers(&tx.directory)? + .iter() + .any(|(_, f)| f.boundary_id == boundary) + { + record_failure(&tx.directory, &boundary, "BOUNDARY_REFUSED")?; + } + } + if markers.iter().any(|m| !m.live) { + Self::reconcile_refusal(&tx)?; + } + Ok(tx) + } + fn check_size(tx: &Transaction<'_>) -> Result<(), AppError> { + let pages: i64 = tx + .query_row("PRAGMA page_count", [], |r| r.get(0)) + .map_err(storage_error)?; + let page_size: i64 = tx + .query_row("PRAGMA page_size", [], |r| r.get(0)) + .map_err(storage_error)?; + if pages * page_size >= MAX_QUEUE_BYTES - 64 * 1024 { + return Err(AppError::Config( + "Capture queue limit reached; sync or inspect held evidence. Nothing was evicted." + .into(), + )); + } + Ok(()) + } + pub fn approve(&mut self, mut binding: Binding) -> Result { + for value in [ + &binding.workspace_id, + &binding.owner_id, + &binding.project_id, + &binding.task_id, + ] { + identifier(value)?; + } + let tx = self.transaction()?; + let refused = tx.failure()?.is_some(); + if refused { + Self::reconcile_refusal(&tx)?; + } + Self::check_size(&tx)?; + let previous = Self::binding_in(&tx, &binding.repository_key)?; + if let Some(old) = &previous { + // Repeating metadata-only setup never renews numeric permission. + Self::revoke_numeric_binding(&tx, old)?; + if old.remote_hash == binding.remote_hash + && old.hint_hash == binding.hint_hash + && old.workspace_id == binding.workspace_id + && old.owner_id == binding.owner_id + && old.origin_hash == binding.origin_hash + && old.project_id == binding.project_id + && old.task_id == binding.task_id + { + Self::abandon_revoked_turns( + &tx, + &old.id, + if old.revoked { &[] } else { &binding.agents }, + )?; + binding.id = old.id.clone(); + binding.version = old.version; + binding.paused = old.paused && !old.revoked; + binding.revoked = false; + tx.execute( + "UPDATE bindings SET data=?2 WHERE repo_key=?1", + params![ + binding.repository_key, + serde_json::to_string(&binding).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + let mut statement=tx.prepare("SELECT o.id,json_extract(s.data,'$.source_namespace'),o.state,o.reason FROM outbox o JOIN sessions s ON s.id=o.session_id WHERE s.binding_id=?1 AND o.state!='acknowledged'").map_err(storage_error)?; + let rows: Vec<(i64, String, String, Option)> = statement + .query_map([&binding.id], |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)) + }) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + for (id, source, state, reason) in rows { + if !binding.agents.contains(&source) { + tx.execute("UPDATE outbox SET state='held',reason='HARNESS_CONSENT_REVOKED' WHERE id=?1",[id]).map_err(storage_error)?; + } else if state == "held" + && matches!( + reason.as_deref(), + Some("HARNESS_CONSENT_REVOKED" | "REPOSITORY_CONSENT_INVALIDATED") + ) + { + tx.execute( + "UPDATE outbox SET state='pending',reason=NULL WHERE id=?1", + [id], + ) + .map_err(storage_error)?; + } + } + tx.ensure_no_new_refusal(refused)?; + tx.commit().map_err(storage_error)?; + return Ok(binding); + } + Self::abandon_revoked_turns(&tx, &old.id, &[])?; + tx.execute("UPDATE outbox SET state='held',reason='MAPPING_CHANGED_REVIEW_REQUIRED' WHERE session_id IN(SELECT id FROM sessions WHERE binding_id=?1) AND state!='acknowledged'",[&old.id]).map_err(storage_error)?; + tx.execute("UPDATE sessions SET data=json_set(data,'$.needs_attention',json('true')) WHERE binding_id=?1",[&old.id]).map_err(storage_error)?; + } + binding.version = previous.as_ref().map_or(1, |b| b.version + 1); + binding.id = hash(format!( + "{}\0{}\0{}\0{}\0{}\0{}\0{}", + binding.repository_key, + binding.workspace_id, + binding.owner_id, + binding.project_id, + binding.task_id, + binding.version, + POLICY + )); + binding.paused = false; + binding.revoked = false; + tx.execute("INSERT INTO bindings(repo_key,data) VALUES(?1,?2) ON CONFLICT(repo_key) DO UPDATE SET data=excluded.data", + params![binding.repository_key, serde_json::to_string(&binding).map_err(storage_error)?]).map_err(storage_error)?; + tx.ensure_no_new_refusal(refused)?; + tx.commit().map_err(storage_error)?; + Ok(binding) + } + fn abandon_native_gap( + tx: &Transaction<'_>, + source_id: &str, + source: &str, + ) -> Result<(), AppError> { + let mut statement=tx.prepare("SELECT data FROM sessions WHERE source_id=?1 AND json_extract(data,'$.source_namespace')=?2").map_err(storage_error)?; + let rows: Vec = statement + .query_map(params![source_id, source], |r| r.get(0)) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + for raw in rows { + let mut session: Session = serde_json::from_str(&raw).map_err(storage_error)?; + session.usage_ledger.require_baseline(); + session.abandon_active()?; + Self::queue(tx, &mut session)?; + tx.execute( + "UPDATE sessions SET data=?2 WHERE id=?1", + params![ + session.id, + serde_json::to_string(&session).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + } + Ok(()) + } + fn hold_binding(tx: &Transaction<'_>, binding_id: &str, reason: &str) -> Result<(), AppError> { + tx.execute("UPDATE outbox SET state='held',reason=?2,claimed_until=0 WHERE session_id IN (SELECT id FROM sessions WHERE binding_id=?1) AND state!='acknowledged' AND (state='pending' OR reason IN ('HARNESS_CONSENT_REVOKED','REPOSITORY_CONSENT_INVALIDATED'))",params![binding_id,reason]).map_err(storage_error)?; + Ok(()) + } + fn invalidate_binding( + tx: &Transaction<'_>, + binding: &Binding, + reason: &str, + ) -> Result<(), AppError> { + Self::revoke_numeric_binding(tx, binding)?; + Self::abandon_revoked_turns(tx, &binding.id, &[])?; + let mut revoked = binding.clone(); + revoked.revoked = true; + revoked.paused = true; + tx.execute( + "UPDATE bindings SET data=?2 WHERE repo_key=?1", + params![ + binding.repository_key, + serde_json::to_string(&revoked).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + Self::hold_binding(tx, &binding.id, reason) + } + fn reconcile_refusal(tx: &Transaction<'_>) -> Result<(), AppError> { + let mut statement=tx.prepare("SELECT DISTINCT binding_id FROM sessions WHERE json_type(data,'$.active')='object'").map_err(storage_error)?; + let bindings: Vec = statement + .query_map([], |r| r.get(0)) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + for binding in bindings { + Self::abandon_revoked_turns(tx, &binding, &[])?; + } + // Refusal markers have no customer/session identifiers. Conservatively + // quarantine all unacknowledged complete bodies; never rewrite frozen bytes + // or automatically release an uncertain body during explicit recovery. + tx.execute("UPDATE outbox SET state='held',reason='REFUSED_BOUNDARY_REVIEW_REQUIRED',claimed_until=0 WHERE state!='acknowledged' AND EXISTS(SELECT 1 FROM json_each(outbox.body,'$.segments') segment WHERE json_extract(segment.value,'$.completeness')='COMPLETE' AND json_extract(segment.value,'$.duration_seconds')>0)",[]).map_err(storage_error)?; + tx.execute("UPDATE sessions SET data=json_set(data,'$.needs_attention',json('true')) WHERE id IN(SELECT session_id FROM outbox WHERE reason='REFUSED_BOUNDARY_REVIEW_REQUIRED')",[]).map_err(storage_error)?; + Ok(()) + } + fn abandon_revoked_turns( + tx: &Transaction<'_>, + binding_id: &str, + remaining_agents: &[String], + ) -> Result<(), AppError> { + let mut statement = tx + .prepare("SELECT data FROM sessions WHERE binding_id=?1") + .map_err(storage_error)?; + let rows: Vec = statement + .query_map([binding_id], |r| r.get(0)) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + for raw in rows { + let mut session: Session = serde_json::from_str(&raw).map_err(storage_error)?; + if remaining_agents.contains(&session.source_namespace) { + continue; + } + session.usage_ledger.require_baseline(); + session.abandon_active()?; + Self::queue(tx, &mut session)?; + tx.execute( + "UPDATE sessions SET data=?2 WHERE id=?1", + params![ + session.id, + serde_json::to_string(&session).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + } + Ok(()) + } + fn binding_in(connection: &Connection, key: &str) -> Result, AppError> { + let value: Option = connection + .query_row("SELECT data FROM bindings WHERE repo_key=?1", [key], |r| { + r.get(0) + }) + .optional() + .map_err(storage_error)?; + value + .map(|v| serde_json::from_str(&v).map_err(storage_error)) + .transpose() + } + /// Observing changed consent invalidates the old clock durably, even if a + /// later command sees the original digest again. + pub fn observe_repository(&mut self, repository: &Repository) -> Result<(), AppError> { + let tx = self.transaction()?; + if tx.failure()?.is_some() { + Self::reconcile_refusal(&tx)?; + } + if let Some(binding) = Self::binding_in(&tx, &repository.key)? { + if !repository.matches_binding(&binding) { + Self::invalidate_binding(&tx, &binding, "REPOSITORY_CONSENT_INVALIDATED")?; + } + } + tx.commit().map_err(storage_error) + } + pub fn binding(&self, key: &str) -> Result, AppError> { + Self::binding_in(&self.connection, key) + } + /// Path-free local policy inspection. Missing policy exits before any + /// functional profile, executable, process-origin or source-file access. + pub fn numeric_status( + &self, + repository: &Repository, + namespace: &str, + ) -> Result { + use crate::capture_usage_consent::{status, ConsentPolicy}; + if !matches!(namespace, "claude-code" | "codex") { + return Err(AppError::InvalidInput( + "Unsupported numeric capture source".into(), + )); + } + let disabled = || status(namespace, false, "NUMERIC_CAPTURE_DISABLED"); + let Some(binding) = Self::binding_in(&self.connection, &repository.key)? else { + return Ok(disabled()); + }; + if binding.revoked + || binding.paused + || !binding.agents.iter().any(|agent| agent == namespace) + || !repository.matches_binding(&binding) + { + return Ok(disabled()); + } + let raw: Option = self + .connection + .query_row( + "SELECT data FROM usage_consents WHERE binding_id=?1 AND namespace=?2", + params![binding.id, namespace], + |row| row.get(0), + ) + .optional() + .map_err(storage_error)?; + let Some(raw) = raw else { + return Ok(disabled()); + }; + let policy = serde_json::from_str::(&raw) + .ok() + .filter(|policy| policy.matches(&binding, namespace)); + Ok(match policy { + None => status(namespace, false, "NUMERIC_CONSENT_NEEDS_REVIEW"), + Some(policy) if !policy.enabled => status( + namespace, + false, + policy + .unavailable_reason + .as_deref() + .unwrap_or("NUMERIC_CAPTURE_DISABLED"), + ), + Some(policy) => status( + namespace, + true, + policy + .unavailable_reason + .as_deref() + .unwrap_or("NUMERIC_SOURCE_UNQUALIFIED"), + ), + }) + } + #[cfg(unix)] + fn numeric_eligible(repository: &Repository, binding: &Binding, namespace: &str) -> bool { + matches!(namespace, "claude-code" | "codex") + && !binding.revoked + && !binding.paused + && repository.matches_binding(binding) + && binding.agents.iter().any(|agent| agent == namespace) + } + #[cfg(unix)] + pub(crate) fn numeric_binding( + &self, + repository: &Repository, + namespace: &str, + ) -> Result { + Self::binding_in(&self.connection, &repository.key)?.filter(|binding| Self::numeric_eligible(repository, binding, namespace)) + .ok_or_else(|| AppError::Config("Numeric capture requires a current active metadata-only repository mapping; run capture setup first".into())) + } + fn numeric_reset_sessions( + tx: &Transaction<'_>, + binding: &Binding, + namespace: &str, + ) -> Result<(), AppError> { + let mut statement = tx.prepare("SELECT data FROM sessions WHERE binding_id=?1 AND json_extract(data,'$.source_namespace')=?2").map_err(storage_error)?; + let rows: Vec = statement + .query_map(params![binding.id, namespace], |row| row.get(0)) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + for raw in rows { + let mut session: Session = serde_json::from_str(&raw).map_err(storage_error)?; + session.usage_ledger.require_baseline(); + session.numeric_authority = None; + tx.execute( + "UPDATE sessions SET data=?2 WHERE id=?1", + params![ + session.id, + serde_json::to_string(&session).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + } + Ok(()) + } + fn revoke_numeric_namespace( + tx: &Transaction<'_>, + binding: &Binding, + namespace: &str, + create: bool, + ) -> Result<(), AppError> { + use crate::capture_usage_consent::ConsentPolicy; + let raw: Option = tx + .query_row( + "SELECT data FROM usage_consents WHERE binding_id=?1 AND namespace=?2", + params![binding.id, namespace], + |row| row.get(0), + ) + .optional() + .map_err(storage_error)?; + if raw.is_none() && !create { + return Ok(()); + } + let old = raw + .as_deref() + .and_then(|raw| serde_json::from_str::(raw).ok()) + .filter(|old| old.matches(binding, namespace)); + let epoch = old.as_ref().map_or(1, |old| { + if old.enabled { + old.epoch.saturating_add(1) + } else { + old.epoch + } + }); + let policy = ConsentPolicy { + policy_version: 1, + binding_id: binding.id.clone(), + binding_version: binding.version, + source_namespace: namespace.into(), + profile_id: old + .as_ref() + .map_or_else(|| "0".repeat(64), |old| old.profile_id.clone()), + profile_digest: old + .as_ref() + .map_or_else(|| "0".repeat(64), |old| old.profile_digest.clone()), + epoch, + enabled: false, + unavailable_reason: Some("NUMERIC_CAPTURE_DISABLED".into()), + }; + tx.execute("INSERT INTO usage_consents(binding_id,namespace,data) VALUES(?1,?2,?3) ON CONFLICT(binding_id,namespace) DO UPDATE SET data=excluded.data", + params![binding.id,namespace,serde_json::to_string(&policy).map_err(storage_error)?]).map_err(storage_error)?; + Self::numeric_reset_sessions(tx, binding, namespace)?; + tx.execute("UPDATE outbox SET state='held',reason='NUMERIC_CONSENT_REVOKED',claimed_until=0 WHERE state!='acknowledged' AND json_array_length(body,'$.usage.records')>0 AND session_id IN(SELECT id FROM sessions WHERE binding_id=?1 AND json_extract(data,'$.source_namespace')=?2)", params![binding.id,namespace]).map_err(storage_error)?; + Ok(()) + } + fn revoke_numeric_binding(tx: &Transaction<'_>, binding: &Binding) -> Result<(), AppError> { + for namespace in ["claude-code", "codex"] { + Self::revoke_numeric_namespace(tx, binding, namespace, false)?; + } + Ok(()) + } + pub(crate) fn disable_numeric( + &mut self, + repository: &Repository, + namespace: &str, + ) -> Result { + if !matches!(namespace, "claude-code" | "codex") { + return Err(AppError::InvalidInput( + "Unsupported numeric capture source".into(), + )); + } + let tx = self.transaction()?; + let binding = Self::binding_in(&tx, &repository.key)? + .ok_or_else(|| AppError::Config("Repository not approved; run capture setup".into()))?; + Self::revoke_numeric_namespace(&tx, &binding, namespace, true)?; + tx.commit().map_err(storage_error)?; + Ok(crate::capture_usage_consent::status( + namespace, + false, + "NUMERIC_CAPTURE_DISABLED", + )) + } + #[cfg(unix)] + pub(crate) fn enable_numeric( + &mut self, + repository: &Repository, + namespace: &str, + prepared: &crate::capture_usage_profile::PreparedProfile, + ) -> Result { + use crate::capture_usage_consent::ConsentPolicy; + let tx = self.transaction()?; + let refused = tx.failure()?.is_some(); + if refused { + return Err(AppError::Config( + "Capture remains paused after a refusal; recover before numeric approval".into(), + )); + } + let binding = Self::binding_in(&tx, &repository.key)?.filter(|binding| Self::numeric_eligible(repository,binding,namespace)) + .filter(|binding| prepared.matches(binding,namespace)).ok_or_else(|| AppError::Config("Numeric consent changed during approval; explicitly qualify the current profile and mapping again".into()))?; + let raw: Option = tx + .query_row( + "SELECT data FROM usage_consents WHERE binding_id=?1 AND namespace=?2", + params![binding.id, namespace], + |row| row.get(0), + ) + .optional() + .map_err(storage_error)?; + let old = raw + .as_deref() + .map(serde_json::from_str::) + .transpose() + .map_err(|_| { + AppError::Config( + "Numeric consent needs review; disable it before approving again".into(), + ) + })?; + let epoch = old + .as_ref() + .map_or(Some(1), |old| old.epoch.checked_add(1)) + .ok_or_else(|| { + AppError::Config( + "Numeric consent epoch is exhausted; collection remains disabled".into(), + ) + })?; + let policy = ConsentPolicy { + policy_version: 1, + binding_id: binding.id.clone(), + binding_version: binding.version, + source_namespace: namespace.into(), + profile_id: prepared.id().into(), + profile_digest: prepared.digest().into(), + epoch, + enabled: true, + unavailable_reason: Some("NUMERIC_SOURCE_UNQUALIFIED".into()), + }; + tx.execute("INSERT INTO usage_consents(binding_id,namespace,data) VALUES(?1,?2,?3) ON CONFLICT(binding_id,namespace) DO UPDATE SET data=excluded.data", params![binding.id,namespace,serde_json::to_string(&policy).map_err(storage_error)?]).map_err(storage_error)?; + Self::numeric_reset_sessions(&tx, &binding, namespace)?; + if !prepared.matches(&binding, namespace) { + return Err(AppError::Config( + "Numeric profile changed before approval committed; explicitly reapprove".into(), + )); + } + tx.ensure_no_new_refusal(refused)?; + tx.commit().map_err(storage_error)?; + let mut status = + crate::capture_usage_consent::status(namespace, true, "NUMERIC_SOURCE_UNQUALIFIED"); + status["notice"] = serde_json::json!("Only minimized partial request observations may be retained after a qualified new Prompt. Provider expenditure remains unknown; charges require review."); + Ok(status) + } + #[cfg(unix)] + fn numeric_policy_in( + connection: &Connection, + binding: &Binding, + source: &str, + ) -> Result, AppError> { + let raw: Option = connection + .query_row( + "SELECT data FROM usage_consents WHERE binding_id=?1 AND namespace=?2", + params![binding.id, source], + |row| row.get(0), + ) + .optional() + .map_err(storage_error)?; + Ok(raw + .filter(|raw| raw.len() <= 4096) + .as_deref() + .and_then(|raw| { + serde_json::from_str::(raw).ok() + }) + .filter(|policy| policy.matches(binding, source))) + } + #[cfg(unix)] + fn policy_current( + connection: &Connection, + binding: &Binding, + policy: &crate::capture_usage_consent::ConsentPolicy, + ) -> Result { + Ok( + Self::numeric_policy_in(connection, binding, &policy.source_namespace)?.is_some_and( + |current| { + current.enabled + && current.epoch == policy.epoch + && current.profile_id == policy.profile_id + && current.profile_digest == policy.profile_digest + }, + ), + ) + } + #[cfg(unix)] + fn normal_factory<'r>( + args: NormalFactoryArgs<'_, 'r>, + session: &mut Session, + ) -> Result, AppError> { + let mut state = NormalFactory { + policy: None, + runtime: args.input.runtime, + approved: None, + profile: None, + origin: None, + source_lease: None, + reason: None, + invalidate: false, + }; + // This database decision precedes every functional profile, native + // image/provenance and source-file operation. Old/default bindings are + // denied without consulting an executable, profile root or hook path. + let Some(policy) = Self::numeric_policy_in(args.connection, args.binding, args.source)? + .filter(|policy| policy.enabled) + else { + if session.numeric_authority.take().is_some() { + session.usage_ledger.require_baseline(); + } + return Ok(state); + }; + let same_epoch = session.numeric_authority.as_ref().is_some_and(|authority| { + authority.profile_id == policy.profile_id + && authority.profile_digest == policy.profile_digest + && authority.epoch == policy.epoch + }); + if !same_epoch { + session.usage_ledger.require_baseline(); + session.numeric_authority = Some(NumericAuthority { + profile_id: policy.profile_id.clone(), + profile_digest: policy.profile_digest.clone(), + epoch: policy.epoch, + source_identity: None, + }); + } + state.policy = Some(policy); + if !matches!( + args.event, + CaptureEvent::Prompt | CaptureEvent::Stop | CaptureEvent::SessionEnd + ) { + return Ok(state); + } + if args.event != CaptureEvent::Prompt + && (!session.usage_ledger.baseline_ready() + || session + .numeric_authority + .as_ref() + .and_then(|authority| authority.source_identity.as_ref()) + .is_none()) + { + state.reason = Some("MISSING_QUALIFIED_PROMPT"); + return Ok(state); + } + let Some(runtime) = args.input.runtime else { + state.reason = Some("LIVE_GUARD_REQUIRED"); + return Ok(state); + }; + if !args + .invocation + .is_some_and(|invocation| invocation.validate(args.directory).is_ok()) + { + state.reason = Some("LIVE_GUARD_REQUIRED"); + return Ok(state); + } + let expected = match args.source { + "claude-code" => "2.1.319", + "codex" => "0.167.0", + _ => "", + }; + if args.version != expected || session.harness_version != args.version { + state.reason = Some("UNSUPPORTED_HARNESS_VERSION"); + state.invalidate = true; + return Ok(state); + } + let policy = state.policy.as_ref().unwrap(); + let profile = match crate::capture_usage_profile::ProfileLease::load( + args.directory, + policy, + runtime.identity(), + ) { + Ok(profile) => profile, + Err(reason) => { + state.reason = Some(reason); + state.invalidate = true; + return Ok(state); + } + }; + if profile.version() != args.version { + state.reason = Some("UNSUPPORTED_HARNESS_VERSION"); + state.invalidate = true; + return Ok(state); + } + let (native, stamp) = profile.native(); + let Some(origin) = crate::capture_usage_origin::OriginLease::verify(native, stamp) else { + state.reason = Some("HARNESS_ORIGIN_UNAVAILABLE"); + return Ok(state); + }; + let Some(path) = args.input.path else { + state.reason = Some("ACTIVE_SOURCE_UNAVAILABLE"); + return Ok(state); + }; + let harness = if args.source == "claude-code" { + Harness::ClaudeCode + } else { + Harness::Codex + }; + let approved = match ApprovedActiveSession::new( + harness, + args.version, + profile.home(), + path, + args.source_id, + ) { + Ok(approved) => approved, + Err(_) => { + state.reason = Some("ACTIVE_SOURCE_UNAVAILABLE"); + return Ok(state); + } + }; + // Recheck the still-current row immediately before allowing the caller + // to open the exact active source. Transaction ordering makes revoke + // before admission win; a stale command-side read cannot authorize it. + if !Self::policy_current(args.connection, args.binding, policy)? { + state.reason = Some("NUMERIC_CAPTURE_DISABLED"); + return Ok(state); + } + state.profile = Some(profile); + state.origin = Some(origin); + state.approved = Some(approved); + Ok(state) + } + #[cfg(unix)] + fn save_numeric_reason( + tx: &Transaction<'_>, + binding: &Binding, + state: &NormalFactory<'_>, + ) -> Result<(), AppError> { + let (Some(policy), Some(reason)) = (&state.policy, state.reason) else { + return Ok(()); + }; + if state.invalidate { + Self::revoke_numeric_namespace(tx, binding, &policy.source_namespace, false)?; + } + let Some(mut current) = Self::numeric_policy_in(tx, binding, &policy.source_namespace)? + else { + return Ok(()); + }; + if !state.invalidate + && (current.epoch != policy.epoch + || current.profile_id != policy.profile_id + || current.profile_digest != policy.profile_digest) + { + return Ok(()); + } + current.unavailable_reason = Some(reason.into()); + tx.execute( + "UPDATE usage_consents SET data=?3 WHERE binding_id=?1 AND namespace=?2", + params![ + binding.id, + policy.source_namespace, + serde_json::to_string(¤t).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + Ok(()) + } + pub fn event(&mut self, repository: &Repository, signal: Signal<'_>) -> Result<(), AppError> { + self.event_inner(repository, signal, None, None) + } + #[cfg(unix)] + pub(crate) fn event_hook( + &mut self, + repository: &Repository, + signal: Signal<'_>, + path: Option<&Path>, + runtime: Option<&crate::capture_runtime_pair::HookRuntime>, + ) -> Result<(), AppError> { + self.event_inner( + repository, + signal, + None, + Some(NormalHookInput { path, runtime }), + ) + } + // Synthetic ledger qualification is accessible only to this private test + // child. It cannot be selected by CLI, environment, default or dev-tools. + #[cfg(all(test, unix))] + fn event_with_usage( + &mut self, + repository: &Repository, + signal: Signal<'_>, + usage_source: Option<&UsageSource<'_>>, + ) -> Result<(), AppError> { + self.event_inner(repository, signal, usage_source, None) + } + fn event_inner( + &mut self, + repository: &Repository, + signal: Signal<'_>, + usage_source: Option<&UsageSource<'_>>, + normal_hook: Option>, + ) -> Result<(), AppError> { + let Signal { + source, + resumed, + source_id, + turn_id, + version, + event, + clock, + } = signal; + identifier(source_id)?; + version_identifier(version)?; + if matches!(event, CaptureEvent::Prompt | CaptureEvent::Stop) && turn_id.is_none() { + return Err(AppError::InvalidInput( + "Missing native turn identity; capture requires qualified prompt_id/turn_id".into(), + )); + } + if let Some(id) = turn_id { + identifier(id)?; + } + #[cfg(unix)] + let (factory_directory, factory_invocation) = + (self.directory.clone(), self.invocation.clone()); + #[cfg(not(unix))] + let _ = normal_hook; + let tx = self.transaction_for_event(true)?; + let self_failure_present = tx.failure()?.is_some(); + if self_failure_present { + Self::reconcile_refusal(&tx)?; + if matches!(event, CaptureEvent::Prompt | CaptureEvent::SessionStart) { + tx.commit().map_err(storage_error)?; + return Err(AppError::Config("Capture is paused after a refused boundary; inspect status and explicitly recover".into())); + } + } + Self::check_size(&tx)?; + let Some(binding) = Self::binding_in(&tx, &repository.key)? else { + // A known native session leaving approved repositories is an + // unobserved gap, not authority to keep its old clock alive. + Self::abandon_native_gap(&tx, source_id, source)?; + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + }; + if !repository.matches_binding(&binding) { + Self::invalidate_binding(&tx, &binding, "REPOSITORY_CONSENT_INVALIDATED")?; + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + if binding.revoked || !binding.agents.iter().any(|a| a == source) { + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + if binding.paused + && !matches!( + event, + CaptureEvent::Stop | CaptureEvent::Interrupt | CaptureEvent::SessionEnd + ) + && !(resumed && event == CaptureEvent::SessionStart) + { + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + let mut statement=tx.prepare("SELECT data FROM sessions WHERE source_id=?1 AND json_extract(data,'$.source_namespace')=?2 AND json_extract(data,'$.binding.workspace_id')=?3 AND json_extract(data,'$.binding.owner_id')=?4 AND json_extract(data,'$.binding.origin_hash')=?5 LIMIT 2").map_err(storage_error)?; + let matches: Vec = statement + .query_map( + params![ + source_id, + source, + binding.workspace_id, + binding.owner_id, + binding.origin_hash + ], + |r| r.get(0), + ) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + if matches.len() > 1 { + return Err(AppError::Config( + "Conflicting canonical session state; evidence requires review".into(), + )); + } + let raw = matches.into_iter().next(); + if raw.is_none() && !matches!(event, CaptureEvent::SessionStart | CaptureEvent::Prompt) { + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + let mut session: Session = raw + .map(|v| serde_json::from_str(&v).map_err(storage_error)) + .transpose()? + .unwrap_or_else(|| Session::begin(&binding, source, source_id, version, clock)); + if session.binding.id != binding.id { + return Err(AppError::Config("Native session mapping changed; review held evidence and begin a new native session".into())); + } + // A native session cannot switch parser versions mid-stream. + let usage_version_matches = session.harness_version == version; + let id = session.id.clone(); + if self_failure_present + && matches!( + event, + CaptureEvent::Stop | CaptureEvent::Interrupt | CaptureEvent::SessionEnd + ) + { + session.abandon_active()?; + } + if resumed && event == CaptureEvent::SessionStart { + session.usage_ledger.require_baseline(); + session.abandon_native_resume(clock)?; + } + match event { + CaptureEvent::SessionStart => {} // Resume must never reset the baseline. + CaptureEvent::Prompt => { + if turn_id.is_some_and(|id| session.seen_turns.contains(id)) { + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + if let Some(active) = &session.active { + if turn_id.is_some_and(|key| key != active.key) { + session.close(clock, false)?; + } else { + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } // Concurrent duplicate hook registrations. + } + if turn_id.is_some_and(|key| session.last_turn.as_deref() == Some(key)) { + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + session.generation += 1; + let key = turn_id + .map(str::to_owned) + .unwrap_or_else(|| format!("turn-{}", session.generation)); + session.active = Some(ActiveTurn { + key, + clock: Some(clock.clone()), + part: 0, + }); + session.lifecycle = "ACTIVE".into(); + } + CaptureEvent::Stop => { + if session + .active + .as_ref() + .is_some_and(|a| turn_id.is_some_and(|id| id != a.key)) + { + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + session.close(clock, true)?; + } + CaptureEvent::Interrupt | CaptureEvent::SessionEnd => { + if event == CaptureEvent::Interrupt + && session + .active + .as_ref() + .is_some_and(|a| turn_id.is_some_and(|id| id != a.key)) + { + tx.ensure_no_new_refusal(self_failure_present)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + session.close(clock, false)?; + if event == CaptureEvent::SessionEnd { + session.lifecycle = if session.needs_attention { + "INCOMPLETE" + } else { + "COMPLETED" + } + .into(); + } + } + } + #[cfg(unix)] + let mut numeric_time_only = None; + #[cfg(unix)] + let mut normal_factory = if !binding.paused && !self_failure_present { + if let Some(input) = normal_hook { + // Clone only for an enabled row, after legitimate timing has + // been reconciled. A late lease failure can roll back numeric + // finalization without dropping that measured interval. + if Self::numeric_policy_in(&tx, &binding, source)? + .is_some_and(|policy| policy.enabled) + { + numeric_time_only = Some(session.clone()); + } + let mut factory = Self::normal_factory( + NormalFactoryArgs { + connection: &tx, + directory: &factory_directory, + invocation: factory_invocation.as_ref(), + binding: &binding, + source, + source_id, + version, + event, + input, + }, + &mut session, + )?; + factory.observe(&mut session, event, source, version, source_id); + Some(factory) + } else { + None + } + } else { + None + }; + // Timing terminal reconciliation remains available during a pause. It + // never authorizes a transcript read or changes the numeric consent epoch. + if !binding.paused && !self_failure_present && usage_source.is_some() { + let approved = usage_source.and_then(|input| { + let harness = match source { + "claude-code" => Some(Harness::ClaudeCode), + "codex" => Some(Harness::Codex), + _ => None, + }; + harness + .filter(|_| { + usage_version_matches + && input.qualified_source == source + && input.qualified_native_session == source_id + }) + .and_then(|h| { + ApprovedActiveSession::new( + h, + version, + input.resolved_home, + input.exact_hook_path, + source_id, + ) + .ok() + }) + }); + if event == CaptureEvent::Prompt { + if let Some(approved) = &approved { + if !session.usage_ledger.baseline_ready() { + let baseline = + read_active_session_request_ids(approved) + .ok() + .filter(|baseline| { + baseline.source_session_id == source_id + && baseline.harness_version == version + && baseline.limitations.is_empty() + && baseline.source_adapter + == if source == "claude-code" { + "CLAUDE_JSONL_2_1_319_V1" + } else { + "CODEX_ROLLOUT_0_167_0_V1" + } + }); + if let Some(baseline) = baseline { + session.usage_ledger.establish_baseline(baseline.record_ids); + } else { + session.usage_ledger.baseline_epoch = None; + session.usage_ledger.incomplete = true; + } + } + } else { + // This turn was not opted into qualified usage at its prompt. + // A terminal capability cannot retroactively authorize it. + session.usage_ledger.require_baseline(); + } + } else if matches!(event, CaptureEvent::Stop | CaptureEvent::SessionEnd) { + if session.usage_ledger.baseline_ready() { + let evidence = approved.and_then(|approved| { + if session.usage_ledger.excluded_request_ids.is_empty() { + read_active_session(&approved).ok() + } else { + read_active_session_excluding_request_ids( + &approved, + &session.usage_ledger.excluded_request_ids, + ) + .ok() + } + }); + if let Some(evidence) = evidence { + session + .usage_ledger + .observe(evidence, source, version, source_id); + } else { + session.usage_ledger.incomplete = true; + } + } else if usage_source.is_some() { + session.usage_ledger.incomplete = true; + } + } + } + #[cfg(unix)] + Self::finalize_normal_event( + &tx, + &mut session, + normal_factory.as_mut(), + EventFinalization { + id: &id, + binding: &binding, + source_id, + was_refused: self_failure_present, + time_only: numeric_time_only.as_ref(), + }, + )?; + #[cfg(not(unix))] + { + tx.ensure_no_new_refusal(self_failure_present)?; + Self::finish_event(&tx, &mut session, &id, &binding, source_id)?; + tx.ensure_no_new_refusal(self_failure_present)?; + } + // Leases remain in this frame until the transaction commit completes. + tx.commit().map_err(storage_error) + } + #[cfg(unix)] + fn finalize_normal_event( + tx: &CaptureTransaction<'_>, + session: &mut Session, + mut factory: Option<&mut NormalFactory<'_>>, + args: EventFinalization<'_>, + ) -> Result<(), AppError> { + if let Some(factory) = factory.as_deref_mut() { + if let Err(reason) = factory.validate_current(tx, args.binding)? { + if let Some(time_only) = args.time_only { + *session = time_only.clone(); + } + factory.fail(session, reason); + } + } + // Only this boundary's finalization is rollback-able. Previous frozen + // bodies and accepted request identities remain immutable. + let numeric_savepoint = factory + .as_ref() + .is_some_and(|factory| factory.policy.is_some()); + if numeric_savepoint { + tx.execute_batch("SAVEPOINT numeric_finalization") + .map_err(storage_error)?; + } + if let Some(factory) = factory.as_deref() { + Self::save_numeric_reason(tx, args.binding, factory)?; + } + tx.ensure_no_new_refusal(args.was_refused)?; + Self::finish_event(tx, session, args.id, args.binding, args.source_id)?; + #[cfg(test)] + if numeric_savepoint { + crate::capture_usage_test_io::after_numeric_write(tx); + } + if let Some(factory) = factory { + if let Err(reason) = factory.validate_current(tx, args.binding)? { + if numeric_savepoint { + tx.execute_batch("ROLLBACK TO numeric_finalization") + .map_err(storage_error)?; + } + if let Some(time_only) = args.time_only { + *session = time_only.clone(); + } + factory.fail(session, reason); + Self::save_numeric_reason(tx, args.binding, factory)?; + Self::finish_event(tx, session, args.id, args.binding, args.source_id)?; + } + } + if numeric_savepoint { + tx.execute_batch("RELEASE numeric_finalization") + .map_err(storage_error)?; + } + tx.ensure_no_new_refusal(args.was_refused)?; + Ok(()) + } + fn finish_event( + tx: &Transaction<'_>, + session: &mut Session, + id: &str, + binding: &Binding, + source_id: &str, + ) -> Result<(), AppError> { + if session.usage_ledger.held { + session.needs_attention = true; + } + Self::queue(tx, session)?; + if session.usage_ledger.held { + tx.execute("UPDATE outbox SET state='held',reason='USAGE_RECORD_CONFLICT',claimed_until=0 WHERE session_id=?1 AND state!='acknowledged'",[&session.id]).map_err(storage_error)?; + } + tx.execute("INSERT INTO sessions(id,binding_id,source_id,data) VALUES(?1,?2,?3,?4) ON CONFLICT(id) DO UPDATE SET data=excluded.data", + params![id,binding.id,source_id,serde_json::to_string(&session).map_err(storage_error)?]).map_err(storage_error)?; + Ok(()) + } + fn queue(tx: &Transaction<'_>, session: &mut Session) -> Result<(), AppError> { + if session.active.is_some() { + return Ok(()); + } + let final_checkpoint = + session.revision > 0 && session.queued_lifecycle != session.lifecycle; + let mut final_checkpoint_sent = false; + while session.queued_segments < session.segments.len() + || (!session.usage_ledger.held + && session.usage_ledger.queued < session.usage_ledger.records.len()) + || (final_checkpoint && !final_checkpoint_sent) + { + let start = session.queued_segments; + let mut end = (start + 100).min(session.segments.len()); + let usage_start = session.usage_ledger.queued; + let mut usage_end = if session.usage_ledger.held { + usage_start + } else { + (usage_start + 25).min(session.usage_ledger.records.len()) + }; + let mut body; + loop { + let mut payload = + session.payload(session.segments[start..end].to_vec(), session.revision + 1)?; + payload.usage = session.usage_ledger.payload(usage_start, usage_end); + body = serde_json::to_string(&payload).map_err(storage_error)?; + if body.len() <= MAX_BODY_BYTES { + break; + } + if usage_end > usage_start { + usage_end -= 1; + } else if end > start { + end -= 1; + } else { + return Err(AppError::Config( + "Capture request exceeds limit; evidence held".into(), + )); + } + } + if session.revision >= i32::MAX as i64 { + return Err(AppError::Config( + "Capture revision limit reached; evidence held for review".into(), + )); + } + session.revision += 1; + tx.execute( + "INSERT INTO outbox(session_id,revision,body,payload_hash) VALUES(?1,?2,?3,?4)", + params![session.id, session.revision, body, hash(body.as_bytes())], + ) + .map_err(storage_error)?; + session.queued_segments = end; + for index in usage_start..usage_end { + session.usage_ledger.record_revisions[index] = session.revision; + } + session.usage_ledger.queued = usage_end; + session.queued_lifecycle = session.lifecycle.clone(); + final_checkpoint_sent = true; + } + Ok(()) + } + pub fn control( + &mut self, + repository: &Repository, + action: &str, + clock: &Clock, + ) -> Result<(), AppError> { + let tx = self.transaction()?; + let refused = tx.failure()?.is_some(); + if refused { + Self::reconcile_refusal(&tx)?; + } + let mut binding = Self::binding_in(&tx, &repository.key)? + .ok_or_else(|| AppError::Config("Repository not approved; run capture setup".into()))?; + if !repository.matches_binding(&binding) { + Self::invalidate_binding(&tx, &binding, "REPOSITORY_CONSENT_INVALIDATED")?; + tx.commit().map_err(storage_error)?; + return Err(AppError::Config( + "Binding changed; explicit reapproval required".into(), + )); + } + if refused && action == "resume" { + tx.commit().map_err(storage_error)?; + return Err(AppError::Config( + "Storage refusal remains paused; explicitly recover before resuming".into(), + )); + } + if action != "resume" { + Self::revoke_numeric_binding(&tx, &binding)?; + } + if action == "resume" && binding.revoked { + return Err(AppError::Config( + "Binding changed or revoked; run capture setup to approve again".into(), + )); + } + if (action == "resume" && !binding.paused) || (action == "pause" && binding.paused) { + tx.ensure_no_new_refusal(refused)?; + tx.commit().map_err(storage_error)?; + return Ok(()); + } + let mut statement = tx + .prepare("SELECT data FROM sessions WHERE binding_id=?1") + .map_err(storage_error)?; + let sessions: Vec = statement + .query_map([&binding.id], |r| r.get(0)) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + for raw in sessions { + let mut session: Session = serde_json::from_str(&raw).map_err(storage_error)?; + if action != "resume" { + session.usage_ledger.require_baseline(); + } + if let Some(mut active) = session.active.take() { + if action == "pause" { + let key = active.key.clone(); + let part = active.part; + session.active = Some(active); + session.close(clock, true)?; + active = ActiveTurn { + key, + clock: None, + part: part + 1, + }; + session.active = Some(active); + } else if action == "resume" { + active.clock = Some(clock.clone()); + session.active = Some(active); + } else { + session.active = Some(active); + session.close(clock, false)?; + } + } + Self::queue(&tx, &mut session)?; + tx.execute( + "UPDATE sessions SET data=?2 WHERE id=?1", + params![ + session.id, + serde_json::to_string(&session).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + } + binding.paused = action != "resume"; + if action == "disable" { + binding.revoked = true; + } + tx.execute( + "UPDATE bindings SET data=?2 WHERE repo_key=?1", + params![ + repository.key, + serde_json::to_string(&binding).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + if binding.revoked { + Self::hold_binding(&tx, &binding.id, "HARNESS_CONSENT_REVOKED")?; + } + tx.ensure_no_new_refusal(refused)?; + tx.commit().map_err(storage_error) + } + pub fn disable_all(&mut self) -> Result<(), AppError> { + let tx = self.transaction()?; + let refused = tx.failure()?.is_some(); + if refused { + Self::reconcile_refusal(&tx)?; + } + let mut statement = tx + .prepare("SELECT data FROM bindings") + .map_err(storage_error)?; + let rows: Vec = statement + .query_map([], |r| r.get(0)) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + let bindings: Vec = rows + .into_iter() + .map(|raw| serde_json::from_str(&raw).map_err(storage_error)) + .collect::>()?; + for mut binding in bindings { + Self::revoke_numeric_binding(&tx, &binding)?; + Self::abandon_revoked_turns(&tx, &binding.id, &[])?; + binding.paused = true; + binding.revoked = true; + tx.execute( + "UPDATE bindings SET data=?2 WHERE repo_key=?1", + params![ + binding.repository_key, + serde_json::to_string(&binding).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + Self::hold_binding(&tx, &binding.id, "HARNESS_CONSENT_REVOKED")?; + } + tx.ensure_no_new_refusal(refused)?; + tx.commit().map_err(storage_error) + } + pub fn binding_delivery_history(&self, binding_id: &str) -> Result { + self.connection.query_row("SELECT EXISTS(SELECT 1 FROM sessions WHERE binding_id=?1 AND json_type(data,'$.canonical_server_id')='text')",[binding_id],|r|r.get(0)).map_err(storage_error) + } + pub fn status(&self) -> Result { + let mut statement = self + .connection + .prepare("SELECT data FROM bindings ORDER BY repo_key") + .map_err(storage_error)?; + let bindings: Vec = statement + .query_map([], |r| r.get::<_, String>(0)) + .map_err(storage_error)? + .map(|r| serde_json::from_str(&r.map_err(storage_error)?).map_err(storage_error)) + .collect::>()?; + let pending = self + .connection + .query_row( + "SELECT COUNT(*) FROM outbox WHERE state='pending'", + [], + |r| r.get(0), + ) + .map_err(storage_error)?; + let held = self + .connection + .query_row("SELECT COUNT(*) FROM outbox WHERE state='held'", [], |r| { + r.get(0) + }) + .map_err(storage_error)?; + let needs_attention = self + .connection + .query_row( + "SELECT COUNT(*) FROM sessions WHERE json_extract(data,'$.needs_attention')=1", + [], + |r| r.get(0), + ) + .map_err(storage_error)?; + let unfinished: i64 = self + .connection + .query_row( + "SELECT COUNT(*) FROM sessions WHERE json_type(data,'$.active')='object'", + [], + |r| r.get(0), + ) + .map_err(storage_error)?; + let mut queue_statement=self.connection.prepare("SELECT s.source_id,o.revision,o.state,o.reason,o.attempts,o.retry_at FROM outbox o JOIN sessions s ON s.id=o.session_id WHERE o.state!='acknowledged' ORDER BY o.id LIMIT 101").map_err(storage_error)?; + let mut queue: Vec = queue_statement + .query_map([], |r| { + Ok(QueueState { + source_session_id: r.get(0)?, + revision: r.get(1)?, + state: r.get(2)?, + reason: r.get(3)?, + attempts: r.get(4)?, + retry_at: r.get(5)?, + }) + }) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + let queue_truncated = queue.len() > 100; + queue.truncate(100); + let delivered: i64 = self + .connection + .query_row( + "SELECT COUNT(*) FROM outbox WHERE state='acknowledged'", + [], + |r| r.get(0), + ) + .map_err(storage_error)?; + let capture_failure = self.failure()?; + let pages: i64 = self + .connection + .query_row("PRAGMA page_count", [], |r| r.get(0)) + .map_err(storage_error)?; + let page_size: i64 = self + .connection + .query_row("PRAGMA page_size", [], |r| r.get(0)) + .map_err(storage_error)?; + let full = pages * page_size >= MAX_QUEUE_BYTES - 64 * 1024; + let invocation_markers = capture_invocations::snapshot(&self.directory)?; + let dead_invocation = invocation_markers.iter().any(|marker| !marker.live); + let storage_paused = full || capture_failure.is_some() || dead_invocation; + let storage_reason = if full { + Some("QUEUE_LIMIT_REACHED".into()) + } else { + capture_failure + .as_ref() + .map(|f| f.reason.clone()) + .or_else(|| dead_invocation.then(|| "UNACKNOWLEDGED_INVOCATION".into())) + }; + Ok(Status { + policy: POLICY, + pending, + held, + needs_attention, + delivery_verified: delivered > 0, + trusted: "UNKNOWN", + bindings, + unfinished, + queue, + queue_truncated, + storage_paused, + storage_reason, + capture_failure, + pending_invocations: invocation_markers.len(), + }) + } + fn failure(&self) -> Result, AppError> { + Ok(read_failure_markers(&self.directory)? + .into_iter() + .next() + .map(|(_, failure)| failure)) + } + /// Source-fixture failure diagnosis only; status retains its earliest refusal. + /// Reuse the bounded strict marker reader and expose no paths or raw bodies. + #[cfg(feature = "dev-tools")] + pub fn developer_failure_probes(&self) -> Result, AppError> { + Ok(read_failure_markers(&self.directory)? + .into_iter() + .filter_map(|(_, failure)| failure.probe) + .collect()) + } + /// Failure-only source-fixture summary, never a normal capture hot path. + /// Selection order is the status reader's order, not causal chronology. + /// Missing associations remain unknown even after a successful snapshot. + /// selected_for_status describes this marker snapshot; reads are not atomic. + #[cfg(feature = "dev-tools")] + pub fn developer_failure_summary(&self) -> Result { + const SAMPLE_LIMIT: usize = 8; + const BYTE_LIMIT: usize = 16 * 1024; + let markers = read_failure_markers(&self.directory)?; + let invocations = capture_invocations::snapshot(&self.directory).ok(); + let total = markers.len(); + let probed = markers.iter().filter(|(_, f)| f.probe.is_some()).count(); + // Keep the selected marker and at least one of each observed probe kind. + let mut selected = Vec::new(); + if total > 0 { + selected.push(0); + } + for has_probe in [false, true] { + if let Some(index) = markers + .iter() + .position(|(_, f)| f.probe.is_some() == has_probe) + { + if !selected.contains(&index) { + selected.push(index); + } + } + } + for index in 0..total { + if selected.len() == SAMPLE_LIMIT { + break; + } + if !selected.contains(&index) { + selected.push(index); + } + } + selected.sort_unstable(); + let records: Vec<_> = selected + .into_iter() + .map(|index| { + let (path, failure) = &markers[index]; + let filename_boundary_match = path + .file_name() + .and_then(|name| name.to_str()) + .and_then(|name| name.strip_prefix("capture-refusal-")) + .and_then(|name| name.strip_suffix(".json")) + .filter(|suffix| { + suffix.len() == 64 && suffix.bytes().all(|b| b.is_ascii_hexdigit()) + }) + .map(|suffix| suffix == failure.boundary_id); + // Positive relations only: a missing/raced snapshot is not absence. + let invocation_nonce_match = invocations.as_ref().and_then(|snapshot| { + snapshot + .iter() + .any(|marker| marker.nonce == failure.boundary_id) + .then_some(true) + }); + let dead_invocation_boundary_match = invocations.as_ref().and_then(|snapshot| { + snapshot + .iter() + .any(|marker| { + !marker.live + && hash(format!("INVOCATION\0{}", marker.nonce)) + == failure.boundary_id + }) + .then_some(true) + }); + // State belongs to this same non-atomic snapshot, not a cause. + let dead_state_match = |preparing| { + invocations.as_ref().and_then(|snapshot| { + snapshot + .iter() + .any(|marker| { + !marker.live + && marker.preparing_state() == Some(preparing) + && hash(format!("INVOCATION\0{}", marker.nonce)) + == failure.boundary_id + }) + .then_some(true) + }) + }; + serde_json::json!({ + "selection_index": index, + "selected_for_status": index == 0, + "failure": failure, + "filename_boundary_match": filename_boundary_match, + "invocation_nonce_match": invocation_nonce_match, + "dead_invocation_boundary_match": dead_invocation_boundary_match, + "dead_preparing_invocation_boundary_match": dead_state_match(true), + "dead_pending_invocation_boundary_match": dead_state_match(false), + }) + }) + .collect(); + let summary = serde_json::json!({ + "selection_order": "observed_at_seconds_then_filename_not_causal", + "association_missing": "UNKNOWN", + "snapshot_relation": "marker_status_and_invocation_reads_are_not_atomic", + "invocation_snapshot": if invocations.is_some() { "observed" } else { "unknown" }, + "total_records": total, + "probed_records": probed, + "unprobed_records": total - probed, + "sample_limit": SAMPLE_LIMIT, + "sampled_records": records.len(), + "omitted_records": total - records.len(), + "byte_limit": BYTE_LIMIT, + "records": records, + }); + if serde_json::to_vec(&summary).map_err(storage_error)?.len() > BYTE_LIMIT { + return Err(storage_error("failure summary limit")); + } + Ok(summary) + } + pub fn recover(&mut self, clock: &Clock) -> Result<(), AppError> { + let tx = self.transaction()?; + let invocations = capture_invocations::snapshot(&tx.directory)?; + if invocations.iter().any(|marker| marker.live) { + return Err(storage_error("live invocation prevents recovery")); + } + Self::check_size(&tx)?; + let markers = read_failure_markers(&tx.directory)?; + if !markers.is_empty() { + Self::reconcile_refusal(&tx)?; + } + let mut statement = tx + .prepare("SELECT data FROM sessions") + .map_err(storage_error)?; + let rows: Vec = statement + .query_map([], |r| r.get(0)) + .map_err(storage_error)? + .collect::>() + .map_err(storage_error)?; + drop(statement); + for raw in rows { + let mut session: Session = serde_json::from_str(&raw).map_err(storage_error)?; + session.usage_ledger.require_baseline(); + session.close(clock, false)?; + Self::queue(&tx, &mut session)?; + tx.execute( + "UPDATE sessions SET data=?2 WHERE id=?1", + params![ + session.id, + serde_json::to_string(&session).map_err(storage_error)? + ], + ) + .map_err(storage_error)?; + } + let directory = tx.directory.clone(); + // Hold authority through commit and exact snapshot removal. New fallback + // publications have unique names and therefore cannot be removed here. + let CaptureTransaction { + inner, + _authority, + notification, + .. + } = tx; + inner.commit().map_err(storage_error)?; + capture_invocations::remove_dead(&directory, &invocations)?; + for (path, _) in markers { + fs::remove_file(path).map_err(storage_error)?; + } + fs::File::open(&directory) + .and_then(|f| f.sync_all()) + .map_err(storage_error)?; + if !read_failure_markers(&directory)?.is_empty() + || !capture_invocations::snapshot(&directory)?.is_empty() + { + return Err(AppError::Config( + "Another boundary was refused during recovery; collection remains paused".into(), + )); + } + drop(_authority); + if let Some(notification) = notification { + notification.released_after_authority(); + } + Ok(()) + } + /// Bounded worker maintenance also runs on empty, disabled and held queues. + pub fn maintain(&mut self, now: i64) -> Result<(), AppError> { + let tx = self.transaction()?; + if tx.failure()?.is_some() { + Self::reconcile_refusal(&tx)?; + } + tx.execute("DELETE FROM outbox WHERE id IN (SELECT id FROM outbox WHERE state='acknowledged' AND acknowledged_at Result, AppError> { + identifier(source_id)?; + let mut statement = self + .connection + .prepare("SELECT data FROM sessions WHERE source_id=?1 ORDER BY id") + .map_err(storage_error)?; + let result = statement + .query_map([source_id], |r| r.get::<_, String>(0)) + .map_err(storage_error)? + .map(|r| serde_json::from_str(&r.map_err(storage_error)?).map_err(storage_error)) + .collect(); + result + } + pub fn has_ready(&self, binding: &Binding, now: i64) -> Result { + if self.failure()?.is_some() || self.invocations_pending()? { + return Ok(false); + } + self.connection.query_row("SELECT EXISTS(SELECT 1 FROM outbox o JOIN sessions s ON s.id=o.session_id WHERE s.binding_id=?1 AND o.state='pending' AND o.retry_at<=?2 AND o.claimed_until<=?2 AND NOT EXISTS(SELECT 1 FROM outbox prior WHERE prior.session_id=o.session_id AND prior.revision Result, AppError> { + let tx = self.transaction()?; + let refused = tx.failure()?.is_some(); + if refused { + Self::reconcile_refusal(&tx)?; + } + if !capture_invocations::snapshot(&tx.directory)?.is_empty() { + tx.commit().map_err(storage_error)?; + return Ok(None); + } + let current = Self::binding_in(&tx, &binding.repository_key)?; + if !current.is_some_and(|b| b.id == binding.id && !b.paused && !b.revoked) { + tx.commit().map_err(storage_error)?; + return Ok(None); + } + let row = tx.query_row("SELECT o.id,o.session_id,o.body,o.payload_hash,o.attempts,o.revision,json_extract(s.data,'$.canonical_server_id'),s.data FROM outbox o JOIN sessions s ON s.id=o.session_id + WHERE s.binding_id=?1 AND o.state='pending' AND o.retry_at<=?2 AND o.claimed_until<=?2 + AND NOT EXISTS (SELECT 1 FROM outbox prior WHERE prior.session_id=o.session_id AND prior.revision(7)?))).optional().map_err(storage_error)?; + let row = if let Some((row, raw)) = row { + let valid = serde_json::from_str::(&raw) + .ok() + .zip(serde_json::from_str::(&row.body).ok()) + .is_some_and(|(session, payload)| { + validate_frozen(&row, &payload, &session, binding) + }); + if !valid { + tx.execute("UPDATE outbox SET state='held',reason='FROZEN_PAYLOAD_INVALID',claimed_until=0 WHERE id=?1",[row.id]).map_err(storage_error)?; + tx.execute("UPDATE sessions SET data=json_set(data,'$.needs_attention',json('true')) WHERE id=?1",[&row.session_id]).map_err(storage_error)?; + tx.commit().map_err(storage_error)?; + return Err(AppError::Config("Frozen capture evidence failed integrity checks; quarantined without transmission".into())); + } + tx.execute( + "UPDATE outbox SET claimed_until=?2 WHERE id=?1", + params![row.id, now + 30], + ) + .map_err(storage_error)?; + Some(row) + } else { + None + }; + tx.ensure_no_new_refusal(refused)?; + tx.commit().map_err(storage_error)?; + Ok(row) + } + pub fn acknowledge(&mut self, row: &Queued, server_id: &str, now: i64) -> Result<(), AppError> { + identifier(server_id)?; + let tx = self.transaction()?; + let current: Option = tx + .query_row( + "SELECT json_extract(data,'$.canonical_server_id') FROM sessions WHERE id=?1", + [&row.session_id], + |r| r.get(0), + ) + .map_err(storage_error)?; + if current.as_deref().is_some_and(|id| id != server_id) { + return Err(AppError::Conflict( + "Canonical capture identity changed; acknowledgement refused".into(), + )); + } + tx.execute( + "UPDATE sessions SET data=json_set(data,'$.canonical_server_id',?2) WHERE id=?1", + params![row.session_id, server_id], + ) + .map_err(storage_error)?; + tx.execute("UPDATE outbox SET state='acknowledged',reason='ACCEPTED',attempts=attempts+1,claimed_until=0,acknowledged_at=?2 WHERE id=?1 AND payload_hash=?3",params![row.id,now,row.hash]).map_err(storage_error)?; + tx.execute( + "DELETE FROM outbox WHERE state='acknowledged' AND acknowledged_at, + ) -> Result<(), AppError> { + let delay = retry_after + .unwrap_or_else(|| (2_i64.pow((row.attempts as u32).min(8)) + (row.id % 7)).min(300)) + .clamp(1, 3600); + let tx = self.transaction()?; + if tx.failure()?.is_some() { + Self::reconcile_refusal(&tx)?; + } + tx.execute("UPDATE outbox SET state=?2,reason=?3,attempts=attempts+1,retry_at=?4,claimed_until=0,acknowledged_at=?5 WHERE id=?1 AND payload_hash=?6 AND state!='held'", + params![row.id,state,reason,now+delay,if state=="acknowledged" {Some(now)} else {None},row.hash]).map_err(storage_error)?; + // Only acknowledged payloads expire. Never silently evict unsent evidence. + tx.execute( + "DELETE FROM outbox WHERE state='acknowledged' AND acknowledged_at bool { + if row.body.len() > MAX_BODY_BYTES + || hash(&row.body) != row.hash + || payload.schema_version != 1 + || payload.revision != row.revision + || payload.expected_revision != row.revision - 1 + || payload.source_namespace != session.source_namespace + || payload.source_session_id != session.source_session_id + || payload.harness_version != session.harness_version + || payload.repository_binding_id != session.binding.id + || payload.repository_binding_id != binding.id + || payload.binding_version != session.binding.version + || payload.project_id != session.binding.project_id + || payload.task_id != session.binding.task_id + || payload.work_kind != "HUMAN_ASSISTED_AGENT_ACTIVITY" + || payload.measurement_method != "OBSERVED_TURN_INTERVALS_V1" + || !matches!(payload.source_namespace.as_str(), "claude-code" | "codex") + || !matches!( + payload.lifecycle.as_str(), + "ACTIVE" | "COMPLETED" | "INCOMPLETE" + ) + || payload.segments.len() > 100 + || !session.usage_ledger.validate_payload( + &payload.usage, + &session.source_namespace, + &session.harness_version, + row.revision, + ) + { + return false; + } + for id in [ + &payload.source_session_id, + &payload.repository_binding_id, + &payload.project_id, + &payload.task_id, + &payload.harness_version, + ] { + if identifier(id).is_err() { + return false; + } + } + let parse = |s: &str| DateTime::parse_from_rfc3339(s).ok().map(|d| d.timestamp()); + let Some(start) = parse(&payload.started_at) else { + return false; + }; + let Some(end) = parse(&payload.observed_through) else { + return false; + }; + if start != session.started_at + || end < start + || payload.revision < 1 + || payload.revision > i32::MAX as i64 + { + return false; + } + let mut keys = std::collections::BTreeSet::new(); + for segment in &payload.segments { + let Some(a) = parse(&segment.started_at) else { + return false; + }; + let Some(b) = parse(&segment.ended_at) else { + return false; + }; + if identifier(&segment.segment_key).is_err() + || !keys.insert(&segment.segment_key) + || a < start + || b > end + || b < a + || b - a > MAX_INTERVAL_SECONDS + || (segment.completeness == "COMPLETE" && segment.duration_seconds != b - a) + || (segment.completeness == "INCOMPLETE" && segment.duration_seconds != 0) + || !matches!(segment.completeness.as_str(), "COMPLETE" | "INCOMPLETE") + { + return false; + } + } + true +} + +/// Bounded metadata-only refusal state. Unique immutable filenames prevent a +/// recovering process from deleting a concurrently published refusal. +fn read_failure_markers(directory: &Path) -> Result, AppError> { + crate::capture_profile_measure!(RefusalReads, { + let mut markers = Vec::new(); + for entry in fs::read_dir(directory).map_err(storage_error)? { + let entry = entry.map_err(storage_error)?; + let name = entry.file_name(); + let Some(name) = name.to_str() else { + continue; + }; + if name != "capture-failure.json" + && !(name.starts_with("capture-refusal-") && name.ends_with(".json")) + { + continue; + } + if markers.len() >= 1024 { + return Err(storage_error("refusal marker limit")); + } + let path = entry.path(); + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC); + } + let file = options.open(&path).map_err(storage_error)?; + let metadata = file.metadata().map_err(storage_error)?; + if !metadata.is_file() || metadata.len() > 1024 { + return Err(storage_error("invalid refusal marker")); + } + let mut bytes = Vec::new(); + file.take(1025) + .read_to_end(&mut bytes) + .map_err(storage_error)?; + if bytes.len() > 1024 { + return Err(storage_error("invalid refusal marker")); + } + let value: CaptureFailure = serde_json::from_slice(&bytes).map_err(storage_error)?; + if !matches!( + value.reason.as_str(), + "STORAGE_UNAVAILABLE" | "QUEUE_LIMIT_REACHED" | "BOUNDARY_REFUSED" + ) || value.boundary_id.len() != 64 + || !value.boundary_id.bytes().all(|b| b.is_ascii_hexdigit()) + { + return Err(storage_error("invalid refusal marker")); + } + markers.push((path, value)); + } + markers + .sort_by(|(ap, a), (bp, b)| a.observed_at.cmp(&b.observed_at).then_with(|| ap.cmp(bp))); + Ok(markers) + }) +} + +// Emergency markers use the reviewed POSIX fsync contract, not Apple's +// stronger drive-wide F_FULLFSYNC used by File::sync_all. SQLite is unchanged. +fn sync_refusal(file: &fs::File) -> std::io::Result<()> { + #[cfg(unix)] + { + use std::os::fd::AsRawFd; + if unsafe { libc::fsync(file.as_raw_fd()) } == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } + } + #[cfg(not(unix))] + { + file.sync_all() + } +} + +pub fn record_failure(directory: &Path, boundary_id: &str, reason: &str) -> Result<(), AppError> { + write_failure(directory, boundary_id, reason, |_| {}) +} +#[cfg(feature = "dev-tools")] +pub(crate) fn record_failure_probed( + directory: &Path, + boundary_id: &str, + reason: &str, + probe: HookFailureProbe, +) -> Result<(), AppError> { + write_failure(directory, boundary_id, reason, |failure| { + failure.probe = Some(probe); + }) +} +fn write_failure( + directory: &Path, + boundary_id: &str, + reason: &str, + enrich: impl FnOnce(&mut CaptureFailure), +) -> Result<(), AppError> { + if !matches!( + reason, + "STORAGE_UNAVAILABLE" | "QUEUE_LIMIT_REACHED" | "BOUNDARY_REFUSED" + ) || boundary_id.len() != 64 + || !boundary_id.bytes().all(|b| b.is_ascii_hexdigit()) + { + return Err(storage_error("invalid failure marker")); + } + if directory.exists() + && fs::symlink_metadata(directory) + .map_err(storage_error)? + .file_type() + .is_symlink() + { + return Err(storage_error("symlink")); + } + fs::create_dir_all(directory).map_err(storage_error)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).map_err(storage_error)?; + } + // Bound reserved refusal storage as well as each marker. At exhaustion, + // existing durable refusal state still keeps collection paused; this new + // boundary is explicitly reported unsaved rather than silently evicted. + let existing = fs::read_dir(directory) + .map_err(storage_error)? + .filter_map(Result::ok) + .filter(|entry| { + entry + .file_name() + .to_str() + .is_some_and(|name| name.starts_with("capture-refusal-") && name.ends_with(".json")) + }) + .take(1024) + .count(); + if existing >= 1024 { + return Err(storage_error("refusal marker limit")); + } + // Never add another busy wait after SQLite's 500ms timeout. Failure of the + // nonblocking lock still permits this append-only emergency publication. + let _authority = AuthorityGuard::acquire(directory, false).ok(); + static SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let unique = hash(format!( + "{}-{}-{}", + std::process::id(), + chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(), + SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + let temporary = directory.join(format!(".capture-refusal-{unique}.tmp")); + let path = directory.join(format!("capture-refusal-{unique}.json")); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let result = (|| { + let mut file = options.open(&temporary).map_err(storage_error)?; + let mut failure = CaptureFailure { + reason: reason.into(), + boundary_id: boundary_id.into(), + observed_at: chrono::Utc::now().timestamp(), + #[cfg(feature = "dev-tools")] + probe: None, + }; + enrich(&mut failure); + use std::io::Write; + file.write_all(&serde_json::to_vec(&failure).map_err(storage_error)?) + .map_err(storage_error)?; + sync_refusal(&file).map_err(storage_error)?; + fs::rename(&temporary, &path).map_err(storage_error)?; + fs::File::open(directory) + .and_then(|f| sync_refusal(&f)) + .map_err(storage_error)?; + Ok(()) + })(); + if temporary.exists() { + let _ = fs::remove_file(temporary); + } + result +} + +#[cfg(test)] +mod failure_probe_tests { + use super::*; + + fn legacy() -> serde_json::Value { + serde_json::json!({ + "reason": "STORAGE_UNAVAILABLE", + "boundary_id": "a".repeat(64), + "observed_at": 1794932360, + }) + } + + #[cfg(feature = "dev-tools")] + fn observed() -> serde_json::Value { + let mut value = legacy(); + value["probe"] = serde_json::json!({ + "phase": "repository", + "owner_fault": "group_deadline", + "setup": null, + }); + value + } + + #[test] + fn legacy_failure_keeps_exact_schema_without_a_probe() { + let failure: CaptureFailure = serde_json::from_value(legacy()).unwrap(); + assert_eq!(serde_json::to_value(failure).unwrap(), legacy()); + } + + #[test] + #[cfg(feature = "dev-tools")] + fn developer_failure_retains_closed_probe_provenance() { + let failure: CaptureFailure = serde_json::from_value(observed()).unwrap(); + assert_eq!(serde_json::to_value(failure).unwrap(), observed()); + } + + #[test] + #[cfg(feature = "dev-tools")] + fn developer_probe_refuses_unknown_fields_and_variants() { + for (key, value) in [ + ("phase", serde_json::json!("PRIVATE_RAW_CANARY")), + ("owner_fault", serde_json::json!("PRIVATE_RAW_CANARY")), + ("unknown", serde_json::json!("PRIVATE_RAW_CANARY")), + ] { + let mut marker = observed(); + marker["probe"][key] = value; + assert!(serde_json::from_value::(marker).is_err()); + } + } + + #[test] + #[cfg(feature = "dev-tools")] + fn developer_setup_probe_is_strict_and_fits_the_existing_marker_limit() { + let mut marker = observed(); + marker["probe"]["setup"] = serde_json::json!({ + "ready_window_ns": u64::MAX, + "pre_spawn_offset_ns": u64::MAX, + "spawn_return_offset_ns": u64::MAX, + "first_ready_poll_offset_ns": u64::MAX, + "deadline_offset_ns": u64::MAX, + "ready_frame_observed": false, + "ready_eof_observed": false, + "deadline_edge": "park_after_receive", + "fault_state": "await_ready", + "park_end_offset_ns": u64::MAX, + "workload_spawn_return_offset_ns": u64::MAX, + "first_park_poll_offset_ns": u64::MAX, + "park_frame_observed": true, + }); + let failure: CaptureFailure = serde_json::from_value(marker.clone()).unwrap(); + assert!(serde_json::to_vec(&failure).unwrap().len() <= 1024); + assert_eq!(serde_json::to_value(failure).unwrap(), marker); + let mut older = marker.clone(); + older["probe"]["setup"]["deadline_edge"] = serde_json::json!("before_receive"); + for key in [ + "park_end_offset_ns", + "workload_spawn_return_offset_ns", + "first_park_poll_offset_ns", + "park_frame_observed", + ] { + older["probe"]["setup"].as_object_mut().unwrap().remove(key); + } + let failure: CaptureFailure = serde_json::from_value(older.clone()).unwrap(); + assert_eq!(serde_json::to_value(failure).unwrap(), older); + for (key, value) in [ + ("deadline_edge", serde_json::json!("PRIVATE_RAW_CANARY")), + ("fault_state", serde_json::json!("PRIVATE_RAW_CANARY")), + ("unknown", serde_json::json!("PRIVATE_RAW_CANARY")), + ] { + let mut invalid = marker.clone(); + invalid["probe"]["setup"][key] = value; + assert!(serde_json::from_value::(invalid).is_err()); + } + } + + #[test] + #[cfg(feature = "dev-tools")] + fn developer_owner_fault_mapping_never_serializes_unselected_text() { + for (reason, expected) in [ + ("GROUP_DEADLINE", HookOwnerFault::GroupDeadline), + ("GROUP_LIFETIME", HookOwnerFault::GroupLifetime), + ( + "SCOPE_OPERATION_DEADLINE", + HookOwnerFault::OperationDeadline, + ), + ("SCOPE_SETUP_DEADLINE", HookOwnerFault::OperationDeadline), + ("SCOPE_PROOF_DEADLINE", HookOwnerFault::ProofDeadline), + ("SCOPE_CLEANUP_DEADLINE", HookOwnerFault::CleanupDeadline), + ("SCOPE_CLOCK", HookOwnerFault::Clock), + ("GROUP_CLOCK", HookOwnerFault::Clock), + ("PRIVATE_RAW_CANARY", HookOwnerFault::Other), + ] { + let fault = HookOwnerFault::from_static(reason); + assert_eq!(fault, expected); + assert!(!serde_json::to_string(&fault).unwrap().contains("PRIVATE")); + } + } + + #[test] + #[cfg(all(feature = "dev-tools", unix))] + fn developer_probe_uses_one_existing_immutable_failure_marker() { + let directory = tempfile::tempdir().unwrap(); + let failure: CaptureFailure = serde_json::from_value(observed()).unwrap(); + record_failure_probed( + directory.path(), + &failure.boundary_id, + &failure.reason, + failure.probe.unwrap(), + ) + .unwrap(); + let markers = read_failure_markers(directory.path()).unwrap(); + assert_eq!(markers.len(), 1); + assert_eq!(markers[0].1.reason, failure.reason); + assert_eq!(markers[0].1.boundary_id, failure.boundary_id); + assert!(markers[0].1.probe.is_some()); + assert!(fs::read(&markers[0].0).unwrap().len() <= 1024); + + let ordinary = tempfile::tempdir().unwrap(); + record_failure(ordinary.path(), &failure.boundary_id, &failure.reason).unwrap(); + let ordinary = read_failure_markers(ordinary.path()).unwrap(); + assert_eq!(ordinary.len(), 1); + let value = serde_json::to_value(&ordinary[0].1).unwrap(); + assert_eq!(value.as_object().unwrap().len(), 3); + assert!(value.get("probe").is_none()); + } + + #[test] + #[cfg(all(feature = "dev-tools", unix))] + fn developer_failure_probes_keep_later_core_diagnostics_after_an_earlier_guard_refusal() { + let directory = tempfile::tempdir().unwrap(); + let store = Store::open(directory.path()).unwrap(); + let mut first = legacy(); + first["reason"] = serde_json::json!("BOUNDARY_REFUSED"); + first["observed_at"] = serde_json::json!(1); + let first_path = directory.path().join("capture-failure.json"); + let original = serde_json::to_vec(&first).unwrap(); + fs::write(&first_path, &original).unwrap(); + let mut expected = Vec::new(); + for phase in [HookFailurePhase::Repository, HookFailurePhase::Permit] { + let probe = HookFailureProbe { + phase, + owner_fault: Some(HookOwnerFault::GroupDeadline), + setup: None, + }; + expected.push(serde_json::to_value(probe).unwrap()); + record_failure_probed( + directory.path(), + &"a".repeat(64), + "STORAGE_UNAVAILABLE", + probe, + ) + .unwrap(); + } + assert_eq!(store.failure().unwrap().unwrap().reason, "BOUNDARY_REFUSED"); + let probes = store.developer_failure_probes().unwrap(); + let mut actual = probes + .into_iter() + .map(|probe| serde_json::to_value(probe).unwrap()) + .collect::>(); + // Same-second immutable marker filename ordering is not phase ordering. + actual.sort_by_key(|value| value.to_string()); + expected.sort_by_key(|value| value.to_string()); + assert_eq!(actual, expected); + assert_eq!(fs::read(&first_path).unwrap(), original); + assert_eq!(read_failure_markers(directory.path()).unwrap().len(), 3); + fs::write( + directory.path().join("capture-refusal-malformed.json"), + b"PRIVATE_MALFORMED_CANARY", + ) + .unwrap(); + assert!(store.developer_failure_probes().is_err()); + } + + #[test] + #[cfg(not(feature = "dev-tools"))] + fn production_reader_rejects_source_fixture_probe_metadata() { + let mut marker = legacy(); + marker["probe"] = serde_json::json!({ "phase": "repository" }); + assert!(serde_json::from_value::(marker).is_err()); + } +} + +#[cfg(all(test, feature = "dev-tools", unix))] +mod failure_summary_tests { + use super::*; + use std::io::Write; + use std::os::unix::fs::{symlink, DirBuilderExt, OpenOptionsExt}; + + fn fixture() -> (tempfile::TempDir, Store) { + let directory = tempfile::Builder::new() + .prefix("PRIVATE_SUMMARY_PATH_") + .tempdir() + .unwrap(); + // macOS temporary paths can traverse /var -> /private/var. + // Supply the real path to the production no-symlink admission checks. + let store = Store::open(&directory.path().canonicalize().unwrap()).unwrap(); + (directory, store) + } + fn probe() -> HookFailureProbe { + HookFailureProbe { + phase: HookFailurePhase::Permit, + owner_fault: None, + setup: None, + } + } + fn private_write(path: &Path, bytes: impl AsRef<[u8]>) { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .unwrap(); + file.write_all(bytes.as_ref()).unwrap(); + } + fn marker( + directory: &Path, + suffix: &str, + boundary: &str, + at: i64, + probe: Option, + ) -> Vec { + let failure = CaptureFailure { + reason: "BOUNDARY_REFUSED".into(), + boundary_id: boundary.into(), + observed_at: at, + probe, + }; + let bytes = serde_json::to_vec(&failure).unwrap(); + assert!(bytes.len() <= 1024); + private_write( + &directory.join(format!("capture-refusal-{suffix}.json")), + &bytes, + ); + bytes + } + fn invocation(directory: &Path, nonce: &str, preparing: bool, bytes: &[u8]) -> PathBuf { + let root = directory.join("capture-invocations"); + if !root.exists() { + fs::DirBuilder::new().mode(0o700).create(&root).unwrap(); + } + let publication = directory.join("capture-invocations-publication.lock"); + if !publication.exists() { + private_write(&publication, []); + } + let path = root.join(format!( + "{nonce}.{}", + if preparing { "preparing" } else { "pending" } + )); + private_write(&path, bytes); + path + } + fn summary(store: &Store) -> serde_json::Value { + let summary = store.developer_failure_summary().unwrap(); + let bytes = serde_json::to_vec(&summary).unwrap(); + assert!(bytes.len() <= 16 * 1024); + assert!(!String::from_utf8(bytes).unwrap().contains("PRIVATE")); + for record in summary["records"].as_array().unwrap() { + for key in [ + "dead_preparing_invocation_boundary_match", + "dead_pending_invocation_boundary_match", + ] { + assert!(record.as_object().unwrap().contains_key(key)); + assert!(record[key].is_null() || record[key] == true); + } + } + summary + } + + #[test] + fn direct_dead_preparing_dead_pending_and_core_records_keep_their_associations() { + let (directory, store) = fixture(); + let preparing = "b".repeat(64); + let pending = "c".repeat(64); + invocation( + directory.path(), + &preparing, + true, + b"KEITO_CAPTURE_PENDING_V1\n", + ); + invocation( + directory.path(), + &pending, + false, + b"KEITO_CAPTURE_PENDING_V1\n", + ); + let direct = "d".repeat(64); + let first = marker(directory.path(), &direct, &direct, 1, None); + marker( + directory.path(), + &"e".repeat(64), + &hash(format!("INVOCATION\0{preparing}")), + 2, + None, + ); + marker( + directory.path(), + &"f".repeat(64), + &hash(format!("INVOCATION\0{pending}")), + 3, + None, + ); + marker( + directory.path(), + &"a".repeat(64), + &hash("synthetic core boundary"), + 4, + Some(probe()), + ); + marker(directory.path(), &preparing, &preparing, 5, None); + let value = summary(&store); + assert_eq!(value["total_records"], 5); + assert_eq!(value["unprobed_records"], 4); + assert_eq!(value["probed_records"], 1); + assert_eq!(value["invocation_snapshot"], "observed"); + let records = value["records"].as_array().unwrap(); + assert_eq!(records[0]["selected_for_status"], true); + assert_eq!(records[0]["failure"]["boundary_id"], direct); + assert_eq!(records[0]["filename_boundary_match"], true); + assert!(records[0]["invocation_nonce_match"].is_null()); + assert_eq!(records[1]["dead_invocation_boundary_match"], true); + assert_eq!(records[1]["filename_boundary_match"], false); + assert_eq!(records[2]["dead_invocation_boundary_match"], true); + assert_eq!(records[1]["dead_preparing_invocation_boundary_match"], true); + assert!(records[1]["dead_pending_invocation_boundary_match"].is_null()); + assert_eq!(records[2]["dead_pending_invocation_boundary_match"], true); + assert!(records[2]["dead_preparing_invocation_boundary_match"].is_null()); + for index in [0, 3, 4] { + assert!(records[index]["dead_preparing_invocation_boundary_match"].is_null()); + assert!(records[index]["dead_pending_invocation_boundary_match"].is_null()); + } + assert_eq!(records[3]["failure"]["probe"]["phase"], "permit"); + assert!(records[3]["dead_invocation_boundary_match"].is_null()); + assert_eq!(records[4]["invocation_nonce_match"], true); + assert_eq!( + fs::read( + directory + .path() + .join(format!("capture-refusal-{direct}.json")) + ) + .unwrap(), + first + ); + assert_eq!(store.failure().unwrap().unwrap().boundary_id, direct); + } + + #[test] + fn same_second_selection_is_lexical_not_write_order_or_causality() { + let (directory, store) = fixture(); + let later_name = "f".repeat(64); + let selected_name = "a".repeat(64); + marker( + directory.path(), + &later_name, + &later_name, + 10, + Some(probe()), + ); + marker(directory.path(), &selected_name, &selected_name, 10, None); + let value = summary(&store); + assert_eq!( + value["selection_order"], + "observed_at_seconds_then_filename_not_causal" + ); + assert_eq!(value["records"][0]["failure"]["boundary_id"], selected_name); + assert_eq!(value["records"][0]["selection_index"], 0); + assert_eq!(value["records"][1]["selected_for_status"], false); + assert_eq!(store.failure().unwrap().unwrap().boundary_id, selected_name); + } + + #[test] + fn invalid_invocation_snapshot_keeps_records_but_associations_unknown() { + let (directory, store) = fixture(); + let nonce = "b".repeat(64); + let boundary = hash(format!("INVOCATION\0{nonce}")); + marker(directory.path(), &"a".repeat(64), &boundary, 1, None); + invocation(directory.path(), &nonce, false, b"PRIVATE_INVALID_MARKER"); + let value = summary(&store); + assert_eq!(value["total_records"], 1); + assert_eq!(value["invocation_snapshot"], "unknown"); + assert!(value["records"][0]["invocation_nonce_match"].is_null()); + assert!(value["records"][0]["dead_invocation_boundary_match"].is_null()); + assert!(value["records"][0]["dead_preparing_invocation_boundary_match"].is_null()); + assert!(value["records"][0]["dead_pending_invocation_boundary_match"].is_null()); + } + + #[test] + fn lost_invocation_association_remains_unknown_after_a_valid_empty_snapshot() { + let (directory, store) = fixture(); + let nonce = "b".repeat(64); + let boundary = hash(format!("INVOCATION\0{nonce}")); + marker(directory.path(), &"a".repeat(64), &boundary, 1, None); + let path = invocation( + directory.path(), + &nonce, + false, + b"KEITO_CAPTURE_PENDING_V1\n", + ); + let before = summary(&store); + assert_eq!(before["records"][0]["dead_invocation_boundary_match"], true); + assert_eq!( + before["records"][0]["dead_pending_invocation_boundary_match"], + true + ); + assert!(before["records"][0]["dead_preparing_invocation_boundary_match"].is_null()); + fs::remove_file(path).unwrap(); + let value = summary(&store); + assert_eq!(value["invocation_snapshot"], "observed"); + assert_eq!(value["association_missing"], "UNKNOWN"); + assert_eq!( + value["snapshot_relation"], + "marker_status_and_invocation_reads_are_not_atomic" + ); + assert!(value["records"][0]["dead_invocation_boundary_match"].is_null()); + assert!(value["records"][0]["dead_preparing_invocation_boundary_match"].is_null()); + assert!(value["records"][0]["dead_pending_invocation_boundary_match"].is_null()); + } + + #[test] + fn malformed_symlink_and_oversized_failure_inputs_are_unavailable() { + for kind in 0..3 { + let (directory, store) = fixture(); + let path = directory + .path() + .join(format!("capture-refusal-{}.json", "a".repeat(64))); + match kind { + 0 => private_write(&path, b"PRIVATE_MALFORMED_CANARY"), + 1 => { + let target = directory.path().join("PRIVATE_TARGET"); + private_write(&target, b"PRIVATE_SYMLINK_CANARY"); + symlink(target, &path).unwrap(); + } + _ => private_write(&path, vec![b'x'; 1025]), + } + assert!(store.developer_failure_summary().is_err()); + } + } + + #[test] + fn reader_cap_and_sample_cap_preserve_selected_and_unprobed_counts() { + let (directory, store) = fixture(); + for index in 0..1024 { + let suffix = format!("{index:064x}"); + marker( + directory.path(), + &suffix, + &suffix, + index, + if index == 0 { Some(probe()) } else { None }, + ); + } + let value = summary(&store); + assert_eq!(value["total_records"], 1024); + assert_eq!(value["sampled_records"], 8); + assert_eq!(value["omitted_records"], 1016); + assert_eq!(value["unprobed_records"], 1023); + assert_eq!(value["probed_records"], 1); + assert_eq!(value["records"][0]["selected_for_status"], true); + marker( + directory.path(), + &format!("{:064x}", 1024), + &"a".repeat(64), + 1024, + None, + ); + assert!(store.developer_failure_summary().is_err()); + } + + #[test] + fn bounded_sample_keeps_a_later_probe_without_losing_the_selected_marker() { + let (directory, store) = fixture(); + let full = HookFailureProbe { + phase: HookFailurePhase::Event, + owner_fault: Some(HookOwnerFault::GroupDeadline), + setup: Some(HookSetupProbe { + fault_state: Some(HookGroupState::AwaitReady), + ready_window_ns: Some(u64::MAX), + pre_spawn_offset_ns: Some(u64::MAX), + spawn_return_offset_ns: Some(u64::MAX), + first_ready_poll_offset_ns: Some(u64::MAX), + deadline_offset_ns: Some(u64::MAX), + ready_frame_observed: true, + ready_eof_observed: true, + deadline_edge: Some(HookReadyEdge::ParkAfterReceive), + park_end_offset_ns: Some(u64::MAX), + workload_spawn_return_offset_ns: Some(u64::MAX), + first_park_poll_offset_ns: Some(u64::MAX), + park_frame_observed: Some(true), + }), + }; + for index in 0..12 { + let suffix = format!("{index:064x}"); + marker( + directory.path(), + &suffix, + &suffix, + index, + if index == 11 { Some(full) } else { None }, + ); + } + let value = summary(&store); + assert_eq!(value["total_records"], 12); + assert_eq!(value["sampled_records"], 8); + assert_eq!(value["omitted_records"], 4); + assert_eq!(value["records"][0]["selected_for_status"], true); + assert!(value["records"] + .as_array() + .unwrap() + .iter() + .any(|record| record["selection_index"] == 11)); + } + + #[test] + fn legacy_filename_has_no_invented_filename_relation_and_empty_summary_is_bounded() { + let (directory, store) = fixture(); + let empty = summary(&store); + assert_eq!(empty["total_records"], 0); + assert_eq!(empty["sampled_records"], 0); + assert_eq!(empty["records"].as_array().unwrap().len(), 0); + let bytes = serde_json::to_vec(&CaptureFailure { + reason: "STORAGE_UNAVAILABLE".into(), + boundary_id: "a".repeat(64), + observed_at: 1, + probe: None, + }) + .unwrap(); + private_write(&directory.path().join("capture-failure.json"), bytes); + let value = summary(&store); + assert!(value["records"][0]["filename_boundary_match"].is_null()); + assert!(value["records"][0]["invocation_nonce_match"].is_null()); + } +} + +#[cfg(all(test, unix))] +mod owned_probe_tests { + use super::*; + use crate::process_ownership::{io::CommandOutput, probes::LeafRunner, scope::CommandResult}; + use std::{collections::VecDeque, io, os::unix::process::ExitStatusExt}; + struct Replies { + values: VecDeque>, + calls: usize, + } + impl LeafRunner for Replies { + fn output( + &mut self, + command: Command, + stdout_cap: usize, + stderr_cap: usize, + ) -> io::Result { + assert_eq!(command.get_program(), "git"); + assert!(stdout_cap <= 1024 * 1024 && stderr_cap <= 8192); + self.calls += 1; + self.values.pop_front().expect("unexpected extra command") + } + } + fn reply(code: i32, bytes: Vec) -> io::Result { + Ok(CommandResult { + status: std::process::ExitStatus::from_raw(code << 8), + output: CommandOutput { + stdout: bytes, + stderr: Vec::new(), + }, + }) + } + #[test] + fn r40_real_repository_resolver_uses_three_results_and_known_empty_exit() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let bytes = root.to_str().unwrap().as_bytes().to_vec(); + let mut replies = Replies { + values: [ + reply(0, bytes.clone()), + reply(0, bytes), + reply(1, Vec::new()), + ] + .into(), + calls: 0, + }; + let repository = Repository::resolve_with(&root, &mut replies).unwrap(); + assert_eq!(replies.calls, 3); + assert_eq!(repository.remote_hash, hash("")); + } + #[test] + fn r40_real_repository_resolver_never_swallows_ownership_failure() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let bytes = root.to_str().unwrap().as_bytes().to_vec(); + let mut replies = Replies { + values: [ + reply(0, bytes.clone()), + reply(0, bytes), + Err(io::Error::other("OWNERSHIP_FAILED")), + ] + .into(), + calls: 0, + }; + assert!(Repository::resolve_with(&root, &mut replies).is_err()); + assert_eq!(replies.calls, 3); + } + struct CohortReplies { + directory: PathBuf, + results: Option>, + fallback: VecDeque>, + } + impl LeafRunner for CohortReplies { + fn repository_outputs( + &mut self, + commands: [Command; 2], + ) -> Option> { + let expected: [&[&str]; 2] = [ + &[ + "rev-parse", + "--path-format=absolute", + "--show-toplevel", + "--git-common-dir", + ], + &["config", "--get-regexp", "^remote\\..*\\.url$"], + ]; + for (command, args) in commands.into_iter().zip(expected) { + assert_eq!(command.get_program(), "git"); + let actual: Vec<_> = command.get_args().collect(); + assert_eq!(actual[0], "-C"); + assert_eq!(actual[1], self.directory.as_os_str()); + assert_eq!( + actual[2..], + args.iter().map(std::ffi::OsStr::new).collect::>() + ); + assert!(command.get_envs().next().is_none()); + } + Some(self.results.take().expect("one repository cohort")) + } + fn output( + &mut self, + command: Command, + stdout_cap: usize, + stderr_cap: usize, + ) -> io::Result { + assert_eq!(command.get_program(), "git"); + assert_eq!((stdout_cap, stderr_cap), (8192, 8192)); + let arguments = command.get_args().collect::>(); + assert_eq!(arguments[0], "-C"); + assert_eq!(arguments[1], self.directory.as_os_str()); + let expected: &[&str] = if self.fallback.len() == 2 { + &["rev-parse", "--show-toplevel"] + } else { + &["rev-parse", "--path-format=absolute", "--git-common-dir"] + }; + assert_eq!( + arguments[2..], + expected + .iter() + .map(std::ffi::OsStr::new) + .collect::>() + ); + self.fallback + .pop_front() + .expect("unexpected sequential repository lookup") + } + } + #[test] + fn repository_cohort_resolver_preserves_commands_remote_sorting_and_empty_exit() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let path = format!("{}\n{}\n", root.display(), root.display()).into_bytes(); + for remotes in [ + reply(1, Vec::new()).unwrap(), + reply(0, b"z url2\na url1\n".to_vec()).unwrap(), + ] { + let expected = if remotes.status.code() == Some(1) { + hash("") + } else { + hash("a url1\nz url2") + }; + let mut runner = CohortReplies { + directory: root.clone(), + fallback: VecDeque::new(), + results: Some(Ok([reply(0, path.clone()).unwrap(), remotes])), + }; + let result = Repository::resolve_with(&root, &mut runner).unwrap(); + assert_eq!(result.key, hash(root.to_string_lossy().as_bytes())); + assert_eq!(result.remote_hash, expected); + assert!(runner.results.is_none()); + } + } + #[test] + fn repository_cohort_resolver_retains_ownership_and_text_refusals() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let path = format!("{}\n{}\n", root.display(), root.display()).into_bytes(); + for refusal in ["owner", "root", "common", "remote"] { + let mut results = [ + reply(0, path.clone()).unwrap(), + reply(1, Vec::new()).unwrap(), + ]; + match refusal { + "root" => results[0] = reply(128, Vec::new()).unwrap(), + "common" => results[0] = reply(0, vec![255]).unwrap(), + "remote" => results[1].output.stderr = b"private error never published".to_vec(), + _ => (), + } + let mut runner = CohortReplies { + directory: root.clone(), + fallback: VecDeque::new(), + results: Some(if refusal == "owner" { + Err(io::Error::other("private owner error")) + } else { + Ok(results) + }), + }; + let error = Repository::resolve_with(&root, &mut runner).unwrap_err(); + assert!(!error.to_string().contains("private")); + } + } + #[test] + fn repository_cohort_newline_paths_use_original_queries_without_guessing_or_hiding_failure() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("line\nbreak"); + let common = temp.path().join("common"); + fs::create_dir(&root).unwrap(); + fs::create_dir(&common).unwrap(); + let root = root.canonicalize().unwrap(); + let common = common.canonicalize().unwrap(); + for fail in [false, true] { + let mut runner = CohortReplies { + directory: root.clone(), + results: Some(Ok([ + reply( + 0, + format!("{}\n{}\n", root.display(), common.display()).into_bytes(), + ) + .unwrap(), + reply(0, b"z url2\na url1\n".to_vec()).unwrap(), + ])), + fallback: [ + if fail { + Err(io::Error::other("PRIVATE_OWNER_ERROR")) + } else { + reply(0, root.to_str().unwrap().as_bytes().to_vec()) + }, + reply(0, common.to_str().unwrap().as_bytes().to_vec()), + ] + .into(), + }; + let result = Repository::resolve_with(&root, &mut runner); + if fail { + assert!(!result.unwrap_err().to_string().contains("PRIVATE")); + assert_eq!(runner.fallback.len(), 1); + } else { + let repository = result.unwrap(); + assert_eq!(repository.key, hash(common.to_string_lossy().as_bytes())); + assert_eq!(repository.remote_hash, hash("a url1\nz url2")); + assert!(runner.fallback.is_empty()); + } + } + } + #[test] + fn repository_cohort_matches_scalar_trimming_and_hint_selection_for_sibling_paths() { + let temp = tempfile::tempdir().unwrap(); + let selected = temp.path().join("repo"); + let actual = temp.path().join("repo "); + fs::create_dir_all(selected.join(".keito")).unwrap(); + fs::create_dir_all(actual.join(".git")).unwrap(); + fs::write( + selected.join(".keito/config.yml"), + b"agent_tracking:\n enabled: false\n", + ) + .unwrap(); + let actual = actual.canonicalize().unwrap(); + let common = actual.join(".git"); + let mut scalar = Replies { + values: [ + reply(0, format!("{}\n", actual.display()).into_bytes()), + reply(0, format!("{}\n", common.display()).into_bytes()), + reply(1, Vec::new()), + ] + .into(), + calls: 0, + }; + let expected = Repository::resolve_with(&actual, &mut scalar).unwrap(); + assert!(expected.disabled); + let mut cohort = CohortReplies { + directory: actual.clone(), + results: Some(Ok([ + reply( + 0, + format!("{}\n{}\n", actual.display(), common.display()).into_bytes(), + ) + .unwrap(), + reply(1, Vec::new()).unwrap(), + ])), + fallback: VecDeque::new(), + }; + let observed = Repository::resolve_with(&actual, &mut cohort).unwrap(); + assert_eq!(observed.key, expected.key); + assert_eq!(observed.remote_hash, expected.remote_hash); + assert_eq!(observed.disabled, expected.disabled); + assert_eq!(observed.hint_hash, expected.hint_hash); + assert_eq!(observed.linked_without_hint, expected.linked_without_hint); + } + #[test] + fn repository_cohort_refused_remote_does_not_start_ambiguous_path_fallback() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let mut runner = CohortReplies { + directory: root.clone(), + results: Some(Ok([ + reply(0, b"/ambiguous\npath\n/common\n".to_vec()).unwrap(), + reply(128, Vec::new()).unwrap(), + ])), + fallback: VecDeque::new(), + }; + assert!(Repository::resolve_with(&root, &mut runner).is_err()); + assert!(runner.fallback.is_empty()); + } + #[test] + fn repository_cohort_missing_invalid_and_oversized_identity_does_not_fall_back() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + for identity in [ + Vec::new(), + b"one".to_vec(), + b"\n\n".to_vec(), + b" \n \n".to_vec(), + vec![255], + format!("{}\n{}", root.display(), "a".repeat(8192)).into_bytes(), + format!( + "{}\n{}{}\n", + root.display(), + root.display(), + " ".repeat(8192) + ) + .into_bytes(), + ] { + let mut runner = CohortReplies { + directory: root.clone(), + results: Some(Ok([ + reply(0, identity).unwrap(), + reply(1, Vec::new()).unwrap(), + ])), + fallback: VecDeque::new(), + }; + assert!(Repository::resolve_with(&root, &mut runner).is_err()); + assert!(runner.fallback.is_empty()); + } + } + #[test] + fn repository_default_canonicalization_refusal_does_not_start_later_commands() { + let temp = tempfile::tempdir().unwrap(); + let mut runner = Replies { + values: [reply( + 0, + temp.path() + .join("absent") + .to_str() + .unwrap() + .as_bytes() + .to_vec(), + )] + .into(), + calls: 0, + }; + assert!(Repository::resolve_with(temp.path(), &mut runner).is_err()); + assert_eq!(runner.calls, 1); + } + #[test] + fn repository_cohort_default_runner_still_short_circuits_invalid_root() { + let mut runner = Replies { + values: [reply(128, Vec::new())].into(), + calls: 0, + }; + assert!(Repository::resolve_with(Path::new("/unused"), &mut runner).is_err()); + assert_eq!(runner.calls, 1); + } +} + +#[cfg(all(test, target_os = "macos"))] +mod native_boot_clock_tests { + use super::*; + + fn sample(seconds: i64, micros: i32) -> String { + native_boot_identity_from(|value, length| { + assert_eq!(value.tv_sec, 0); + assert_eq!(value.tv_usec, 0); + assert_eq!(*length, std::mem::size_of::()); + value.tv_sec = seconds; + value.tv_usec = micros; + 0 + }) + .unwrap() + } + + #[test] + fn native_boot_clock_valid_sample_has_stable_domain_and_field_identity() { + let first = sample(1_700_000_000, 123); + assert_eq!(first, hash("macos-kern-boottime-v1:1700000000:123")); + assert_eq!(first, sample(1_700_000_000, 123)); + assert_ne!(first, sample(1_700_000_001, 123)); + assert_ne!(first, sample(1_700_000_000, 124)); + assert_eq!(first.len(), 64); + } + + #[test] + fn native_boot_clock_invalid_status_size_and_values_never_fall_back() { + for (status, length, seconds, micros) in [ + (-1, std::mem::size_of::(), 1, 0), + (0, 0, 1, 0), + (0, std::mem::size_of::() - 1, 1, 0), + (0, std::mem::size_of::() + 1, 1, 0), + (0, std::mem::size_of::(), 0, 0), + (0, std::mem::size_of::(), -1, 0), + (0, std::mem::size_of::(), 1, -1), + (0, std::mem::size_of::(), 1, 1_000_000), + ] { + assert!(native_boot_identity_from(|value, size| { + value.tv_sec = seconds; + value.tv_usec = micros; + *size = length; + status + }) + .is_none()); + } + } + + #[test] + fn native_boot_clock_keeps_elapsed_boot_rollback_and_drift_refusals() { + let start = Clock { + wall: 100, + monotonic: 100, + boot: sample(1_700_000_000, 0), + }; + let mut end = Clock { + wall: 130, + monotonic: 130, + boot: start.boot.clone(), + }; + assert_eq!(start.elapsed(&end), Some(30)); + end.boot = sample(1_700_000_001, 0); + assert_eq!(start.elapsed(&end), None); + end.boot = start.boot.clone(); + end.wall = 99; + assert_eq!(start.elapsed(&end), None); + end.wall = 140; + assert_eq!(start.elapsed(&end), None); + } + + #[test] + fn native_boot_clock_legacy_identity_closes_zero_incomplete_with_attention() { + let before = Clock { + wall: 100, + monotonic: 100, + boot: hash("legacy-formatted-sysctl-output"), + }; + let after = Clock { + wall: 130, + monotonic: 130, + boot: sample(1_700_000_000, 0), + }; + let binding = Binding { + repository_key: hash("repo"), + remote_hash: hash(""), + hint_hash: hash("hint"), + id: hash("binding"), + version: 1, + workspace_id: "co_synthetic".into(), + owner_id: "owner_synthetic".into(), + origin_hash: hash("origin"), + project_id: "project_synthetic".into(), + task_id: "task_synthetic".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }; + let mut session = Session::begin(&binding, "codex", "session", "0.167.0", &before); + session.active = Some(ActiveTurn { + key: "turn".into(), + part: 0, + clock: Some(before), + }); + session.close(&after, true).unwrap(); + assert!(session.needs_attention); + assert!(session.active.is_none()); + assert_eq!(session.segments.len(), 1); + assert_eq!(session.segments[0].duration_seconds, 0); + assert_eq!(session.segments[0].completeness, "INCOMPLETE"); + assert_eq!(session.segments[0].started_at, session.segments[0].ended_at); + } +} diff --git a/src/capture_authority.rs b/src/capture_authority.rs new file mode 100644 index 0000000..9b310e2 --- /dev/null +++ b/src/capture_authority.rs @@ -0,0 +1,101 @@ +//! Cross-process refusal authority. Acquire SQLite first, then this bounded lock. +//! Marker publication never waits for the lock and uses immutable unique files. +use crate::error::AppError; +use std::fs::File; +#[cfg(unix)] +use std::fs::OpenOptions; +use std::path::Path; +#[cfg(unix)] +use std::time::{Duration, Instant}; +fn refused() -> AppError { + AppError::Config("Capture authority unavailable; collection remains paused".into()) +} +pub struct AuthorityGuard { + _file: File, +} +#[cfg(unix)] +pub(crate) struct PublicationReadGuard { + _guard: AuthorityGuard, +} +impl AuthorityGuard { + #[cfg(unix)] + pub fn publication(parent: &File) -> Result { + Self::publication_mode(parent, false) + } + #[cfg(unix)] + pub(crate) fn publication_read(parent: &File) -> Result { + Ok(PublicationReadGuard { + _guard: Self::publication_mode(parent, true)?, + }) + } + #[cfg(unix)] + fn publication_mode(parent: &File, shared: bool) -> Result { + use std::os::fd::{AsRawFd, FromRawFd}; + let name = std::ffi::CString::new("capture-invocations-publication.lock") + .map_err(|_| refused())?; + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDWR | libc::O_CREAT | libc::O_NOFOLLOW | libc::O_CLOEXEC, + 0o600, + ) + }; + if fd < 0 { + return Err(refused()); + } + Self::lock_mode(unsafe { File::from_raw_fd(fd) }, true, shared) + } + #[cfg(unix)] + pub fn acquire(directory: &Path, wait: bool) -> Result { + use std::os::unix::fs::OpenOptionsExt; + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(directory.join("capture-authority.lock")) + .map_err(|_| refused())?; + Self::lock(file, wait) + } + #[cfg(unix)] + fn lock(file: File, wait: bool) -> Result { + Self::lock_mode(file, wait, false) + } + #[cfg(unix)] + fn lock_mode(file: File, wait: bool, shared: bool) -> Result { + use std::os::fd::AsRawFd; + use std::os::unix::fs::MetadataExt; + use std::os::unix::fs::PermissionsExt; + let metadata = file.metadata().map_err(|_| refused())?; + if !metadata.is_file() + || metadata.nlink() != 1 + || metadata.uid() != unsafe { libc::geteuid() } + { + return Err(refused()); + } + file.set_permissions(std::fs::Permissions::from_mode(0o600)) + .map_err(|_| refused())?; + let start = Instant::now(); + let mode = if shared { libc::LOCK_SH } else { libc::LOCK_EX }; + loop { + if unsafe { libc::flock(file.as_raw_fd(), mode | libc::LOCK_NB) } == 0 { + return Ok(Self { _file: file }); + } + let error = std::io::Error::last_os_error(); + if !wait + || error.kind() != std::io::ErrorKind::WouldBlock + || start.elapsed() >= Duration::from_millis(25) + { + return Err(refused()); + } + std::thread::sleep(Duration::from_millis(1)); + } + } + #[cfg(not(unix))] + pub fn acquire(_directory: &Path, _wait: bool) -> Result { + Err(refused()) + } +} diff --git a/src/capture_busy.rs b/src/capture_busy.rs new file mode 100644 index 0000000..1af76d7 --- /dev/null +++ b/src/capture_busy.rs @@ -0,0 +1,742 @@ +//! Private SQLite admission budget. Preserve the bundled 500ms/backoff/14-sleep +//! ceiling while accounting for actual monotonic elapsed time, including OS +//! oversleep. Scheduling can still delay a callback; this is not a hard OS bound. +use std::time::Duration; + +const BUDGET: Duration = Duration::from_millis(500); +const DELAYS_MS: [u64; 14] = [1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100, 100, 72]; + +#[derive(Default)] +pub(crate) struct BusyBudget { + operation: Option, +} + +struct Operation { + started: Duration, + last_observed: Duration, + next_count: i32, + hints_allowed: bool, + hinted_attempt_pending: bool, + unelapsed_backoff: Duration, +} + +impl BusyBudget { + #[cfg(test)] + pub(crate) fn retry( + &mut self, + count: i32, + mut now: impl FnMut() -> Option, + mut sleep: impl FnMut(Duration), + ) -> bool { + self.retry_hinted(count, &mut now, |delay, _| { + sleep(delay); + false + }) + } + pub(crate) fn retry_hinted( + &mut self, + count: i32, + mut now: impl FnMut() -> Option, + mut sleep: impl FnMut(Duration, bool) -> bool, + ) -> bool { + let Some(delay) = usize::try_from(count) + .ok() + .and_then(|index| DELAYS_MS.get(index)) + else { + self.operation = None; + return false; + }; + let Some(before) = now() else { + self.operation = None; + return false; + }; + // SQLite count zero starts a distinct locking operation. Never reset + // the budget for later callbacks belonging to that operation. + if count == 0 { + self.operation = Some(Operation { + started: before, + last_observed: before, + next_count: 0, + hints_allowed: true, + hinted_attempt_pending: false, + unelapsed_backoff: Duration::ZERO, + }); + } + let Some(operation) = &mut self.operation else { + return false; + }; + if count != operation.next_count || before < operation.last_observed { + self.operation = None; + return false; + } + let Some(remaining) = before + .checked_sub(operation.started) + .and_then(|elapsed| BUDGET.checked_sub(elapsed)) + .filter(|remaining| !remaining.is_zero()) + else { + self.operation = None; + return false; + }; + // Another callback means the preceding hinted SQL attempt FAILED. + // Disable later hints and restore that delay's unelapsed portion so + // repeated commit/reacquire races cannot spend all attempts early. + if operation.hinted_attempt_pending { + operation.hints_allowed = false; + operation.hinted_attempt_pending = false; + } + let restored = std::mem::take(&mut operation.unelapsed_backoff); + let requested = Duration::from_millis(*delay) + .saturating_add(restored) + .min(remaining); + // The final timer-only callback cannot manufacture an extra retry. + let allow_hint = operation.hints_allowed && (count as usize) + 1 < DELAYS_MS.len(); + let hinted = sleep(requested, allow_hint); + let Some(after) = now() else { + self.operation = None; + return false; + }; + if after < before + || after + .checked_sub(operation.started) + .is_none_or(|elapsed| elapsed >= BUDGET) + { + self.operation = None; + return false; + } + if allow_hint && hinted { + operation.hinted_attempt_pending = true; + operation.unelapsed_backoff = requested.saturating_sub(after - before); + } + operation.last_observed = after; + operation.next_count += 1; + true + } +} + +// Optional in-process wake hints only. Every wake returns to SQLite's ORIGINAL +// busy callback/count; BusyBudget owns all500ms/14callback refusal decisions. +#[derive(Clone)] +pub(crate) struct ReleaseNotifier(std::sync::Arc); +struct WakeQueue { + waiters: std::sync::Mutex>>, +} +struct Waiter { + state: std::sync::Mutex, + ready: std::sync::Condvar, + until: std::time::Instant, +} +#[derive(Clone, Copy, PartialEq, Eq)] +enum WaitState { + Waiting, + Selected, + Retired, +} +#[cfg(unix)] +#[derive(PartialEq, Eq)] +struct DatabaseKey { + path: std::path::PathBuf, + device: u64, + inode: u64, +} +#[cfg(unix)] +type Registry = Vec<(DatabaseKey, std::sync::Weak)>; +#[cfg(unix)] +const MAX_DATABASE_HINTS: usize = 256; +const MAX_WAIT_HINTS: usize = 4096; +#[cfg(unix)] +static WAKE_REGISTRY: std::sync::OnceLock> = std::sync::OnceLock::new(); +impl ReleaseNotifier { + pub(crate) fn for_database(path: &std::path::Path) -> Option { + #[cfg(unix)] + { + Self::for_registry(path, WAKE_REGISTRY.get_or_init(Default::default)) + } + #[cfg(not(unix))] + { + let _ = path; + None + } + } + #[cfg(unix)] + fn for_registry(path: &std::path::Path, registry: &std::sync::Mutex) -> Option { + use std::os::unix::fs::MetadataExt; + let path = path.canonicalize().ok()?; + let metadata = std::fs::metadata(&path).ok()?; + if !metadata.is_file() { + return None; + } + let key = DatabaseKey { + path, + device: metadata.dev(), + inode: metadata.ino(), + }; + let mut registry = registry.try_lock().ok()?; + registry.retain(|(_, weak)| weak.strong_count() != 0); + if let Some(queue) = registry + .iter() + .find_map(|(candidate, weak)| (candidate == &key).then(|| weak.upgrade()).flatten()) + { + return Some(Self(queue)); + } + if registry.len() >= MAX_DATABASE_HINTS || registry.try_reserve(1).is_err() { + return None; + } + let queue = std::sync::Arc::new(WakeQueue { + waiters: std::sync::Mutex::new(std::collections::VecDeque::new()), + }); + registry.push((key, std::sync::Arc::downgrade(&queue))); + Some(Self(queue)) + } + fn register(&self, until: std::time::Instant) -> Option> { + let waiter = std::sync::Arc::new(Waiter { + state: std::sync::Mutex::new(WaitState::Waiting), + ready: std::sync::Condvar::new(), + until, + }); + let mut queue = self.0.waiters.try_lock().ok()?; + queue.retain(|weak| weak.strong_count() != 0); + if queue.len() >= MAX_WAIT_HINTS || queue.try_reserve(1).is_err() { + return None; + } + queue.push_back(std::sync::Arc::downgrade(&waiter)); + Some(waiter) + } + pub(crate) fn wait(&self, requested: Duration) -> bool { + let Some(until) = std::time::Instant::now().checked_add(requested) else { + std::thread::sleep(requested); + return false; + }; + let fallback = + || std::thread::sleep(until.saturating_duration_since(std::time::Instant::now())); + let Some(waiter) = self.register(until) else { + fallback(); + return false; + }; + let Ok(mut state) = waiter.state.try_lock() else { + fallback(); + return false; + }; + loop { + if *state == WaitState::Selected { + *state = WaitState::Retired; + return true; + } + if *state == WaitState::Retired { + return false; + } + let remaining = until.saturating_duration_since(std::time::Instant::now()); + if remaining.is_zero() { + *state = WaitState::Retired; + return false; + } + match waiter.ready.wait_timeout(state, remaining) { + Ok((next, _)) => state = next, + Err(error) => { + let (mut next, _) = error.into_inner(); + *next = WaitState::Retired; + drop(next); + fallback(); + return false; + } + } + // Spurious/cross-queue wakes cannot return this callback early: + // keep the SAME absolute timer unless this node was selected. + } + } + // Only successful writer commit + subsequent original AuthorityGuard drop + // call this. Error/rollback/unknown-release paths emit NO scheduling hint. + pub(crate) fn released_after_authority(&self) { + let Ok(mut queue) = self.0.waiters.try_lock() else { + return; + }; + while let Some(weak) = queue.pop_front() { + let Some(waiter) = weak.upgrade() else { + continue; + }; + let Ok(mut state) = waiter.state.try_lock() else { + continue; + }; + if *state != WaitState::Waiting { + continue; + } + if std::time::Instant::now() >= waiter.until { + *state = WaitState::Retired; + continue; + } + *state = WaitState::Selected; + drop(state); + drop(queue); + // Per-node condition variable: never wake an arbitrary ticket. + waiter.ready.notify_one(); + return; + } + // No already-waiting node: discard, never bank a future retry credit. + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn tick(policy: &mut BusyBudget, count: i32, clock: &Cell) -> bool { + policy.retry( + count, + || Some(Duration::from_millis(clock.get())), + |delay| clock.set(clock.get() + delay.as_millis() as u64), + ) + } + + #[test] + fn normal_backoff_retains_500ms_requested_sleep_and_fourteen_sleep_ceiling() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(0); + let mut sleeps = Vec::new(); + for count in 0..=14 { + if !policy.retry( + count, + || Some(Duration::from_millis(clock.get())), + |delay| { + sleeps.push(delay.as_millis() as u64); + clock.set(clock.get() + delay.as_millis() as u64); + }, + ) { + break; + } + } + // Independently state the bundled policy, rather than comparing the + // implementation against its own schedule constant. + assert_eq!( + sleeps, + [1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100, 100, 72] + ); + assert_eq!(Duration::from_millis(clock.get()), BUDGET); + assert!(!tick(&mut policy, 14, &clock)); + } + + #[test] + fn failed_release_hint_cannot_compress_all_attempts_before_contention_ends() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(Duration::ZERO); + let mut hints = 0; + let mut admitted = false; + for count in 0..=14 { + let retry = policy.retry_hinted( + count, + || Some(clock.get()), + |delay, allowed| { + if allowed { + hints += 1; + clock.set(clock.get() + Duration::from_micros(100)); + true + } else { + clock.set(clock.get() + delay); + false + } + }, + ); + if !retry { + break; + } + // A committing writer immediately reacquires; hinted attempts fail + // until contention genuinely ends at400ms. No SQL retry is added. + if clock.get() >= Duration::from_millis(400) { + admitted = true; + break; + } + } + assert!( + admitted, + "early notices exhausted attempts before the writer released" + ); + assert_eq!( + hints, 1, + "an unsuccessful hinted attempt must disable later hints" + ); + assert_eq!(clock.get(), Duration::from_millis(428)); + } + #[test] + fn restored_hint_backoff_is_capped_by_the_original_elapsed_deadline() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(Duration::ZERO); + assert!(policy.retry_hinted( + 0, + || Some(clock.get()), + |_, allowed| { + assert!(allowed); + clock.set(Duration::from_micros(100)); + true + } + )); + clock.set(Duration::from_micros(499_500)); + let mut requested = Duration::ZERO; + assert!(!policy.retry_hinted( + 1, + || Some(clock.get()), + |delay, allowed| { + assert!(!allowed); + requested = delay; + clock.set(clock.get() + delay); + false + } + )); + assert_eq!(requested, Duration::from_micros(500)); + assert_eq!(clock.get(), BUDGET); + } + #[test] + fn a_distinct_count_zero_clears_failed_hint_state_without_carrying_delay() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(Duration::ZERO); + assert!(policy.retry_hinted( + 0, + || Some(clock.get()), + |_, allowed| { + assert!(allowed); + clock.set(Duration::from_micros(100)); + true + } + )); + assert!(policy.retry_hinted( + 1, + || Some(clock.get()), + |delay, allowed| { + assert!(!allowed); + assert_eq!(delay, Duration::from_micros(2900)); + clock.set(clock.get() + delay); + false + } + )); + assert!(policy.retry_hinted( + 0, + || Some(clock.get()), + |delay, allowed| { + assert!(allowed); + assert_eq!(delay, Duration::from_millis(1)); + clock.set(clock.get() + delay); + false + } + )); + } + #[test] + fn final_callback_remains_timer_only_and_never_resets_the_attempt_ceiling() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(Duration::ZERO); + for count in 0..14 { + let retry = policy.retry_hinted( + count, + || Some(clock.get()), + |delay, allowed| { + assert_eq!(allowed, count < 13); + clock.set(clock.get() + delay); + false + }, + ); + assert_eq!(retry, count < 13); + } + assert_eq!(clock.get(), BUDGET); + assert!(!policy.retry_hinted(14, || Some(clock.get()), |_, _| panic!("extra sleep"))); + } + #[test] + fn one_oversleep_stops_without_an_additional_lock_retry() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(100); + let retry = policy.retry( + 0, + || Some(Duration::from_millis(clock.get())), + |_| clock.set(701), + ); + assert!( + !retry, + "a 601ms first sleep exhausted the 500ms operation budget" + ); + } + + #[test] + fn scheduler_delay_between_callbacks_does_not_receive_a_fresh_budget() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(100); + assert!(tick(&mut policy, 0, &clock)); + clock.set(650); + let mut slept = false; + let retry = policy.retry( + 1, + || Some(Duration::from_millis(clock.get())), + |_| slept = true, + ); + assert!(!retry, "callback one must retain callback zero's deadline"); + assert!( + !slept, + "an expired operation must not request another sleep" + ); + } + + #[test] + fn remaining_elapsed_budget_caps_the_next_requested_sleep() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(0); + assert!(tick(&mut policy, 0, &clock)); + clock.set(499); + let mut requested = None; + let retry = policy.retry( + 1, + || Some(Duration::from_millis(clock.get())), + |delay| { + requested = Some(delay); + clock.set(clock.get() + delay.as_millis() as u64); + }, + ); + assert_eq!(requested, Some(Duration::from_millis(1))); + assert!(!retry); + } + + #[test] + fn backwards_clock_between_callbacks_fails_closed_until_a_new_operation() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(100); + assert!(tick(&mut policy, 0, &clock)); + clock.set(99); + let mut slept = false; + assert!(!policy.retry( + 1, + || Some(Duration::from_millis(clock.get())), + |_| slept = true, + )); + assert!(!slept); + clock.set(102); + assert!( + !tick(&mut policy, 2, &clock), + "same failed operation stays closed" + ); + clock.set(10_000); + assert!( + tick(&mut policy, 0, &clock), + "count zero starts a distinct operation" + ); + } + + #[test] + fn backwards_clock_during_sleep_does_not_restart_the_budget() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(100); + assert!(!policy.retry( + 0, + || Some(Duration::from_millis(clock.get())), + |_| clock.set(99), + )); + } + + #[test] + fn count_zero_resets_only_for_a_distinct_sqlite_locking_operation() { + let mut policy = BusyBudget::default(); + let clock = Cell::new(100); + for count in 0..=14 { + if !tick(&mut policy, count, &clock) { + break; + } + } + clock.set(10_000); + assert!(tick(&mut policy, 0, &clock)); + assert_eq!(clock.get(), 10_001); + assert!(tick(&mut policy, 1, &clock)); + assert_eq!(clock.get(), 10_003); + } + + fn refused_without_sleep(policy: &mut BusyBudget, count: i32) { + let mut requested = Vec::new(); + assert!(!policy.retry( + count, + || Some(Duration::from_millis(10)), + |delay| requested.push(delay) + )); + assert!( + requested.is_empty(), + "refused callback requested an unintended sleep" + ); + } + + #[test] + fn invalid_counts_clear_live_state_and_only_fresh_zero_can_recover() { + for invalid in [-1, 14, 15, i32::MAX] { + let clock = Cell::new(0); + let mut policy = BusyBudget::default(); + assert!(tick(&mut policy, 0, &clock)); + refused_without_sleep(&mut policy, invalid); + refused_without_sleep(&mut policy, 1); + clock.set(20_000); + assert!(tick(&mut policy, 0, &clock)); + assert_eq!(clock.get(), 20_001); + } + } + + #[test] + fn initial_skipped_and_repeated_nonzero_counts_never_restart_a_budget() { + let mut initial = BusyBudget::default(); + refused_without_sleep(&mut initial, 1); + refused_without_sleep(&mut initial, 2); + for repeat in [false, true] { + let clock = Cell::new(0); + let mut policy = BusyBudget::default(); + assert!(tick(&mut policy, 0, &clock)); + if repeat { + assert!(tick(&mut policy, 1, &clock)); + } + refused_without_sleep(&mut policy, if repeat { 1 } else { 2 }); + refused_without_sleep(&mut policy, 3); + clock.set(20_000); + assert!(tick(&mut policy, 0, &clock)); + assert_eq!(clock.get(), 20_001); + } + } + + #[test] + fn unavailable_clock_before_sleep_clears_state_without_sleeping() { + let clock = Cell::new(0); + let mut policy = BusyBudget::default(); + assert!(tick(&mut policy, 0, &clock)); + let mut sleeps = 0; + assert!(!policy.retry(1, || None, |_| sleeps += 1)); + assert_eq!(sleeps, 0); + refused_without_sleep(&mut policy, 2); + clock.set(20_000); + assert!(tick(&mut policy, 0, &clock)); + assert_eq!(clock.get(), 20_001); + } + + #[test] + fn unavailable_clock_after_sleep_clears_state_without_an_extra_retry() { + let mut policy = BusyBudget::default(); + let observations = Cell::new(0); + let mut requested = Vec::new(); + assert!(!policy.retry( + 0, + || { + observations.set(observations.get() + 1); + (observations.get() == 1).then_some(Duration::ZERO) + }, + |delay| requested.push(delay) + )); + assert_eq!(observations.get(), 2); + assert_eq!(requested, [Duration::from_millis(1)]); + refused_without_sleep(&mut policy, 1); + let clock = Cell::new(20_000); + assert!(tick(&mut policy, 0, &clock)); + assert_eq!(clock.get(), 20_001); + } +} + +#[cfg(test)] +mod notify_one_tests { + use super::*; + use std::sync::{Arc, Mutex}; + fn queue() -> ReleaseNotifier { + ReleaseNotifier(Arc::new(WakeQueue { + waiters: Mutex::new(Default::default()), + })) + } + fn future() -> std::time::Instant { + std::time::Instant::now() + .checked_add(Duration::from_secs(1)) + .unwrap() + } + #[test] + fn release_selects_one_current_waiter_and_never_banks_credit() { + let queue = queue(); + queue.released_after_authority(); + let a = queue.register(future()).unwrap(); + let b = queue.register(future()).unwrap(); + assert_eq!(*a.state.lock().unwrap() as u8, WaitState::Waiting as u8); + queue.released_after_authority(); + assert_eq!(*a.state.lock().unwrap() as u8, WaitState::Selected as u8); + assert_eq!(*b.state.lock().unwrap() as u8, WaitState::Waiting as u8); + queue.released_after_authority(); + assert_eq!(*b.state.lock().unwrap() as u8, WaitState::Selected as u8); + queue.released_after_authority(); + let c = queue.register(future()).unwrap(); + assert_eq!(*c.state.lock().unwrap() as u8, WaitState::Waiting as u8); + } + #[test] + fn spurious_and_other_database_wakes_cannot_select_a_ticket() { + let a = queue(); + let b = queue(); + let waiter = a.register(future()).unwrap(); + waiter.ready.notify_one(); + b.released_after_authority(); + assert_eq!( + *waiter.state.lock().unwrap() as u8, + WaitState::Waiting as u8 + ); + a.released_after_authority(); + assert_eq!( + *waiter.state.lock().unwrap() as u8, + WaitState::Selected as u8 + ); + } + #[test] + fn expired_and_retired_tickets_do_not_consume_the_next_release() { + let queue = queue(); + let expired = queue.register(std::time::Instant::now()).unwrap(); + let retired = queue.register(future()).unwrap(); + *retired.state.lock().unwrap() = WaitState::Retired; + let live = queue.register(future()).unwrap(); + queue.released_after_authority(); + assert_eq!( + *expired.state.lock().unwrap() as u8, + WaitState::Retired as u8 + ); + assert_eq!(*live.state.lock().unwrap() as u8, WaitState::Selected as u8); + } + #[test] + fn queue_contention_and_capacity_fall_back_without_selecting_or_blocking() { + let queue = queue(); + let live = queue.register(future()).unwrap(); + let mut locked = queue.0.waiters.lock().unwrap(); + assert!(queue.register(future()).is_none()); + queue.released_after_authority(); + assert_eq!(*live.state.lock().unwrap() as u8, WaitState::Waiting as u8); + locked.clear(); + for _ in 0..MAX_WAIT_HINTS { + locked.push_back(Arc::downgrade(&live)); + } + drop(locked); + assert!(queue.register(future()).is_none()); + } + #[cfg(unix)] + #[test] + fn database_registry_shares_only_the_same_live_file_identity() { + let registry = Mutex::new(Vec::new()); + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let a_path = root.join("a.sqlite3"); + let b_path = root.join("b.sqlite3"); + std::fs::write(&a_path, []).unwrap(); + std::fs::write(&b_path, []).unwrap(); + let a = ReleaseNotifier::for_registry(&a_path, ®istry).unwrap(); + let same = ReleaseNotifier::for_registry(&a_path, ®istry).unwrap(); + let b = ReleaseNotifier::for_registry(&b_path, ®istry).unwrap(); + let a_waiter = a.register(future()).unwrap(); + let b_waiter = b.register(future()).unwrap(); + b.released_after_authority(); + assert!(*a_waiter.state.lock().unwrap() == WaitState::Waiting); + assert!(*b_waiter.state.lock().unwrap() == WaitState::Selected); + same.released_after_authority(); + assert!(*a_waiter.state.lock().unwrap() == WaitState::Selected); + let old_waiter = a.register(future()).unwrap(); + std::fs::rename(&a_path, root.join("retained-old.sqlite3")).unwrap(); + std::fs::write(&a_path, []).unwrap(); + let replaced = ReleaseNotifier::for_registry(&a_path, ®istry).unwrap(); + replaced.released_after_authority(); + assert!(*old_waiter.state.lock().unwrap() == WaitState::Waiting); + a.released_after_authority(); + assert!(*old_waiter.state.lock().unwrap() == WaitState::Selected); + } + #[test] + fn poisoned_queue_disables_hints_without_panic_or_new_authority() { + let queue = queue(); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _locked = queue.0.waiters.lock().unwrap(); + panic!("controlled poison"); + })); + assert!(queue.register(future()).is_none()); + queue.released_after_authority(); + } +} diff --git a/src/capture_command_owner.rs b/src/capture_command_owner.rs new file mode 100644 index 0000000..cab25d3 --- /dev/null +++ b/src/capture_command_owner.rs @@ -0,0 +1,662 @@ +//! Command ownership for actual capture probes. No credentials, consent or +//! qualified-source authority is constructed here. +use crate::{ + capture_runtime_pair, + error::{AppError, CaptureProbeReason}, + process_ownership::{ + group::CleanupPolicy, + image::VerifiedKeeperImage, + io::IoPlan, + probes::LeafRunner, + protocol::ProtocolError, + scope::{CommandResult, Scope}, + }, +}; +use std::{io, process::Command}; + +const STANDALONE_NS: u64 = 1_000_000_000; +const HOOK_NS: u64 = 500_000_000; +// This is the command-owner lifetime, not a whole-install/whole-usage wall-clock +// guarantee: some high-level callers verify a pair before constructing it. +fn probe_policy(hook: bool) -> CleanupPolicy { + if hook { + CleanupPolicy::HookShort + } else { + CleanupPolicy::CommandProbe + } +} +pub(crate) const LEAF_END_ENV: &str = "KEITO_CAPTURE_LEAF_END_NS"; +fn refused() -> AppError { + AppError::Config("Capture command ownership unavailable; collection remains paused".into()) +} +pub(crate) fn version_probe_error(error: io::Error) -> AppError { + let reason = match error + .get_ref() + .and_then(|cause| cause.downcast_ref::()) + { + Some(ProtocolError("SCOPE_ADMISSION")) => CaptureProbeReason::AdmissionRefused, + Some(ProtocolError( + "SCOPE_OPERATION_DEADLINE" + | "SCOPE_PROOF_DEADLINE" + | "SCOPE_CLEANUP_DEADLINE" + | "GROUP_DEADLINE" + | "GROUP_LIFETIME", + )) => CaptureProbeReason::Deadline, + Some(ProtocolError("SCOPE_CLOCK")) => CaptureProbeReason::Clock, + Some(_) => CaptureProbeReason::Ownership, + None => CaptureProbeReason::Unavailable, + }; + AppError::CaptureVersionProbe { + reason, + cleanup_unverified: false, + } +} +fn finish_result(result: Result, clean: bool) -> Result { + if clean { + return result; + } + match result { + Err(AppError::CaptureVersionProbe { reason, .. }) => Err(AppError::CaptureVersionProbe { + reason, + cleanup_unverified: true, + }), + _ => Err(refused()), + } +} +const PARENT_KEYS: [&str; 7] = [ + "KEITO_PROCESS_OWNER_FD", + "KEITO_PROCESS_OWNER_NONCE", + "KEITO_PROCESS_OWNER_PID", + "KEITO_PROCESS_OWNER_END_NS", + "KEITO_PROCESS_OWNER_CONTRACT", + "KEITO_SOURCE_OWNER_FD", + "KEITO_SOURCE_OWNER_NONCE", +]; +fn parent_present(mut present: impl FnMut(&str) -> bool) -> bool { + PARENT_KEYS.iter().any(|key| present(key)) +} +enum Image<'a> { + Owned(VerifiedKeeperImage), + Borrowed(&'a VerifiedKeeperImage), +} +pub(crate) struct CommandOwner<'a> { + scope: ScopeRef<'a>, + image: Image<'a>, + end: u64, + policy: CleanupPolicy, +} +enum ScopeRef<'a> { + Owned(Box), + Borrowed(&'a mut Scope), +} +impl std::ops::Deref for ScopeRef<'_> { + type Target = Scope; + fn deref(&self) -> &Scope { + match self { + Self::Owned(s) => s, + Self::Borrowed(s) => s, + } + } +} +impl std::ops::DerefMut for ScopeRef<'_> { + fn deref_mut(&mut self) -> &mut Scope { + match self { + Self::Owned(s) => s, + Self::Borrowed(s) => s, + } + } +} +fn local_install_scope(defaults: bool) -> Result { + if parent_present(|key| std::env::var_os(key).is_some()) + || [LEAF_END_ENV, "KEITO_CAPTURE_INVOCATION_NONCE"] + .iter() + .any(|key| std::env::var_os(key).is_some()) + { + return Err(refused()); + } + let at = crate::process_ownership::scope::monotonic_now().map_err(|_| refused())?; + let end = at + .checked_add(if defaults { + STANDALONE_NS + } else { + crate::process_ownership::scope::INSTALL_OPERATION_NS + }) + .ok_or_else(refused)?; + Scope::local_entry(end).map_err(|_| refused()) +} +pub(crate) fn defaults_install_scope() -> Result { + local_install_scope(true) +} + +/// One consuming preflight on the containing operation; no second endpoint. +pub(crate) struct InstallerPreflight<'a> { + scope: Option>, + image: Option, + runtime: Option, +} +pub(crate) struct InstallerPublication<'a> { + scope: ScopeRef<'a>, + finished: bool, +} +impl<'a> InstallerPreflight<'a> { + pub(crate) fn new(scope: Option<&'a mut Scope>, expected: usize) -> Result { + let scope = match scope { + Some(scope) => ScopeRef::Borrowed(scope), + None => ScopeRef::Owned(Box::new(local_install_scope(false)?)), + }; + // Construct the failure guard BEFORE the first cohort/pair work. + let mut preflight = Self { + scope: Some(scope), + image: None, + runtime: None, + }; + preflight + .scope + .as_mut() + .unwrap() + .begin_installer_preflight(expected) + .map_err(|_| refused())?; + let runtime = capture_runtime_pair::current()?; + let image = VerifiedKeeperImage::open(&runtime.guard_path, &runtime.guard_sha256) + .map_err(|_| refused())?; + preflight.image = Some(image); + preflight.runtime = Some(runtime); + Ok(preflight) + } + pub(crate) fn runtime(&self) -> &capture_runtime_pair::CaptureRuntimeIdentity { + self.runtime + .as_ref() + .expect("constructed installer runtime") + } + pub(crate) fn seal(mut self) -> Result, AppError> { + self.scope + .as_mut() + .unwrap() + .seal_installer_preflight() + .map_err(|_| refused())?; + Ok(InstallerPublication { + scope: self.scope.take().unwrap(), + finished: false, + }) + } +} +impl LeafRunner for InstallerPreflight<'_> { + fn output( + &mut self, + command: Command, + stdout_cap: usize, + stderr_cap: usize, + ) -> io::Result { + let plan = IoPlan::new(Vec::new(), stdout_cap, stderr_cap)?; + let scope = self.scope.as_mut().unwrap(); + let result = scope.run_installer_verified(command, plan, self.image.as_ref().unwrap()); + result.map_err(|error| match scope.first_fault() { + Some(reason) => io::Error::new(error.kind(), reason), + None => error, + }) + } +} +impl Drop for InstallerPreflight<'_> { + fn drop(&mut self) { + if let Some(scope) = self.scope.as_mut() { + let end = scope.hard_end(); + scope.begin_cancel(ProtocolError("SCOPE_PREFLIGHT_DROPPED"), end); + } + } +} +impl InstallerPublication<'_> { + pub(crate) fn check_live(&mut self) -> Result<(), AppError> { + self.scope + .check_installer_publication() + .map_err(|_| refused()) + } + pub(crate) fn finish(mut self, result: Result<(), AppError>) -> Result<(), AppError> { + let result = if matches!(&self.scope, ScopeRef::Owned(_)) { + let resources = self.scope.finish().clean; + let terminal = self.scope.publish_terminal(resources && result.is_ok()); + match result { + Err(error) => Err(error), + Ok(()) if resources && terminal => Ok(()), + _ => Err(refused()), + } + } else { + result + }; + self.finished = true; + result + } +} +impl Drop for InstallerPublication<'_> { + fn drop(&mut self) { + if !self.finished { + let end = self.scope.hard_end(); + self.scope + .begin_cancel(ProtocolError("SCOPE_INSTALLER_DROPPED"), end); + } + } +} +impl CommandOwner<'static> { + pub(crate) fn standalone() -> Result { + // Never ignore an attached/partial parent in a convenience API. The + // actual entry Session must pass its borrowed runner explicitly. + if parent_present(|key| std::env::var_os(key).is_some()) { + return Err(refused()); + } + for key in [LEAF_END_ENV, "KEITO_CAPTURE_INVOCATION_NONCE"] { + if std::env::var_os(key).is_some() { + return Err(refused()); + } + } + let end = crate::process_ownership::scope::monotonic_now() + .map_err(|_| refused())? + .saturating_add(STANDALONE_NS); + let identity = capture_runtime_pair::current()?; + let image = VerifiedKeeperImage::open(&identity.guard_path, &identity.guard_sha256) + .map_err(|_| refused())?; + Ok(Self { + scope: ScopeRef::Owned(Box::new(Scope::local_entry(end).map_err(|_| refused())?)), + image: Image::Owned(image), + end, + policy: probe_policy(false), + }) + } +} +impl<'a> CommandOwner<'a> { + pub(crate) fn with_scope(scope: &'a mut Scope) -> Result { + let at = crate::process_ownership::scope::monotonic_now().map_err(|_| refused())?; + let end = scope.hard_end().min(at.saturating_add(STANDALONE_NS)); + scope.tighten_end(end); + let identity = capture_runtime_pair::current()?; + let image = VerifiedKeeperImage::open(&identity.guard_path, &identity.guard_sha256) + .map_err(|_| refused())?; + Ok(Self { + scope: ScopeRef::Borrowed(scope), + image: Image::Owned(image), + end, + policy: probe_policy(false), + }) + } + pub(crate) fn for_hook( + runtime: &'a capture_runtime_pair::HookRuntime, + scope: &'a mut Scope, + ) -> Result { + let at = crate::process_ownership::scope::monotonic_now().map_err(|_| refused())?; + let raw = std::env::var(LEAF_END_ENV).map_err(|_| refused())?; + let inherited = raw + .parse::() + .ok() + .filter(|n| n.to_string() == raw && *n > at) + .ok_or_else(refused)?; + let end = inherited + .min(at.saturating_add(HOOK_NS)) + .min(scope.hard_end()); + scope.tighten_end(end); + scope + .set_hook_setup_directory(crate::capture_invocations::hook_setup_directory()?) + .map_err(|_| refused())?; + Ok(Self { + scope: ScopeRef::Borrowed(scope), + image: Image::Borrowed(runtime.keeper()), + end, + policy: probe_policy(true), + }) + } + pub(crate) fn finish_clean(&mut self) -> bool { + self.scope.finish().clean + } + #[cfg(feature = "dev-tools")] + pub(crate) fn failure_probe( + &self, + phase: crate::capture::HookFailurePhase, + ) -> crate::capture::HookFailureProbe { + crate::capture::HookFailureProbe { + phase, + owner_fault: self + .scope + .first_fault() + .map(|fault| crate::capture::HookOwnerFault::from_static(fault.0)), + setup: self.scope.first_fault_setup_trace().map(hook_setup_probe), + } + } + pub(crate) fn finish(&mut self, result: Result) -> Result { + finish_result(result, self.finish_clean()) + } + pub(crate) fn fail_ack(&mut self) { + self.scope + .begin_cancel(ProtocolError("HOOK_ACK_WRITE"), self.end); + } + pub(crate) fn read_event(&mut self, max: usize) -> Result, AppError> { + struct Flags(i32, crate::process_ownership::protocol::SharedOwner); + impl Drop for Flags { + fn drop(&mut self) { + if unsafe { libc::fcntl(0, libc::F_SETFL, self.0) } < 0 { + self.1 + .borrow_mut() + .poison(ProtocolError("HOOK_INPUT_FLAGS")); + } + } + } + let flags = unsafe { libc::fcntl(0, libc::F_GETFL) }; + if flags < 0 || unsafe { libc::fcntl(0, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 { + self.scope + .begin_cancel(ProtocolError("HOOK_INPUT_FLAGS"), self.end); + return Err(refused()); + } + let _flags = Flags(flags, self.scope.owner_state()); + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(max.saturating_add(1)).is_err() + || bytes.capacity() > max.saturating_add(1) + { + self.scope + .begin_cancel(ProtocolError("HOOK_INPUT_ALLOCATION"), self.end); + return Err(refused()); + } + loop { + self.scope.poll(); + if self.scope.first_fault().is_some() { + return Err(refused()); + } + let mut part = [0u8; 4096]; + let count = unsafe { libc::read(0, part.as_mut_ptr().cast(), part.len()) }; + if count == 0 { + return Ok(bytes); + } + if count > 0 { + let count = count as usize; + if bytes.len().saturating_add(count) > max { + self.scope + .begin_cancel(ProtocolError("HOOK_INPUT_LIMIT"), self.end); + return Err(refused()); + } + bytes.extend_from_slice(&part[..count]); + } else { + let e = io::Error::last_os_error(); + if !matches!( + e.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted + ) { + self.scope + .begin_cancel(ProtocolError("HOOK_INPUT_READ"), self.end); + return Err(refused()); + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + } +} +#[cfg(feature = "dev-tools")] +fn hook_setup_probe( + trace: crate::process_ownership::group::SetupTrace, +) -> crate::capture::HookSetupProbe { + let offset = |at: u64| at.checked_sub(trace.setup_start_ns); + crate::capture::HookSetupProbe { + fault_state: trace.fault_origin.map(|(_, state)| match state { + "AWAIT_READY" => crate::capture::HookGroupState::AwaitReady, + "READY" => crate::capture::HookGroupState::Ready, + "JOINED" => crate::capture::HookGroupState::Joined, + "PARKED" => crate::capture::HookGroupState::Parked, + "CLEANING" => crate::capture::HookGroupState::Cleaning, + "GONE" => crate::capture::HookGroupState::Gone, + "RELEASED" => crate::capture::HookGroupState::Released, + "FAILED" => crate::capture::HookGroupState::Failed, + _ => crate::capture::HookGroupState::Other, + }), + ready_window_ns: offset(trace.ready_end_ns), + pre_spawn_offset_ns: offset(trace.pre_spawn_ns), + spawn_return_offset_ns: trace.spawn_return_ns.and_then(offset), + first_ready_poll_offset_ns: trace.first_ready_poll_ns.and_then(offset), + deadline_offset_ns: trace.deadline_observed.and_then(|(_, at)| offset(at)), + ready_frame_observed: trace.ready_frame_observed, + ready_eof_observed: trace.ready_eof_observed, + deadline_edge: trace.deadline_observed.and_then(|(edge, _)| match edge { + "READY_BEFORE_RECEIVE" => Some(crate::capture::HookReadyEdge::BeforeReceive), + "READY_AFTER_RECEIVE" => Some(crate::capture::HookReadyEdge::AfterReceive), + "PARK_BEFORE_RECEIVE" => Some(crate::capture::HookReadyEdge::ParkBeforeReceive), + "PARK_AFTER_RECEIVE" => Some(crate::capture::HookReadyEdge::ParkAfterReceive), + _ => None, + }), + park_end_offset_ns: trace.park_end_ns.and_then(offset), + workload_spawn_return_offset_ns: trace.workload_spawn_return_ns.and_then(offset), + first_park_poll_offset_ns: trace.first_park_poll_ns.and_then(offset), + park_frame_observed: trace.park_end_ns.map(|_| trace.park_frame_observed), + } +} +impl LeafRunner for CommandOwner<'_> { + fn repository_outputs( + &mut self, + commands: [Command; 2], + ) -> Option> { + if self.policy != CleanupPolicy::HookShort { + return None; + } + let image = match &self.image { + Image::Owned(image) => image, + Image::Borrowed(image) => image, + }; + let result = self.scope.run_verified_repository(commands, image); + Some(result.map_err(|error| match self.scope.first_fault() { + Some(reason) => io::Error::new(error.kind(), reason), + None => error, + })) + } + fn output( + &mut self, + command: Command, + stdout_cap: usize, + stderr_cap: usize, + ) -> io::Result { + let image = match &self.image { + Image::Owned(image) => image, + Image::Borrowed(image) => image, + }; + let plan = IoPlan::new(Vec::new(), stdout_cap, stderr_cap)?; + let result = if self.policy == CleanupPolicy::HookShort { + self.scope.run_verified(command, plan, image) + } else { + self.scope + .run_verified_with_policy(command, plan, image, self.policy) + }; + // Preserve only the owner's static fault type. Generic error bodies + // stay unexamined and cannot become public probe diagnostics. + result.map_err(|error| match self.scope.first_fault() { + Some(reason) => io::Error::new(error.kind(), reason), + None => error, + }) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + #[cfg(feature = "dev-tools")] + fn hook_probe_preserves_setup_offsets_without_restarting_the_ready_window() { + let probe = hook_setup_probe(crate::process_ownership::group::SetupTrace { + setup_start_ns: 100, + ready_end_ns: 120, + pre_spawn_ns: 115, + spawn_return_ns: Some(125), + first_ready_poll_ns: Some(127), + last_ready_before_ns: Some(127), + last_ready_after_ns: None, + ready_frame_observed: false, + ready_eof_observed: false, + deadline_observed: Some(("READY_BEFORE_RECEIVE", 127)), + fault_origin: None, + ..Default::default() + }); + assert_eq!(probe.ready_window_ns, Some(20)); + assert_eq!(probe.pre_spawn_offset_ns, Some(15)); + assert_eq!(probe.spawn_return_offset_ns, Some(25)); + assert_eq!(probe.first_ready_poll_offset_ns, Some(27)); + assert_eq!(probe.deadline_offset_ns, Some(27)); + assert!(matches!( + probe.deadline_edge, + Some(crate::capture::HookReadyEdge::BeforeReceive) + )); + assert!(!probe.ready_frame_observed); + } + + #[test] + #[cfg(feature = "dev-tools")] + fn hook_probe_does_not_invent_offsets_for_missing_or_backwards_observations() { + let probe = hook_setup_probe(crate::process_ownership::group::SetupTrace { + setup_start_ns: 100, + ready_end_ns: 99, + pre_spawn_ns: 0, + spawn_return_ns: None, + first_ready_poll_ns: Some(98), + last_ready_before_ns: None, + last_ready_after_ns: None, + ready_frame_observed: false, + ready_eof_observed: false, + deadline_observed: None, + fault_origin: None, + ..Default::default() + }); + assert!(probe.ready_window_ns.is_none()); + assert!(probe.pre_spawn_offset_ns.is_none()); + assert!(probe.spawn_return_offset_ns.is_none()); + assert!(probe.first_ready_poll_offset_ns.is_none()); + assert!(probe.deadline_offset_ns.is_none()); + assert!(probe.deadline_edge.is_none()); + } + #[test] + #[cfg(feature = "dev-tools")] + fn failure_setup_trace_state_is_closed_and_missing_origin_stays_unknown() { + use crate::capture::HookGroupState; + use crate::process_ownership::group::SetupTrace; + assert!(hook_setup_probe(SetupTrace::default()) + .fault_state + .is_none()); + for (state, expected) in [ + ("AWAIT_READY", HookGroupState::AwaitReady), + ("READY", HookGroupState::Ready), + ("JOINED", HookGroupState::Joined), + ("PARKED", HookGroupState::Parked), + ("CLEANING", HookGroupState::Cleaning), + ("GONE", HookGroupState::Gone), + ("RELEASED", HookGroupState::Released), + ("FAILED", HookGroupState::Failed), + ("PRIVATE_RAW_CANARY", HookGroupState::Other), + ] { + let probe = hook_setup_probe(SetupTrace { + fault_origin: Some(("GROUP_DEADLINE", state)), + ..Default::default() + }); + assert_eq!(probe.fault_state, Some(expected)); + assert!(!serde_json::to_string(&probe).unwrap().contains("PRIVATE")); + } + } + #[test] + #[cfg(feature = "dev-tools")] + fn hook_probe_retains_late_park_observations_without_rebasing_the_end() { + use crate::capture::{HookGroupState, HookReadyEdge}; + use crate::process_ownership::group::SetupTrace; + let probe = hook_setup_probe(SetupTrace { + setup_start_ns: 100, + park_end_ns: Some(150), + workload_spawn_return_ns: Some(155), + first_park_poll_ns: Some(158), + deadline_observed: Some(("PARK_BEFORE_RECEIVE", 158)), + fault_origin: Some(("GROUP_DEADLINE", "JOINED")), + ..Default::default() + }); + assert_eq!(probe.fault_state, Some(HookGroupState::Joined)); + assert_eq!(probe.park_end_offset_ns, Some(50)); + assert_eq!(probe.workload_spawn_return_offset_ns, Some(55)); + assert_eq!(probe.first_park_poll_offset_ns, Some(58)); + assert_eq!(probe.deadline_offset_ns, Some(58)); + assert_eq!(probe.park_frame_observed, Some(false)); + assert!(matches!( + probe.deadline_edge, + Some(HookReadyEdge::ParkBeforeReceive) + )); + let observed = hook_setup_probe(SetupTrace { + setup_start_ns: 100, + park_end_ns: Some(150), + park_frame_observed: true, + deadline_observed: Some(("PARK_AFTER_RECEIVE", 151)), + ..Default::default() + }); + assert_eq!(observed.park_frame_observed, Some(true)); + assert!(matches!( + observed.deadline_edge, + Some(HookReadyEdge::ParkAfterReceive) + )); + let missing = hook_setup_probe(SetupTrace::default()); + assert!(missing.park_end_offset_ns.is_none()); + assert!(missing.workload_spawn_return_offset_ns.is_none()); + assert!(missing.first_park_poll_offset_ns.is_none()); + assert!(missing.park_frame_observed.is_none()); + let backwards = hook_setup_probe(SetupTrace { + setup_start_ns: 100, + park_end_ns: Some(99), + workload_spawn_return_ns: Some(98), + first_park_poll_ns: Some(97), + ..Default::default() + }); + assert!(backwards.park_end_offset_ns.is_none()); + assert!(backwards.workload_spawn_return_offset_ns.is_none()); + assert!(backwards.first_park_poll_offset_ns.is_none()); + } + #[test] + fn installer_dropped_unsealed_handle_keeps_its_borrowed_owner_failed() { + let end = crate::process_ownership::scope::monotonic_now().unwrap() + 4_000_000_000; + let mut scope = Scope::with_owner(Default::default(), end); + scope.begin_installer_preflight(1).unwrap(); + { + // Actual partial-construction guard, before any image is prepared. + let _preflight = InstallerPreflight { + scope: Some(ScopeRef::Borrowed(&mut scope)), + image: None, + runtime: None, + }; + } + assert_eq!( + scope.first_fault(), + Some(ProtocolError("SCOPE_PREFLIGHT_DROPPED")) + ); + assert!(scope.report().admission_closed); + assert!(!scope.report().clean); + assert!(!scope.publish_terminal(true)); + } + #[test] + fn version_probe_failure_keeps_first_reason_when_finish_is_unproved() { + let original: Result<(), AppError> = Err(version_probe_error(io::Error::other( + ProtocolError("SCOPE_ADMISSION"), + ))); + let error = finish_result(original, false).unwrap_err(); + let value: serde_json::Value = serde_json::from_str(&error.to_json()).unwrap(); + assert_eq!(value["details"]["reason"], "admission_refused"); + assert_eq!(value["details"]["cleanup_status"], "unverified"); + assert_eq!(value["details"]["cleanup_unverified"], true); + assert!(!error.to_json().contains("auth login")); + assert!(finish_result(Ok(()), false).is_err()); + } + #[test] + fn process_ownership_command_probe_selection_keeps_hooks_short() { + assert_eq!(probe_policy(false), CleanupPolicy::CommandProbe); + assert_eq!(probe_policy(true), CleanupPolicy::HookShort); + assert_eq!(STANDALONE_NS, 1_000_000_000); + assert_eq!(HOOK_NS, 500_000_000); + } + #[test] + fn r40_any_partial_parent_requires_the_explicit_entry_owner() { + assert!(!parent_present(|_| false)); + for field in PARENT_KEYS { + assert!(parent_present(|key| key == field)); + } + } + #[test] + fn r41_installed_owner_requires_the_new_guard_contract() { + assert_eq!(crate::capture_runtime_pair::GUARD_CONTRACT, 2); + } + #[test] + fn r41_dispatch_execs_the_native_owner_without_watchdog_children() { + let source = include_str!("../skills/keito-time-track/hooks/dispatch.sh"); + assert!(source.contains("exec \"$guard_cmd\" --internal-dispatch-v2")); + assert!(!source.contains("sleep ")); + assert!(!source.contains("watchdog=")); + assert!(!source.contains("kill -")); + } +} diff --git a/src/capture_invocations.rs b/src/capture_invocations.rs new file mode 100644 index 0000000..eaeb433 --- /dev/null +++ b/src/capture_invocations.rs @@ -0,0 +1,692 @@ +//! Invocation safety flags, not accounting. No native identity or raw hook data. +use crate::error::AppError; +use std::{ + fs, + path::{Path, PathBuf}, +}; +#[cfg(unix)] +use std::{ + fs::File, + io::{Read, Write}, + sync::Arc, +}; +#[cfg(unix)] +pub const ACK: &[u8] = b"KEITO_CAPTURE_DURABLE_V1\n"; +#[cfg(unix)] +const PENDING: &[u8] = b"KEITO_CAPTURE_PENDING_V1\n"; +fn refused() -> AppError { + AppError::Config("Capture invocation authority unavailable; collection remains paused".into()) +} +#[cfg(unix)] +fn nonce_valid(nonce: &str) -> bool { + nonce.len() == 64 && nonce.bytes().all(|b| b.is_ascii_hexdigit()) +} +#[derive(Clone)] +pub struct Permit { + #[cfg(unix)] + nonce: String, + // Pin the verified live inode through validation/commit/ACK and every clone. + // A read-only descriptor owns no guardian flock and closes across exec. + #[cfg(unix)] + marker: Arc, +} +pub struct Marker { + pub nonce: String, + pub live: bool, + #[cfg(unix)] + device: u64, + #[cfg(unix)] + inode: u64, + #[cfg(unix)] + preparing: bool, +} +#[cfg(feature = "dev-tools")] +impl Marker { + /// State already validated by the existing strict snapshot; no new probe. + pub(crate) fn preparing_state(&self) -> Option { + #[cfg(unix)] + { + Some(self.preparing) + } + #[cfg(not(unix))] + { + None + } + } +} +/// Capture state follows effective-user passwd HOME, never a hook's HOME/CWD. +pub fn directory() -> Result { + if let Some(path) = std::env::var_os("KEITO_CAPTURE_HOME") { + return Ok(PathBuf::from(path)); + } + #[cfg(unix)] + { + use std::ffi::CStr; + use std::os::unix::ffi::OsStrExt; + let mut buffer = vec![0u8; 64 * 1024]; + let mut entry = std::mem::MaybeUninit::::uninit(); + let mut result = std::ptr::null_mut(); + let code = unsafe { + libc::getpwuid_r( + libc::geteuid(), + entry.as_mut_ptr(), + buffer.as_mut_ptr().cast(), + buffer.len(), + &mut result, + ) + }; + if code != 0 || result.is_null() { + return Err(refused()); + } + let entry = unsafe { entry.assume_init() }; + if entry.pw_dir.is_null() { + return Err(refused()); + } + let home = PathBuf::from(std::ffi::OsStr::from_bytes( + unsafe { CStr::from_ptr(entry.pw_dir) }.to_bytes(), + )); + if !home.is_absolute() || home == Path::new("/") { + return Err(refused()); + } + #[cfg(target_os = "macos")] + { + Ok(home.join("Library/Application Support/keito/capture")) + } + #[cfg(not(target_os = "macos"))] + { + Ok(home.join(".config/keito/capture")) + } + } + #[cfg(not(unix))] + { + Err(refused()) + } +} +#[cfg(unix)] +pub(crate) fn hook_setup_directory() -> Result { + private_directory(&directory()?, 1) +} +#[cfg(unix)] +fn private_directory(directory: &Path, private_components: usize) -> Result { + use std::ffi::CString; + use std::os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::{ffi::OsStrExt, fs::MetadataExt}, + }; + if !directory.is_absolute() + || directory + .as_os_str() + .to_str() + .is_none_or(|p| p.split('/').any(|c| c == "." || c == "..")) + { + return Err(refused()); + } + let name = CString::new("/").map_err(|_| refused())?; + let fd = unsafe { + libc::open( + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + let mut parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let parts: Vec<_> = directory + .components() + .filter_map(|c| { + if let std::path::Component::Normal(n) = c { + Some(n) + } else { + None + } + }) + .collect(); + for (index, part) in parts.iter().enumerate() { + let name = CString::new(part.as_bytes()).map_err(|_| refused())?; + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW, + ) + }; + if fd < 0 { + return Err(refused()); + } + parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let metadata = File::from(parent.try_clone().map_err(|_| refused())?) + .metadata() + .map_err(|_| refused())?; + if metadata.uid() != 0 && metadata.uid() != unsafe { libc::geteuid() } { + return Err(refused()); + } + if index + private_components >= parts.len() + && (metadata.uid() != unsafe { libc::geteuid() } || metadata.mode() & 0o777 != 0o700) + { + return Err(refused()); + } + } + Ok(File::from(parent)) +} +#[cfg(unix)] +fn root(directory: &Path) -> Result { + private_directory(&directory.join("capture-invocations"), 2) +} +#[cfg(unix)] +fn publication(directory: &Path) -> Result { + crate::capture_authority::AuthorityGuard::publication(&private_directory(directory, 1)?) +} +#[cfg(unix)] +fn publication_read( + directory: &Path, +) -> Result { + crate::capture_authority::AuthorityGuard::publication_read(&private_directory(directory, 1)?) +} +#[cfg(unix)] +fn names(root: &File) -> Result, AppError> { + use std::ffi::CStr; + use std::os::fd::AsRawFd; + let fd = unsafe { libc::dup(root.as_raw_fd()) }; + if fd < 0 { + return Err(refused()); + } + let dir = unsafe { libc::fdopendir(fd) }; + if dir.is_null() { + unsafe { libc::close(fd) }; + return Err(refused()); + } + let mut result = Vec::new(); + let failed; + loop { + #[cfg(target_os = "macos")] + unsafe { + *libc::__error() = 0; + } + #[cfg(target_os = "linux")] + unsafe { + *libc::__errno_location() = 0; + } + let entry = unsafe { libc::readdir(dir) }; + if entry.is_null() { + #[cfg(target_os = "macos")] + { + failed = unsafe { *libc::__error() } != 0; + } + #[cfg(target_os = "linux")] + { + failed = unsafe { *libc::__errno_location() } != 0; + } + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + { + failed = true; + } + break; + } + let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }; + let Ok(name) = name.to_str() else { + failed = true; + break; + }; + if matches!(name, "." | "..") { + continue; + } + if result.len() >= 1024 { + failed = true; + break; + } + result.push(name.to_owned()); + } + unsafe { libc::closedir(dir) }; + if failed { + Err(refused()) + } else { + Ok(result) + } +} +#[cfg(unix)] +fn inspect(root: &File, nonce: &str, preparing: bool) -> Result { + // Snapshot/dead probes must release any successful probe flock immediately. + Ok(inspect_file(root, nonce, preparing)?.0) +} +#[cfg(unix)] +fn inspect_file(root: &File, nonce: &str, preparing: bool) -> Result<(Marker, File), AppError> { + use std::ffi::CString; + use std::os::{ + fd::{AsRawFd, FromRawFd}, + unix::fs::MetadataExt, + }; + if !nonce_valid(nonce) { + return Err(refused()); + } + let name = CString::new(format!( + "{nonce}.{}", + if preparing { "preparing" } else { "pending" } + )) + .map_err(|_| refused())?; + let fd = unsafe { + libc::openat( + root.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + let mut file = unsafe { File::from_raw_fd(fd) }; + let m = file.metadata().map_err(|_| refused())?; + if !m.is_file() + || m.nlink() != 1 + || m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != 0o600 + || m.len() > PENDING.len() as u64 + || (!preparing && m.len() != PENDING.len() as u64) + { + return Err(refused()); + } + let mut bytes = Vec::new(); + std::io::Read::by_ref(&mut file) + .take((PENDING.len() + 1) as u64) + .read_to_end(&mut bytes) + .map_err(|_| refused())?; + if (!preparing && bytes != PENDING) || (preparing && !PENDING.starts_with(&bytes)) { + return Err(refused()); + } + // Guardians hold EX. Dead-marker readers must use SH so another reader + // cannot mistake a temporary probe lock for a live guardian. + let code = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) }; + let live = if code == 0 { + false + } else if std::io::Error::last_os_error().kind() == std::io::ErrorKind::WouldBlock { + true + } else { + return Err(refused()); + }; + Ok(( + Marker { + nonce: nonce.to_owned(), + live, + device: m.dev(), + inode: m.ino(), + preparing, + }, + file, + )) +} +pub fn snapshot(directory: &Path) -> Result, AppError> { + let path = directory.join("capture-invocations"); + let exists = |path: &Path| match fs::symlink_metadata(path) { + Ok(_) => Ok(true), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(_) => Err(refused()), + }; + if !exists(&path)? && !exists(&directory.join("capture-invocations-publication.lock"))? { + return Ok(vec![]); + } + #[cfg(unix)] + { + let _publication = publication(directory)?; + match fs::symlink_metadata(&path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]), + Err(_) => return Err(refused()), + Ok(_) => (), + } + let root = root(directory)?; + let mut markers = Vec::new(); + for name in names(&root)? { + let (nonce, preparing) = if let Some(n) = name.strip_suffix(".pending") { + (n, false) + } else if let Some(n) = name.strip_suffix(".preparing") { + (n, true) + } else { + return Err(refused()); + }; + markers.push(inspect(&root, nonce, preparing)?); + } + Ok(markers) + } + #[cfg(not(unix))] + { + Err(refused()) + } +} +pub fn protect_ack(fd: i32) -> Result<(), AppError> { + #[cfg(unix)] + { + if !(3..=1024).contains(&fd) { + return Err(refused()); + } + let mut info = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstat(fd, info.as_mut_ptr()) } != 0 { + return Err(refused()); + } + if unsafe { info.assume_init() }.st_mode & libc::S_IFMT != libc::S_IFIFO { + return Err(refused()); + } + let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; + if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) } < 0 { + return Err(refused()); + } + Ok(()) + } + #[cfg(not(unix))] + { + let _ = fd; + Err(refused()) + } +} +impl Permit { + pub fn new(directory: &Path, nonce: &str) -> Result { + #[cfg(unix)] + { + // Known pending files are immutable. Share reads, but retain the + // publication barrier against writers and legacy EX reader probes. + let _publication = publication_read(directory)?; + let (m, file) = inspect_file(&root(directory)?, nonce, false)?; + if !m.live { + return Err(refused()); + } + Ok(Self { + nonce: m.nonce, + marker: Arc::new(file), + }) + } + #[cfg(not(unix))] + { + let _ = (directory, nonce); + Err(refused()) + } + } + pub fn validate(&self, directory: &Path) -> Result<(), AppError> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let expected = self.marker.metadata().map_err(|_| refused())?; + if expected.nlink() != 1 { + return Err(refused()); + } + let current = Self::new(directory, &self.nonce)?; + let observed = current.marker.metadata().map_err(|_| refused())?; + if observed.dev() != expected.dev() || observed.ino() != expected.ino() { + return Err(refused()); + } + Ok(()) + } + #[cfg(not(unix))] + { + let _ = directory; + Err(refused()) + } + } + pub fn acknowledge(&self, directory: &Path, fd: i32) -> Result<(), AppError> { + self.validate(directory)?; + #[cfg(unix)] + { + use std::os::fd::FromRawFd; + if !(3..=1024).contains(&fd) { + return Err(refused()); + } + let mut info = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstat(fd, info.as_mut_ptr()) } != 0 { + return Err(refused()); + } + let info = unsafe { info.assume_init() }; + if info.st_mode & libc::S_IFMT != libc::S_IFIFO { + return Err(refused()); + } + let mut pipe = unsafe { File::from_raw_fd(fd) }; + pipe.write_all(ACK).map_err(|_| refused())?; + pipe.flush().map_err(|_| refused())?; + Ok(()) + } + #[cfg(not(unix))] + { + let _ = fd; + Err(refused()) + } + } +} +pub fn remove_dead(directory: &Path, markers: &[Marker]) -> Result<(), AppError> { + #[cfg(unix)] + { + use std::ffi::CString; + use std::os::fd::AsRawFd; + if markers.is_empty() { + return Ok(()); + } + let _publication = publication(directory)?; + let root = root(directory)?; + for marker in markers { + let current = inspect(&root, &marker.nonce, marker.preparing)?; + if current.live || current.device != marker.device || current.inode != marker.inode { + return Err(refused()); + } + let name = CString::new(format!( + "{}.{}", + marker.nonce, + if marker.preparing { + "preparing" + } else { + "pending" + } + )) + .map_err(|_| refused())?; + if unsafe { libc::unlinkat(root.as_raw_fd(), name.as_ptr(), 0) } != 0 { + return Err(refused()); + } + } + root.sync_all().map_err(|_| refused())?; + Ok(()) + } + #[cfg(not(unix))] + { + let _ = (directory, markers); + Err(refused()) + } +} + +#[cfg(all(test, unix))] +mod permit_tests { + use super::*; + use std::os::{ + fd::AsRawFd, + unix::fs::{OpenOptionsExt, PermissionsExt}, + }; + fn marker(root: &Path, nonce: &str, live: bool) -> File { + let directory = root.join("capture-invocations"); + fs::create_dir_all(&directory).unwrap(); + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap(); + let mut file = fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .mode(0o600) + .open(directory.join(format!("{nonce}.pending"))) + .unwrap(); + file.write_all(PENDING).unwrap(); + file.sync_all().unwrap(); + if live { + assert_eq!( + unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + } + file + } + + fn shared_publication(root: &Path) -> File { + drop(publication(root).unwrap()); + let file = fs::OpenOptions::new() + .read(true) + .write(true) + .open(root.join("capture-invocations-publication.lock")) + .unwrap(); + assert_eq!( + unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) }, + 0 + ); + file + } + + #[test] + fn known_live_nonce_validation_shares_publication_with_other_readers() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let nonce = crate::capture::hash("already-published-live-nonce"); + let _guardian = marker(&root, &nonce, true); + let held_publication = shared_publication(&root); + let permit = Permit::new(&root, &nonce).unwrap(); + permit.validate(&root).unwrap(); + // A namespace snapshot still needs serialization; this optimization + // is solely for the already-published, immutable known nonce. + assert!(snapshot(&root).is_err()); + drop(held_publication); + let markers = snapshot(&root).unwrap(); + assert_eq!(markers.len(), 1); + assert!(markers[0].live); + assert!(remove_dead(&root, &markers).is_err()); + permit.validate(&root).unwrap(); + } + + #[test] + fn shared_nonce_reads_keep_content_liveness_and_inode_refusals() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let nonce = crate::capture::hash("retained-inode-under-publication"); + let guardian = marker(&root, &nonce, true); + let permit = Permit::new(&root, &nonce).unwrap(); + let _held_publication = shared_publication(&root); + permit.validate(&root).unwrap(); + let path = root.join(format!("capture-invocations/{nonce}.pending")); + fs::write(&path, b"PRIVATE_MALFORMED_CANARY").unwrap(); + assert!(Permit::new(&root, &nonce).is_err()); + assert!(permit.validate(&root).is_err()); + fs::write(&path, PENDING).unwrap(); + permit.validate(&root).unwrap(); + drop(guardian); + assert!(Permit::new(&root, &nonce).is_err()); + assert!(permit.validate(&root).is_err()); + fs::remove_file(&path).unwrap(); + let _replacement_guardian = marker(&root, &nonce, true); + assert!(permit.validate(&root).is_err()); + assert!(Permit::new(&root, &nonce).is_ok()); + } + + #[test] + fn legacy_exclusive_reader_probe_cannot_impersonate_a_guardian() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let nonce = crate::capture::hash("legacy-dead-reader-probe"); + drop(marker(&root, &nonce, false)); + let held_publication = publication(&root).unwrap(); + let legacy_probe = + File::open(root.join(format!("capture-invocations/{nonce}.pending"))).unwrap(); + assert_eq!( + unsafe { libc::flock(legacy_probe.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + assert!(Permit::new(&root, &nonce).is_err()); + drop(legacy_probe); + drop(held_publication); + assert!(Permit::new(&root, &nonce).is_err()); + } + + #[test] + fn concurrent_dead_reader_probes_are_not_live_and_do_not_block_dead_removal() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let nonce = crate::capture::hash("overlapping-dead-reader-probes"); + drop(marker(&root, &nonce, false)); + let held_publication = shared_publication(&root); + let (observed, dead_probe) = + inspect_file(&super::root(&root).unwrap(), &nonce, false).unwrap(); + assert!(!observed.live); + assert!(Permit::new(&root, &nonce).is_err()); + drop(held_publication); + remove_dead(&root, &[observed]).unwrap(); + assert_eq!(dead_probe.metadata().unwrap().len(), PENDING.len() as u64); + assert!(Permit::new(&root, &nonce).is_err()); + } + + #[test] + fn live_permit_pins_readonly_cloexec_inode_until_last_clone_without_keeping_guardian_alive() { + use std::os::{fd::AsRawFd, unix::fs::MetadataExt}; + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let nonce = crate::capture::hash("pinned-permit"); + let guard = marker(&root, &nonce, true); + let identity = guard.metadata().unwrap(); + let permit = Permit::new(&root, &nonce).unwrap(); + let cloned = permit.clone(); + assert!(permit.validate(&root).is_ok()); + drop(guard); + // Retaining a read descriptor must not retain the guardian's exclusive lock. + assert!(permit.validate(&root).is_err()); + let dead = snapshot(&root).unwrap(); + assert_eq!(dead.len(), 1); + assert!(!dead[0].live); + remove_dead(&root, &dead).unwrap(); + assert_eq!( + fs::read_dir(root.join("capture-invocations")) + .unwrap() + .count(), + 0 + ); + let matching = || { + fs::read_dir("/dev/fd") + .unwrap() + .filter_map(|entry| { + let fd = entry.ok()?.file_name().to_str()?.parse::().ok()?; + let mut info = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstat(fd, info.as_mut_ptr()) } != 0 { + return None; + } + let info = unsafe { info.assume_init() }; + #[cfg(target_os = "macos")] + let device = info.st_dev as u64; + #[cfg(not(target_os = "macos"))] + let device = info.st_dev; + if device != identity.dev() || info.st_ino != identity.ino() { + return None; + } + Some((unsafe { libc::fcntl(fd, libc::F_GETFD) }, unsafe { + libc::fcntl(fd, libc::F_GETFL) + })) + }) + .collect::>() + }; + let held = matching(); + assert!( + !held.is_empty(), + "accepted Permit dropped its verified descriptor, permitting inode ABA" + ); + assert!(held + .iter() + .all(|(descriptor, access)| descriptor & libc::FD_CLOEXEC != 0 + && access & libc::O_ACCMODE == libc::O_RDONLY)); + let replacement = marker(&root, &nonce, true); + assert_ne!( + ( + replacement.metadata().unwrap().dev(), + replacement.metadata().unwrap().ino() + ), + (identity.dev(), identity.ino()) + ); + assert!(permit.validate(&root).is_err()); + drop(permit); + assert!(!matching().is_empty(), "Permit clone lost the pin"); + drop(cloned); + assert!( + matching().is_empty(), + "last Permit clone leaked its descriptor" + ); + // Keep the replacement's guardian live until every pin assertion completes. + assert!(replacement.as_raw_fd() >= 0); + } +} diff --git a/src/capture_mapping.rs b/src/capture_mapping.rs new file mode 100644 index 0000000..6de0e59 --- /dev/null +++ b/src/capture_mapping.rs @@ -0,0 +1,34 @@ +//! Platform boundary for recoverable repository mapping publication. +/// Holds the private setup lock until successful commit or conflict-aware rollback. +pub struct MappingIds<'a> { + pub workspace: &'a str, + pub client: &'a str, + pub project: &'a str, + pub task: &'a str, +} + +#[cfg(unix)] +#[path = "capture_mapping_unix.rs"] +mod implementation; +#[cfg(not(unix))] +mod implementation { + use super::MappingIds; + use crate::error::AppError; + use std::path::Path; + pub struct MappingPublication; + fn unsupported() -> AppError { + AppError::Config("Native coding-agent capture setup is not supported on this platform. Manual CLI time workflows remain available.".into()) + } + impl MappingPublication { + pub fn begin(_: &Path, _: &MappingIds<'_>) -> Result { + Err(unsupported()) + } + pub fn commit(&mut self) -> Result<(), AppError> { + Err(unsupported()) + } + pub fn rollback(&mut self) -> Result<(), AppError> { + Err(unsupported()) + } + } +} +pub use implementation::MappingPublication; diff --git a/src/capture_mapping_unix.rs b/src/capture_mapping_unix.rs new file mode 100644 index 0000000..7b3f845 --- /dev/null +++ b/src/capture_mapping_unix.rs @@ -0,0 +1,401 @@ +//! Recoverable mapping-hint publication; never grants consent itself. +use super::MappingIds; +use crate::adapter_files::{checkpoint, conflict, digest, failure, hex, identifier, Dir}; +use crate::error::AppError; +use base64::{engine::general_purpose::STANDARD, Engine}; +use serde::{Deserialize, Serialize}; +use std::fs::File; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; + +const HINT: &str = "config.yml"; +const JOURNAL: &str = ".capture-mapping-recovery.json"; +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Recovery { + schema_version: u8, + original: Option, + mode: u32, + candidate_sha256: String, +} + +pub struct MappingPublication { + directory: Dir, + _lock: File, + original: Option>, + candidate: Vec, + finished: bool, +} +impl MappingPublication { + pub fn begin(root: &Path, ids: &MappingIds) -> Result { + if [ids.workspace, ids.client, ids.project, ids.task] + .iter() + .any(|v| !identifier(v, 128)) + { + return Err(AppError::InvalidInput( + "Mapping identifiers are invalid; no mapping was replaced.".into(), + )); + } + let directory = Dir::anchor(root)?.child(".keito", true)?; + let lock = directory.lock(".capture-setup.lock")?; + if directory.exists(JOURNAL)? { + restore_pending(&directory)?; + return Err(AppError::Conflict("Recovered the prior mapping after interrupted setup. Core consent may have committed; inspect capture status and explicitly reapprove before continuing.".into())); + } + let original = directory.read(HINT, 64 * 1024)?; + let mode = if original.is_some() { + directory + .open(HINT)? + .metadata() + .map_err(|_| failure())? + .permissions() + .mode() + & 0o777 + } else { + 0o600 + }; + let candidate=serde_json::to_vec_pretty(&serde_json::json!({"version":1,"workspace_id":ids.workspace,"client_id":ids.client,"project_id":ids.project,"task_id":ids.task,"agent_tracking":{"enabled":true,"source":"agent","redact_notes":true}})).map_err(|_|failure())?; + let recovery = Recovery { + schema_version: 1, + original: original.as_ref().map(|b| STANDARD.encode(b)), + mode, + candidate_sha256: digest(&candidate), + }; + directory.atomic( + JOURNAL, + &serde_json::to_vec(&recovery).map_err(|_| failure())?, + 0o600, + Some(None), + "mapping-journal-fsynced", + )?; + let guard = Self { + directory, + _lock: lock, + original, + candidate, + finished: false, + }; + guard.directory.atomic( + HINT, + &guard.candidate, + 0o600, + Some(guard.original.as_deref()), + "mapping-candidate-fsynced", + )?; + checkpoint("mapping-published"); + Ok(guard) + } + pub fn commit(&mut self) -> Result<(), AppError> { + if self.finished { + return Err(failure()); + } + self.directory.verify()?; + if self.directory.read(HINT, 64 * 1024)?.as_deref() != Some(self.candidate.as_slice()) { + return Err(conflict()); + } + self.directory.unlink(JOURNAL, false)?; + self.finished = true; + Ok(()) + } + pub fn rollback(&mut self) -> Result<(), AppError> { + if self.finished { + return Ok(()); + } + restore_pending(&self.directory)?; + self.finished = true; + Ok(()) + } +} +impl Drop for MappingPublication { + fn drop(&mut self) { + if !self.finished { + let _ = self.rollback(); + } + } +} +fn restore_pending(directory: &Dir) -> Result<(), AppError> { + directory.verify()?; + let bytes = directory.read(JOURNAL, 256 * 1024)?.ok_or_else(failure)?; + let recovery: Recovery = serde_json::from_slice(&bytes).map_err(|_| failure())?; + if recovery.schema_version != 1 || recovery.mode > 0o777 || !hex(&recovery.candidate_sha256, 64) + { + return Err(failure()); + } + let original = recovery + .original + .map(|b| STANDARD.decode(b).map_err(|_| failure())) + .transpose()?; + if original.as_ref().is_some_and(|b| b.len() > 64 * 1024) { + return Err(failure()); + } + let current = directory.read(HINT, 64 * 1024)?; + if current != original { + if !current + .as_ref() + .is_some_and(|b| digest(b) == recovery.candidate_sha256) + { + return Err(conflict()); + } + match original { + Some(ref original) => directory.atomic( + HINT, + original, + recovery.mode, + Some(current.as_deref()), + "mapping-rollback-fsynced", + )?, + None => { + checkpoint("mapping-delete-before"); + if directory.read(HINT, 64 * 1024)? != current { + return Err(conflict()); + } + directory.unlink(HINT, false)?; + } + } + } + directory.unlink(JOURNAL, false) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::adapter_files::set_hook; + use std::fs; + use std::os::unix::fs::{symlink, PermissionsExt}; + fn begin(root: &Path) -> Result { + MappingPublication::begin( + root, + &MappingIds { + workspace: "w1", + client: "c1", + project: "p1", + task: "t1", + }, + ) + } + #[test] + fn failed_core_restores_exact_disabled_hint_and_mode() { + let r = tempfile::tempdir().unwrap(); + let d = r.path().join(".keito"); + fs::create_dir(&d).unwrap(); + let old = b"{\"agent_tracking\":{\"enabled\":false},\"project_id\":\"prior\"}\n"; + fs::write(d.join(HINT), old).unwrap(); + fs::set_permissions(d.join(HINT), fs::Permissions::from_mode(0o640)).unwrap(); + let guard = begin(r.path()).unwrap(); + assert_ne!(fs::read(d.join(HINT)).unwrap(), old); + drop(guard); + assert_eq!(fs::read(d.join(HINT)).unwrap(), old); + assert_eq!( + fs::metadata(d.join(HINT)).unwrap().permissions().mode() & 0o777, + 0o640 + ); + assert!(!d.join(JOURNAL).exists()); + } + #[test] + fn successful_setup_commits_hint_without_recovery_data() { + let r = tempfile::tempdir().unwrap(); + begin(r.path()).unwrap().commit().unwrap(); + let d = r.path().join(".keito"); + let v: serde_json::Value = + serde_json::from_slice(&fs::read(d.join(HINT)).unwrap()).unwrap(); + assert_eq!(v["client_id"], "c1"); + assert_eq!(v["agent_tracking"]["enabled"], true); + assert_eq!( + fs::metadata(d.join(HINT)).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert!(!d.join(JOURNAL).exists()); + } + #[test] + fn failed_new_setup_removes_only_its_candidate() { + let r = tempfile::tempdir().unwrap(); + begin(r.path()).unwrap().rollback().unwrap(); + assert!(!r.path().join(".keito/config.yml").exists()); + } + #[test] + fn lock_serializes_consent_publication() { + let r = tempfile::tempdir().unwrap(); + let guard = begin(r.path()).unwrap(); + assert!(begin(r.path()).is_err()); + drop(guard); + assert!(begin(r.path()).is_ok()); + } + #[test] + fn external_edit_is_retained_with_journal_and_blocks_replay() { + let r = tempfile::tempdir().unwrap(); + let mut guard = begin(r.path()).unwrap(); + let d = r.path().join(".keito"); + fs::write(d.join(HINT), b"external disabled hint").unwrap(); + assert!(guard.rollback().is_err()); + assert_eq!(fs::read(d.join(HINT)).unwrap(), b"external disabled hint"); + assert!(d.join(JOURNAL).exists()); + assert!(begin(r.path()).is_err()); + assert_eq!(fs::read(d.join(HINT)).unwrap(), b"external disabled hint"); + } + #[test] + fn external_edit_after_candidate_fsync_is_never_replaced() { + let r = tempfile::tempdir().unwrap(); + let d = r.path().join(".keito"); + let target = d.join(HINT); + let edited = target.clone(); + set_hook(Some(Box::new(move |p| { + if p == "mapping-candidate-fsynced" { + fs::write(&edited, b"late external").unwrap(); + } + }))); + let result = begin(r.path()); + set_hook(None); + assert!(result.is_err()); + assert_eq!(fs::read(target).unwrap(), b"late external"); + assert!(d.join(JOURNAL).exists()); + } + #[test] + fn external_edit_after_rollback_fsync_is_never_replaced() { + let r = tempfile::tempdir().unwrap(); + let d = r.path().join(".keito"); + fs::create_dir(&d).unwrap(); + fs::write(d.join(HINT), b"old disabled").unwrap(); + let mut guard = begin(r.path()).unwrap(); + let edited = d.join(HINT); + set_hook(Some(Box::new(move |p| { + if p == "mapping-rollback-fsynced" { + fs::write(&edited, b"late rollback edit").unwrap(); + } + }))); + let result = guard.rollback(); + set_hook(None); + assert!(result.is_err()); + assert_eq!(fs::read(d.join(HINT)).unwrap(), b"late rollback edit"); + assert!(d.join(JOURNAL).exists()); + } + #[test] + fn abandoned_publication_recovers_then_stops_before_reapproval() { + let r = tempfile::tempdir().unwrap(); + let mut guard = begin(r.path()).unwrap(); + let d = r.path().join(".keito"); + guard.finished = true; + drop(guard); + assert!(begin(r.path()).is_err()); + assert!(!d.join(HINT).exists()); + assert!(!d.join(JOURNAL).exists()); + } + #[test] + fn invalid_ids_and_symlinks_never_modify_external_files() { + let r = tempfile::tempdir().unwrap(); + assert!(MappingPublication::begin( + r.path(), + &MappingIds { + workspace: "../bad", + client: "c", + project: "p", + task: "t" + } + ) + .is_err()); + assert!(!r.path().join(".keito").exists()); + let external = tempfile::tempdir().unwrap(); + fs::write(external.path().join(HINT), b"outside").unwrap(); + symlink(external.path(), r.path().join(".keito")).unwrap(); + assert!(begin(r.path()).is_err()); + assert_eq!(fs::read(external.path().join(HINT)).unwrap(), b"outside"); + } + #[test] + fn corrupt_recovery_never_echoes_content_or_follows_paths() { + let r = tempfile::tempdir().unwrap(); + let d = r.path().join(".keito"); + fs::create_dir(&d).unwrap(); + fs::write(d.join(HINT), b"preserve").unwrap(); + for bad in [ + b"[]".as_slice(), + b"{\"schema_version\":1,\"original\":\"PRIVATE_SECRET\"}", + ] { + fs::write(d.join(JOURNAL), bad).unwrap(); + let e = match begin(r.path()) { + Ok(_) => panic!("unsafe recovery"), + Err(e) => e.to_string(), + }; + assert!(!e.contains("PRIVATE_SECRET")); + assert!(!e.contains(&r.path().display().to_string())); + assert_eq!(fs::read(d.join(HINT)).unwrap(), b"preserve"); + } + } + #[test] + fn legacy_python_base64_journal_recovers_exact_prior_bytes_and_stops() { + let r = tempfile::tempdir().unwrap(); + let d = r.path().join(".keito"); + fs::create_dir(&d).unwrap(); + let old = b"{\"agent_tracking\":{\"enabled\":false}}\n"; + let candidate = b"{\"project_id\":\"candidate\"}"; + fs::write(d.join(HINT), candidate).unwrap(); + let journal = serde_json::json!({"schema_version":1,"original":STANDARD.encode(old),"mode":416,"candidate_sha256":digest(candidate)}); + fs::write(d.join(JOURNAL), serde_json::to_vec(&journal).unwrap()).unwrap(); + assert!(begin(r.path()).is_err()); + assert_eq!(fs::read(d.join(HINT)).unwrap(), old); + assert_eq!( + fs::metadata(d.join(HINT)).unwrap().permissions().mode() & 0o777, + 0o640 + ); + assert!(!d.join(JOURNAL).exists()); + } + #[test] + fn mapping_signal_fixture_child() { + let Ok(root) = std::env::var("KEITO_TEST_MAPPING_KILL_ROOT") else { + return; + }; + let root = std::path::PathBuf::from(root).canonicalize().unwrap(); + let home = root.join("home with ' literal $"); + assert_eq!( + std::env::var_os("HOME").map(std::path::PathBuf::from), + Some(home.clone()) + ); + assert_eq!( + std::env::var_os("KEITO_CAPTURE_HOME").map(std::path::PathBuf::from), + Some(home.join("capture")) + ); + set_hook(Some(Box::new(move |p| { + if p == "mapping-published" { + unsafe { + libc::kill(libc::getpid(), libc::SIGKILL); + } + } + }))); + let _guard = begin(&root.join("repository")).unwrap(); + panic!("SIGKILL boundary was not reached"); + } + #[test] + fn actual_sigkill_restores_hint_on_next_begin_without_replaying_consent() { + use std::os::unix::process::ExitStatusExt; + let r = tempfile::tempdir().unwrap(); + let home = r.path().join("home with ' literal $"); + let capture = home.join("capture"); + fs::create_dir_all(&capture).unwrap(); + let repo = r.path().join("repository"); + let d = repo.join(".keito"); + fs::create_dir_all(&d).unwrap(); + let old = b"{\"agent_tracking\":{\"enabled\":false},\"project_id\":\"prior\"}"; + fs::write(d.join(HINT), old).unwrap(); + let output = crate::skill_adapter::tests::isolated_fixture_process( + r.path(), + Some(&home), + Some(&capture), + ) + .unwrap() + .args([ + "--exact", + "capture_mapping::implementation::tests::mapping_signal_fixture_child", + "--nocapture", + ]) + .env( + "KEITO_TEST_MAPPING_KILL_ROOT", + r.path().canonicalize().unwrap(), + ) + .output() + .unwrap(); + assert_eq!(output.status.signal(), Some(libc::SIGKILL)); + assert_ne!(fs::read(d.join(HINT)).unwrap(), old); + assert!(d.join(JOURNAL).exists()); + assert!(begin(&repo).is_err()); + assert_eq!(fs::read(d.join(HINT)).unwrap(), old); + assert!(!d.join(JOURNAL).exists()); + } +} diff --git a/src/capture_profile.rs b/src/capture_profile.rs new file mode 100644 index 0000000..9cf99c6 --- /dev/null +++ b/src/capture_profile.rs @@ -0,0 +1,925 @@ +//! Diagnostic-only, fixed numeric successful-hook timings. No capture authority. +//! Compiled only with capture-profile; instrumented artifacts are NONPUBLISHABLE. +use std::{ + cell::{Cell, RefCell}, + ffi::CString, + fmt, + fmt::Write as _, + fs::File, + os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::ffi::OsStrExt, + }, + path::{Component, Path}, +}; +const STAGES: usize = 26; +const REQUESTED_START: usize = 20; +const REQUESTED_WAITS: usize = 6; +const MAX_RECORD: usize = 1024; +#[derive(Clone, Copy)] +#[repr(usize)] +pub enum Phase { + Pair, + CoreHash, + GuardHash, + Repository, + Clock, + StoreOpen, + EventTransaction, + Commit, + OwnerFinish, + Ack, + Whole, + PermitValidation, + SqliteBegin, + AuthorityAcquire, + RefusalReads, + RepoReadyPoll, + RepoParkPoll, + RepoRunningPoll, + RepoCleaningPoll, + RepoDonePoll, + RepoSetupWait, + RepoRunningWait, + RepoCleaningWait, + RepoMixedWait, + RepoUnknownWait, + RepoFinishWait, +} +#[derive(Clone)] +struct Record { + event: u8, + start: Option, + accepted: bool, + repository_depth: u32, + valid: u32, + unknown: u32, + ns: [u64; STAGES], + counts: [u32; STAGES], + requested_ns: [u64; REQUESTED_WAITS], +} +impl Record { + fn new(event: u8, start: Option) -> Self { + Self { + event, + start, + accepted: false, + repository_depth: 0, + valid: 0, + unknown: 0, + ns: [0; STAGES], + counts: [0; STAGES], + requested_ns: [0; REQUESTED_WAITS], + } + } + fn observe(&mut self, phase: Phase, start: Option, end: Option) { + self.observe_requested(phase, start, end, None); + } + fn observe_requested( + &mut self, + phase: Phase, + start: Option, + end: Option, + requested: Option, + ) { + let index = phase as usize; + let bit = 1u32 << index; + if self.unknown & bit != 0 { + return; + } + let wait = index + .checked_sub(REQUESTED_START) + .filter(|i| *i < REQUESTED_WAITS); + let requested_sum = match (wait, requested) { + (Some(i), Some(ns)) => self.requested_ns[i].checked_add(ns), + (None, None) => Some(0), + _ => None, + }; + let elapsed = start.zip(end).and_then(|(a, b)| b.checked_sub(a)); + let sum = elapsed.and_then(|n| self.ns[index].checked_add(n)); + let count = self.counts[index].checked_add(1); + if let (Some(sum), Some(count), Some(requested_sum)) = (sum, count, requested_sum) { + self.ns[index] = sum; + self.counts[index] = count; + self.valid |= bit; + if let Some(i) = wait { + self.requested_ns[i] = requested_sum; + } + } else { + self.valid &= !bit; + self.unknown |= bit; + self.ns[index] = 0; + self.counts[index] = 0; + if let Some(i) = wait { + self.requested_ns[i] = 0; + } + } + } + fn format(&self, limit: usize) -> Result { + let mut output = Buffer { + bytes: [0; MAX_RECORD], + length: 0, + limit: limit.min(MAX_RECORD), + }; + write!(&mut output, "[2,1,{},{}", self.event, self.valid)?; + for value in self.ns { + write!(&mut output, ",{value}")?; + } + for value in self.counts { + write!(&mut output, ",{value}")?; + } + for value in self.requested_ns { + write!(&mut output, ",{value}")?; + } + output.write_str("]\n")?; + Ok(output) + } +} +struct Buffer { + bytes: [u8; MAX_RECORD], + length: usize, + limit: usize, +} +impl fmt::Write for Buffer { + fn write_str(&mut self, text: &str) -> fmt::Result { + let end = self + .length + .checked_add(text.len()) + .filter(|n| *n <= self.limit) + .ok_or(fmt::Error)?; + self.bytes[self.length..end].copy_from_slice(text.as_bytes()); + self.length = end; + Ok(()) + } +} +thread_local! { + static ACTIVE: RefCell> = const { RefCell::new(None) }; + // Lost numeric observations only; never cancellation/admission authority. + static REPO_LOST: Cell = const { Cell::new(false) }; +} +const REPO_MASK: u32 = (1 << 3) | (((1 << STAGES) - 1) & !((1 << 15) - 1)); +fn repository_phase(phase: Phase) -> bool { + (phase as usize) >= 15 +} +fn lose_repository() { + let _ = REPO_LOST.try_with(|lost| lost.set(true)); +} +fn apply_repository_loss(record: &mut Record) { + if REPO_LOST + .try_with(|lost| lost.replace(false)) + .unwrap_or(true) + { + record.valid &= !REPO_MASK; + record.unknown |= REPO_MASK; + for index in 0..STAGES { + if REPO_MASK & (1 << index) != 0 { + record.ns[index] = 0; + record.counts[index] = 0; + } + } + record.requested_ns = [0; REQUESTED_WAITS]; + } +} +struct RepositoryDepth { + entered: bool, +} +impl RepositoryDepth { + fn enter() -> Self { + let entered = ACTIVE + .try_with(|active| { + let Ok(mut active) = active.try_borrow_mut() else { + lose_repository(); + return false; + }; + let Some(record) = active.as_mut() else { + return false; + }; + apply_repository_loss(record); + if let Some(next) = record.repository_depth.checked_add(1) { + record.repository_depth = next; + true + } else { + lose_repository(); + apply_repository_loss(record); + false + } + }) + .unwrap_or(false); + Self { entered } + } +} +impl Drop for RepositoryDepth { + fn drop(&mut self) { + if !self.entered { + return; + } + let _ = ACTIVE.try_with(|active| { + let Ok(mut active) = active.try_borrow_mut() else { + lose_repository(); + return; + }; + if let Some(record) = active.as_mut() { + if let Some(next) = record.repository_depth.checked_sub(1) { + record.repository_depth = next; + } else { + lose_repository(); + } + apply_repository_loss(record); + } + }); + } +} +fn now() -> Option { + let mut value = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, value.as_mut_ptr()) } != 0 { + return None; + } + let value = unsafe { value.assume_init() }; + let ns = u64::try_from(value.tv_nsec) + .ok() + .filter(|n| *n < 1_000_000_000)?; + u64::try_from(value.tv_sec) + .ok()? + .checked_mul(1_000_000_000)? + .checked_add(ns) +} +pub fn begin(event: u8) { + if option_env!("KEITO_CAPTURE_PROFILE_SINK").is_none() { + return; + } + let start = now(); + let _ = REPO_LOST.try_with(|lost| lost.set(false)); + let _ = ACTIVE.try_with(|active| { + if let Ok(mut active) = active.try_borrow_mut() { + *active = (1..=5).contains(&event).then(|| Record::new(event, start)); + } + }); +} +fn keep(value: T, observe: impl FnOnce() -> bool) -> T { + let _ = observe(); + value +} +pub fn measure(phase: Phase, operation: impl FnOnce() -> T) -> T { + if option_env!("KEITO_CAPTURE_PROFILE_SINK").is_none() { + return operation(); + } + let enabled = ACTIVE + .try_with(|a| match a.try_borrow() { + Ok(record) => record.is_some(), + Err(_) => { + if matches!(phase, Phase::Repository) { + lose_repository(); + } + false + } + }) + .unwrap_or(false); + if !enabled { + return operation(); + } + run_measured(phase, now(), now, operation) +} +fn run_measured( + phase: Phase, + start: Option, + clock: impl FnOnce() -> Option, + operation: impl FnOnce() -> T, +) -> T { + let depth = matches!(phase, Phase::Repository).then(RepositoryDepth::enter); + let value = operation(); + drop(depth); // restore also on return/error; RAII restores during unwind + let end = clock(); + keep(value, || { + ACTIVE + .try_with(|active| { + if let Ok(mut active) = active.try_borrow_mut() { + if let Some(record) = active.as_mut() { + apply_repository_loss(record); + record.observe(phase, start, end); + if matches!(phase, Phase::Repository) && record.unknown & REPO_MASK != 0 { + lose_repository(); + apply_repository_loss(record); + } + return true; + } + } + if matches!(phase, Phase::Repository) { + lose_repository(); + } + false + }) + .unwrap_or(false) + }) +} + +fn span_enabled(phase: Phase, sink: bool) -> bool { + sink && ACTIVE + .try_with(|a| { + let Ok(mut active) = a.try_borrow_mut() else { + if repository_phase(phase) { + lose_repository(); + } + return false; + }; + let Some(record) = active.as_mut() else { + return false; + }; + apply_repository_loss(record); + !repository_phase(phase) + || (record.repository_depth > 0 && record.unknown & REPO_MASK == 0) + }) + .unwrap_or(false) +} +/// Numeric observation only. Dropping this span does not finish/cancel/admit +/// any operation or touch the sink. Explicit drop preserves borrowed results. +pub struct Span { + phase: Phase, + start: Option, + requested: Option, + enabled: bool, +} +impl Span { + pub fn start(phase: Phase) -> Self { + Self::new(phase, None) + } + pub fn wait(phase: Phase, requested_ns: u64) -> Self { + Self::new(phase, Some(requested_ns)) + } + fn new(phase: Phase, requested: Option) -> Self { + Self::with_clock( + phase, + requested, + option_env!("KEITO_CAPTURE_PROFILE_SINK").is_some(), + now, + ) + } + fn with_clock( + phase: Phase, + requested: Option, + sink: bool, + clock: impl FnOnce() -> Option, + ) -> Self { + let enabled = span_enabled(phase, sink); + Self { + phase, + requested, + enabled, + start: if enabled { clock() } else { None }, + } + } + fn record_at(&self, record: &mut Record, end: Option) { + record.observe_requested(self.phase, self.start, end, self.requested); + // A failed repository observation disables later repository spans. + // Invalidate earlier partial totals too, so omitted later work cannot + // be mistaken for a complete, lower-cost stage observation. + if repository_phase(self.phase) && record.unknown & REPO_MASK != 0 { + lose_repository(); + apply_repository_loss(record); + } + } +} +impl Span { + fn stop_with_clock(&self, clock: impl FnOnce() -> Option) { + if !self.enabled { + return; + } + if repository_phase(self.phase) && !span_enabled(self.phase, true) { + lose_repository(); + return; + } + let end = clock(); + let _ = ACTIVE.try_with(|active| { + if let Ok(mut active) = active.try_borrow_mut() { + if let Some(record) = active.as_mut() { + apply_repository_loss(record); + self.record_at(record, end); + } else if repository_phase(self.phase) { + lose_repository(); + } + } else if repository_phase(self.phase) { + lose_repository(); + } + }); + } +} +impl Drop for Span { + fn drop(&mut self) { + self.stop_with_clock(now); + } +} +pub fn measure_ack(accepted: bool, operation: impl FnOnce() -> Result) -> Result { + let result = measure(Phase::Ack, operation); + complete(accepted && result.is_ok()); + result +} +pub fn complete(accepted: bool) { + if option_env!("KEITO_CAPTURE_PROFILE_SINK").is_none() { + return; + } + let end = now(); + let _ = ACTIVE.try_with(|active| { + if let Ok(mut active) = active.try_borrow_mut() { + if let Some(record) = active.as_mut() { + record.accepted = accepted; + record.observe(Phase::Whole, record.start, end); + } + } + }); +} +fn sink_facts( + mode: libc::mode_t, + uid: libc::uid_t, + links: libc::nlink_t, + own_uid: libc::uid_t, +) -> bool { + mode & libc::S_IFMT == libc::S_IFREG && mode & 0o7777 == 0o600 && uid == own_uid && links == 1 +} +fn write_once(bytes: &[u8], write: impl FnOnce(&[u8]) -> std::io::Result) -> bool { + !bytes.is_empty() && bytes.len() <= MAX_RECORD && write(bytes).is_ok_and(|n| n == bytes.len()) +} +fn before(end: u64) -> bool { + now().is_some_and(|at| at < end) +} +fn append(path: &str, record: &Buffer, end: u64) -> Option<()> { + let path = Path::new(path); + let raw = path.as_os_str().as_bytes(); + if !path.is_absolute() + || raw.len() > 4096 + || raw.split(|b| *b == b'/').any(|p| p == b"." || p == b"..") + { + return None; + } + let count = path + .components() + .filter(|p| matches!(p, Component::Normal(_))) + .count(); + if !(2..=128).contains(&count) { + return None; + } + let parts: Vec<_> = path + .components() + .filter_map(|p| { + if let Component::Normal(p) = p { + Some(p) + } else { + None + } + }) + .collect(); + if parts.len() < 2 || parts.len() > 128 || !before(end) { + return None; + } + let fd = unsafe { + libc::open( + c"/".as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return None; + } + let mut parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let own_uid = unsafe { libc::geteuid() }; + for (index, part) in parts[..parts.len() - 1].iter().enumerate() { + if !before(end) { + return None; + } + let name = CString::new(part.as_bytes()).ok()?; + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return None; + } + parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let mut info = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstat(parent.as_raw_fd(), info.as_mut_ptr()) } != 0 { + return None; + } + let info = unsafe { info.assume_init() }; + if info.st_uid != 0 && info.st_uid != own_uid { + return None; + } + if index + 2 == parts.len() && (info.st_uid != own_uid || info.st_mode & 0o7777 != 0o700) { + return None; + } + } + if !before(end) { + return None; + } + let name = CString::new(parts.last()?.as_bytes()).ok()?; + let mut prior = std::mem::MaybeUninit::::uninit(); + if unsafe { + libc::fstatat( + parent.as_raw_fd(), + name.as_ptr(), + prior.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { + return None; + } + let prior = unsafe { prior.assume_init() }; + if !sink_facts(prior.st_mode, prior.st_uid, prior.st_nlink, own_uid) || !before(end) { + return None; + } + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_WRONLY | libc::O_APPEND | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return None; + } + let sink = unsafe { File::from_raw_fd(fd) }; + let mut opened = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstat(sink.as_raw_fd(), opened.as_mut_ptr()) } != 0 { + return None; + } + let info = unsafe { opened.assume_init() }; + if prior.st_dev != info.st_dev + || prior.st_ino != info.st_ino + || !sink_facts(info.st_mode, info.st_uid, info.st_nlink, own_uid) + { + return None; + } + let mut named = std::mem::MaybeUninit::::uninit(); + if unsafe { + libc::fstatat( + parent.as_raw_fd(), + name.as_ptr(), + named.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { + return None; + } + let named = unsafe { named.assume_init() }; + if named.st_dev != info.st_dev + || named.st_ino != info.st_ino + || !sink_facts(named.st_mode, named.st_uid, named.st_nlink, own_uid) + || !before(end) + { + return None; + } + write_once(&record.bytes[..record.length], |bytes| { + let count = unsafe { libc::write(sink.as_raw_fd(), bytes.as_ptr().cast(), bytes.len()) }; + if count < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(count as usize) + } + }) + .then_some(()) +} +/// Called only after the original main owner finish + terminal publication. +/// Logical result is untouched. File IO is NOT a preemptible wall-clock bound: +/// it can delay child wait and makes this artifact diagnostic NONPUBLISHABLE. +pub fn finish(original_success: bool, end: Option) { + let Some(path) = option_env!("KEITO_CAPTURE_PROFILE_SINK") else { + return; + }; + let mut record = ACTIVE + .try_with(|a| a.try_borrow_mut().ok().and_then(|mut a| a.take())) + .ok() + .flatten(); + if let Some(record) = record.as_mut() { + apply_repository_loss(record); + } + let Some(record) = record.filter(|r| r.accepted && original_success) else { + return; + }; + let Some(end) = end else { + return; + }; + if let Ok(bytes) = record.format(MAX_RECORD) { + let _ = append(path, &bytes, end); + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn ack_wrapper_preserves_noncopy_results_and_executes_once() { + struct DropCount<'a>(&'a std::cell::Cell); + impl Drop for DropCount<'_> { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + let called = std::cell::Cell::new(0); + let dropped = std::cell::Cell::new(0); + let result = measure_ack(true, || { + called.set(called.get() + 1); + Ok::<_, ()>(DropCount(&dropped)) + }); + assert!(result.is_ok()); + assert_eq!(called.get(), 1); + assert_eq!(dropped.get(), 0); + drop(result); + assert_eq!(dropped.get(), 1); + let result = measure_ack(true, || { + called.set(called.get() + 1); + Err::<(), _>(DropCount(&dropped)) + }); + assert!(result.is_err()); + assert_eq!(called.get(), 2); + assert_eq!(dropped.get(), 1); + drop(result); + assert_eq!(dropped.get(), 2); + } + #[test] + fn fixed_numeric_record_round_trips_extremes_without_strings() { + let mut record = Record::new(2, Some(1)); + record.valid = (1 << STAGES) - 1; + record.ns = [u64::MAX; STAGES]; + record.counts = [u32::MAX; STAGES]; + record.requested_ns = [u64::MAX; REQUESTED_WAITS]; + let output = record.format(MAX_RECORD).unwrap(); + assert!(output.length <= MAX_RECORD); + let values: Vec = serde_json::from_slice(&output.bytes[..output.length]).unwrap(); + assert_eq!(values.len(), 4 + 2 * STAGES + REQUESTED_WAITS); + assert_eq!(&values[..4], &[2, 1, 2, (1 << STAGES) - 1]); + assert!(values[4..4 + STAGES].iter().all(|n| *n == u64::MAX)); + } + #[test] + fn missing_backwards_and_overflow_clocks_stay_unknown() { + let mut record = Record::new(1, None); + record.observe(Phase::Pair, None, Some(10)); + record.observe(Phase::Pair, Some(10), Some(20)); + assert_eq!(record.valid & 1, 0); + assert_eq!(record.counts[0], 0); + record.observe(Phase::CoreHash, Some(10), Some(9)); + assert_eq!(record.valid & 2, 0); + record.ns[2] = u64::MAX; + record.observe(Phase::GuardHash, Some(0), Some(1)); + assert_eq!(record.valid & 4, 0); + assert_eq!(record.ns[2], 0); + } + #[test] + fn repeated_phase_accumulates_exact_durations_and_counts() { + let mut record = Record::new(1, Some(0)); + record.observe(Phase::Commit, Some(1), Some(4)); + record.observe(Phase::Commit, Some(5), Some(10)); + assert_eq!(record.ns[7], 8); + assert_eq!(record.counts[7], 2); + assert_ne!(record.valid & (1 << 7), 0); + } + #[test] + fn formatting_failure_and_writer_faults_preserve_original_result() { + let record = Record::new(1, Some(0)); + assert!(record.format(1).is_err()); + let original: Result = Err(17); + assert_eq!(keep(original, || false), Err(17)); + let count = std::cell::Cell::new(0); + assert!(!write_once(b"[1]\n", |_| { + count.set(count.get() + 1); + Err(std::io::Error::from(std::io::ErrorKind::Interrupted)) + })); + assert_eq!(count.get(), 1); + assert!(!write_once(b"[1]\n", |_| Ok(2))); + assert!(!write_once(&[0; MAX_RECORD + 1], |_| panic!( + "oversize writer invoked" + ))); + assert!(write_once(b"[1]\n", |b| Ok(b.len()))); + } + #[test] + fn sink_metadata_refuses_wrong_owner_mode_links_and_nonregular_files() { + let regular = libc::S_IFREG | 0o600; + assert!(sink_facts(regular, 42, 1, 42)); + assert!(!sink_facts(regular, 41, 1, 42)); + assert!(!sink_facts(regular, 42, 2, 42)); + assert!(!sink_facts(libc::S_IFREG | 0o644, 42, 1, 42)); + assert!(!sink_facts(libc::S_IFREG | 0o4600, 42, 1, 42)); + assert!(!sink_facts(libc::S_IFLNK | 0o600, 42, 1, 42)); + } + #[test] + fn span_records_borrow_safe_single_interval_without_io() { + let mut record = Record::new(1, Some(0)); + let span = Span { + phase: Phase::SqliteBegin, + start: Some(10), + requested: None, + enabled: false, + }; + span.record_at(&mut record, Some(25)); + assert_eq!(record.ns[Phase::SqliteBegin as usize], 15); + assert_eq!(record.counts[Phase::SqliteBegin as usize], 1); + } + #[test] + fn requested_waits_accumulate_and_overflow_or_missing_value_stays_unknown() { + let mut record = Record::new(1, Some(0)); + record.observe_requested(Phase::RepoSetupWait, Some(1), Some(4), Some(10)); + record.observe_requested(Phase::RepoSetupWait, Some(5), Some(8), Some(20)); + assert_eq!(record.requested_ns[0], 30); + assert_eq!(record.ns[20], 6); + assert_eq!(record.counts[20], 2); + record.requested_ns[0] = u64::MAX; + record.observe_requested(Phase::RepoSetupWait, Some(9), Some(10), Some(1)); + assert_eq!(record.valid & (1 << 20), 0); + assert_eq!(record.requested_ns[0], 0); + record.observe_requested(Phase::RepoSetupWait, Some(11), Some(12), Some(1)); + assert_eq!(record.counts[20], 0); + record.observe(Phase::RepoRunningWait, Some(1), Some(2)); + assert_eq!(record.valid & (1 << 21), 0); + } + #[test] + fn repository_clock_loss_invalidates_partial_totals_before_later_spans_are_skipped() { + with_numeric_record(|| { + run_measured( + Phase::Repository, + Some(0), + || Some(10), + || { + let earlier = Span::with_clock(Phase::RepoReadyPoll, None, true, || Some(1)); + earlier.stop_with_clock(|| Some(2)); + std::mem::forget(earlier); + let failed = Span::with_clock(Phase::RepoParkPoll, None, true, || Some(3)); + failed.stop_with_clock(|| None); + std::mem::forget(failed); + let later = Span::with_clock(Phase::RepoCleaningPoll, None, true, || { + panic!("invalid repository metrics must not read another clock") + }); + assert!(!later.enabled); + }, + ); + ACTIVE.with(|active| { + let active = active.borrow(); + let record = active.as_ref().unwrap(); + assert_eq!(record.valid & REPO_MASK, 0); + assert_eq!(record.unknown & REPO_MASK, REPO_MASK); + assert_eq!(record.counts[Phase::RepoReadyPoll as usize], 0); + assert_eq!(record.ns[Phase::RepoReadyPoll as usize], 0); + assert_eq!(record.requested_ns, [0; REQUESTED_WAITS]); + }); + }); + } + #[test] + fn schema_two_keeps_phase_prefix_and_fixed_requested_tail() { + assert_eq!(Phase::Whole as usize, 10); + assert_eq!(Phase::PermitValidation as usize, 11); + assert_eq!(Phase::RefusalReads as usize, 14); + assert_eq!(Phase::RepoReadyPoll as usize, 15); + assert_eq!(Phase::RepoFinishWait as usize, STAGES - 1); + let mut record = Record::new(2, Some(0)); + record.observe_requested(Phase::RepoFinishWait, Some(1), Some(3), Some(7)); + let row = record.format(MAX_RECORD).unwrap(); + let values: Vec = serde_json::from_slice(&row.bytes[..row.length]).unwrap(); + assert_eq!(values.len(), 62); + assert_eq!(values[0], 2); + assert_eq!(values[61], 7); + } + + fn with_numeric_record(operation: impl FnOnce()) { + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + let _ = ACTIVE.try_with(|a| { + if let Ok(mut a) = a.try_borrow_mut() { + *a = None; + } + }); + let _ = REPO_LOST.try_with(|lost| lost.set(false)); + } + } + ACTIVE.with(|a| *a.borrow_mut() = Some(Record::new(1, Some(0)))); + REPO_LOST.with(|lost| lost.set(false)); + let _reset = Reset; + operation(); + } + fn depth() -> u32 { + ACTIVE.with(|a| a.borrow().as_ref().unwrap().repository_depth) + } + #[test] + fn repository_depth_restores_normal_error_nested_and_unwind_paths() { + with_numeric_record(|| { + assert_eq!(depth(), 0); + let result = run_measured( + Phase::Repository, + Some(1), + || Some(10), + || { + assert_eq!(depth(), 1); + run_measured( + Phase::Repository, + Some(2), + || Some(5), + || assert_eq!(depth(), 2), + ); + assert_eq!(depth(), 1); + Err::<(), u8>(7) + }, + ); + assert_eq!(result, Err(7)); + assert_eq!(depth(), 0); + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + run_measured( + Phase::Repository, + Some(1), + || Some(2), + || panic!("synthetic unwind"), + ) + })); + assert!(panic.is_err()); + assert_eq!(depth(), 0); + }); + } + #[test] + fn repository_spans_need_sink_active_record_and_repository_depth_before_clock() { + ACTIVE.with(|a| *a.borrow_mut() = None); + REPO_LOST.with(|lost| lost.set(false)); + let clocks = Cell::new(0); + let tick = || { + clocks.set(clocks.get() + 1); + Some(1) + }; + let inactive = Span::with_clock(Phase::RepoReadyPoll, None, false, tick); + assert!(!inactive.enabled); + assert_eq!(clocks.get(), 0); + let no_record = Span::with_clock(Phase::RepoReadyPoll, None, true, tick); + assert!(!no_record.enabled); + assert_eq!(clocks.get(), 0); + with_numeric_record(|| { + let outside = Span::with_clock(Phase::RepoReadyPoll, None, true, tick); + assert!(!outside.enabled); + assert_eq!(clocks.get(), 0); + run_measured( + Phase::Repository, + Some(0), + || Some(2), + || { + let span = Span::with_clock(Phase::RepoReadyPoll, None, true, tick); + assert!(span.enabled); + assert_eq!(clocks.get(), 1); + std::mem::forget(span); // injected-clock gating test; avoid actual Drop clock + }, + ); + }); + } + #[test] + fn escaped_repository_span_stops_without_clock_and_is_unknown() { + with_numeric_record(|| { + let span = run_measured( + Phase::Repository, + Some(0), + || Some(3), + || Span::with_clock(Phase::RepoReadyPoll, None, true, || Some(1)), + ); + assert_eq!(depth(), 0); + let clocks = Cell::new(0); + span.stop_with_clock(|| { + clocks.set(1); + Some(5) + }); + assert_eq!(clocks.get(), 0); + ACTIVE.with(|a| { + let mut a = a.borrow_mut(); + let record = a.as_mut().unwrap(); + apply_repository_loss(record); + assert_eq!(record.valid & REPO_MASK, 0); + }); + }); + } + #[test] + fn repository_overflow_and_borrow_loss_invalidate_instead_of_faking_zero_cost() { + with_numeric_record(|| { + ACTIVE.with(|a| a.borrow_mut().as_mut().unwrap().repository_depth = u32::MAX); + let _depth = RepositoryDepth::enter(); + ACTIVE + .with(|a| assert_eq!(a.borrow().as_ref().unwrap().unknown & REPO_MASK, REPO_MASK)); + }); + with_numeric_record(|| { + ACTIVE.with(|a| { + let mut held = a.borrow_mut(); + let record = held.as_mut().unwrap(); + record.valid |= 1 << 15; + record.ns[15] = 5; + record.counts[15] = 1; + let clocks = Cell::new(0); + let span = Span::with_clock(Phase::RepoReadyPoll, None, true, || { + clocks.set(1); + Some(1) + }); + assert!(!span.enabled); + assert_eq!(clocks.get(), 0); + }); + ACTIVE.with(|a| { + let mut a = a.borrow_mut(); + let record = a.as_mut().unwrap(); + apply_repository_loss(record); + assert_eq!(record.unknown & REPO_MASK, REPO_MASK); + assert_eq!(record.valid & REPO_MASK, 0); + assert_eq!(record.ns[15], 0); + assert_eq!(record.counts[15], 0); + }); + }); + } +} diff --git a/src/capture_runtime_pair.rs b/src/capture_runtime_pair.rs new file mode 100644 index 0000000..9b43ee9 --- /dev/null +++ b/src/capture_runtime_pair.rs @@ -0,0 +1,434 @@ +//! Release-pair identity used by native adapter installation. +//! +//! This descriptor is transport data, not evidence of trust by itself. Production +//! callers must obtain it from the compiled release-anchor verifier. A local +//! manifest or a same-directory executable never establishes release identity. +use serde::Serialize; +use std::path::PathBuf; + +pub const GUARD_CONTRACT: u32 = 2; +#[cfg(unix)] +static IMAGE_PATH: std::sync::OnceLock = std::sync::OnceLock::new(); +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub struct CaptureRuntimeIdentity { + pub core_path: PathBuf, + pub guard_path: PathBuf, + pub core_sha256: String, + pub guard_sha256: String, + pub version: String, + pub target: String, + pub guard_contract: u32, +} + +use crate::error::AppError; +use serde::Deserialize; +#[cfg(unix)] +use sha2::{Digest, Sha256}; +use std::{collections::BTreeMap, path::Path}; +#[cfg(unix)] +use std::{fs, io::Read, path::Component}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Manifest { + manifest_contract: u32, + version: String, + target: String, + guard_contract: u32, + files: BTreeMap, +} +fn refused() -> AppError { + AppError::Config("Capture requires an intact official keito / keito-capture-guard release pair; manual CLI commands remain available".into()) +} +#[cfg(unix)] +fn read_file_with( + path: &Path, + max: u64, + executable: bool, + consume: impl FnOnce(&fs::File, u64) -> Result<(T, u64), AppError>, +) -> Result { + use std::{ + ffi::CString, + os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::{ffi::OsStrExt, fs::MetadataExt}, + }, + }; + if !path.is_absolute() + || path + .components() + .any(|p| matches!(p, Component::ParentDir | Component::CurDir)) + { + return Err(refused()); + } + let fd = unsafe { + libc::open( + CString::new("/").unwrap().as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + let mut parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let parts: Vec<_> = path + .components() + .filter_map(|p| { + if let Component::Normal(p) = p { + Some(p) + } else { + None + } + }) + .collect(); + let (leaf, ancestors) = parts.split_last().ok_or_else(refused)?; + for part in ancestors { + let name = CString::new(part.as_bytes()).map_err(|_| refused())?; + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + parent = unsafe { OwnedFd::from_raw_fd(fd) }; + } + let name = CString::new(leaf.as_bytes()).map_err(|_| refused())?; + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + let file = unsafe { fs::File::from_raw_fd(fd) }; + let before = file.metadata().map_err(|_| refused())?; + if !before.is_file() + || before.len() > max + || before.mode() & 0o022 != 0 + || (executable && before.mode() & 0o111 == 0) + || before.uid() != 0 && before.uid() != unsafe { libc::geteuid() } + { + return Err(refused()); + } + let (output, bytes_read) = consume(&file, max)?; + let after = file.metadata().map_err(|_| refused())?; + let mut current = std::mem::MaybeUninit::::uninit(); + if unsafe { + libc::fstatat( + parent.as_raw_fd(), + name.as_ptr(), + current.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { + return Err(refused()); + } + let current = unsafe { current.assume_init() }; + if bytes_read > max + || before.dev() != after.dev() + || before.ino() != after.ino() + || before.len() != after.len() + || before.mode() != after.mode() + || before.uid() != after.uid() + || before.mtime() != after.mtime() + || before.mtime_nsec() != after.mtime_nsec() + || current.st_dev as u128 != u128::from(before.dev()) + || u128::from(current.st_ino) != u128::from(before.ino()) + { + return Err(refused()); + } + Ok(output) +} +#[cfg(unix)] +fn read_file(path: &Path, max: u64, executable: bool) -> Result, AppError> { + read_file_with(path, max, executable, |file, max| { + let mut bytes = Vec::new(); + let mut bounded = file.take(max + 1); + bounded.read_to_end(&mut bytes).map_err(|_| refused())?; + let length = bytes.len() as u64; + Ok((bytes, length)) + }) +} +#[cfg(not(unix))] +fn read_file(_: &Path, _: u64, _: bool) -> Result, AppError> { + Err(refused()) +} +#[cfg(unix)] +fn hash_reader(reader: &mut impl Read, max: u64) -> Result<(String, u64), AppError> { + let mut hash = Sha256::new(); + let mut bytes_read = 0u64; + let mut buffer = [0u8; 64 * 1024]; + let mut bounded = reader.take(max + 1); + loop { + let count = match bounded.read(&mut buffer) { + Ok(count) => count, + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => return Err(refused()), + }; + if count == 0 { + break; + } + bytes_read = bytes_read.checked_add(count as u64).ok_or_else(refused)?; + if bytes_read > max { + return Err(refused()); + } + hash.update(&buffer[..count]); + } + let digest = hash + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + Ok((digest, bytes_read)) +} +#[cfg(unix)] +fn hash_file(path: &Path) -> Result { + read_file_with(path, 128 * 1024 * 1024, true, |file, max| { + // The SAME retained descriptor and pre/post path+inode gates still + // verify every image byte. Only the whole-image Vec is removed. + hash_reader(&mut &*file, max) + }) +} +#[cfg(not(unix))] +fn hash_file(path: &Path) -> Result { + Ok(crate::capture::hash(read_file( + path, + 128 * 1024 * 1024, + true, + )?)) +} +/// Pure filesystem qualification against a caller-supplied compiled identity. +/// The release command uses only its embedded anchor, never manifest trust. +pub fn verify( + core: &Path, + guard_hash: &str, + version: &str, + target: &str, +) -> Result { + if guard_hash.len() != 64 + || !guard_hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err(refused()); + } + let parent = core.parent().ok_or_else(refused)?; + let guard = parent.join("keito-capture-guard"); + let core_sha256 = crate::capture_profile_measure!(CoreHash, hash_file(core))?; + let guard_sha256 = crate::capture_profile_measure!(GuardHash, hash_file(&guard))?; + if guard_sha256 != guard_hash { + return Err(refused()); + } + let path = parent.join("capture-runtime-manifest.json"); + let manifest: Manifest = + serde_json::from_slice(&read_file(&path, 16384, false)?).map_err(|_| refused())?; + if manifest.manifest_contract != 1 + || manifest.guard_contract != GUARD_CONTRACT + || manifest.version != version + || manifest.target != target + || manifest.files.len() != 2 + || manifest.files.get("keito") != Some(&core_sha256) + || manifest.files.get("keito-capture-guard") != Some(&guard_sha256) + { + return Err(refused()); + } + Ok(CaptureRuntimeIdentity { + core_path: core.into(), + guard_path: guard, + core_sha256, + guard_sha256, + version: version.into(), + target: target.into(), + guard_contract: GUARD_CONTRACT, + }) +} +/// Must run synchronously before constructing Tokio or parsing CLI input. +/// Only stdio, ACK, and this read-only image descriptor cross kernel exec. +/// The image descriptor is closed before this function returns, including errors. +pub fn bootstrap_image() -> Result<(), AppError> { + #[cfg(unix)] + { + use std::os::{ + fd::{AsRawFd, FromRawFd}, + unix::fs::MetadataExt, + }; + let Some(raw) = std::env::var_os("KEITO_CAPTURE_IMAGE_FD") else { + return Ok(()); + }; + let fd = raw + .to_str() + .and_then(|v| v.parse::().ok()) + .filter(|v| (5..=1024).contains(v)) + .ok_or_else(refused)?; + let file = unsafe { fs::File::from_raw_fd(fd) }; + if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 { + return Err(refused()); + } + let metadata = file.metadata().map_err(|_| refused())?; + if !metadata.is_file() + || unsafe { libc::fcntl(fd, libc::F_GETFL) } & libc::O_ACCMODE != libc::O_RDONLY + { + return Err(refused()); + } + #[cfg(target_os = "macos")] + let path = { + use std::{ffi::CStr, os::unix::ffi::OsStrExt}; + let mut buffer = [0i8; libc::PATH_MAX as usize]; + if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buffer.as_mut_ptr()) } < 0 { + return Err(refused()); + } + PathBuf::from(std::ffi::OsStr::from_bytes( + unsafe { CStr::from_ptr(buffer.as_ptr()) }.to_bytes(), + )) + }; + #[cfg(not(target_os = "macos"))] + let path = + fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).map_err(|_| refused())?; + let actual = fs::symlink_metadata(&path).map_err(|_| refused())?; + if !path.is_absolute() + || actual.file_type().is_symlink() + || actual.dev() != metadata.dev() + || actual.ino() != metadata.ino() + { + return Err(refused()); + } + let running = std::env::current_exe().map_err(|_| refused())?; + let running_metadata = fs::metadata(&running).map_err(|_| refused())?; + if running_metadata.dev() != metadata.dev() || running_metadata.ino() != metadata.ino() { + return Err(refused()); + } + drop(file); + IMAGE_PATH.set(path).map_err(|_| refused())?; + std::env::remove_var("KEITO_CAPTURE_IMAGE_FD"); + Ok(()) + } + #[cfg(not(unix))] + { + if std::env::var_os("KEITO_CAPTURE_IMAGE_FD").is_some() { + Err(refused()) + } else { + Ok(()) + } + } +} +pub fn current() -> Result { + #[cfg(unix)] + { + let anchor = option_env!("KEITO_RELEASE_GUARD_SHA256").ok_or_else(refused)?; + let core = if let Some(path) = IMAGE_PATH.get() { + path.clone() + } else { + std::env::current_exe().map_err(|_| refused())? + }; + verify( + &core, + anchor, + env!("CARGO_PKG_VERSION"), + env!("KEITO_BUILD_TARGET"), + ) + } + #[cfg(not(unix))] + { + Err(refused()) + } +} + +/// Sealed actual verifier result for a normal guarded hook. The public runtime +/// descriptor remains transport data; callers cannot deserialize this proof. +#[cfg(unix)] +pub(crate) struct HookRuntime { + identity: CaptureRuntimeIdentity, + keeper: crate::process_ownership::image::VerifiedKeeperImage, +} +#[cfg(unix)] +impl HookRuntime { + pub(crate) fn current(expected_core: &str) -> Result { + let identity = current()?; + if identity.core_sha256 != expected_core { + return Err(refused()); + } + let keeper = crate::process_ownership::image::VerifiedKeeperImage::open( + &identity.guard_path, + &identity.guard_sha256, + ) + .map_err(|_| refused())?; + Ok(Self { identity, keeper }) + } + pub(crate) fn identity(&self) -> &CaptureRuntimeIdentity { + &self.identity + } + pub(crate) fn keeper(&self) -> &crate::process_ownership::image::VerifiedKeeperImage { + &self.keeper + } +} + +#[cfg(all(test, unix))] +mod streaming_hash_tests { + use super::*; + use std::io::{self, Cursor}; + #[test] + fn stream_digest_matches_exact_whole_buffer_sha256_at_chunk_boundaries() { + for length in [0, 1, 65535, 65536, 65537, 131073] { + let bytes: Vec = (0..length).map(|n| (n % 251) as u8).collect(); + let (digest, count) = hash_reader(&mut Cursor::new(&bytes), length as u64).unwrap(); + assert_eq!(digest, crate::capture::hash(&bytes)); + assert_eq!(count, length as u64); + } + } + #[test] + fn excess_byte_is_refused_instead_of_accepting_a_hashed_prefix() { + assert!(hash_reader(&mut Cursor::new(b"a"), 0).is_err()); + assert!(hash_reader(&mut Cursor::new(b"abc"), 2).is_err()); + let (digest, count) = hash_reader(&mut Cursor::new(b"ab"), 2).unwrap(); + assert_eq!(digest, crate::capture::hash(b"ab")); + assert_eq!(count, 2); + } + struct InterruptedThenChunks { + bytes: Cursor>, + interrupted: bool, + } + impl Read for InterruptedThenChunks { + fn read(&mut self, output: &mut [u8]) -> io::Result { + if !self.interrupted { + self.interrupted = true; + return Err(io::Error::from(io::ErrorKind::Interrupted)); + } + let end = output.len().min(3); + self.bytes.read(&mut output[..end]) + } + } + #[test] + fn interrupted_and_partial_reads_preserve_exact_digest_and_count() { + let bytes = b"complete image bytes after interruption".to_vec(); + let mut reader = InterruptedThenChunks { + bytes: Cursor::new(bytes.clone()), + interrupted: false, + }; + let (digest, count) = hash_reader(&mut reader, bytes.len() as u64).unwrap(); + assert_eq!(digest, crate::capture::hash(&bytes)); + assert_eq!(count, bytes.len() as u64); + } + struct FailsAfterPrefix(bool); + impl Read for FailsAfterPrefix { + fn read(&mut self, output: &mut [u8]) -> io::Result { + if self.0 { + return Err(io::Error::from(io::ErrorKind::Other)); + } + self.0 = true; + output[0] = b'x'; + Ok(1) + } + } + #[test] + fn a_read_fault_never_returns_a_partial_digest() { + assert!(hash_reader(&mut FailsAfterPrefix(false), 10).is_err()); + } +} diff --git a/src/capture_supervisor.rs b/src/capture_supervisor.rs new file mode 100644 index 0000000..83b6904 --- /dev/null +++ b/src/capture_supervisor.rs @@ -0,0 +1,354 @@ +//! macOS operational service configuration. Paths remain device-local and are +//! never part of capture evidence, queue records or transport. +use crate::capture::hash; +use crate::error::AppError; +use serde::Serialize; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Command; + +const MARKER: &str = "METADATA_ONLY_OBSERVED_TURNS_V1"; +fn failure() -> AppError { + AppError::Config("Capture worker service operation failed; prior settings retained where possible. Inspect worker-status before retrying.".into()) +} +fn xml(value: &str) -> String { + value + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} +#[derive(Clone)] +pub struct Supervisor { + pub home: PathBuf, + pub launchctl: PathBuf, + pub uid: u32, +} +#[derive(Debug, Serialize)] +pub struct OwnedWorker { + pub worker_id: String, + pub status: WorkerStatus, +} +#[derive(Debug, Serialize)] +pub struct WorkerStatus { + pub supported: bool, + pub installed: bool, + pub observation: String, + pub loaded: bool, + pub running: bool, + pub stale: bool, + pub policy: &'static str, +} +pub struct WorkerConfig<'a> { + pub repository_key: &'a str, + pub repository_root: &'a Path, + pub executable: &'a Path, + pub capture_home: &'a Path, + pub workspace_id: &'a str, + pub api_origin: &'a str, +} +impl Supervisor { + pub fn system() -> Result { + #[cfg(target_os = "macos")] + { + Ok(Self { + home: dirs::home_dir().ok_or_else(failure)?, + launchctl: PathBuf::from("/bin/launchctl"), + uid: unsafe { libc::getuid() }, + }) + } + #[cfg(not(target_os = "macos"))] + { + Err(AppError::Config("Automatic worker supervision is currently qualified for macOS only; run capture worker under your own supervisor".into())) + } + } + fn label(key: &str) -> String { + format!("com.keito.capture.{}", hash(key)) + } + fn file(&self, key: &str) -> PathBuf { + self.home + .join("Library/LaunchAgents") + .join(format!("{}.plist", Self::label(key))) + } + fn domain(&self) -> String { + format!("gui/{}", self.uid) + } + fn service(&self, key: &str) -> String { + format!("{}/{}", self.domain(), Self::label(key)) + } + pub fn render(&self, config: &WorkerConfig<'_>) -> Result { + crate::capture::identifier(config.workspace_id)?; + let url = reqwest::Url::parse(config.api_origin).map_err(|_| failure())?; + if !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + || (url.scheme() != "https" + && !(url.scheme() == "http" + && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")))) + { + return Err(failure()); + } + let binary = fs::read(config.executable).map_err(|_| failure())?; + Ok(format!( + r#" + + +Label{label} +KeitoCapturePolicy{policy} +KeitoRepositoryKey{repository_key} +KeitoBinarySha256{binary_hash} +ProgramArguments{executable}--workspace{workspace}captureworker--interval-seconds5--expected-runtime-hash{binary_hash} +WorkingDirectory{repository} +EnvironmentVariablesKEITO_CAPTURE_HOME{capture_home}KEITO_API_URL{origin} +RunAtLoadKeepAlive +ProcessTypeBackgroundThrottleInterval10 +StandardOutPath/dev/nullStandardErrorPath/dev/null + +"#, + label = Self::label(config.repository_key), + policy = MARKER, + repository_key = xml(config.repository_key), + binary_hash = hash(binary), + executable = xml(&config.executable.to_string_lossy()), + workspace = xml(config.workspace_id), + repository = xml(&config.repository_root.to_string_lossy()), + capture_home = xml(&config.capture_home.to_string_lossy()), + origin = xml(config.api_origin) + )) + } + fn owned(contents: &str, key: &str) -> bool { + contents.contains(&format!( + "Label{}", + Self::label(key) + )) && contents.contains(&format!( + "KeitoCapturePolicy{MARKER}" + )) + } + fn ensure_parents(&self) -> Result<(), AppError> { + let mut cursor = self.home.clone(); + for part in ["", "Library", "LaunchAgents"] { + if !part.is_empty() { + cursor.push(part); + } + if let Ok(metadata) = fs::symlink_metadata(&cursor) { + if metadata.file_type().is_symlink() || !metadata.is_dir() { + return Err(failure()); + } + } + } + Ok(()) + } + fn read(&self, key: &str) -> Result>, AppError> { + self.ensure_parents()?; + let file = self.file(key); + if !file.exists() { + return Ok(None); + } + let metadata = fs::symlink_metadata(&file).map_err(|_| failure())?; + if metadata.file_type().is_symlink() || metadata.len() > 64 * 1024 { + return Err(failure()); + } + let bytes = fs::read(&file).map_err(|_| failure())?; + if !Self::owned(&String::from_utf8_lossy(&bytes), key) { + return Err(AppError::Config( + "Refusing to replace an unrecognized launch agent; no settings changed".into(), + )); + } + Ok(Some(bytes)) + } + fn atomic_write(&self, key: &str, bytes: &[u8]) -> Result<(), AppError> { + self.ensure_parents()?; + let file = self.file(key); + let directory = file.parent().ok_or_else(failure)?; + if directory.exists() + && fs::symlink_metadata(directory) + .map_err(|_| failure())? + .file_type() + .is_symlink() + { + return Err(failure()); + } + let created = !directory.exists(); + fs::create_dir_all(directory).map_err(|_| failure())?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if created { + fs::set_permissions(directory, fs::Permissions::from_mode(0o700)) + .map_err(|_| failure())?; + } + } + #[cfg(not(unix))] + let _ = created; + let temporary = file.with_extension(format!("plist.{}.tmp", std::process::id())); + let result = (|| { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut output = options.open(&temporary).map_err(|_| failure())?; + output.write_all(bytes).map_err(|_| failure())?; + output.sync_all().map_err(|_| failure())?; + fs::rename(&temporary, &file).map_err(|_| failure())?; + Ok(()) + })(); + if temporary.exists() { + let _ = fs::remove_file(temporary); + } + result + } + pub fn list(&self) -> Result, AppError> { + self.ensure_parents()?; + let directory = self.home.join("Library/LaunchAgents"); + if !directory.exists() { + return Ok(vec![]); + } + let mut workers = Vec::new(); + for entry in fs::read_dir(directory).map_err(|_| failure())? { + let entry = entry.map_err(|_| failure())?; + if !entry + .file_name() + .to_string_lossy() + .starts_with("com.keito.capture.") + || entry.path().extension().is_none_or(|v| v != "plist") + { + continue; + } + let metadata = fs::symlink_metadata(entry.path()).map_err(|_| failure())?; + if metadata.file_type().is_symlink() || metadata.len() > 64 * 1024 { + continue; + } + let bytes = fs::read(entry.path()).map_err(|_| failure())?; + let text = String::from_utf8_lossy(&bytes); + let prefix = "KeitoRepositoryKey"; + let Some(key) = text + .split_once(prefix) + .and_then(|(_, v)| v.split_once("").map(|(v, _)| v)) + else { + continue; + }; + if key.len() != 64 + || !key.bytes().all(|b| b.is_ascii_hexdigit()) + || !Self::owned(&text, key) + { + continue; + } + workers.push(OwnedWorker { + worker_id: key.to_owned(), + status: self.status(key, None)?, + }); + } + workers.sort_by(|a, b| a.worker_id.cmp(&b.worker_id)); + Ok(workers) + } + fn observe(&self, key: &str) -> (&'static str, bool) { + let Ok(output) = Command::new(&self.launchctl) + .args(["print", &self.service(key)]) + .output() + else { + return ("UNKNOWN", false); + }; + if output.status.success() { + let text = String::from_utf8_lossy(&output.stdout); + return ( + "LOADED", + text.contains("state = running") + && text.lines().any(|line| line.trim().starts_with("pid = ")), + ); + } + let error = String::from_utf8_lossy(&output.stderr); + if error.contains("Could not find service") && error.contains(&Self::label(key)) { + ("ABSENT", false) + } else { + ("UNKNOWN", false) + } + } + pub fn status( + &self, + key: &str, + config: Option<&WorkerConfig<'_>>, + ) -> Result { + let contents = self.read(key)?; + let installed = contents.is_some(); + let (observation, running) = self.observe(key); + let loaded = observation == "LOADED"; + let stale = if let (Some(existing), Some(config)) = (&contents, config) { + *existing != self.render(config)?.as_bytes() + } else if let Some(existing) = &contents { + let executable = std::env::current_exe().map_err(|_| failure())?; + let current = hash(fs::read(executable).map_err(|_| failure())?); + !String::from_utf8_lossy(existing).contains(&format!( + "KeitoBinarySha256{current}" + )) + } else { + false + }; + Ok(WorkerStatus { + supported: true, + installed, + observation: observation.into(), + loaded, + running, + stale, + policy: MARKER, + }) + } + pub fn install(&self, config: &WorkerConfig<'_>) -> Result { + let key = config.repository_key; + let desired = self.render(config)?; + let prior = self.read(key)?; + if prior.as_deref() == Some(desired.as_bytes()) && self.status(key, Some(config))?.running { + return self.status(key, Some(config)); + } + self.atomic_write(key, desired.as_bytes())?; + let _ = Command::new(&self.launchctl) + .args(["bootout", &self.service(key)]) + .output(); + let result = Command::new(&self.launchctl) + .arg("bootstrap") + .arg(self.domain()) + .arg(self.file(key)) + .output(); + if !result.is_ok_and(|o| o.status.success()) { + if let Some(prior) = prior { + self.atomic_write(key, &prior)?; + let _ = Command::new(&self.launchctl) + .arg("bootstrap") + .arg(self.domain()) + .arg(self.file(key)) + .output(); + } else { + let _ = fs::remove_file(self.file(key)); + } + return Err(failure()); + } + self.status(key, Some(config)) + } + pub fn uninstall(&self, key: &str) -> Result { + if self.read(key)?.is_none() { + let status = self.status(key, None)?; + if status.observation != "ABSENT" { + return Err(AppError::Config( + "Worker absence could not be verified; inspect launchd state before cleanup" + .into(), + )); + } + return Ok(status); + } + let _ = Command::new(&self.launchctl) + .args(["bootout", &self.service(key)]) + .output(); + let status = self.status(key, None)?; + if status.observation != "ABSENT" { + return Err(AppError::Config("Worker unload or observation failed; owned settings retained until absence is verified".into())); + } + fs::remove_file(self.file(key)).map_err(|_| failure())?; + self.status(key, None) + } +} diff --git a/src/capture_usage.rs b/src/capture_usage.rs new file mode 100644 index 0000000..7bc099d --- /dev/null +++ b/src/capture_usage.rs @@ -0,0 +1,971 @@ +//! Bounded active-session readers; normal numeric extraction remains gated. +//! +//! No consent, hook installation, watcher, raw persistence, complete-coverage +//! claim, pricing or expense creation. Supported numeric shapes are based on +//! minimized probes; stream/interruption/finality qualification remains pending. +//! Consent baselines use identity-only decoding, not historical numeric evidence. +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Component, Path, PathBuf}; + +pub const MAX_SNAPSHOT_BYTES: usize = 1024 * 1024; +pub const MAX_LINE_BYTES: usize = 1024 * 1024; +const MAX_RECORDS: usize = 4096; +const MAX_COUNTER: u64 = 1_000_000_000_000; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Harness { + ClaudeCode, + Codex, +} +impl Harness { + fn version(self) -> &'static str { + match self { + Self::ClaudeCode => "2.1.319", + Self::Codex => "0.167.0", + } + } + fn adapter(self) -> &'static str { + match self { + Self::ClaudeCode => "CLAUDE_JSONL_2_1_319_V1", + Self::Codex => "CODEX_ROLLOUT_0_167_0_V1", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UsageReadError { + UnsupportedVersion, + UnsafePath, + InvalidSession, + Unavailable, + TooLarge, + InvalidRecord, + #[cfg(unix)] + SourceChanged, +} +impl std::fmt::Display for UsageReadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Active-session usage unavailable ({self:?}).") + } +} +impl std::error::Error for UsageReadError {} + +// Deliberately no Debug/Serialize: the path is a transient capability, never an +// evidence or diagnostic field. The caller owns consent and active-session proof. +pub struct ApprovedActiveSession { + harness: Harness, + session_id: String, + path: PathBuf, +} +// Untrusted, path-free decoder identity; it grants no file access or Store consent. +struct DecoderIdentity<'a> { + harness: Harness, + session_id: &'a str, +} +impl ApprovedActiveSession { + fn decoder_identity(&self) -> DecoderIdentity<'_> { + DecoderIdentity { + harness: self.harness, + session_id: &self.session_id, + } + } + + /// `resolved_home` must come from the consent-owning core, never hook input. + /// A hook path alone is not authorization. Only harness-managed roots qualify. + /// No environment/config is read and no path is searched or canonicalized. + pub fn new( + harness: Harness, + version: &str, + resolved_home: &Path, + path: &Path, + session_id: &str, + ) -> Result { + if version != harness.version() { + return Err(UsageReadError::UnsupportedVersion); + } + if !native_session_id(session_id) { + return Err(UsageReadError::InvalidSession); + } + if !absolute_clean(resolved_home) + || resolved_home == Path::new("/") + || !absolute_clean(path) + { + return Err(UsageReadError::UnsafePath); + } + let root = resolved_home.join(match harness { + Harness::ClaudeCode => ".claude/projects", + Harness::Codex => ".codex/sessions", + }); + let relative = path + .strip_prefix(root) + .map_err(|_| UsageReadError::UnsafePath)?; + let parts: Vec<_> = relative.components().collect(); + let filename = path + .file_name() + .and_then(|n| n.to_str()) + .ok_or(UsageReadError::UnsafePath)?; + let allowed = match harness { + Harness::ClaudeCode => parts.len() == 2 && filename == format!("{session_id}.jsonl"), + Harness::Codex => { + parts.len() == 4 + && parts[..3].iter().zip([4, 2, 2]).all(|(p, n)| { + p.as_os_str() + .to_str() + .is_some_and(|s| s.len() == n && s.bytes().all(|b| b.is_ascii_digit())) + }) + && filename.starts_with("rollout-") + && filename.ends_with(&format!("-{session_id}.jsonl")) + } + }; + if !allowed { + return Err(UsageReadError::UnsafePath); + } + Ok(Self { + harness, + session_id: session_id.to_owned(), + path: path.to_owned(), + }) + } +} +fn native_session_id(value: &str) -> bool { + value.len() == 36 + && value.bytes().enumerate().all(|(i, b)| { + if [8, 13, 18, 23].contains(&i) { + b == b'-' + } else { + b.is_ascii_hexdigit() + } + }) +} +fn absolute_clean(path: &Path) -> bool { + // `components` normalizes interior '.', so inspect raw spelling as well. + path.is_absolute() + && path + .as_os_str() + .to_str() + .is_some_and(|s| !s.split('/').any(|p| p == "." || p == "..")) + && path + .components() + .all(|c| matches!(c, Component::RootDir | Component::Normal(_))) +} + +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub struct RequestUsage { + pub source_adapter: &'static str, + pub source_record_id: String, + pub source_turn_id: Option, + pub model: Option, + pub model_provenance: &'static str, + pub counter_semantics: &'static str, + pub input_basis: &'static str, + pub input_tokens: Option, + pub cached_input_tokens: Option, + pub cache_write_input_tokens: Option, + pub output_tokens: Option, + pub reasoning_output_tokens: Option, +} +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub struct UsageEvidence { + pub source_session_id: String, + pub harness_version: &'static str, + pub coverage: &'static str, + pub coverage_reason: &'static str, + pub requests: Vec, + pub limitations: Vec<&'static str>, +} + +/// Consent baselines retain source identities only, never historical counters, +/// model names, transcript paths, content or provisional usage snapshots. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub struct ObservedRequestIds { + pub source_session_id: String, + pub harness_version: &'static str, + pub source_adapter: &'static str, + pub record_ids: BTreeSet, + pub limitations: Vec<&'static str>, +} + +pub fn read_active_session_request_ids( + approved: &ApprovedActiveSession, +) -> Result { + let bytes = bounded_snapshot(&approved.path)?; + parse_request_ids(&approved.decoder_identity(), &bytes) +} +fn parse_request_ids( + approved: &DecoderIdentity<'_>, + bytes: &[u8], +) -> Result { + let (lines, incomplete_tail) = complete_lines(bytes)?; + let mut record_ids = BTreeSet::new(); + let mut saw_meta = false; + for line in lines { + let header: Header = decode(line)?; + match (approved.harness, header.kind.as_str()) { + (Harness::ClaudeCode, "assistant") => { + record_ids.insert(claude_request_id(approved, line)?); + } + (Harness::Codex, "session_meta") => { + verify_session_meta(approved, line)?; + saw_meta = true; + } + (Harness::Codex, "token_usage_record") => { + record_ids.insert(codex_request_id(approved, line, saw_meta)?); + } + _ => (), + } + } + if approved.harness == Harness::Codex && !saw_meta { + return Err(UsageReadError::InvalidSession); + } + Ok(ObservedRequestIds { + source_session_id: approved.session_id.to_owned(), + harness_version: approved.harness.version(), + source_adapter: approved.harness.adapter(), + record_ids, + limitations: if incomplete_tail { + vec!["INCOMPLETE_TAIL"] + } else { + vec![] + }, + }) +} + +pub fn read_active_session_excluding_request_ids( + approved: &ApprovedActiveSession, + excluded: &BTreeSet, +) -> Result { + let bytes = bounded_snapshot(&approved.path)?; + parse_snapshot(&approved.decoder_identity(), &bytes, excluded) +} + +pub fn read_active_session( + approved: &ApprovedActiveSession, +) -> Result { + read_active_session_excluding_request_ids(approved, &BTreeSet::new()) +} +#[cfg(unix)] +fn bounded_snapshot(path: &Path) -> Result, UsageReadError> { + let (bytes, _lease) = leased_snapshot(path, None)?; + Ok(bytes) +} + +/// Commit-held read-only inode and named-path identity. No Debug/serialization: +/// neither this transient path nor raw bytes belong to persisted evidence. +#[cfg(unix)] +pub(crate) struct SourceLease { + file: std::fs::File, + path: PathBuf, + before: std::fs::Metadata, +} +#[cfg(unix)] +impl SourceLease { + pub(crate) fn identity(&self) -> Option { + use std::os::unix::fs::MetadataExt; + let created = self + .before + .created() + .ok()? + .duration_since(std::time::UNIX_EPOCH) + .ok()?; + Some(crate::capture::hash(format!( + "{}:{}:{}:{}:{}", + self.before.dev(), + self.before.ino(), + self.before.uid(), + created.as_secs(), + created.subsec_nanos() + ))) + } + fn same(&self, metadata: &std::fs::Metadata) -> bool { + use std::os::unix::fs::MetadataExt; + metadata.is_file() + && metadata.nlink() == 1 + && metadata.uid() == unsafe { libc::geteuid() } + && metadata.dev() == self.before.dev() + && metadata.ino() == self.before.ino() + && metadata.mode() == self.before.mode() + && metadata.len() == self.before.len() + && metadata.mtime() == self.before.mtime() + && metadata.mtime_nsec() == self.before.mtime_nsec() + && metadata.ctime() == self.before.ctime() + && metadata.ctime_nsec() == self.before.ctime_nsec() + } + pub(crate) fn valid(&self) -> bool { + self.file + .metadata() + .is_ok_and(|metadata| self.same(&metadata)) + && open_active_file(&self.path) + .and_then(|file| file.metadata().map_err(|_| UsageReadError::SourceChanged)) + .is_ok_and(|metadata| self.same(&metadata)) + } +} + +#[cfg(unix)] +pub(crate) fn read_request_ids_leased( + approved: &ApprovedActiveSession, +) -> Result<(ObservedRequestIds, SourceLease), UsageReadError> { + let (bytes, lease) = leased_snapshot(&approved.path, None)?; + let ids = parse_request_ids(&approved.decoder_identity(), &bytes)?; + Ok((ids, lease)) +} +#[cfg(unix)] +pub(crate) fn read_requests_leased( + approved: &ApprovedActiveSession, + excluded: &BTreeSet, + expected_identity: &str, +) -> Result<(UsageEvidence, SourceLease), UsageReadError> { + let (bytes, lease) = leased_snapshot(&approved.path, Some(expected_identity))?; + let evidence = parse_snapshot(&approved.decoder_identity(), &bytes, excluded)?; + Ok((evidence, lease)) +} + +#[cfg(unix)] +fn open_active_file(path: &Path) -> Result { + use std::ffi::CString; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::os::unix::ffi::OsStrExt; + // Pin every directory by descriptor. No stat-then-open window, symlink + // traversal, FIFO blocking, recursive search or fallback filename. + let name = CString::new("/").map_err(|_| UsageReadError::UnsafePath)?; + let root_fd = unsafe { + libc::open( + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if root_fd < 0 { + return Err(UsageReadError::Unavailable); + } + let mut parent = unsafe { OwnedFd::from_raw_fd(root_fd) }; + let parts: Vec<_> = path + .components() + .filter_map(|c| { + if let Component::Normal(v) = c { + Some(v) + } else { + None + } + }) + .collect(); + for (index, part) in parts.iter().enumerate() { + let name = CString::new(part.as_bytes()).map_err(|_| UsageReadError::UnsafePath)?; + let last = index + 1 == parts.len(); + let flags = libc::O_RDONLY + | libc::O_CLOEXEC + | libc::O_NOFOLLOW + | libc::O_NONBLOCK + | if last { 0 } else { libc::O_DIRECTORY }; + let fd = unsafe { libc::openat(parent.as_raw_fd(), name.as_ptr(), flags) }; + if fd < 0 { + return Err(UsageReadError::UnsafePath); + } + parent = unsafe { OwnedFd::from_raw_fd(fd) }; + } + Ok(std::fs::File::from(parent)) +} + +#[cfg(unix)] +fn leased_snapshot( + path: &Path, + expected_identity: Option<&str>, +) -> Result<(Vec, SourceLease), UsageReadError> { + #[cfg(test)] + crate::capture_usage_test_io::observe(2); + use std::{io::Read, os::unix::fs::MetadataExt}; + let file = open_active_file(path)?; + let before = file.metadata().map_err(|_| UsageReadError::Unavailable)?; + if !before.is_file() || before.nlink() != 1 || before.uid() != unsafe { libc::geteuid() } { + return Err(UsageReadError::UnsafePath); + } + if before.len() > MAX_SNAPSHOT_BYTES as u64 { + return Err(UsageReadError::TooLarge); + } + let mut lease = SourceLease { + file, + path: path.into(), + before, + }; + if expected_identity.is_some_and(|expected| lease.identity().as_deref() != Some(expected)) { + return Err(UsageReadError::SourceChanged); + } + let mut bytes = Vec::with_capacity(lease.before.len() as usize); + lease + .file + .by_ref() + .take((MAX_SNAPSHOT_BYTES + 1) as u64) + .read_to_end(&mut bytes) + .map_err(|_| UsageReadError::Unavailable)?; + if bytes.len() > MAX_SNAPSHOT_BYTES { + return Err(UsageReadError::TooLarge); + } + if bytes.len() as u64 != lease.before.len() || !lease.valid() { + return Err(UsageReadError::SourceChanged); + } + Ok((bytes, lease)) +} +#[cfg(not(unix))] +fn bounded_snapshot(_path: &Path) -> Result, UsageReadError> { + Err(UsageReadError::Unavailable) +} + +#[derive(Deserialize)] +struct Header { + #[serde(rename = "type")] + kind: String, +} +#[derive(Deserialize)] +struct ClaudeIdentity { + #[serde(rename = "sessionId")] + session_id: String, +} +#[derive(Deserialize)] +struct ClaudeObservedRecord { + message: ClaudeObservedMessage, +} +#[derive(Deserialize)] +struct ClaudeObservedMessage { + id: String, +} +#[derive(Deserialize)] +struct ClaudeRecord { + #[serde(rename = "sessionId")] + session_id: String, + message: ClaudeMessage, +} +#[derive(Deserialize)] +struct ClaudeMessage { + id: String, + model: Option, + usage: Option, + stop_reason: Option, +} +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +enum ClaudeStopReason { + ToolUse, + EndTurn, + #[serde(other)] + Unqualified, +} +#[derive(Deserialize)] +struct ClaudeTokens { + input_tokens: Option, + cache_creation_input_tokens: Option, + cache_read_input_tokens: Option, + output_tokens: Option, +} +#[derive(Deserialize)] +struct Envelope { + payload: T, +} +#[derive(Deserialize)] +struct SessionMeta { + id: String, + session_id: String, + cli_version: Option, +} +#[derive(Deserialize)] +struct TurnContext { + turn_id: Option, + model: Option, + session_id: Option, + thread_id: Option, +} +#[derive(Deserialize)] +struct LifecycleEvent { + #[serde(rename = "type")] + kind: String, + turn_id: Option, + session_id: Option, + thread_id: Option, +} +#[derive(Deserialize)] +struct CodexRecord { + thread_id: String, + session_id: String, + turn_id: String, + root_turn_id: String, + response_id: String, + usage: Option, +} +#[derive(Deserialize)] +struct CodexObservedRecord { + thread_id: String, + session_id: String, + turn_id: String, + root_turn_id: String, + response_id: String, +} +#[derive(Deserialize)] +struct CodexTokens { + input_tokens: Option, + cached_input_tokens: Option, + cache_write_input_tokens: Option, + output_tokens: Option, + reasoning_output_tokens: Option, +} +fn decode<'a, T: Deserialize<'a>>(line: &'a [u8]) -> Result { + // IgnoredAny can skip deeper than serde's ordinary value recursion limit. + // Budget nesting even in fields we discard, without materializing prose. + let (mut depth, mut quoted, mut escaped) = (0usize, false, false); + for byte in line { + if quoted { + if escaped { + escaped = false; + } else if *byte == b'\\' { + escaped = true; + } else if *byte == b'"' { + quoted = false; + } + } else { + match byte { + b'"' => quoted = true, + b'{' | b'[' => { + depth += 1; + if depth > 64 { + return Err(UsageReadError::InvalidRecord); + } + } + b'}' | b']' => depth = depth.saturating_sub(1), + _ => (), + } + } + } + // Typed decoding ignores prose without retaining values; duplicate known + // fields fail closed. Neither JSON decoder errors nor input are exposed. + serde_json::from_slice(line).map_err(|_| UsageReadError::InvalidRecord) +} +fn opaque(value: &str) -> bool { + !value.is_empty() + && value.len() <= 128 + && value.as_bytes()[0].is_ascii_alphanumeric() + && !value.contains("..") + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_.:-".contains(&b)) + && ![ + "kto_", + "sk-", + "sk_", + "akia", + "asia", + "ghp_", + "gho_", + "ghu_", + "ghs_", + "ghr_", + "github_pat_", + "xoxb-", + "xoxp-", + ] + .iter() + .any(|p| value.to_ascii_lowercase().starts_with(p)) +} +fn identifier(value: &str) -> Result<(), UsageReadError> { + if opaque(value) { + Ok(()) + } else { + Err(UsageReadError::InvalidRecord) + } +} +fn model(value: Option) -> Result, UsageReadError> { + if let Some(ref v) = value { + identifier(v)?; + } + Ok(value) +} +fn complete_lines(bytes: &[u8]) -> Result<(Vec<&[u8]>, bool), UsageReadError> { + if bytes.len() > MAX_SNAPSHOT_BYTES { + return Err(UsageReadError::TooLarge); + } + let mut lines = Vec::new(); + let mut count = 0; + let mut tail = false; + for chunk in bytes.split_inclusive(|b| *b == b'\n') { + if chunk.last() != Some(&b'\n') { + tail = true; + break; + } + let line = &chunk[..chunk.len() - 1]; + count += 1; + if count > MAX_RECORDS || line.len() > MAX_LINE_BYTES { + return Err(UsageReadError::TooLarge); + } + if !line.iter().all(u8::is_ascii_whitespace) { + lines.push(line); + } + } + Ok((lines, tail)) +} +fn claude_request_id( + approved: &DecoderIdentity<'_>, + line: &[u8], +) -> Result { + let identity: ClaudeIdentity = decode(line).map_err(|_| UsageReadError::InvalidSession)?; + if identity.session_id != approved.session_id { + return Err(UsageReadError::InvalidSession); + } + let record: ClaudeObservedRecord = decode(line)?; + identifier(&record.message.id)?; + if !record.message.id.starts_with("msg_") { + return Err(UsageReadError::InvalidRecord); + } + Ok(record.message.id) +} +fn verify_session_meta(approved: &DecoderIdentity<'_>, line: &[u8]) -> Result<(), UsageReadError> { + let meta: Envelope = decode(line).map_err(|_| UsageReadError::InvalidSession)?; + if meta.payload.id != approved.session_id || meta.payload.session_id != approved.session_id { + return Err(UsageReadError::InvalidSession); + } + if meta.payload.cli_version.as_deref() != Some(approved.harness.version()) { + return Err(UsageReadError::UnsupportedVersion); + } + Ok(()) +} +fn codex_request_id( + approved: &DecoderIdentity<'_>, + line: &[u8], + saw_meta: bool, +) -> Result { + let raw: Envelope = decode(line)?; + let raw = raw.payload; + if !saw_meta || raw.session_id != approved.session_id || raw.thread_id != approved.session_id { + return Err(UsageReadError::InvalidSession); + } + identifier(&raw.response_id)?; + identifier(&raw.turn_id)?; + identifier(&raw.root_turn_id)?; + if !raw.response_id.starts_with("resp_") { + return Err(UsageReadError::InvalidRecord); + } + Ok(raw.response_id) +} +fn validate_counters(request: &RequestUsage) -> Result<(), UsageReadError> { + if [ + request.input_tokens, + request.cached_input_tokens, + request.cache_write_input_tokens, + request.output_tokens, + request.reasoning_output_tokens, + ] + .into_iter() + .flatten() + .any(|n| n > MAX_COUNTER) + { + return Err(UsageReadError::InvalidRecord); + } + if request + .reasoning_output_tokens + .zip(request.output_tokens) + .is_some_and(|(reasoning, output)| reasoning > output) + || (request.input_basis == "CODEX_TOTAL_INPUT" + && request.input_tokens.is_some_and(|input| { + request.cached_input_tokens.unwrap_or(0) + + request.cache_write_input_tokens.unwrap_or(0) + > input + })) + { + return Err(UsageReadError::InvalidRecord); + } + // Claude cache categories are additional input; normalization belongs to + // the server. Codex cached input and reasoning remain their raw subsets. + Ok(()) +} +fn parse_snapshot( + approved: &DecoderIdentity<'_>, + bytes: &[u8], + excluded: &BTreeSet, +) -> Result { + if bytes.len() > MAX_SNAPSHOT_BYTES { + return Err(UsageReadError::TooLarge); + } + let mut limitations = BTreeSet::new(); + let mut contexts: BTreeMap> = BTreeMap::new(); + let mut candidates = Vec::new(); + let mut held_requests = BTreeSet::new(); + let mut provisional_requests = BTreeSet::new(); + let mut final_requests = BTreeSet::new(); + let mut started_turns = BTreeSet::new(); + let mut completed_turns = BTreeSet::new(); + let mut interrupted_turns = BTreeSet::new(); + let mut saw_meta = false; + let mut records = 0; + let mut start = 0; + for (index, byte) in bytes.iter().enumerate() { + if *byte != b'\n' { + continue; + } + let line = &bytes[start..index]; + start = index + 1; + if line.len() > MAX_LINE_BYTES { + return Err(UsageReadError::TooLarge); + } + records += 1; + if records > MAX_RECORDS { + return Err(UsageReadError::TooLarge); + } + if line.iter().all(u8::is_ascii_whitespace) { + continue; + } + let header: Header = decode(line)?; + match (approved.harness, header.kind.as_str()) { + (Harness::ClaudeCode, "assistant") => { + let id = claude_request_id(approved, line)?; + // A consent baseline excludes historical IDs before decoding + // their numeric, model or finality fields. They never become + // numeric evidence or conflicts in this authorized epoch. + if excluded.contains(&id) { + continue; + } + // A filename is not identity. Every usage-bearing record must + // identify this exact approved session. + let identity: ClaudeIdentity = + decode(line).map_err(|_| UsageReadError::InvalidSession)?; + if identity.session_id != approved.session_id { + return Err(UsageReadError::InvalidSession); + } + let raw: ClaudeRecord = decode(line)?; + if raw.session_id != approved.session_id { + return Err(UsageReadError::InvalidSession); + } + identifier(&raw.message.id)?; + if !raw.message.id.starts_with("msg_") { + return Err(UsageReadError::InvalidRecord); + } + // Provisional stream counters are cumulative snapshots, not + // deltas. Ignore them, then consume a qualified final once. + // Actual same-ID stream delivery remains a qualification gate; + // the policy follows the primary final-usage contract. + match raw.message.stop_reason { + None => { + provisional_requests.insert(raw.message.id); + continue; + } + Some(ClaudeStopReason::Unqualified) => { + held_requests.insert(raw.message.id); + limitations.insert("UNKNOWN_REQUEST_FINALITY"); + continue; + } + Some(ClaudeStopReason::ToolUse | ClaudeStopReason::EndTurn) => { + final_requests.insert(raw.message.id.clone()); + } + } + let usage = raw.message.usage; + if usage.is_none() { + limitations.insert("MISSING_USAGE"); + } + let model = model(raw.message.model)?; + if model.is_none() { + limitations.insert("MISSING_MODEL"); + } + candidates.push(RequestUsage { + source_adapter: approved.harness.adapter(), + source_record_id: raw.message.id, + source_turn_id: None, + model_provenance: if model.is_some() { + "RESPONSE_MODEL" + } else { + "UNKNOWN" + }, + model, + counter_semantics: "REQUEST_DELTA", + input_basis: "CLAUDE_UNCACHED_INPUT", + input_tokens: usage.as_ref().and_then(|u| u.input_tokens), + cached_input_tokens: usage.as_ref().and_then(|u| u.cache_read_input_tokens), + cache_write_input_tokens: usage + .as_ref() + .and_then(|u| u.cache_creation_input_tokens), + output_tokens: usage.as_ref().and_then(|u| u.output_tokens), + reasoning_output_tokens: None, + }); + } + (Harness::Codex, "session_meta") => { + verify_session_meta(approved, line)?; + saw_meta = true; + } + (Harness::Codex, "event_msg") => { + let event: Envelope = decode(line)?; + let event = event.payload; + if event.session_id.is_some_and(|id| id != approved.session_id) + || event.thread_id.is_some_and(|id| id != approved.session_id) + { + return Err(UsageReadError::InvalidSession); + } + if ["task_started", "task_complete", "turn_aborted"].contains(&event.kind.as_str()) + { + let turn = event.turn_id.ok_or(UsageReadError::InvalidRecord)?; + identifier(&turn)?; + match event.kind.as_str() { + "task_started" => { + started_turns.insert(turn); + } + "task_complete" => { + completed_turns.insert(turn); + } + "turn_aborted" => { + interrupted_turns.insert(turn); + } + _ => (), + } + } + } + (Harness::Codex, "turn_context") => { + let raw: Envelope = decode(line)?; + if raw + .payload + .session_id + .is_some_and(|id| id != approved.session_id) + || raw + .payload + .thread_id + .is_some_and(|id| id != approved.session_id) + { + return Err(UsageReadError::InvalidSession); + } + if let Some(turn) = raw.payload.turn_id { + identifier(&turn)?; + let value = model(raw.payload.model)?; + // Conflicting same-turn model snapshots mean unknown + // attribution, never last-model-wins after compaction. + if let Some(previous) = contexts.get(&turn) { + if previous != &value { + contexts.insert(turn, None); + limitations.insert("CONFLICTING_TURN_MODELS"); + } + } else { + contexts.insert(turn, value); + } + } + } + (Harness::Codex, "token_usage_record") => { + let id = codex_request_id(approved, line, saw_meta)?; + if excluded.contains(&id) { + continue; + } + let raw: Envelope = decode(line)?; + let raw = raw.payload; + if !saw_meta + || raw.session_id != approved.session_id + || raw.thread_id != approved.session_id + { + return Err(UsageReadError::InvalidSession); + } + identifier(&raw.response_id)?; + identifier(&raw.turn_id)?; + identifier(&raw.root_turn_id)?; + if !raw.response_id.starts_with("resp_") { + return Err(UsageReadError::InvalidRecord); + } + let usage = raw.usage; + if usage.is_none() { + limitations.insert("MISSING_USAGE"); + } + candidates.push(RequestUsage { + source_adapter: approved.harness.adapter(), + source_record_id: raw.response_id, + source_turn_id: Some(raw.turn_id), + model: None, + model_provenance: "UNKNOWN", + counter_semantics: "REQUEST_DELTA", + input_basis: "CODEX_TOTAL_INPUT", + input_tokens: usage.as_ref().and_then(|u| u.input_tokens), + cached_input_tokens: usage.as_ref().and_then(|u| u.cached_input_tokens), + cache_write_input_tokens: usage + .as_ref() + .and_then(|u| u.cache_write_input_tokens), + output_tokens: usage.as_ref().and_then(|u| u.output_tokens), + reasoning_output_tokens: usage.as_ref().and_then(|u| u.reasoning_output_tokens), + }); + } + _ => (), + } + } + if start < bytes.len() { + limitations.insert("INCOMPLETE_TAIL"); + } + if approved.harness == Harness::Codex && !saw_meta { + return Err(UsageReadError::InvalidSession); + } + if provisional_requests + .difference(&final_requests) + .next() + .is_some() + { + // This is resolvable incomplete coverage, not a permanent conflict. + limitations.insert("PENDING_REQUEST_FINALITY"); + } + let mut requests: BTreeMap> = BTreeMap::new(); + for mut request in candidates { + if let Some(turn) = &request.source_turn_id { + request.model = contexts.get(turn).and_then(Clone::clone); + if request.model.is_some() { + request.model_provenance = "TURN_CONFIG"; + } else { + limitations.insert("MISSING_MODEL"); + } + } + validate_counters(&request)?; + if request.input_tokens.is_none() && request.output_tokens.is_none() { + limitations.insert("MISSING_USAGE"); + } + match requests.get(&request.source_record_id) { + None => { + requests.insert(request.source_record_id.clone(), Some(request)); + } + Some(Some(previous)) if previous == &request => (), + _ => { + limitations.insert("CONFLICTING_REQUEST_RECORDS"); + requests.insert(request.source_record_id.clone(), None); + } + } + } + let requests: Vec<_> = requests + .into_values() + .flatten() + .filter(|r| !held_requests.contains(&r.source_record_id)) + .filter(|r| r.input_tokens.is_some() || r.output_tokens.is_some()) + .collect(); + let observed_turns: BTreeSet<_> = requests + .iter() + .filter_map(|r| r.source_turn_id.as_ref()) + .collect(); + if !interrupted_turns.is_empty() { + limitations.insert("INTERRUPTED_TURN"); + } + if started_turns + .iter() + .any(|turn| !completed_turns.contains(turn) && !interrupted_turns.contains(turn)) + { + limitations.insert("IN_PROGRESS_TURN"); + } + if started_turns + .iter() + .chain(completed_turns.iter()) + .chain(interrupted_turns.iter()) + .any(|turn| !observed_turns.contains(turn)) + { + // The aborted probe emitted no usage record. Absence cannot establish + // zero provider consumption, even after an explicit terminal event. + limitations.insert("MISSING_TURN_USAGE"); + } + if requests.is_empty() { + limitations.insert("NO_OBSERVED_REQUEST_RECORDS"); + } + Ok(UsageEvidence { + source_session_id: approved.session_id.to_owned(), + harness_version: approved.harness.version(), + coverage: "PARTIAL", + coverage_reason: "OBSERVED_REQUEST_RECORDS", + requests, + limitations: limitations.into_iter().collect(), + }) +} + +#[cfg(test)] +#[path = "../tests/unit/capture_usage_parser.rs"] +mod parser_tests; + +#[cfg(all(test, unix))] +#[path = "../tests/unit/capture_usage_lease.rs"] +mod lease_tests; diff --git a/src/capture_usage_consent.rs b/src/capture_usage_consent.rs new file mode 100644 index 0000000..acdd1d3 --- /dev/null +++ b/src/capture_usage_consent.rs @@ -0,0 +1,64 @@ +//! Path-free persisted numeric policy. Functional profile paths belong only in +//! the separately approved private device record, never this SQLite policy. +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ConsentPolicy { + pub policy_version: u8, + pub binding_id: String, + pub binding_version: i64, + pub source_namespace: String, + pub profile_id: String, + pub profile_digest: String, + pub epoch: u64, + pub enabled: bool, + #[serde(default)] + pub unavailable_reason: Option, +} + +impl ConsentPolicy { + pub(crate) fn matches(&self, binding: &crate::capture::Binding, namespace: &str) -> bool { + let digest = |s: &str| { + s.len() == 64 + && s.bytes() + .all(|v| v.is_ascii_digit() || (b'a'..=b'f').contains(&v)) + }; + self.policy_version == 1 + && self.binding_id == binding.id + && self.binding_version == binding.version + && self.source_namespace == namespace + && matches!(namespace, "claude-code" | "codex") + && digest(&self.profile_id) + && digest(&self.profile_digest) + && self.epoch > 0 + && self.unavailable_reason.as_deref().is_none_or(known_reason) + } +} + +pub(crate) fn known_reason(reason: &str) -> bool { + matches!( + reason, + "NUMERIC_CAPTURE_DISABLED" + | "NUMERIC_SOURCE_UNQUALIFIED" + | "PROFILE_UNAVAILABLE" + | "PROFILE_CHANGED" + | "HARNESS_CHANGED" + | "REGISTRATION_CHANGED" + | "RUNTIME_CHANGED" + | "UNSUPPORTED_SOURCE" + | "UNSUPPORTED_HARNESS_VERSION" + | "HARNESS_ORIGIN_UNAVAILABLE" + | "LIVE_GUARD_REQUIRED" + | "ACTIVE_SOURCE_UNAVAILABLE" + | "MISSING_QUALIFIED_PROMPT" + | "SOURCE_CHANGED" + | "SOURCE_PARSE_UNAVAILABLE" + | "OBSERVED_REQUEST_RECORDS" + ) +} + +pub(crate) fn status(namespace: &str, enabled: bool, reason: &str) -> serde_json::Value { + serde_json::json!({"source_namespace":namespace,"enabled":enabled, + "status":"UNAVAILABLE","reason":reason}) +} diff --git a/src/capture_usage_ledger.rs b/src/capture_usage_ledger.rs new file mode 100644 index 0000000..0b5d77e --- /dev/null +++ b/src/capture_usage_ledger.rs @@ -0,0 +1,251 @@ +//! Minimized immutable request evidence. Raw transcripts and paths are never storage types. +use crate::capture_usage::UsageEvidence; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct UsageRecord { + pub source_adapter: String, + pub source_record_id: String, + pub source_turn_id: Option, + pub model: Option, + pub model_provenance: String, + pub counter_semantics: String, + pub input_basis: String, + pub input_tokens: Option, + pub cached_input_tokens: Option, + pub cache_write_input_tokens: Option, + pub output_tokens: Option, + pub reasoning_output_tokens: Option, +} +fn opaque(value: &str) -> bool { + crate::capture::identifier(value).is_ok() + && ![ + "kto_", + "sk-", + "sk_", + "akia", + "asia", + "ghp_", + "gho_", + "ghu_", + "ghs_", + "ghr_", + "github_pat_", + "xoxb-", + "xoxp-", + ] + .iter() + .any(|p| value.to_ascii_lowercase().starts_with(p)) +} +impl UsageRecord { + pub fn valid(&self, source: &str, version: &str) -> bool { + let claude = source == "claude-code" && version == "2.1.319"; + let codex = source == "codex" && version == "0.167.0"; + (claude || codex) + && self.source_adapter + == if claude { + "CLAUDE_JSONL_2_1_319_V1" + } else { + "CODEX_ROLLOUT_0_167_0_V1" + } + && self.input_basis + == if claude { + "CLAUDE_UNCACHED_INPUT" + } else { + "CODEX_TOTAL_INPUT" + } + && self.counter_semantics == "REQUEST_DELTA" + && opaque(&self.source_record_id) + && self.source_turn_id.as_deref().is_none_or(opaque) + && self.model.as_deref().is_none_or(opaque) + && matches!( + self.model_provenance.as_str(), + "RESPONSE_MODEL" | "TURN_CONFIG" | "UNKNOWN" + ) + && (self.model.is_none() == (self.model_provenance == "UNKNOWN")) + && if claude { + self.model_provenance != "TURN_CONFIG" + } else { + self.source_turn_id.is_some() && self.model_provenance != "RESPONSE_MODEL" + } + && (self.input_tokens.is_some() || self.output_tokens.is_some()) + && [ + self.input_tokens, + self.cached_input_tokens, + self.cache_write_input_tokens, + self.output_tokens, + self.reasoning_output_tokens, + ] + .into_iter() + .flatten() + .all(|v| v <= 1_000_000_000_000) + && !self + .reasoning_output_tokens + .zip(self.output_tokens) + .is_some_and(|(r, o)| r > o) + && (claude + || self.input_tokens.is_none_or(|i| { + self.cached_input_tokens.unwrap_or(0) + + self.cache_write_input_tokens.unwrap_or(0) + <= i + })) + } +} +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UsageLedger { + pub records: Vec, + pub record_revisions: Vec, + pub queued: usize, + pub incomplete: bool, + pub held: bool, + #[serde(default)] + pub consent_epoch: u64, + #[serde(default)] + pub baseline_epoch: Option, + #[serde(default)] + pub excluded_request_ids: std::collections::BTreeSet, +} +impl UsageLedger { + pub fn baseline_ready(&self) -> bool { + self.baseline_epoch == Some(self.consent_epoch) + } + pub fn require_baseline(&mut self) { + self.consent_epoch = self.consent_epoch.saturating_add(1); + self.baseline_epoch = None; + self.incomplete = true; + } + /// Persist identifiers only. Prior immutable accepted records remain eligible + /// for conflict checking; no excluded record's counters enter this ledger. + pub fn establish_baseline(&mut self, ids: std::collections::BTreeSet) -> bool { + self.baseline_epoch = None; + if ids.len() > 4096 || ids.iter().any(|id| !opaque(id)) { + self.incomplete = true; + return false; + } + let mut excluded = self.excluded_request_ids.clone(); + excluded.extend( + ids.into_iter() + .filter(|id| !self.records.iter().any(|old| old.source_record_id == *id)), + ); + if excluded.len() > 16384 { + self.incomplete = true; + return false; + } + self.incomplete |= !excluded.is_empty(); + self.excluded_request_ids = excluded; + self.baseline_epoch = Some(self.consent_epoch); + true + } + /// Validate the whole snapshot before changing any minimized records. + pub fn observe(&mut self, evidence: UsageEvidence, source: &str, version: &str, session: &str) { + if !self.baseline_ready() { + self.incomplete = true; + return; + } + if evidence.source_session_id != session + || evidence.harness_version != version + || evidence.coverage != "PARTIAL" + { + self.incomplete = true; + return; + } + if evidence.limitations.iter().any(|reason| { + matches!( + *reason, + "CONFLICTING_REQUEST_RECORDS" | "UNKNOWN_REQUEST_FINALITY" + ) + }) { + self.held = true; + self.incomplete = true; + return; + } + let candidate = serde_json::to_value(&evidence.requests) + .ok() + .and_then(|v| serde_json::from_value::>(v).ok()); + let Some(candidate) = candidate.filter(|v| v.iter().all(|r| r.valid(source, version))) + else { + self.incomplete = true; + return; + }; + let candidate: Vec<_> = candidate + .into_iter() + .filter(|r| { + !self.excluded_request_ids.contains(&r.source_record_id) + || self + .records + .iter() + .any(|old| old.source_record_id == r.source_record_id) + }) + .collect(); + if candidate.iter().any(|r| { + self.records + .iter() + .any(|old| old.source_record_id == r.source_record_id && old != r) + }) { + self.held = true; + self.incomplete = true; + return; + } + self.incomplete |= !evidence.limitations.is_empty(); + for record in candidate { + if !self + .records + .iter() + .any(|old| old.source_record_id == record.source_record_id) + { + self.records.push(record); + self.record_revisions.push(0); + } + } + } + pub fn payload(&self, start: usize, end: usize) -> serde_json::Value { + if start == end { + return serde_json::json!({"status":"UNAVAILABLE","reason":"NO_QUALIFIED_USAGE_EVIDENCE","models":[]}); + } + serde_json::json!({"schema_version":1,"status":"PARTIAL","reason":if self.incomplete {"INCOMPLETE_USAGE_EVIDENCE"} else {"OBSERVED_REQUEST_RECORDS"},"records":self.records[start..end]}) + } + pub fn validate_payload( + &self, + raw: &serde_json::Value, + source: &str, + version: &str, + revision: i64, + ) -> bool { + if raw + == &serde_json::json!({"status":"UNAVAILABLE","reason":"NO_QUALIFIED_USAGE_EVIDENCE","models":[]}) + { + return true; + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Partial { + schema_version: u8, + status: String, + reason: String, + records: Vec, + } + let Ok(p) = serde_json::from_value::(raw.clone()) else { + return false; + }; + let mut ids = std::collections::BTreeSet::new(); + p.schema_version == 1 + && p.status == "PARTIAL" + && matches!( + p.reason.as_str(), + "OBSERVED_REQUEST_RECORDS" | "INCOMPLETE_USAGE_EVIDENCE" + ) + && !p.records.is_empty() + && p.records.len() <= 25 + && p.records.iter().all(|r| { + r.valid(source, version) + && ids.insert(&r.source_record_id) + && self + .records + .iter() + .position(|old| old == r) + .is_some_and(|i| self.record_revisions.get(i) == Some(&revision)) + }) + } +} diff --git a/src/capture_usage_origin.rs b/src/capture_usage_origin.rs new file mode 100644 index 0000000..cea97bc --- /dev/null +++ b/src/capture_usage_origin.rs @@ -0,0 +1,265 @@ +//! Bounded cooperative native-image provenance, never provider attestation. +//! Inspect at most eight same-user ancestors, only PID/start/parent/image +//! metadata. No argv, environment, cwd, open-file list or process enumeration. +#![cfg(unix)] +use crate::capture_usage_profile::FileStamp; +use std::{ + collections::BTreeSet, + fs::File, + path::{Path, PathBuf}, +}; + +#[derive(Clone, PartialEq, Eq)] +struct Snapshot { + pid: i32, + parent: i32, + started: (u64, u64), + image: PathBuf, +} +pub(crate) struct OriginLease { + nodes: Vec, + native_path: PathBuf, + native_stamp: FileStamp, + native_file: File, +} + +impl OriginLease { + pub(crate) fn verify(native_path: &Path, native_stamp: &FileStamp) -> Option { + #[cfg(test)] + crate::capture_usage_test_io::observe(1); + let (nodes, native_file) = + collect_chain(unsafe { libc::getppid() }, observe, |node, file| { + node.image == native_path + && file + .metadata() + .is_ok_and(|metadata| native_stamp.matches_metadata(&metadata)) + })?; + let lease = Self { + nodes, + native_path: native_path.into(), + native_stamp: native_stamp.clone(), + native_file, + }; + lease.valid().then_some(lease) + } + pub(crate) fn valid(&self) -> bool { + if self.nodes.is_empty() + || self.nodes.len() > 8 + || unsafe { libc::getppid() } != self.nodes[0].pid + || !self + .native_stamp + .matches_metadata(&match self.native_file.metadata() { + Ok(metadata) => metadata, + Err(_) => return false, + }) + { + return false; + } + if !stable_chain(&self.nodes, unsafe { libc::getppid() }, observe) { + return false; + } + let Some(native) = self.nodes.last() else { + return false; + }; + if native.image != self.native_path { + return false; + } + // Current named-image freshness is checked as well as the executing + // image. Replaced/upgraded binaries need explicit profile approval. + crate::capture_usage_profile::image_metadata(&self.native_path) + .is_some_and(|metadata| self.native_stamp.matches_metadata(&metadata)) + } +} + +// Both helpers consume only the fixed metadata observations. Tests provide inert +// snapshots, never an alternate positive runtime or origin capability. +fn collect_chain( + mut pid: i32, + mut read: impl FnMut(i32) -> Option<(Snapshot, File)>, + matches: impl Fn(&Snapshot, &File) -> bool, +) -> Option<(Vec, File)> { + let mut seen = BTreeSet::new(); + let mut nodes = Vec::new(); + for _ in 0..8 { + if pid <= 0 || !seen.insert(pid) { + return None; + } + let (node, file) = read(pid)?; + if node.pid != pid || node.started.0 == 0 || node.parent == pid { + return None; + } + let matched = matches(&node, &file); + pid = node.parent; + nodes.push(node); + if matched { + return Some((nodes, file)); + } + } + None +} +fn stable_chain( + nodes: &[Snapshot], + parent: i32, + mut read: impl FnMut(i32) -> Option<(Snapshot, File)>, +) -> bool { + !nodes.is_empty() + && nodes.len() <= 8 + && nodes[0].pid == parent + && nodes.windows(2).all(|pair| pair[0].parent == pair[1].pid) + && nodes + .iter() + .all(|node| read(node.pid).is_some_and(|(current, _)| current == *node)) +} + +#[cfg(target_os = "macos")] +fn observe(pid: i32) -> Option<(Snapshot, File)> { + use std::os::unix::ffi::OsStringExt; + fn identity(pid: i32) -> Option<(i32, (u64, u64))> { + let mut info = std::mem::MaybeUninit::::uninit(); + let size = i32::try_from(std::mem::size_of::()).ok()?; + let length = unsafe { + libc::proc_pidinfo( + pid, + libc::PROC_PIDTBSDINFO, + 0, + info.as_mut_ptr().cast(), + size, + ) + }; + if length != size { + return None; + } + let info = unsafe { info.assume_init() }; + if info.pbi_pid != u32::try_from(pid).ok()? + || info.pbi_uid != unsafe { libc::geteuid() } + || info.pbi_ruid != unsafe { libc::geteuid() } + || info.pbi_start_tvsec == 0 + { + return None; + } + Some(( + i32::try_from(info.pbi_ppid).ok()?, + (info.pbi_start_tvsec, info.pbi_start_tvusec), + )) + } + let before = identity(pid)?; + let mut bytes = [0u8; 4096]; + let length = unsafe { + libc::proc_pidpath( + pid, + bytes.as_mut_ptr().cast(), + u32::try_from(bytes.len()).ok()?, + ) + }; + if length <= 0 || usize::try_from(length).ok()? >= bytes.len() { + return None; + } + let end = bytes.iter().position(|byte| *byte == 0)?; + let image = PathBuf::from(std::ffi::OsString::from_vec(bytes[..end].to_vec())); + if !image.is_absolute() || identity(pid)? != before { + return None; + } + // Darwin reports a kernel path rather than an executable descriptor. Open + // it through the same no-follow metadata boundary and repeat PID/start/path + // observations in valid(). This retains the documented Darwin path/image + // race and cooperative threat limit; it is not executable sealing. + let file = crate::capture_usage_profile::open_image_metadata(&image)?; + Some(( + Snapshot { + pid, + parent: before.0, + started: before.1, + image, + }, + file, + )) +} + +#[cfg(target_os = "linux")] +fn observe(pid: i32) -> Option<(Snapshot, File)> { + use std::{io::Read, os::unix::fs::MetadataExt}; + fn identity(pid: i32) -> Option<(i32, (u64, u64))> { + if pid <= 0 + || std::fs::metadata(format!("/proc/{pid}")).ok()?.uid() != unsafe { libc::geteuid() } + { + return None; + } + let mut status = Vec::new(); + File::open(format!("/proc/{pid}/status")) + .ok()? + .take(65537) + .read_to_end(&mut status) + .ok()?; + if status.len() > 65536 { + return None; + } + let status = std::str::from_utf8(&status).ok()?; + let uids: Vec = status + .lines() + .find_map(|line| line.strip_prefix("Uid:"))? + .split_whitespace() + .map(str::parse) + .collect::>() + .ok()?; + if uids.len() != 4 || uids.iter().any(|uid| *uid != unsafe { libc::geteuid() }) { + return None; + } + let mut data = Vec::new(); + File::open(format!("/proc/{pid}/stat")) + .ok()? + .take(4097) + .read_to_end(&mut data) + .ok()?; + if data.len() > 4096 { + return None; + } + let text = std::str::from_utf8(&data).ok()?; + let prefix = text.find(' ')?; + if text[..prefix].parse::().ok()? != pid { + return None; + } + let end = text.rfind(')')?; + let fields: Vec<_> = text[end + 1..].split_whitespace().take(20).collect(); + if fields.len() != 20 { + return None; + } + Some((fields[1].parse().ok()?, (fields[19].parse().ok()?, 0))) + } + let mut filesystem = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::statfs(c"/proc".as_ptr(), filesystem.as_mut_ptr()) } != 0 { + return None; + } + if i128::from(unsafe { filesystem.assume_init() }.f_type) != i128::from(libc::PROC_SUPER_MAGIC) + { + return None; + } + let before = identity(pid)?; + let image = std::fs::read_link(format!("/proc/{pid}/exe")).ok()?; + if !image.is_absolute() { + return None; + } + // The kernel procfs executable link intentionally follows the executing + // image, unlike configured paths. Opening it pins that inode for the lease. + let file = File::open(format!("/proc/{pid}/exe")).ok()?; + if identity(pid)? != before { + return None; + } + Some(( + Snapshot { + pid, + parent: before.0, + started: before.1, + image, + }, + file, + )) +} + +#[cfg(not(any(target_os = "macos", target_os = "linux")))] +fn observe(_: i32) -> Option<(Snapshot, File)> { + None +} + +#[cfg(test)] +#[path = "../tests/unit/capture_usage_origin.rs"] +mod tests; diff --git a/src/capture_usage_profile.rs b/src/capture_usage_profile.rs new file mode 100644 index 0000000..37a44d2 --- /dev/null +++ b/src/capture_usage_profile.rs @@ -0,0 +1,911 @@ +//! Explicit local numeric opt-in configuration. Functional paths are private +//! device configuration, never usage evidence, SQLite policy, diagnostics or +//! outbox fields. This module does not read a transcript or grant hook authority. +#![cfg(unix)] +use crate::{ + adapter_files::{digest, hex, nonce, Dir}, + capture::Binding, + capture_runtime_pair::CaptureRuntimeIdentity, + cli::skill::SkillAgent, + error::AppError, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + ffi::CString, + fs::{self, File, Metadata}, + io::Read, + os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::{ffi::OsStrExt, fs::MetadataExt, process::CommandExt}, + }, + path::{Component, Path, PathBuf}, + process::{Command, Stdio}, +}; + +const MAX_PROFILE_BYTES: usize = 64 * 1024; +// Enable-only executable admission. The supported Claude native image is +//321,995,200bytes; stream a bounded image once, never hash it in a hook. +const MAX_IMAGE_BYTES: u64 = 512 * 1024 * 1024; +fn refused() -> AppError { + AppError::Config("Numeric profile qualification is unavailable; review the supported native version, managed installation and explicit profile approval. Metadata capture remains available.".into()) +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct DirectoryStamp { + device: u64, + inode: u64, + owner: u32, + mode: u32, + created_seconds: u64, + created_nanos: u32, +} +impl DirectoryStamp { + fn observe(path: &Path) -> Result { + let metadata = walk(path, true)?.metadata().map_err(|_| refused())?; + if !metadata.is_dir() || metadata.uid() != unsafe { libc::geteuid() } { + return Err(refused()); + } + // Ordinary child creation changes directory mtime/ctime. Birth time + // instead distinguishes a removed/recreated root even after inode reuse. + // Filesystems without this identity component stay unqualified. + let created = metadata + .created() + .map_err(|_| refused())? + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| refused())?; + Ok(Self { + device: metadata.dev(), + inode: metadata.ino(), + owner: metadata.uid(), + mode: metadata.mode(), + created_seconds: created.as_secs(), + created_nanos: created.subsec_nanos(), + }) + } + fn matches(&self, path: &Path) -> bool { + Self::observe(path).is_ok_and(|current| { + current.device == self.device + && current.inode == self.inode + && current.owner == self.owner + && current.mode == self.mode + && current.created_seconds == self.created_seconds + && current.created_nanos == self.created_nanos + }) + } +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct FileStamp { + device: u64, + inode: u64, + owner: u32, + mode: u32, + links: u64, + bytes: u64, + modified_seconds: i64, + modified_nanos: i64, + changed_seconds: i64, + changed_nanos: i64, +} +impl FileStamp { + fn from_metadata(metadata: &Metadata) -> Result { + let owner = metadata.uid(); + if !metadata.is_file() + || metadata.nlink() != 1 + || metadata.mode() & 0o022 != 0 + || (owner != 0 && owner != unsafe { libc::geteuid() }) + { + return Err(refused()); + } + Ok(Self { + device: metadata.dev(), + inode: metadata.ino(), + owner, + mode: metadata.mode(), + links: metadata.nlink(), + bytes: metadata.len(), + modified_seconds: metadata.mtime(), + modified_nanos: metadata.mtime_nsec(), + changed_seconds: metadata.ctime(), + changed_nanos: metadata.ctime_nsec(), + }) + } + fn observe(path: &Path) -> Result { + Self::from_metadata(&walk(path, false)?.metadata().map_err(|_| refused())?) + } + pub(crate) fn matches_metadata(&self, metadata: &Metadata) -> bool { + Self::from_metadata(metadata).is_ok_and(|current| { + current.device == self.device + && current.inode == self.inode + && current.owner == self.owner + && current.mode == self.mode + && current.links == self.links + && current.bytes == self.bytes + && current.modified_seconds == self.modified_seconds + && current.modified_nanos == self.modified_nanos + && current.changed_seconds == self.changed_seconds + && current.changed_nanos == self.changed_nanos + }) + } + fn matches(&self, path: &Path) -> bool { + walk(path, false) + .and_then(|file| file.metadata().map_err(|_| refused())) + .is_ok_and(|metadata| self.matches_metadata(&metadata)) + } +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct FilePin { + path: PathBuf, + stamp: Option, +} +impl FilePin { + fn observe(path: PathBuf, optional: bool) -> Result { + let missing = fs::symlink_metadata(&path) + .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound); + let stamp = if optional && missing { + None + } else { + Some(FileStamp::observe(&path)?) + }; + Ok(Self { path, stamp }) + } + fn matches(&self) -> bool { + match &self.stamp { + Some(stamp) => stamp.matches(&self.path), + None => fs::symlink_metadata(&self.path) + .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound), + } + } +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct ImagePin { + path: PathBuf, + stamp: FileStamp, + sha256: String, +} +impl ImagePin { + fn observe(path: &Path, native: bool) -> Result { + canonical(path)?; + let mut file = walk(path, false)?; + let stamp = FileStamp::from_metadata(&file.metadata().map_err(|_| refused())?)?; + if stamp.mode & 0o111 == 0 || stamp.bytes > MAX_IMAGE_BYTES { + return Err(refused()); + } + let mut hasher = Sha256::new(); + let mut block = [0u8; 64 * 1024]; + let mut prefix = Vec::with_capacity(4); + let mut total = 0u64; + loop { + let count = file.read(&mut block).map_err(|_| refused())?; + if count == 0 { + break; + } + total += count as u64; + if total > MAX_IMAGE_BYTES { + return Err(refused()); + } + if prefix.len() < 4 { + prefix.extend_from_slice(&block[..count.min(4 - prefix.len())]); + } + if native && prefix.len() == 4 && !native_image(&prefix) { + return Err(refused()); + } + hasher.update(&block[..count]); + } + if total != stamp.bytes || !stamp.matches_metadata(&file.metadata().map_err(|_| refused())?) + { + return Err(refused()); + } + if native && !native_image(&prefix) { + return Err(refused()); + } + Ok(Self { + path: path.to_owned(), + stamp, + sha256: hasher + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(), + }) + } + fn matches(&self) -> bool { + hex(&self.sha256, 64) && self.stamp.matches(&self.path) + } +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct ProfileRecord { + schema_version: u8, + profile_id: String, + source_namespace: String, + harness_version: String, + home: PathBuf, + home_stamp: DirectoryStamp, + profile_root: PathBuf, + profile_stamp: DirectoryStamp, + managed_root: PathBuf, + managed_stamp: DirectoryStamp, + generation_root: PathBuf, + generation_stamp: DirectoryStamp, + registration_digest: String, + runtime_core_sha256: String, + runtime_guard_sha256: String, + launcher: ImagePin, + native: ImagePin, + files: Vec, +} + +pub(crate) struct PreparedProfile { + id: String, + digest: String, + binding_id: String, + binding_version: i64, + namespace: String, + record: ProfileRecord, + record_path: PathBuf, + record_stamp: FileStamp, +} +impl PreparedProfile { + pub(crate) fn id(&self) -> &str { + &self.id + } + pub(crate) fn digest(&self) -> &str { + &self.digest + } + pub(crate) fn matches(&self, binding: &Binding, namespace: &str) -> bool { + self.binding_id == binding.id + && self.binding_version == binding.version + && self.namespace == namespace + && self.record_stamp.matches(&self.record_path) + && self.record.home_stamp.matches(&self.record.home) + && self.record.profile_stamp.matches(&self.record.profile_root) + && self.record.managed_stamp.matches(&self.record.managed_root) + && self + .record + .generation_stamp + .matches(&self.record.generation_root) + && self.record.launcher.matches() + && self.record.native.matches() + && self.record.files.iter().all(FilePin::matches) + } +} + +/// Loaded only after fresh transactional persisted consent. Holding this value +/// grants no source access by itself; the caller must also prove a live guarded +/// invocation and actual bounded native origin, then exact active session/path. +pub(crate) struct ProfileLease { + record: ProfileRecord, + record_path: PathBuf, + record_stamp: FileStamp, + _record_file: File, +} +impl ProfileLease { + pub(crate) fn load( + directory: &Path, + policy: &crate::capture_usage_consent::ConsentPolicy, + runtime: &CaptureRuntimeIdentity, + ) -> Result { + #[cfg(test)] + crate::capture_usage_test_io::observe(0); + if !policy.enabled || !hex(&policy.profile_id, 64) || !hex(&policy.profile_digest, 64) { + return Err("NUMERIC_CAPTURE_DISABLED"); + } + let path = directory + .join("profiles") + .join(format!("{}.json", policy.profile_id)); + let mut file = walk(&path, false).map_err(|_| "PROFILE_UNAVAILABLE")?; + let metadata = file.metadata().map_err(|_| "PROFILE_UNAVAILABLE")?; + if metadata.uid() != unsafe { libc::geteuid() } + || metadata.mode() & 0o777 != 0o600 + || metadata.len() > MAX_PROFILE_BYTES as u64 + { + return Err("PROFILE_UNAVAILABLE"); + } + let stamp = FileStamp::from_metadata(&metadata).map_err(|_| "PROFILE_UNAVAILABLE")?; + let mut bytes = Vec::new(); + file.by_ref() + .take((MAX_PROFILE_BYTES + 1) as u64) + .read_to_end(&mut bytes) + .map_err(|_| "PROFILE_UNAVAILABLE")?; + if bytes.len() > MAX_PROFILE_BYTES + || digest(&bytes) != policy.profile_digest + || !stamp.matches_metadata(&file.metadata().map_err(|_| "PROFILE_CHANGED")?) + { + return Err("PROFILE_CHANGED"); + } + let record: ProfileRecord = + serde_json::from_slice(&bytes).map_err(|_| "PROFILE_UNAVAILABLE")?; + let (host, source, version) = match policy.source_namespace.as_str() { + "claude-code" => (".claude", "projects", "2.1.319"), + "codex" => (".codex", "sessions", "0.167.0"), + _ => return Err("UNSUPPORTED_SOURCE"), + }; + if record.schema_version != 1 + || record.profile_id != policy.profile_id + || record.source_namespace != policy.source_namespace + || record.harness_version != version + || record.profile_root != record.home.join(host) + || record.managed_root != record.profile_root.join(source) + || record.files.len() > 70 + || !hex(&record.registration_digest, 64) + || !hex(&record.launcher.sha256, 64) + || !hex(&record.native.sha256, 64) + { + return Err("PROFILE_UNAVAILABLE"); + } + let parent = record.profile_root.join(".keito-capture-generations"); + if record.generation_root.parent() != Some(parent.as_path()) + || record + .generation_root + .file_name() + .and_then(|name| name.to_str()) + .is_none_or(|name| !hex(name, 64)) + { + return Err("REGISTRATION_CHANGED"); + } + let lease = Self { + record, + record_path: path, + record_stamp: stamp, + _record_file: file, + }; + lease.validate(runtime)?; + Ok(lease) + } + pub(crate) fn home(&self) -> &Path { + &self.record.home + } + pub(crate) fn version(&self) -> &str { + &self.record.harness_version + } + pub(crate) fn native(&self) -> (&Path, &FileStamp) { + (&self.record.native.path, &self.record.native.stamp) + } + pub(crate) fn validate(&self, runtime: &CaptureRuntimeIdentity) -> Result<(), &'static str> { + if self.record.runtime_core_sha256 != runtime.core_sha256 + || self.record.runtime_guard_sha256 != runtime.guard_sha256 + { + return Err("RUNTIME_CHANGED"); + } + if !self.record_stamp.matches(&self.record_path) + || !self.record_stamp.matches_metadata( + &self + ._record_file + .metadata() + .map_err(|_| "PROFILE_CHANGED")?, + ) + || !self.record.home_stamp.matches(&self.record.home) + || !self.record.profile_stamp.matches(&self.record.profile_root) + || !self.record.managed_stamp.matches(&self.record.managed_root) + { + return Err("PROFILE_CHANGED"); + } + if !self.record.launcher.matches() || !self.record.native.matches() { + return Err("HARNESS_CHANGED"); + } + if !self + .record + .generation_stamp + .matches(&self.record.generation_root) + || !self.record.files.iter().all(FilePin::matches) + { + return Err("REGISTRATION_CHANGED"); + } + Ok(()) + } +} + +pub(crate) fn open_image_metadata(path: &Path) -> Option { + let file = walk(path, false).ok()?; + if !file.metadata().ok()?.is_file() { + return None; + } + Some(file) +} +pub(crate) fn image_metadata(path: &Path) -> Option { + open_image_metadata(path)?.metadata().ok() +} + +fn canonical(path: &Path) -> Result<(), AppError> { + if !path.is_absolute() + || path == Path::new("/") + || path + .as_os_str() + .as_bytes() + .split(|c| *c == b'/') + .any(|c| c == b"." || c == b"..") + || path.canonicalize().map_err(|_| refused())? != path + { + return Err(refused()); + } + Ok(()) +} +fn walk(path: &Path, directory: bool) -> Result { + if !path.is_absolute() + || path + .as_os_str() + .as_bytes() + .split(|c| *c == b'/') + .any(|c| c == b"." || c == b"..") + { + return Err(refused()); + } + let root = CString::new("/").map_err(|_| refused())?; + let fd = unsafe { + libc::open( + root.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + let mut parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let parts: Vec<_> = path + .components() + .filter_map(|part| { + if let Component::Normal(value) = part { + Some(value) + } else { + None + } + }) + .collect(); + for (index, part) in parts.iter().enumerate() { + let name = CString::new(part.as_bytes()).map_err(|_| refused())?; + let flags = libc::O_RDONLY + | libc::O_CLOEXEC + | libc::O_NOFOLLOW + | libc::O_NONBLOCK + | if directory || index + 1 < parts.len() { + libc::O_DIRECTORY + } else { + 0 + }; + let fd = unsafe { libc::openat(parent.as_raw_fd(), name.as_ptr(), flags) }; + if fd < 0 { + return Err(refused()); + } + parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let metadata = File::from(parent.try_clone().map_err(|_| refused())?) + .metadata() + .map_err(|_| refused())?; + if metadata.uid() != 0 && metadata.uid() != unsafe { libc::geteuid() } { + return Err(refused()); + } + } + Ok(parent.into()) +} +fn native_image(bytes: &[u8]) -> bool { + #[cfg(target_os = "linux")] + { + bytes.starts_with(b"\x7fELF") + } + #[cfg(target_os = "macos")] + { + [ + b"\xcf\xfa\xed\xfe".as_slice(), + b"\xce\xfa\xed\xfe", + b"\xfe\xed\xfa\xcf", + b"\xfe\xed\xfa\xce", + b"\xca\xfe\xba\xbe", + b"\xca\xfe\xba\xbf", + ] + .iter() + .any(|magic| bytes.starts_with(magic)) + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + { + let _ = bytes; + false + } +} + +fn observed_version( + native: &ImagePin, + home: &Path, + expected: &str, + runner: &mut impl crate::process_ownership::probes::LeafRunner, +) -> Result<(), AppError> { + let file = walk(&native.path, false)?; + if !native + .stamp + .matches_metadata(&file.metadata().map_err(|_| refused())?) + { + return Err(refused()); + } + let fd = file.as_raw_fd(); + #[cfg(target_os = "linux")] + let mut command = Command::new(format!("/proc/self/fd/{fd}")); + #[cfg(not(target_os = "linux"))] + let mut command = Command::new(&native.path); + let name = CString::new(native.path.as_os_str().as_bytes()).map_err(|_| refused())?; + let device = native.stamp.device; + let inode = native.stamp.inode; + command + .env_clear() + .env("HOME", home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("PATH", "/usr/bin:/bin") + .arg("--version") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + #[cfg(target_os = "macos")] + command.env( + "__CF_USER_TEXT_ENCODING", + format!("0x{:X}:0:0", unsafe { libc::getuid() }), + ); + unsafe { + command.pre_exec(move || { + let mut metadata = std::mem::MaybeUninit::::uninit(); + if libc::lstat(name.as_ptr(), metadata.as_mut_ptr()) != 0 { + return Err(std::io::Error::last_os_error()); + } + let metadata = metadata.assume_init(); + if metadata.st_dev as u128 != u128::from(device) + || metadata.st_ino as u128 != u128::from(inode) + || metadata.st_mode & libc::S_IFMT != libc::S_IFREG + { + return Err(std::io::Error::from_raw_os_error(libc::ESTALE)); + } + if libc::fcntl(fd, libc::F_SETFD, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let result = runner + .output(command, 8192, 8192) + .map_err(crate::capture_command_owner::version_probe_error)?; + if !result.status.success() { + return Err(refused()); + } + let bytes = String::from_utf8(result.output.stdout).map_err(|_| refused())?; + if !bytes.split_whitespace().any(|part| part == expected) || !native.matches() { + return Err(refused()); + } + Ok(()) +} + +pub(crate) struct ProfileOptions<'a> { + pub directory: &'a Path, + pub binding: &'a Binding, + pub namespace: &'a str, + pub home: &'a Path, + pub launcher: &'a Path, + pub native: Option<&'a Path>, + pub runtime: &'a CaptureRuntimeIdentity, +} + +/// Explicit enable-only work: full managed-install inspection, one bounded +/// exact-native version probe and atomic private configuration publication. +/// This returns no transcript capability and cannot bypass normal hook consent. +pub(crate) fn approve(options: ProfileOptions<'_>) -> Result { + let mut owner = crate::capture_command_owner::CommandOwner::standalone()?; + let result = approve_with_runner(options, &mut owner); + owner.finish(result) +} +pub(crate) fn approve_with_runner( + options: ProfileOptions<'_>, + runner: &mut impl crate::process_ownership::probes::LeafRunner, +) -> Result { + let (agent, host, source, version) = match options.namespace { + "claude-code" => (SkillAgent::ClaudeCode, ".claude", "projects", "2.1.319"), + "codex" => (SkillAgent::Codex, ".codex", "sessions", "0.167.0"), + _ => return Err(refused()), + }; + canonical(options.home)?; + if !crate::skill_adapter::inspect(options.home, agent, Some(options.runtime))? { + return Err(refused()); + } + let home_stamp = DirectoryStamp::observe(options.home)?; + let host_dir = Dir::anchor(options.home)?.child(host, false)?; + let profile_stamp = DirectoryStamp::observe(&host_dir.path)?; + let receipt_path = options + .home + .join(host) + .join("skills/keito-time-track/capture-install.json"); + let receipt_stamp = FileStamp::observe(&receipt_path)?; + let mut receipt_bytes = Vec::new(); + walk(&receipt_path, false)? + .take(512 * 1024 + 1) + .read_to_end(&mut receipt_bytes) + .map_err(|_| refused())?; + if receipt_bytes.len() > 512 * 1024 { + return Err(refused()); + } + let receipt: serde_json::Value = + serde_json::from_slice(&receipt_bytes).map_err(|_| refused())?; + if receipt["harness_version"] != version { + return Err(refused()); + } + let generation = receipt["generation"] + .as_str() + .filter(|generation| hex(generation, 64)) + .ok_or_else(refused)?; + let generation_root = options + .home + .join(host) + .join(".keito-capture-generations") + .join(generation); + let generation_stamp = DirectoryStamp::observe(&generation_root)?; + let config_path = options.home.join(host).join(if agent == SkillAgent::Codex { + "hooks.json" + } else { + "settings.json" + }); + let config_stamp = FileStamp::observe(&config_path)?; + let mut config_bytes = Vec::new(); + walk(&config_path, false)? + .take(1024 * 1024 + 1) + .read_to_end(&mut config_bytes) + .map_err(|_| refused())?; + if config_bytes.len() > 1024 * 1024 { + return Err(refused()); + } + let config: serde_json::Value = serde_json::from_slice(&config_bytes).map_err(|_| refused())?; + let dispatch = generation_root.join("hooks/dispatch.sh"); + let dispatch = dispatch.to_str().ok_or_else(refused)?; + let mut entries = Vec::new(); + for event in [ + "SessionStart", + "UserPromptSubmit", + "Stop", + "SessionEnd", + if agent == SkillAgent::Codex { + "Interrupt" + } else { + "StopFailure" + }, + ] { + let groups = config["hooks"][event].as_array().ok_or_else(refused)?; + let owned: Vec<_> = groups + .iter() + .filter(|group| { + group["hooks"].as_array().is_some_and(|hooks| { + hooks.iter().any(|hook| { + hook["command"] + .as_str() + .and_then(crate::skill_adapter::registration_words) + .is_some_and(|words| words.iter().any(|word| word == dispatch)) + }) + }) + }) + .collect(); + if owned.len() != 1 { + return Err(refused()); + } + entries.push((event, owned[0])); + } + let registration_digest = digest(serde_json::to_vec(&entries).map_err(|_| refused())?); + // An executable option is not a transcript-read escape hatch. Reject both + // managed source trees before opening either executable candidate. + for executable in [options.launcher, options.native.unwrap_or(options.launcher)] { + if [ + options.home.join(".claude/projects"), + options.home.join(".codex/sessions"), + ] + .iter() + .any(|root| executable.starts_with(root)) + { + return Err(refused()); + } + } + let native_path = options.native.unwrap_or(options.launcher); + let native = ImagePin::observe(native_path, true)?; + let launcher = if native_path == options.launcher { + native.clone() + } else { + ImagePin::observe(options.launcher, false)? + }; + observed_version(&native, options.home, version, runner)?; + if !receipt_stamp.matches(&receipt_path) || !config_stamp.matches(&config_path) { + return Err(refused()); + } + let managed = host_dir.child(source, true)?; + let managed_stamp = DirectoryStamp::observe(&managed.path)?; + let mut files = vec![ + FilePin::observe(config_path.clone(), false)?, + FilePin::observe(receipt_path.clone(), false)?, + FilePin::observe(generation_root.join("capture-install.json"), false)?, + FilePin::observe(options.runtime.core_path.clone(), false)?, + FilePin::observe(options.runtime.guard_path.clone(), false)?, + ]; + if agent == SkillAgent::Codex { + files.push(FilePin::observe( + options.home.join(host).join("config.toml"), + true, + )?); + } + let payload = receipt["files"].as_object().ok_or_else(refused)?; + if payload.len() > 64 { + return Err(refused()); + } + for relative in payload.keys() { + let path = Path::new(relative); + if !path + .components() + .all(|part| matches!(part, Component::Normal(_))) + { + return Err(refused()); + } + files.push(FilePin::observe(generation_root.join(path), false)?); + } + if !crate::skill_adapter::inspect(options.home, agent, Some(options.runtime))? + || !receipt_stamp.matches(&receipt_path) + || !config_stamp.matches(&config_path) + || !files.iter().all(FilePin::matches) + { + return Err(refused()); + } + let id = nonce()?; + let record = ProfileRecord { + schema_version: 1, + profile_id: id.clone(), + source_namespace: options.namespace.into(), + harness_version: version.into(), + home: options.home.into(), + home_stamp, + profile_root: host_dir.path.clone(), + profile_stamp, + managed_root: managed.path.clone(), + managed_stamp, + generation_root, + generation_stamp, + registration_digest, + runtime_core_sha256: options.runtime.core_sha256.clone(), + runtime_guard_sha256: options.runtime.guard_sha256.clone(), + launcher, + native, + files, + }; + let bytes = serde_json::to_vec(&record).map_err(|_| refused())?; + if bytes.len() > MAX_PROFILE_BYTES { + return Err(refused()); + } + let profiles = Dir::anchor(options.directory)?.child("profiles", true)?; + if profiles.metadata()?.mode() & 0o777 != 0o700 { + return Err(refused()); + } + profiles.atomic( + &format!("{id}.json"), + &bytes, + 0o600, + Some(None), + "numeric-profile-published", + )?; + let record_path = profiles.path.join(format!("{id}.json")); + let record_stamp = FileStamp::observe(&record_path)?; + let prepared = PreparedProfile { + id, + digest: digest(bytes), + binding_id: options.binding.id.clone(), + binding_version: options.binding.version, + namespace: options.namespace.into(), + record, + record_path, + record_stamp, + }; + if !prepared.matches(options.binding, options.namespace) { + return Err(refused()); + } + Ok(prepared) +} + +#[cfg(all(test, any(target_os = "macos", target_os = "linux")))] +mod tests { + use super::*; + use std::{ + io::{self, Write}, + os::unix::fs::PermissionsExt, + }; + + #[test] + fn version_probe_enable_preserves_closed_owner_reason_without_execution() { + struct FailedProbe(&'static str); + impl crate::process_ownership::probes::LeafRunner for FailedProbe { + fn output( + &mut self, + command: Command, + stdout_cap: usize, + stderr_cap: usize, + ) -> io::Result { + assert_eq!( + command.get_args().collect::>(), + vec![std::ffi::OsStr::new("--version")] + ); + assert_eq!((stdout_cap, stderr_cap), (8192, 8192)); + Err(io::Error::other( + crate::process_ownership::protocol::ProtocolError(self.0), + )) + } + } + let temp = tempfile::tempdir().unwrap(); + let home = temp.path().canonicalize().unwrap(); + let path = home.join("inert-header-never-executed"); + #[cfg(target_os = "macos")] + fs::write(&path, b"\xcf\xfa\xed\xfe").unwrap(); + #[cfg(target_os = "linux")] + fs::write(&path, b"\x7fELF").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + let native = ImagePin::observe(&path, true).unwrap(); + for (fault, expected) in [ + ("SCOPE_OPERATION_DEADLINE", "deadline"), + ("SCOPE_ADMISSION", "admission_refused"), + ("SCOPE_CLOCK", "clock"), + ("SCOPE_PARENT_CANCELLED", "ownership"), + ("PRIVATE_UNRECOGNIZED_FAULT", "ownership"), + ] { + let error = + observed_version(&native, &home, "0.167.0", &mut FailedProbe(fault)).unwrap_err(); + let value: serde_json::Value = serde_json::from_str(&error.to_json()).unwrap(); + assert_eq!(value["code"], 8); + assert_eq!(value["details"]["kind"], "capture_version_probe"); + assert_eq!(value["details"]["reason"], expected); + assert!(!error.to_json().contains("PRIVATE_")); + assert!(!error.to_json().contains("auth login")); + } + } + + #[test] + fn enable_time_native_pin_accepts_the_target_claude_image_size_without_execution() { + // Target compatibility metadata is321,995,200bytes. This owned sparse + // header fixture tests only enable-time size/hash admission, never a + // real executable/version, process origin or source approval. + let temp = tempfile::tempdir().unwrap(); + let path = temp + .path() + .canonicalize() + .unwrap() + .join("owned-inert-large-native"); + let mut file = fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(&path) + .unwrap(); + #[cfg(target_os = "macos")] + file.write_all(b"\xcf\xfa\xed\xfe").unwrap(); + #[cfg(target_os = "linux")] + file.write_all(b"\x7fELF").unwrap(); + file.set_len(321_995_200).unwrap(); + drop(file); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + let pin = ImagePin::observe(&path, true); + assert!( + pin.is_ok(), + "enable-time image bound excludes the supported target's native binary size" + ); + assert_eq!(pin.unwrap().stamp.bytes, 321_995_200); + } + + #[test] + fn enable_time_image_limit_stays_bounded_and_rejects_oversize_metadata() { + assert_eq!(MAX_IMAGE_BYTES, 512 * 1024 * 1024); + let temp = tempfile::tempdir().unwrap(); + let path = temp + .path() + .canonicalize() + .unwrap() + .join("owned-inert-oversize"); + let file = fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(&path) + .unwrap(); + file.set_len(512 * 1024 * 1024 + 1).unwrap(); + drop(file); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + assert!(ImagePin::observe(&path, true).is_err()); + } +} diff --git a/src/capture_usage_test_io.rs b/src/capture_usage_test_io.rs new file mode 100644 index 0000000..8f55470 --- /dev/null +++ b/src/capture_usage_test_io.rs @@ -0,0 +1,56 @@ +//! Private denied/counting observers. Never compiled into an installed binary; +//! they cannot create a positive runtime, consent, profile or source capability. +use std::cell::RefCell; +thread_local! { static STATE: RefCell> = const { RefCell::new(None) }; } +pub(crate) struct Denied; +impl Denied { + pub(crate) fn arm() -> Self { + STATE.with(|state| { + assert!(state.borrow().is_none()); + *state.borrow_mut() = Some([0; 3]); + }); + Self + } + pub(crate) fn counts(&self) -> [usize; 3] { + STATE.with(|state| state.borrow().unwrap()) + } +} +impl Drop for Denied { + fn drop(&mut self) { + STATE.with(|state| *state.borrow_mut() = None); + } +} +pub(crate) fn observe(index: usize) { + STATE.with(|state| { + if let Some(counts) = state.borrow_mut().as_mut() { + counts[index] += 1; + panic!("denied numeric profile/origin/source operation reached"); + } + }); +} + +// A one-shot negative fault after the first SQLite queue/session writes. Only +// cfg(test) code can arm it; it never supplies a runtime/profile approval. +type WriteFault = Box; +thread_local! { static AFTER_WRITE: RefCell> = const {RefCell::new(None)}; } +pub(crate) struct AfterWrite; +impl AfterWrite { + pub(crate) fn arm(action: impl FnOnce(&rusqlite::Connection) + 'static) -> Self { + AFTER_WRITE.with(|slot| { + assert!(slot.borrow().is_none()); + *slot.borrow_mut() = Some(Box::new(action)); + }); + Self + } +} +impl Drop for AfterWrite { + fn drop(&mut self) { + AFTER_WRITE.with(|slot| *slot.borrow_mut() = None); + } +} +pub(crate) fn after_numeric_write(connection: &rusqlite::Connection) { + let action = AFTER_WRITE.with(|slot| slot.borrow_mut().take()); + if let Some(action) = action { + action(connection); + } +} diff --git a/src/cli/capture.rs b/src/cli/capture.rs new file mode 100644 index 0000000..b567460 --- /dev/null +++ b/src/cli/capture.rs @@ -0,0 +1,167 @@ +use clap::{Args, Subcommand, ValueEnum}; + +#[derive(Args)] +#[command(about = "Capture opted-in coding turns as private, pending-review evidence")] +pub struct CaptureCommand { + #[command(subcommand)] + pub command: CaptureSubcommand, +} + +#[derive(Subcommand)] +pub enum CaptureSubcommand { + /// Validate and explicitly approve this repository's mapping on this device + Setup { + #[arg(long, value_enum, required = true)] + agent: Vec, + #[arg(long)] + project: String, + #[arg(long)] + task: String, + /// Client identifier for an explicitly requested repository hint + #[arg(long, required_if_eq("write_hint", "true"))] + client: Option, + /// Transactionally publish this mapping hint alongside device approval + #[arg(long, requires = "client")] + write_hint: bool, + /// Confirm the displayed metadata-only mapping policy; never bill automatically + #[arg(long, required = true)] + confirm: bool, + /// Install/update this repository's macOS launchd worker (device-only paths) + #[arg(long)] + install_worker: bool, + }, + /// Inspect local consent, queue and delivery state (no network) + Status, + /// Inspect or manage separate numeric-usage consent for this repository + Usage { + #[command(subcommand)] + command: CaptureUsageSubcommand, + }, + /// Reconcile unfinished intervals after a storage-refused boundary, without inventing time + Recover { + /// Acknowledge that refused boundaries cannot be reconstructed + #[arg(long, required = true)] + confirm: bool, + }, + /// Inspect minimized evidence for an exact original harness session identifier + Preview { + #[arg(long)] + session: String, + }, + /// Deliver frozen queued revisions; never fall back to ordinary time writes + Sync, + /// Run a bounded supervised foreground sync loop until interrupted + Worker { + #[arg(long, default_value_t = 5, value_parser = clap::value_parser!(u64).range(1..=60))] + interval_seconds: u64, + /// Refuse supervised execution after an unapproved runtime replacement + #[arg(long)] + expected_runtime_hash: Option, + }, + /// Inspect the current repository's macOS worker service without network writes + WorkerStatus { + /// Discover integration-owned workers, including stale or removed repositories + #[arg(long)] + all: bool, + }, + /// Stop/remove only this repository's integration-owned launchd service + WorkerUninstall { + #[arg( + long, + required_unless_present = "worker_id", + conflicts_with = "worker_id" + )] + repo: bool, + /// Opaque worker ID from worker-status --all; works after repository removal + #[arg(long, required_unless_present = "repo")] + worker_id: Option, + }, + /// Exclude paused intervals and hold this repository's queued deliveries + Pause { + #[arg(long, required = true)] + repo: bool, + }, + /// Resume this repository after rechecking its approved binding + Resume { + #[arg(long, required = true)] + repo: bool, + }, + /// Revoke this repository's consent and hold its unsent evidence + Disable { + #[arg(long, required = true)] + repo: bool, + }, + /// Disable collection and uploads for every approved repository on this device + DisableAll, + /// Persist an allowlisted lifecycle signal from bounded JSON on stdin; no network + Hook { + #[arg(long, value_enum)] + agent: CaptureAgent, + #[arg(long, value_enum)] + event: CaptureEvent, + #[arg(long)] + harness_version: String, + }, +} + +#[derive(Subcommand)] +pub enum CaptureUsageSubcommand { + /// Explicitly approve bounded local numeric reading for this binding/namespace + #[command( + long_about = "Approve numeric capture separately from metadata-only timing. Only the exact active native session file under this approved HOME's managed .claude/projects or .codex/sessions layout may be read by a qualified guarded hook. Prompts, code, tool arguments and source paths are not retained as usage evidence. Observations remain partial, provider expenditure remains unknown, and charging still requires review. The next qualified Prompt must establish a historical identity exclusion baseline." + )] + Enable { + #[arg(long, required = true)] + repo: bool, + #[arg(long, value_enum)] + agent: CaptureAgent, + /// Canonical owned HOME containing the managed harness registration + #[arg(long)] + profile_home: std::path::PathBuf, + /// Canonical approved launcher; a wrapper also requires --native-executable + #[arg(long)] + harness_executable: std::path::PathBuf, + /// Exact native image whose bounded --version result is approved + #[arg(long)] + native_executable: Option, + /// Confirm bounded active-file reading and minimized numeric retention + #[arg(long, required = true)] + confirm: bool, + }, + /// Withdraw only this namespace's numeric consent; timing consent is separate + Disable { + #[arg(long, required = true)] + repo: bool, + #[arg(long, value_enum)] + agent: CaptureAgent, + }, + /// Inspect numeric consent without reading harness profiles or session files + Status { + #[arg(long, required = true)] + repo: bool, + #[arg(long, value_enum)] + agent: CaptureAgent, + }, +} + +#[derive(Clone, Copy, Debug, ValueEnum, PartialEq, Eq)] +pub enum CaptureAgent { + ClaudeCode, + Codex, +} +impl CaptureAgent { + pub fn namespace(self) -> &'static str { + match self { + Self::ClaudeCode => "claude-code", + Self::Codex => "codex", + } + } +} +#[derive(Clone, Copy, Debug, ValueEnum, PartialEq, Eq)] +pub enum CaptureEvent { + SessionStart, + Prompt, + Stop, + Interrupt, + SessionEnd, +} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index b6e8f64..eb3d3a0 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1,4 +1,5 @@ pub mod auth; +pub mod capture; pub mod clients; pub mod projects; pub mod skill; @@ -97,6 +98,8 @@ this value in Keito under Settings > API & Developers > Company ID." #[derive(Subcommand)] #[allow(clippy::large_enum_variant)] pub enum Command { + /// Capture opted-in coding activity for review before charging + Capture(capture::CaptureCommand), /// Manage authentication (login, logout, status, whoami) Auth(auth::AuthCommand), /// Browse clients diff --git a/src/cli/skill.rs b/src/cli/skill.rs index c29cb5b..b74f00c 100644 --- a/src/cli/skill.rs +++ b/src/cli/skill.rs @@ -7,7 +7,7 @@ uses the CLI for authentication and API writes, then installs Claude Code / Codex lifecycle hooks so local coding sessions can be logged automatically. EXAMPLES: - keito skill install + keito skill install --agent claude-code --agent codex keito skill install --agent codex keito skill team-init optional keito skill status --json @@ -21,10 +21,11 @@ pub struct SkillCommand { pub enum SkillSubcommand { /// Install the Keito Skill and configure supported agent hooks #[command(long_about = "\ -Install the Keito Skill with the pinned open skills installer package, then run -the installed hook installer for each selected agent. +Install the bundled Keito Skill and selected lifecycle hooks with the native Rust +installer and verified official CLI/guard release pair. External --source values +use the pinned open skills installer to fetch the payload before native registration. -By default this configures both Codex and Claude Code. The skill still needs +Choose explicit --agent targets in scripts, or select targets interactively. The skill still needs per-repository setup after installation: cd into a client repo and run /track-time-keito to select its Keito client, project, and task.")] Install { @@ -36,16 +37,33 @@ per-repository setup after installation: cd into a client repo and run #[arg(long, value_enum)] agent: Vec, - /// Skip the skills installer and only run hook installers if present + /// Reuse an existing skill payload for native hook installation #[arg(long)] skip_skills_add: bool, + + /// Confirm migration of integration-owned legacy plugin/direct hooks + #[arg(long)] + confirm_migration: bool, + }, + + /// Remove only selected integration-owned adapters, preserving unrelated configuration + Uninstall { + #[arg(long, value_enum, required = true)] + agent: Vec, }, + /// Verify the release-bound native runtime pair without changing local state + Runtime, + /// Show install/auth/hook status for the Keito Skill Status, /// Run readiness checks and print next actions - Doctor, + Doctor { + /// Verify live authentication without submitting capture evidence + #[arg(long)] + live: bool, + }, /// Add repo-level Keito tracking guidance for agent teammates #[command(long_about = "\ diff --git a/src/commands/auth.rs b/src/commands/auth.rs index 639e671..4ad8281 100644 --- a/src/commands/auth.rs +++ b/src/commands/auth.rs @@ -91,8 +91,8 @@ async fn maybe_offer_skill_install(global: &GlobalFlags, mode: OutputMode) -> Re } let install = Confirm::new() - .with_prompt("Install the Keito agent skill for Claude Code / Codex?") - .default(true) + .with_prompt("Choose and install coding-agent adapters now?") + .default(false) .interact() .map_err(|e| AppError::Config(format!("Input error: {e}")))?; diff --git a/src/commands/capture.rs b/src/commands/capture.rs new file mode 100644 index 0000000..9245051 --- /dev/null +++ b/src/commands/capture.rs @@ -0,0 +1,1018 @@ +use crate::api::client::KeitorClient; +use crate::capture::{self, Binding, Clock, Repository, Store, MAX_EVENT_BYTES}; +use crate::cli::capture::{CaptureCommand, CaptureSubcommand, CaptureUsageSubcommand}; +use crate::cli::GlobalFlags; +use crate::config::{AppConfig, ResolvedAuth}; +use crate::error::AppError; +use crate::output::OutputMode; +use serde_json::{json, Value}; +#[cfg(not(unix))] +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +fn directory() -> Result { + crate::capture_invocations::directory() +} +fn current_repo() -> Result { + let cwd = std::env::current_dir() + .map_err(|_| AppError::Config("Cannot identify working directory".into()))?; + Repository::resolve(&cwd) +} +#[cfg(unix)] +fn current_repo_scoped( + scope: &mut Option<&mut crate::process_ownership::scope::Scope>, +) -> Result { + match scope.as_deref_mut() { + Some(scope) => { + let mut owner = crate::capture_command_owner::CommandOwner::with_scope(scope)?; + let cwd = std::env::current_dir() + .map_err(|_| AppError::Config("Cannot identify working directory".into()))?; + Repository::resolve_with(&cwd, &mut owner) + } + None => current_repo(), + } +} +fn print(value: Value, quiet: bool) -> Result<(), AppError> { + if !quiet { + println!( + "{}", + serde_json::to_string_pretty(&value) + .map_err(|_| AppError::Config("Cannot render capture state".into()))? + ); + } + Ok(()) +} + +struct SetupOptions { + agent: Vec, + project: String, + task: String, + selected_client: Option, + write_hint: bool, + confirm: bool, + install_worker: bool, +} +async fn setup( + options: SetupOptions, + global: &GlobalFlags, + mapping: &mut Option, +) -> Result<(), AppError> { + let SetupOptions { + agent, + project, + task, + selected_client, + write_hint, + confirm, + install_worker, + } = options; + if !confirm { + return Err(AppError::InvalidInput( + "Explicit --confirm is required for metadata-only capture consent".into(), + )); + } + capture::identifier(&project)?; + capture::identifier(&task)?; + let auth = ResolvedAuth::resolve(global).map_err(sanitize_error)?; + let config = AppConfig::load().map_err(sanitize_error)?; + let client = KeitorClient::new(&auth, &config.api_base_url())?; + let me = client.get_me().await.map_err(sanitize_error)?; + if me.is_personal_read_only_sync() { + return Err(AppError::Auth( + "Capture requires a full-access credential".into(), + )); + } + capture::identifier(&me.id)?; + let projects = client.list_projects().await.map_err(sanitize_error)?; + if !projects.iter().any(|p| { + p.id == project + && p.is_active + && selected_client + .as_ref() + .is_none_or(|id| p.client.as_ref().is_some_and(|c| &c.id == id)) + }) { + return Err(AppError::NotFound( + "Project unavailable; choose an active accessible project".into(), + )); + } + let tasks = client + .list_tasks_for_project(Some(&project)) + .await + .map_err(sanitize_error)?; + if !tasks.iter().any(|t| t.id == task && t.is_active) { + return Err(AppError::NotFound( + "Task unavailable on the selected project".into(), + )); + } + *mapping = if write_hint { + let root = crate::commands::skill::git_repo_root()? + .canonicalize() + .map_err(|_| AppError::Config("Cannot identify canonical Git root".into()))?; + Some(crate::capture_mapping::MappingPublication::begin( + &root, + &crate::capture_mapping::MappingIds { + workspace: &auth.workspace_id, + client: selected_client.as_deref().ok_or_else(|| { + AppError::InvalidInput("Explicit client is required for --write-hint".into()) + })?, + project: &project, + task: &task, + }, + )?) + } else { + None + }; + tokio::task::yield_now().await; + let repo = current_repo()?; + if repo.disabled { + return Err(AppError::Config( + "Repository hint disables capture; enable it before approving".into(), + )); + } + let mut store = Store::open(&directory()?)?; + if install_worker && config.api_key.as_deref().is_none_or(str::is_empty) { + return Err(AppError::Config("The supervised worker requires credentials saved by keito auth login; environment-only credentials are never copied to service settings".into())); + } + let approved = store.approve(Binding { + repository_key: repo.key, + remote_hash: repo.remote_hash, + hint_hash: repo.hint_hash, + id: String::new(), + version: 0, + workspace_id: auth.workspace_id, + owner_id: me.id, + origin_hash: capture::hash(config.api_base_url().trim_end_matches('/')), + project_id: project, + task_id: task, + agents: agent + .into_iter() + .map(|a| a.namespace().to_owned()) + .collect(), + paused: false, + revoked: false, + })?; + let worker = if install_worker { + Some(install_worker_service( + &approved, + &origin_for_worker(&config), + &directory()?, + )?) + } else { + None + }; + tokio::task::yield_now().await; + if let Some(mapping) = mapping.as_mut() { + mapping.commit()?; + } + print( + json!({"status":"approved","worker":worker,"policy":"METADATA_ONLY_OBSERVED_TURNS_V1","binding":approved, + "notice":"Only minimized timing metadata leaves this device. Captures require review before charging. Start capture worker for automatic delivery.","usage":"UNAVAILABLE"}), + global.quiet, + ) +} + +async fn setup_cancelled() { + #[cfg(unix)] + { + if let Ok(mut termination) = + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + { + tokio::select! { _ = termination.recv() => {}, _ = tokio::signal::ctrl_c() => {} } + return; + } + } + let _ = tokio::signal::ctrl_c().await; +} + +pub async fn run( + cmd: CaptureCommand, + global: &GlobalFlags, + _mode: OutputMode, +) -> Result<(), AppError> { + #[cfg(unix)] + { + run_inner(cmd, global, _mode, None).await + } + #[cfg(not(unix))] + { + run_inner(cmd, global, _mode).await + } +} +#[cfg(unix)] +pub async fn run_with_scope( + cmd: CaptureCommand, + global: &GlobalFlags, + mode: OutputMode, + scope: Option<&mut crate::process_ownership::scope::Scope>, +) -> Result<(), AppError> { + run_inner(cmd, global, mode, scope).await +} +async fn run_inner( + cmd: CaptureCommand, + global: &GlobalFlags, + _mode: OutputMode, + #[cfg(unix)] mut entry_scope: Option<&mut crate::process_ownership::scope::Scope>, +) -> Result<(), AppError> { + if cfg!(not(unix)) { + return Err(AppError::Config( + "Automatic capture is unsupported on this platform; manual time commands remain available".into(), + )); + } + match cmd.command { + CaptureSubcommand::Usage { command } => match command { + CaptureUsageSubcommand::Status { agent, .. } => { + #[cfg(unix)] + let repository = current_repo_scoped(&mut entry_scope)?; + #[cfg(not(unix))] + let repository = current_repo()?; + let mut store = Store::open(&directory()?)?; + store.observe_repository(&repository)?; + print( + store.numeric_status(&repository, agent.namespace())?, + global.quiet, + ) + } + CaptureUsageSubcommand::Disable { agent, .. } => { + #[cfg(unix)] + let repository = current_repo_scoped(&mut entry_scope)?; + #[cfg(not(unix))] + let repository = current_repo()?; + let mut store = Store::open(&directory()?)?; + print( + store.disable_numeric(&repository, agent.namespace())?, + global.quiet, + ) + } + CaptureUsageSubcommand::Enable { + agent, + profile_home, + harness_executable, + native_executable, + .. + } => { + #[cfg(unix)] + { + let runtime = crate::capture_runtime_pair::current()?; + let repository = current_repo_scoped(&mut entry_scope)?; + let capture_directory = directory()?; + let mut store = Store::open(&capture_directory)?; + let binding = store.numeric_binding(&repository, agent.namespace())?; + let options = crate::capture_usage_profile::ProfileOptions { + directory: &capture_directory, + binding: &binding, + namespace: agent.namespace(), + home: &profile_home, + launcher: &harness_executable, + native: native_executable.as_deref(), + runtime: &runtime, + }; + let prepared = if let Some(scope) = entry_scope.as_deref_mut() { + let mut owner = + crate::capture_command_owner::CommandOwner::with_scope(scope)?; + crate::capture_usage_profile::approve_with_runner(options, &mut owner)? + } else { + crate::capture_usage_profile::approve(options)? + }; + print( + store.enable_numeric(&repository, agent.namespace(), &prepared)?, + global.quiet, + ) + } + #[cfg(not(unix))] + { + let _ = (agent, profile_home, harness_executable, native_executable); + Err(AppError::Config("Automatic capture is unsupported on this platform; manual time commands remain available".into())) + } + } + }, + CaptureSubcommand::Hook { + agent, + event, + harness_version, + } => { + #[cfg(all(unix, feature = "capture-profile"))] + crate::capture_profile::begin(match event { + crate::cli::capture::CaptureEvent::Prompt => 1, + crate::cli::capture::CaptureEvent::Stop => 2, + crate::cli::capture::CaptureEvent::SessionStart => 3, + crate::cli::capture::CaptureEvent::Interrupt => 4, + crate::cli::capture::CaptureEvent::SessionEnd => 5, + }); + // A malformed/unknown hook must never block coding or echo raw input. + let mut boundary_id = None; + let invocation_nonce = std::env::var("KEITO_CAPTURE_INVOCATION_NONCE").ok(); + #[cfg(unix)] + let hook_runtime = invocation_nonce + .as_ref() + .map(|_| { + crate::capture_profile_measure!( + Pair, + crate::capture_runtime_pair::HookRuntime::current( + &std::env::var("KEITO_CAPTURE_CORE_SHA256").unwrap_or_default(), + ) + ) + }) + .transpose()?; + #[cfg(unix)] + let mut command_owner = match (hook_runtime.as_ref(), entry_scope) { + (Some(runtime), Some(scope)) => Some( + crate::capture_command_owner::CommandOwner::for_hook(runtime, scope)?, + ), + _ => None, + }; + let ack_fd = std::env::var("KEITO_CAPTURE_ACK_FD") + .ok() + .and_then(|fd| fd.parse::().ok()) + .filter(|fd| *fd == 3 && crate::capture_invocations::protect_ack(*fd).is_ok()); + let mut accepted_store = None; + #[cfg(feature = "dev-tools")] + let mut failure_phase = capture::HookFailurePhase::Input; + let result = (|| { + #[cfg(unix)] + let owner = command_owner.as_mut().ok_or_else(|| { + AppError::Config( + "Capture hook requires a verified guarded command owner".into(), + ) + })?; + #[cfg(unix)] + let bytes = owner.read_event(MAX_EVENT_BYTES)?; + #[cfg(not(unix))] + let bytes = { + let mut bytes = Vec::new(); + std::io::stdin() + .take((MAX_EVENT_BYTES + 1) as u64) + .read_to_end(&mut bytes) + .map_err(|_| AppError::InvalidInput("Cannot read capture event".into()))?; + if bytes.len() > MAX_EVENT_BYTES { + return Err(AppError::InvalidInput( + "Capture input limit exceeded".into(), + )); + } + bytes + }; + #[cfg(feature = "dev-tools")] + { + failure_phase = capture::HookFailurePhase::Parse; + } + let value: Value = serde_json::from_slice(&bytes) + .map_err(|_| AppError::InvalidInput("Malformed capture event".into()))?; + let source_id = value + .get("session_id") + .and_then(Value::as_str) + .ok_or_else(|| AppError::InvalidInput("Missing session identity".into()))?; + capture::identifier(source_id)?; + let turn_id = value + .get(if agent.namespace() == "claude-code" { + "prompt_id" + } else { + "turn_id" + }) + .and_then(Value::as_str); + if let Some(turn) = turn_id { + capture::identifier(turn)?; + } + boundary_id = Some(capture::hash(format!( + "{}\0{}\0{}\0{:?}", + agent.namespace(), + source_id, + turn_id.unwrap_or("no-turn"), + event + ))); + let cwd = value + .get("cwd") + .and_then(Value::as_str) + .ok_or_else(|| AppError::InvalidInput("Missing repository identity".into()))?; + #[cfg(feature = "dev-tools")] + { + failure_phase = capture::HookFailurePhase::Repository; + } + #[cfg(unix)] + let repo = crate::capture_profile_measure!( + Repository, + Repository::resolve_with(Path::new(cwd), owner) + )?; + #[cfg(not(unix))] + let repo = Repository::resolve(Path::new(cwd))?; + #[cfg(feature = "dev-tools")] + { + failure_phase = capture::HookFailurePhase::Store; + } + let mut store = + crate::capture_profile_measure!(StoreOpen, Store::open(&directory()?))?; + #[cfg(feature = "dev-tools")] + { + failure_phase = capture::HookFailurePhase::Permit; + } + if let Some(nonce) = &invocation_nonce { + store.hook_invocation(nonce)?; + } + #[cfg(feature = "dev-tools")] + { + failure_phase = capture::HookFailurePhase::Clock; + } + #[cfg(unix)] + let clock = crate::capture_profile_measure!(Clock, Clock::now_with(owner))?; + #[cfg(not(unix))] + let clock = Clock::now()?; + let signal = capture::Signal { + source: agent.namespace(), + resumed: event == crate::cli::capture::CaptureEvent::SessionStart + && value.get("source").and_then(Value::as_str) == Some("resume"), + source_id, + turn_id, + version: &harness_version, + event, + clock: &clock, + }; + #[cfg(feature = "dev-tools")] + { + failure_phase = capture::HookFailurePhase::Event; + } + #[cfg(unix)] + crate::capture_profile_measure!( + EventTransaction, + store.event_hook( + &repo, + signal, + value + .get("transcript_path") + .and_then(Value::as_str) + .map(Path::new), + hook_runtime.as_ref(), + ) + )?; + #[cfg(not(unix))] + store.event(&repo, signal)?; + accepted_store = Some(store); + Ok(()) + })(); + #[cfg(all(unix, feature = "capture-profile"))] + let profile_event_accepted = result.is_ok(); + let mut ack_store = None; + if let Err(error) = result { + let reason = match error { + AppError::Config(ref message) if message.contains("queue limit") => { + "QUEUE_LIMIT_REACHED" + } + AppError::Config(_) => "STORAGE_UNAVAILABLE", + _ => "BOUNDARY_REFUSED", + }; + let failure_identity = boundary_id + .clone() + .unwrap_or_else(|| capture::hash("UNIDENTIFIED_REFUSED_BOUNDARY")); + let saved = directory().ok().is_some_and(|directory| { + #[cfg(feature = "dev-tools")] + { + let probe = capture::HookFailureProbe { + phase: failure_phase, + owner_fault: None, + setup: None, + }; + #[cfg(unix)] + let probe = command_owner + .as_ref() + .map_or(probe, |owner| owner.failure_probe(failure_phase)); + capture::record_failure_probed(&directory, &failure_identity, reason, probe) + .is_ok() + } + #[cfg(not(feature = "dev-tools"))] + capture::record_failure(&directory, &failure_identity, reason).is_ok() + }); + if saved && boundary_id.is_some() { + if let (Some(nonce), Some(_)) = (&invocation_nonce, ack_fd) { + if let Ok(mut store) = directory().and_then(|d| Store::open(&d)) { + if store.hook_invocation(nonce).is_ok() { + ack_store = Some(store); + } + } + } + } + eprintln!( + "Keito capture refused this boundary; no time was invented. {}", + if saved { + "A minimized failure marker was saved; inspect capture status and use capture recover --confirm." + } else { + "The boundary could not be saved; inspect local storage and capture status before resuming." + } + ); + } else { + ack_store = accepted_store; + } + // Preserve the original business/durability predicate above, but + // never acknowledge it until the actual command owner has finished. + #[cfg(unix)] + let resources_clean = crate::capture_profile_measure!( + OwnerFinish, + command_owner + .as_mut() + .is_some_and(|owner| owner.finish_clean()) + ); + #[cfg(not(unix))] + let resources_clean = false; + if resources_clean { + if let (Some(store), Some(fd)) = (ack_store, ack_fd) { + if crate::capture_profile_measure!( + Ack, + store.acknowledge_hook(fd), + profile_event_accepted + ) + .is_err() + { + #[cfg(unix)] + if let Some(owner) = command_owner.as_mut() { + owner.fail_ack(); + } + } + } + } + Ok(()) + } + CaptureSubcommand::Setup { + agent, + project, + task, + client: selected_client, + write_hint, + confirm, + install_worker, + } => { + let mut mapping: Option = None; + let result = tokio::select! { + biased; + _ = setup_cancelled() => Err(AppError::Config("Capture setup interrupted; inspect local approval before retrying".into())), + result = setup(SetupOptions {agent, project, task, selected_client, write_hint, confirm, install_worker}, global, &mut mapping) => result, + }; + if result.is_err() { + if let Some(mapping) = mapping.as_mut() { + mapping.rollback()?; + } + } + result + } + CaptureSubcommand::Status => { + let mut store = Store::open(&directory()?)?; + #[cfg(unix)] + let repository = current_repo_scoped(&mut entry_scope); + #[cfg(not(unix))] + let repository = current_repo(); + if let Ok(repository) = &repository { + store.observe_repository(repository)?; + } + let mut value = serde_json::to_value(store.status()?) + .map_err(|_| AppError::Config("Cannot render capture status".into()))?; + value["current_repository"] = match repository { + Ok(repo) => match store.binding(&repo.key)? { + Some(b) => { + json!({"approved":!b.revoked,"paused":b.paused,"mapping_current":repo.matches_binding(&b),"binding_id":b.id}) + } + None => json!({"approved":false,"reason":"LOCAL_APPROVAL_REQUIRED"}), + }, + Err(_) => json!({"approved":false,"reason":"REPOSITORY_UNAVAILABLE"}), + }; + print(value, global.quiet) + } + CaptureSubcommand::Recover { confirm } => { + if !confirm { + return Err(AppError::InvalidInput( + "Explicit confirmation is required before acknowledging refused boundaries" + .into(), + )); + } + let mut store = Store::open(&directory()?)?; + store.recover(&Clock::now()?)?; + print( + json!({"status":"recovered","notice":"Unfinished intervals were marked incomplete. Potentially affected frozen complete revisions remain held for review; recovery does not release uncertain evidence."}), + global.quiet, + ) + } + CaptureSubcommand::Preview { session } => { + let store = Store::open(&directory()?)?; + print(json!({"sessions":store.preview(&session)?}), global.quiet) + } + CaptureSubcommand::Sync => { + let result = sync(global).await?; + print(result, global.quiet) + } + CaptureSubcommand::Worker { + interval_seconds, + expected_runtime_hash, + } => { + // Foreground supervisor: launchd/systemd/the operator owns lifetime. A + // detached hook child is never the sole delivery/durability mechanism. + loop { + if let Some(expected) = &expected_runtime_hash { + verify_runtime_hash(expected)?; + } + let _ = sync(global).await; + tokio::select! { _ = tokio::signal::ctrl_c() => break, _ = tokio::time::sleep(Duration::from_secs(interval_seconds)) => {} } + } + Ok(()) + } + CaptureSubcommand::WorkerStatus { all } => { + if all { + let value = match crate::capture_supervisor::Supervisor::system() { + Ok(supervisor) => json!({"workers":supervisor.list()?}), + Err(_) => json!({"supported":false,"workers":[]}), + }; + return print(value, global.quiet); + } + let value = match ( + current_repo(), + crate::capture_supervisor::Supervisor::system(), + ) { + (Ok(repo), Ok(supervisor)) => { + let executable = std::env::current_exe() + .map_err(|_| AppError::Config("Cannot identify worker runtime".into()))?; + let cwd = std::env::current_dir().map_err(|_| { + AppError::Config("Cannot identify worker repository".into()) + })?; + let mut store = Store::open(&directory()?)?; + store.observe_repository(&repo)?; + let binding = store.binding(&repo.key)?; + let config = AppConfig::load().map_err(sanitize_error)?; + let origin = config.api_base_url(); + let capture_home = directory()?; + let expected = + binding + .as_ref() + .map(|binding| crate::capture_supervisor::WorkerConfig { + repository_key: &repo.key, + repository_root: &cwd, + executable: &executable, + capture_home: &capture_home, + workspace_id: &binding.workspace_id, + api_origin: &origin, + }); + serde_json::to_value(supervisor.status(&repo.key, expected.as_ref())?) + .map_err(|_| AppError::Config("Cannot inspect worker service".into()))? + } + _ => { + json!({"supported":cfg!(target_os="macos"),"installed":false,"running":false,"stale":false}) + } + }; + print(value, global.quiet) + } + CaptureSubcommand::WorkerUninstall { worker_id, .. } => { + let key = if let Some(id) = worker_id { + if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(AppError::InvalidInput("Invalid worker identity".into())); + } + id + } else { + current_repo()?.key + }; + let supervisor = crate::capture_supervisor::Supervisor::system()?; + print( + serde_json::to_value(supervisor.uninstall(&key)?) + .map_err(|_| AppError::Config("Cannot inspect worker service".into()))?, + global.quiet, + ) + } + CaptureSubcommand::Pause { .. } + | CaptureSubcommand::Resume { .. } + | CaptureSubcommand::Disable { .. } => { + let action = match cmd.command { + CaptureSubcommand::Pause { .. } => "pause", + CaptureSubcommand::Resume { .. } => "resume", + _ => "disable", + }; + #[cfg(unix)] + let repo = current_repo_scoped(&mut entry_scope)?; + #[cfg(not(unix))] + let repo = current_repo()?; + #[cfg(unix)] + let clock = match entry_scope { + Some(scope) => { + let mut owner = crate::capture_command_owner::CommandOwner::with_scope(scope)?; + Clock::now_with(&mut owner)? + } + None => Clock::now()?, + }; + #[cfg(not(unix))] + let clock = Clock::now()?; + let mut store = Store::open(&directory()?)?; + store.control(&repo, action, &clock)?; + print( + json!({"status":action,"binding":store.binding(&repo.key)?}), + global.quiet, + ) + } + CaptureSubcommand::DisableAll => { + let mut store = Store::open(&directory()?)?; + store.disable_all()?; + print( + json!({"status":"disabled_all","notice":"Unsent evidence retained; no further uploads are authorized"}), + global.quiet, + ) + } + } +} + +async fn sync(global: &GlobalFlags) -> Result { + let mut store = Store::open(&directory()?)?; + store.maintain(UtcClock::seconds())?; + let repo = current_repo()?; + store.observe_repository(&repo)?; + let Some(binding) = store.binding(&repo.key)? else { + return Ok(json!({"accepted":0,"held":0,"reason":"LOCAL_APPROVAL_REQUIRED"})); + }; + if !repo.matches_binding(&binding) || binding.paused || binding.revoked { + return Ok(json!({"accepted":0,"held":1,"reason":"BINDING_REAPPROVAL_REQUIRED"})); + } + if !store.has_ready(&binding, UtcClock::seconds())? { + return Ok(json!({"accepted":0,"held":0,"pending":store.status()?.pending})); + } + let auth = ResolvedAuth::resolve(global).map_err(sanitize_error)?; + let config = AppConfig::load().map_err(sanitize_error)?; + let origin = config.api_base_url(); + if binding.workspace_id != auth.workspace_id + || binding.origin_hash != capture::hash(origin.trim_end_matches('/')) + { + return Ok(json!({"accepted":0,"held":1,"reason":"BINDING_REAPPROVAL_REQUIRED"})); + } + let client = KeitorClient::new(&auth, &origin)?; + let me = client.get_me().await.map_err(sanitize_error)?; + if binding.owner_id != me.id { + return Ok(json!({"accepted":0,"held":1,"reason":"BINDING_REAPPROVAL_REQUIRED"})); + } + let mut accepted = 0; + let mut held = 0; + let mut retryable = 0; + let http = reqwest::Client::builder() + .timeout(Duration::from_secs(5)) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|_| AppError::Network("Cannot initialize capture transport".into()))?; + // A sync invocation has bounded work; queued revisions remain durable. + for _ in 0..100 { + let current_repository = current_repo()?; + store.observe_repository(¤t_repository)?; + let current_auth = ResolvedAuth::resolve(global).map_err(sanitize_error)?; + let current_origin = AppConfig::load().map_err(sanitize_error)?.api_base_url(); + if current_repository.key != binding.repository_key + || !current_repository.matches_binding(&binding) + || current_auth.workspace_id != auth.workspace_id + || current_auth.api_key != auth.api_key + || current_origin.trim_end_matches('/') != origin.trim_end_matches('/') + { + held += 1; + break; + } + let now = UtcClock::seconds(); + let Some(row) = store.claim(&binding, now)? else { + break; + }; + if store.status()?.storage_paused || store.invocations_pending()? { + break; + } + // Current consent was checked atomically at claim. The server rechecks + // authority before accepting every revision and replay. + let response = http + .post(format!( + "{}/api/v2/agent-sessions", + origin.trim_end_matches('/') + )) + .header("Authorization", format!("Bearer {}", auth.api_key)) + .header("Keito-Account-Id", &auth.workspace_id) + .header("Content-Type", "application/json") + .header("Idempotency-Key", &row.hash) + .header("X-Keito-Client", "cli") + .header("X-Keito-Client-Version", env!("CARGO_PKG_VERSION")) + .body(row.body.clone()) + .send() + .await; + match response { + Err(_) => { + store.finish(&row, "pending", "NETWORK_UNAVAILABLE", now, None)?; + retryable += 1; + break; + } + Ok(response) => { + let status = response.status().as_u16(); + let retry_after = response + .headers() + .get("Retry-After") + .and_then(|h| h.to_str().ok()) + .and_then(|h| retry_after_delay(h, now)); + if (200..300).contains(&status) { + // Read bounded acknowledgements; never persist server prose. + if response.content_length().is_some_and(|n| n > 64 * 1024) { + store.finish(&row, "pending", "INVALID_ACKNOWLEDGEMENT", now, None)?; + retryable += 1; + break; + } + let acknowledgement = bounded_ack(response).await.and_then(|value| { + serde_json::from_value::(value).ok() + }); + if let Some(ack) = acknowledgement.filter(|a| a.agent_session.valid(&row)) { + store.acknowledge(&row, &ack.agent_session.id, now)?; + accepted += 1; + } else { + store.finish(&row, "pending", "INVALID_ACKNOWLEDGEMENT", now, None)?; + retryable += 1; + break; + } + } else if status == 429 || status >= 500 { + store.finish( + &row, + "pending", + if status == 429 { + "RATE_LIMITED" + } else { + "SERVER_UNAVAILABLE" + }, + now, + retry_after, + )?; + retryable += 1; + break; + } else { + let body = bounded_ack(response).await; + let code = body.as_ref().and_then(safe_error_code); + if status == 409 && matches!(code, Some("in_progress" | "projection_pending")) { + store.finish( + &row, + "pending", + if code == Some("in_progress") { + "IN_PROGRESS" + } else { + "PROJECTION_PENDING" + }, + now, + retry_after, + )?; + retryable += 1; + break; + } + let reason = match status { + 401 => "NEEDS_AUTH", + 403 => "FORBIDDEN_OR_DISABLED", + 404 => "MAPPING_OR_API_UNAVAILABLE", + 409 => "REVISION_CONFLICT", + 413 => "PAYLOAD_LIMIT", + _ => "REQUEST_REJECTED", + }; + let state = if matches!(status, 401 | 403 | 404) { + "pending" + } else { + "held" + }; + store.finish(&row, state, reason, now, retry_after.or(Some(60)))?; + held += 1; + break; + } + } + } + } + Ok( + json!({"accepted":accepted,"held":held,"retryable":retryable,"pending":store.status()?.pending}), + ) +} +struct UtcClock; +impl UtcClock { + fn seconds() -> i64 { + chrono::Utc::now().timestamp() + } +} + +async fn bounded_ack(mut response: reqwest::Response) -> Option { + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.ok()? { + if body.len().checked_add(chunk.len())? > 64 * 1024 { + return None; + } + body.extend_from_slice(&chunk); + } + serde_json::from_slice(&body).ok() +} + +fn origin_for_worker(config: &AppConfig) -> String { + config.api_base_url() +} +fn install_worker_service( + binding: &Binding, + origin: &str, + capture_home: &Path, +) -> Result { + let supervisor = crate::capture_supervisor::Supervisor::system()?; + let cwd = std::env::current_dir() + .map_err(|_| AppError::Config("Cannot identify worker repository".into()))?; + let executable = std::env::current_exe() + .map_err(|_| AppError::Config("Cannot identify CLI runtime".into()))?; + let config = crate::capture_supervisor::WorkerConfig { + repository_key: &binding.repository_key, + repository_root: &cwd, + executable: &executable, + capture_home, + workspace_id: &binding.workspace_id, + api_origin: origin, + }; + supervisor.install(&config) +} + +fn sanitize_error(error: AppError) -> AppError { + match error { + AppError::Auth(_) => AppError::Auth( + "Capture preflight needs valid current credentials and workspace permission".into(), + ), + AppError::RateLimited { + retry_after_seconds, + } => AppError::RateLimited { + retry_after_seconds, + }, + AppError::Network(_) => AppError::Network( + "Capture preflight network unavailable; frozen evidence retained".into(), + ), + AppError::NotFound(_) => AppError::NotFound( + "Capture mapping unavailable; review the selected project and task".into(), + ), + AppError::Conflict(_) => { + AppError::Conflict("Capture preflight conflicted; review current authority".into()) + } + AppError::InvalidInput(_) => { + AppError::InvalidInput("Capture preflight rejected the request".into()) + } + AppError::Config(_)=>AppError::Config("Capture configuration unavailable; repair local settings without printing their contents".into()), + _ => AppError::ServerError( + "Capture preflight unavailable; no response content retained".into(), + ), + } +} + +fn verify_runtime_hash(expected: &str) -> Result<(), AppError> { + if expected.len() != 64 || !expected.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(AppError::InvalidInput( + "Invalid expected runtime digest".into(), + )); + } + let path = std::env::current_exe() + .map_err(|_| AppError::Config("Cannot verify worker runtime".into()))?; + let bytes = + std::fs::read(path).map_err(|_| AppError::Config("Cannot verify worker runtime".into()))?; + if capture::hash(bytes) != expected { + return Err(AppError::Config("Capture worker runtime changed; explicitly reinstall the reviewed worker before delivery".into())); + } + Ok(()) +} + +#[derive(serde::Deserialize)] +struct AcknowledgementEnvelope { + agent_session: Acknowledgement, +} +#[derive(serde::Deserialize)] +struct Acknowledgement { + id: String, + revision: i64, + projection_state: String, + review_state: String, +} +impl Acknowledgement { + fn valid(&self, row: &capture::Queued) -> bool { + capture::identifier(&self.id).is_ok() + && self.revision == row.revision + && matches!(self.projection_state.as_str(), "PENDING" | "PROJECTED") + && matches!( + self.review_state.as_str(), + "PENDING" | "APPROVED" | "EXCLUDED" | "NEEDS_ATTENTION" | "NEEDS_MAPPING" + ) + && row + .canonical_server_id + .as_deref() + .is_none_or(|id| id == self.id) + } +} +fn safe_error_code(body: &Value) -> Option<&str> { + body.get("reason") + .and_then(Value::as_str) + .or_else(|| { + body.get("error") + .and_then(|v| v.get("code")) + .and_then(Value::as_str) + }) + .or_else(|| body.get("code").and_then(Value::as_str)) + .filter(|v| { + matches!( + *v, + "in_progress" + | "projection_pending" + | "revision_conflict" + | "mapping_invalid" + | "needs_auth" + | "review_required" + | "forbidden_payload" + | "unsupported_schema" + ) + }) +} +fn retry_after_delay(header: &str, now: i64) -> Option { + header + .parse::() + .ok() + .or_else(|| { + chrono::DateTime::parse_from_rfc2822(header) + .ok() + .map(|date| date.timestamp().saturating_sub(now)) + }) + .map(|seconds| seconds.clamp(1, 3600)) +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 1330985..40dffab 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,4 +1,5 @@ pub mod auth; +pub mod capture; pub mod clients; pub mod projects; pub mod skill; diff --git a/src/commands/skill.rs b/src/commands/skill.rs index 47000bf..d333a78 100644 --- a/src/commands/skill.rs +++ b/src/commands/skill.rs @@ -1,6 +1,8 @@ use colored::Colorize; +use dialoguer::MultiSelect; use serde::Serialize; use std::fs; +use std::io::IsTerminal; use std::path::{Path, PathBuf}; use std::process::{Command as ProcessCommand, Stdio}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -21,7 +23,15 @@ struct SkillStatus { cli_path: Option, npx_installed: bool, jq_installed: bool, + capture_runtime: String, + credentials_configured: bool, authenticated: bool, + authentication_state: String, + hook_trust: String, + delivery_verified: bool, + ready: bool, + capture: serde_json::Value, + worker: serde_json::Value, account_id: Option, codex: AgentStatus, claude_code: AgentStatus, @@ -33,6 +43,7 @@ struct AgentStatus { skill_path: Option, hooks_configured: bool, hook_config_path: Option, + guard_runtime: String, } #[derive(Debug)] @@ -64,30 +75,45 @@ const BUNDLED_SKILL_FILES: &[BundledSkillFile] = &[ executable: false, }, BundledSkillFile { - path: "hooks/lib/config.sh", - contents: include_str!("../../skills/keito-time-track/hooks/lib/config.sh"), + path: "hooks/claude-plugin.json", + contents: include_str!("../../skills/keito-time-track/hooks/claude-plugin.json"), executable: false, }, BundledSkillFile { - path: "hooks/lib/duration.sh", - contents: include_str!("../../skills/keito-time-track/hooks/lib/duration.sh"), - executable: false, + path: "hooks/dispatch.sh", + contents: include_str!("../../skills/keito-time-track/hooks/dispatch.sh"), + executable: true, }, BundledSkillFile { - path: "hooks/lib/log.sh", - contents: include_str!("../../skills/keito-time-track/hooks/lib/log.sh"), - executable: false, + path: "hooks/interrupt.sh", + contents: include_str!("../../skills/keito-time-track/hooks/interrupt.sh"), + executable: true, + }, + BundledSkillFile { + path: "hooks/prompt.sh", + contents: include_str!("../../skills/keito-time-track/hooks/prompt.sh"), + executable: true, }, BundledSkillFile { path: "hooks/session-end.sh", contents: include_str!("../../skills/keito-time-track/hooks/session-end.sh"), executable: true, }, + BundledSkillFile { + path: "hooks/session-finalize.sh", + contents: include_str!("../../skills/keito-time-track/hooks/session-finalize.sh"), + executable: true, + }, BundledSkillFile { path: "hooks/session-start.sh", contents: include_str!("../../skills/keito-time-track/hooks/session-start.sh"), executable: true, }, + BundledSkillFile { + path: "hooks/stop.sh", + contents: include_str!("../../skills/keito-time-track/hooks/stop.sh"), + executable: true, + }, BundledSkillFile { path: "installers/install-claude-code.sh", contents: include_str!("../../skills/keito-time-track/installers/install-claude-code.sh"), @@ -98,6 +124,16 @@ const BUNDLED_SKILL_FILES: &[BundledSkillFile] = &[ contents: include_str!("../../skills/keito-time-track/installers/install-codex.sh"), executable: true, }, + BundledSkillFile { + path: "installers/install.sh", + contents: include_str!("../../skills/keito-time-track/installers/install.sh"), + executable: true, + }, + BundledSkillFile { + path: "installers/uninstall.sh", + contents: include_str!("../../skills/keito-time-track/installers/uninstall.sh"), + executable: true, + }, BundledSkillFile { path: "scripts/disable.sh", contents: include_str!("../../skills/keito-time-track/scripts/disable.sh"), @@ -147,32 +183,97 @@ pub async fn run( cmd: SkillCommand, global: &GlobalFlags, mode: OutputMode, +) -> Result<(), AppError> { + #[cfg(unix)] + { + run_with_scope(cmd, global, mode, None).await + } + #[cfg(not(unix))] + { + run_inner(cmd, global, mode).await + } +} +#[cfg(unix)] +pub async fn run_with_scope( + cmd: SkillCommand, + global: &GlobalFlags, + mode: OutputMode, + scope: Option<&mut crate::process_ownership::scope::Scope>, +) -> Result<(), AppError> { + run_inner(cmd, global, mode, scope).await +} +async fn run_inner( + cmd: SkillCommand, + global: &GlobalFlags, + mode: OutputMode, + #[cfg(unix)] scope: Option<&mut crate::process_ownership::scope::Scope>, ) -> Result<(), AppError> { match cmd.command { SkillSubcommand::Install { source, agent, skip_skills_add, + confirm_migration, } => { install( global, mode, &source, - selected_agents(agent), + selected_agents(agent)?, skip_skills_add, + confirm_migration, + #[cfg(unix)] + scope, ) .await } - SkillSubcommand::Status => status(global, mode, false).await, - SkillSubcommand::Doctor => status(global, mode, true).await, + SkillSubcommand::Uninstall { agent } => { + uninstall(selected_agents(agent)?, global, mode).await + } + SkillSubcommand::Runtime => { + let runtime = crate::capture_runtime_pair::current()?; + if !global.quiet { + println!( + "{}", + serde_json::to_string(&runtime) + .map_err(|_| AppError::Config("Cannot render runtime identity".into()))? + ); + } + Ok(()) + } + SkillSubcommand::Status => status(global, mode, false, false).await, + SkillSubcommand::Doctor { live } => status(global, mode, true, live).await, SkillSubcommand::TeamInit { mode: team_mode } => team_init(team_mode, global, mode).await, } } pub async fn install_defaults(global: &GlobalFlags, mode: OutputMode) -> Result<(), AppError> { + #[cfg(unix)] + let mut ordinary_scope = crate::capture_command_owner::defaults_install_scope()?; let source = std::env::var("KEITO_SKILL_SOURCE").unwrap_or_else(|_| BUNDLED_SKILL_SOURCE.into()); - install(global, mode, &source, default_agents(), false).await + let result = install( + global, + mode, + &source, + selected_agents(vec![])?, + false, + false, + #[cfg(unix)] + Some(&mut ordinary_scope), + ) + .await; + #[cfg(unix)] + { + let resources = ordinary_scope.finish().clean; + let terminal = ordinary_scope.publish_terminal(resources && result.is_ok()); + if result.is_ok() && (!resources || !terminal) { + return Err(AppError::Config( + "Default installer ownership did not settle".into(), + )); + } + } + result } async fn install( @@ -181,6 +282,8 @@ async fn install( source: &str, agents: Vec, skip_skills_add: bool, + confirm_migration: bool, + #[cfg(unix)] scope: Option<&mut crate::process_ownership::scope::Scope>, ) -> Result<(), AppError> { let source = source.trim(); let use_bundled = source.is_empty() || source == BUNDLED_SKILL_SOURCE; @@ -190,35 +293,55 @@ async fn install( "npx is required for an external skill source. Install Node.js, use --source bundled, or run the manual skill installer.".into(), )); } - if find_in_path("jq").is_none() { - return Err(AppError::Config( - "jq is required by the Keito Skill hook installers and runtime scripts.".into(), - )); - } - - let bundled_skill = if !skip_skills_add && use_bundled { - Some(materialize_bundled_skill()?) - } else { - None - }; - - for agent in &agents { - let show_child_output = !global.quiet && mode == OutputMode::Table; - if skip_skills_add { - run_hook_installer(*agent, show_child_output)?; - } else if let Some(skill) = bundled_skill.as_ref() { - run_bundled_hook_installer(*agent, show_child_output, &skill.skill_root)?; + #[cfg(unix)] + return install_native( + global, + mode, + source, + agents, + skip_skills_add, + confirm_migration, + scope, + ); + #[cfg(not(unix))] + { + let runtime = crate::capture_runtime_pair::current()?; + let home = dirs::home_dir() + .ok_or_else(|| AppError::Config("Cannot identify profile home".into()))?; + let bundled_skill = if !skip_skills_add && use_bundled { + Some(materialize_bundled_skill()?) } else { - run_skills_add(source, *agent, show_child_output)?; - run_hook_installer(*agent, show_child_output)?; + None + }; + for agent in &agents { + let root = prepare_install_root( + source, + *agent, + bundled_skill + .as_ref() + .map(|skill| skill.skill_root.as_path()), + !skip_skills_add && !use_bundled, + !global.quiet && mode == OutputMode::Table, + )?; + let options = crate::skill_adapter::InstallOptions { + source_root: &root, + profile_home: &home, + agent: *agent, + runtime: &runtime, + confirm_migration, + harness_version: None, + }; + crate::skill_adapter::install(options)?; } - } - if global.quiet { - return Ok(()); - } + if global.quiet { + return Ok(()); + } - let current = collect_status(global); + print_install_status(collect_status(global), mode) + } +} +fn print_install_status(current: SkillStatus, mode: OutputMode) -> Result<(), AppError> { if mode == OutputMode::Json { println!( "{}", @@ -235,8 +358,333 @@ async fn install( Ok(()) } -async fn status(global: &GlobalFlags, mode: OutputMode, doctor: bool) -> Result<(), AppError> { - let current = collect_status(global); +fn prepare_install_root( + source: &str, + agent: SkillAgent, + bundled: Option<&Path>, + download: bool, + show_output: bool, +) -> Result { + if download { + run_skills_add(source, agent, show_output)?; + } + if let Some(root) = bundled { + return Ok(root.to_owned()); + } + hook_installer_path(agent) + .and_then(|path| path.parent()?.parent().map(Path::to_path_buf)) + .ok_or_else(|| AppError::Config("Keito skill source is unavailable".into())) +} +#[cfg(unix)] +pub(crate) trait InstallSteps { + fn probe(&mut self, agent: SkillAgent) -> Result; + fn barrier(&mut self) -> Result<(), AppError>; + fn publish(&mut self, agent: SkillAgent, version: String) -> Result<(), AppError>; +} +#[cfg(unix)] +pub(crate) fn selected_install( + agents: &[SkillAgent], + steps: &mut impl InstallSteps, +) -> Result<(), AppError> { + if !(1..=2).contains(&agents.len()) || (agents.len() == 2 && agents[0] == agents[1]) { + return Err(AppError::InvalidInput( + "Select one or two distinct installer targets".into(), + )); + } + let mut versions = Vec::with_capacity(agents.len()); + for agent in agents { + versions.push((*agent, steps.probe(*agent)?)); + } + steps.barrier()?; + for (agent, version) in versions { + steps.publish(agent, version)?; + } + Ok(()) +} +#[cfg(unix)] +struct CurrentInstallSteps<'a, 'scope> { + preflight: Option>, + publication: Option>, + runtime: crate::capture_runtime_pair::CaptureRuntimeIdentity, + home: PathBuf, + source: &'a str, + bundled: Option, + materialize: bool, + download: bool, + show_output: bool, + confirm_migration: bool, +} +#[cfg(unix)] +impl InstallSteps for CurrentInstallSteps<'_, '_> { + fn probe(&mut self, agent: SkillAgent) -> Result { + let runner = self + .preflight + .as_mut() + .ok_or_else(|| AppError::Config("Installer preflight already consumed".into()))?; + crate::skill_adapter::detect_version(agent, runner) + } + fn barrier(&mut self) -> Result<(), AppError> { + let preflight = self + .preflight + .take() + .ok_or_else(|| AppError::Config("Installer preflight already consumed".into()))?; + self.publication = Some(preflight.seal()?); + Ok(()) + } + fn publish(&mut self, agent: SkillAgent, version: String) -> Result<(), AppError> { + crate::adapter_files::installer_phase_event(if agent == SkillAgent::Codex { + 40 + } else { + 41 + }); + let publication = self.publication.as_mut().ok_or_else(|| { + AppError::Config("Installer publication requires settled preflight".into()) + })?; + publication.check_live()?; + if self.materialize && self.bundled.is_none() { + self.bundled = Some(materialize_bundled_skill()?); + } + publication.check_live()?; + let root = prepare_install_root( + self.source, + agent, + self.bundled + .as_ref() + .map(|skill| skill.skill_root.as_path()), + self.download, + self.show_output, + )?; + publication.check_live()?; + crate::skill_adapter::install_prepared( + crate::skill_adapter::InstallOptions { + source_root: &root, + profile_home: &self.home, + agent, + runtime: &self.runtime, + confirm_migration: self.confirm_migration, + harness_version: None, + }, + version, + &mut || { + crate::adapter_files::installer_phase_event(30); + let result = publication.check_live(); + crate::adapter_files::installer_phase_event(if result.is_ok() { 31 } else { 32 }); + result + }, + )?; + Ok(()) + } +} +#[cfg(unix)] +fn install_native( + global: &GlobalFlags, + mode: OutputMode, + source: &str, + agents: Vec, + skip_skills_add: bool, + confirm_migration: bool, + scope: Option<&mut crate::process_ownership::scope::Scope>, +) -> Result<(), AppError> { + #[cfg(feature = "dev-tools")] + { + crate::adapter_files::installer_phase_trace::with_trace( + || { + crate::adapter_files::installer_phase_trace::Guard::begin( + std::env::var_os("KEITO_SOURCE_QA_INSTALL_PHASE_TRACE").as_deref() + == Some(std::ffi::OsStr::new("v1")), + ) + }, + || { + install_native_body( + global, + mode, + source, + agents, + skip_skills_add, + confirm_migration, + scope, + ) + }, + ) + } + #[cfg(not(feature = "dev-tools"))] + { + install_native_body( + global, + mode, + source, + agents, + skip_skills_add, + confirm_migration, + scope, + ) + } +} +#[cfg(unix)] +fn install_native_body( + global: &GlobalFlags, + mode: OutputMode, + source: &str, + agents: Vec, + skip_skills_add: bool, + confirm_migration: bool, + scope: Option<&mut crate::process_ownership::scope::Scope>, +) -> Result<(), AppError> { + let preflight = crate::capture_command_owner::InstallerPreflight::new(scope, agents.len())?; + let runtime = preflight.runtime().clone(); + let home = + dirs::home_dir().ok_or_else(|| AppError::Config("Cannot identify profile home".into()))?; + let use_bundled = source.is_empty() || source == BUNDLED_SKILL_SOURCE; + let mut steps = CurrentInstallSteps { + preflight: Some(preflight), + publication: None, + runtime, + home, + source, + bundled: None, + materialize: !skip_skills_add && use_bundled, + download: !skip_skills_add && !use_bundled, + show_output: !global.quiet && mode == OutputMode::Table, + confirm_migration, + }; + let result = (|| { + selected_install(&agents, &mut steps)?; + let publication = steps.publication.as_mut().unwrap(); + publication.check_live()?; + if !global.quiet { + // Installation does not run a second process cohort or doctor. + let status = collect_installed_status(global); + publication.check_live()?; + print_install_status(status, mode)?; + } + publication.check_live() + })(); + let publication = steps.publication.take(); + // Scratch cleanup is part of the operation, including standalone finality. + // A late cleanup cannot be hidden behind an earlier clean terminal. + drop(steps.bundled.take()); + match publication { + Some(publication) => publication.finish(result), + None => result, + } +} + +#[cfg(all(test, unix))] +mod installer_order_tests { + use super::*; + struct Recorder { + events: Vec, + fail: Option<&'static str>, + } + impl Recorder { + fn event(&mut self, event: String) -> Result<(), AppError> { + let fail = self.fail == Some(event.as_str()); + self.events.push(event); + if fail { + Err(AppError::Config("Injected installer step failure".into())) + } else { + Ok(()) + } + } + } + impl InstallSteps for Recorder { + fn probe(&mut self, agent: SkillAgent) -> Result { + self.event(format!("probe:{}", agent.skills_cli_name()))?; + Ok("synthetic-version".into()) + } + fn barrier(&mut self) -> Result<(), AppError> { + self.event("barrier".into()) + } + fn publish(&mut self, agent: SkillAgent, _: String) -> Result<(), AppError> { + self.event(format!("publish:{}", agent.skills_cli_name())) + } + } + fn run(fail: Option<&'static str>) -> (Recorder, Result<(), AppError>) { + let mut recorder = Recorder { + events: vec![], + fail, + }; + let result = selected_install(&[SkillAgent::Codex, SkillAgent::ClaudeCode], &mut recorder); + (recorder, result) + } + #[test] + fn installer_order_all_probes_and_barrier_precede_publication() { + let (recorder, result) = run(None); + assert!(result.is_ok()); + assert_eq!( + recorder.events, + [ + "probe:codex", + "probe:claude-code", + "barrier", + "publish:codex", + "publish:claude-code" + ] + ); + } + #[test] + fn installer_order_second_probe_refusal_publishes_nothing() { + let (recorder, result) = run(Some("probe:claude-code")); + assert!(result.is_err()); + assert_eq!(recorder.events, ["probe:codex", "probe:claude-code"]); + } + #[test] + fn installer_order_barrier_refusal_publishes_nothing() { + let (recorder, result) = run(Some("barrier")); + assert!(result.is_err()); + assert_eq!( + recorder.events, + ["probe:codex", "probe:claude-code", "barrier"] + ); + } + #[test] + fn installer_order_first_probe_refusal_is_an_unchanged_control() { + let (recorder, result) = run(Some("probe:codex")); + assert!(result.is_err()); + assert_eq!(recorder.events, ["probe:codex"]); + } +} + +async fn status( + global: &GlobalFlags, + mode: OutputMode, + doctor: bool, + live: bool, +) -> Result<(), AppError> { + let mut current = collect_status(global); + if live { + let auth = ResolvedAuth::resolve(global)?; + let config = crate::config::AppConfig::load()?; + let client = crate::api::client::KeitorClient::new(&auth, &config.api_base_url())?; + match client.get_me().await { + Ok(me) if !me.is_personal_read_only_sync() => { + current.authenticated = true; + current.authentication_state = "VERIFIED".into(); + let repository = &mut current.capture["current_repository"]; + let matches = repository["approved"] == true + && repository["mapping_current"] == true + && repository["paused"] != true + && repository["workspace_id"].as_str() == Some(auth.workspace_id.as_str()) + && repository["owner_id"].as_str() == Some(me.id.as_str()) + && repository["origin_hash"].as_str() + == Some( + crate::capture::hash(config.api_base_url().trim_end_matches('/')) + .as_str(), + ); + repository["authentication_binding"] = + serde_json::json!(if matches { "MATCHED" } else { "MISMATCH" }); + current.delivery_verified = + matches && repository["delivery_history_verified"] == true; + current.capture["delivery_verified"] = serde_json::json!(current.delivery_verified); + } + Ok(_) => { + current.authentication_state = "INCOMPATIBLE_CREDENTIAL".into(); + } + Err(_) => { + current.authentication_state = "NEEDS_AUTH_OR_NETWORK".into(); + } + } + } if global.quiet { return Ok(()); @@ -255,16 +703,41 @@ async fn status(global: &GlobalFlags, mode: OutputMode, doctor: bool) -> Result< Ok(()) } -fn selected_agents(agents: Vec) -> Vec { - if agents.is_empty() { - default_agents() - } else { - agents +fn selected_agents(agents: Vec) -> Result, AppError> { + if !agents.is_empty() { + let mut selected = Vec::new(); + for agent in agents { + if !selected.contains(&agent) { + selected.push(agent); + } + } + return Ok(selected); } -} - -fn default_agents() -> Vec { - vec![SkillAgent::Codex, SkillAgent::ClaudeCode] + if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { + return Err(AppError::InvalidInput( + "Select explicit adapter targets: --agent claude-code and/or --agent codex".into(), + )); + } + let selected = MultiSelect::new() + .with_prompt("Install which coding-agent adapters?") + .items(["Claude Code", "Codex"]) + .interact() + .map_err(|_| AppError::Config("Cannot read adapter target selection".into()))?; + if selected.is_empty() { + return Err(AppError::InvalidInput( + "No adapters selected; nothing installed".into(), + )); + } + Ok(selected + .into_iter() + .map(|i| { + if i == 0 { + SkillAgent::ClaudeCode + } else { + SkillAgent::Codex + } + }) + .collect()) } fn run_skills_add(source: &str, agent: SkillAgent, show_output: bool) -> Result<(), AppError> { @@ -300,57 +773,6 @@ fn run_skills_add(source: &str, agent: SkillAgent, show_output: bool) -> Result< Ok(()) } -fn run_bundled_hook_installer( - agent: SkillAgent, - show_output: bool, - skill_root: &Path, -) -> Result<(), AppError> { - let installer_name = match agent { - SkillAgent::Codex => "install-codex.sh", - SkillAgent::ClaudeCode => "install-claude-code.sh", - }; - let script = skill_root.join("installers").join(installer_name); - run_installer_script(agent, show_output, &script) -} - -fn run_hook_installer(agent: SkillAgent, show_output: bool) -> Result<(), AppError> { - let script = hook_installer_path(agent).ok_or_else(|| { - AppError::Config(format!( - "Keito Skill files were not found for {} after install", - agent.display_name() - )) - })?; - - run_installer_script(agent, show_output, &script) -} - -fn run_installer_script( - agent: SkillAgent, - show_output: bool, - script: &Path, -) -> Result<(), AppError> { - let current_exe = std::env::current_exe() - .map_err(|e| AppError::Config(format!("Could not resolve current keito binary: {e}")))?; - - let status = ProcessCommand::new("bash") - .arg(script) - .env("KEITO_CLI_BIN", current_exe) - .stdin(Stdio::null()) - .stdout(child_stdio(show_output)) - .stderr(child_stdio(show_output)) - .status() - .map_err(|e| AppError::Config(format!("Failed to run hook installer: {e}")))?; - - if !status.success() { - return Err(AppError::Config(format!( - "Hook installer failed for {}", - agent.display_name() - ))); - } - - Ok(()) -} - fn materialize_bundled_skill() -> Result { let unique = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -359,6 +781,17 @@ fn materialize_bundled_skill() -> Result { let temp_root = std::env::temp_dir().join(format!("keito-skill-{}-{unique}", std::process::id())); let skill_root = temp_root.join(SKILL_NAME); + let builder = fs::DirBuilder::new(); + #[cfg(unix)] + let mut builder = builder; + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder + .create(&temp_root) + .map_err(|_| AppError::Config("Cannot create private bundled skill source".into()))?; for file in BUNDLED_SKILL_FILES { let path = skill_root.join(file.path); @@ -436,6 +869,26 @@ fn hook_installer_path(agent: SkillAgent) -> Option { fn collect_status(global: &GlobalFlags) -> SkillStatus { let auth = ResolvedAuth::resolve(global).ok(); + let (capture, worker) = capture_diagnostics(global); + status_from_diagnostics(auth, capture, worker) +} +#[cfg(unix)] +fn collect_installed_status(global: &GlobalFlags) -> SkillStatus { + status_from_diagnostics( + ResolvedAuth::resolve(global).ok(), + serde_json::json!({"status":"NOT_CHECKED_AFTER_INSTALL", "delivery_verified":false}), + serde_json::json!({"status":"NOT_CHECKED_AFTER_INSTALL"}), + ) +} +fn status_from_diagnostics( + auth: Option, + capture: serde_json::Value, + worker: serde_json::Value, +) -> SkillStatus { + let delivery_verified = capture + .get("delivery_verified") + .and_then(serde_json::Value::as_bool) + == Some(true); SkillStatus { cli_installed: true, cli_path: std::env::current_exe() @@ -443,7 +896,20 @@ fn collect_status(global: &GlobalFlags) -> SkillStatus { .map(|path| path.display().to_string()), npx_installed: find_in_path("npx").is_some(), jq_installed: find_in_path("jq").is_some(), - authenticated: auth.is_some(), + capture_runtime: if crate::capture_runtime_pair::current().is_ok() { + "VERIFIED_RELEASE_PAIR" + } else { + "UNQUALIFIED_OR_STALE" + } + .into(), + credentials_configured: auth.is_some(), + authenticated: false, + authentication_state: "UNVERIFIED".into(), + hook_trust: "UNKNOWN_REVIEW_IN_HARNESS".into(), + delivery_verified, + ready: false, + capture, + worker, account_id: auth.map(|auth| auth.workspace_id), codex: agent_status(SkillAgent::Codex), claude_code: agent_status(SkillAgent::ClaudeCode), @@ -463,14 +929,21 @@ fn agent_status(agent: SkillAgent) -> AgentStatus { SkillAgent::Codex => home.join(".codex/hooks.json"), SkillAgent::ClaudeCode => home.join(".claude/settings.json"), }); - let hooks_configured = hook_config_path - .as_ref() - .is_some_and(|path| hook_configured(path)); + let runtime = crate::capture_runtime_pair::current().ok(); + let hooks_configured = home.as_ref().is_some_and(|home| { + crate::skill_adapter::inspect(home, agent, runtime.as_ref()).unwrap_or(false) + }); AgentStatus { skill_installed: skill_path.is_some(), skill_path: skill_path.map(|path| path.display().to_string()), hooks_configured, + guard_runtime: if runtime.is_some() { + "VERIFIED_RELEASE_PAIR" + } else { + "UNQUALIFIED_OR_STALE" + } + .into(), hook_config_path: hook_config_path.map(|path| path.display().to_string()), } } @@ -479,13 +952,17 @@ fn first_existing(paths: &[PathBuf]) -> Option { paths.iter().find(|path| path.exists()).cloned() } -fn hook_configured(path: &Path) -> bool { - let Ok(contents) = std::fs::read_to_string(path) else { - return false; - }; - contents.contains(SKILL_NAME) - && contents.contains("session-start.sh") - && contents.contains("session-end.sh") +async fn uninstall( + agents: Vec, + global: &GlobalFlags, + mode: OutputMode, +) -> Result<(), AppError> { + let home = + dirs::home_dir().ok_or_else(|| AppError::Config("Cannot identify profile home".into()))?; + for agent in agents { + crate::skill_adapter::uninstall(&home, agent)?; + } + status(global, mode, false, false).await } fn find_in_path(binary: &str) -> Option { @@ -529,8 +1006,34 @@ fn print_status(status: &SkillStatus, doctor: bool) { println!("CLI path: {path}"); } println!("npx available: {}", yes_no(status.npx_installed)); - println!("jq available: {}", yes_no(status.jq_installed)); - println!("Authenticated: {}", yes_no(status.authenticated)); + println!("Native capture runtime: {}", status.capture_runtime); + println!( + "Credentials configured: {}", + yes_no(status.credentials_configured) + ); + println!("Live authentication: {}", status.authentication_state); + println!("Hook trust: {}", status.hook_trust); + println!( + "Capture delivery verified: {}", + yes_no(status.delivery_verified) + ); + println!( + "Repository approval: {}", + status.capture["current_repository"]["approved"] + .as_bool() + .unwrap_or(false) + ); + println!( + "Storage paused: {}", + status.capture["storage_paused"].as_bool().unwrap_or(true) + ); + println!( + "Worker installed/loaded/running: {}/{}/{}", + status.worker["installed"].as_bool().unwrap_or(false), + status.worker["loaded"].as_bool().unwrap_or(false), + status.worker["running"].as_bool().unwrap_or(false) + ); + println!("Ready: no (unknown trust/delivery is not ready)"); if let Some(account_id) = &status.account_id { println!("Account ID: {account_id}"); } @@ -543,14 +1046,14 @@ fn print_status(status: &SkillStatus, doctor: bool) { if !status.npx_installed { println!("- Install Node.js/npm so npx is available."); } - if !status.jq_installed { - println!("- Install jq."); + if status.capture_runtime != "VERIFIED_RELEASE_PAIR" { + println!("- Install the official paired Keito release for native capture."); } if !status.authenticated { println!("- Run keito auth login."); } if !status.codex.hooks_configured && !status.claude_code.hooks_configured { - println!("- Run keito skill install."); + println!("- Run keito skill install --agent ."); } if status.authenticated && (status.codex.hooks_configured || status.claude_code.hooks_configured) @@ -656,8 +1159,9 @@ run `/track-time-keito` from Codex or Claude Code to create the repo-local `.keito/config.yml` project/task mapping. Do not commit `.keito/config.yml`; it is specific to one Keito account, -client, project, and task. The lifecycle hooks create one `source=agent` time -entry when a tracked session ends, so do not create duplicate manual entries. +client, project, and task. After explicit local approval, supported turn hooks create +pending-review capture records. Do not create duplicate manual time entries for +captured activity. Review the evidence before approving any client charge. ", claude: "\ ## Keito Time Tracking @@ -668,8 +1172,9 @@ run `/track-time-keito` to create the repo-local `.keito/config.yml` project/task mapping. Do not commit `.keito/config.yml`; it is specific to one Keito account, -client, project, and task. The lifecycle hooks create one `source=agent` time -entry when a tracked session ends, so do not create duplicate manual entries. +client, project, and task. After explicit local approval, supported turn hooks create +pending-review capture records. Do not create duplicate manual time entries for +captured activity. Review the evidence before approving any client charge. ", }, SkillTeamMode::Required => TeamGuidance { @@ -678,35 +1183,41 @@ entry when a tracked session ends, so do not create duplicate manual entries. Keito agent time tracking is required before billable coding work in this repository. Before starting, verify `keito skill status --json`. If the skill -or hooks are missing, stop and tell the user to run `keito skill install`. +or hooks are missing, stop and tell the user to run `keito skill install --agent `. If `.keito/config.yml` is missing for this worktree, stop and run `/track-time-keito` from Codex or Claude Code so the user can choose the Keito client, project, and task. Do not guess project or task IDs. Do not commit `.keito/config.yml`. -The lifecycle hooks create one `source=agent` time entry when a tracked session -ends. Do not create duplicate manual entries for the same coding session. +The lifecycle hooks save minimized observed-turn evidence in a private local queue. +A separately supervised worker sends canonical revisions for review; elapsed activity +is not permission to bill. Verify local consent, worker and delivery with +`keito capture status --json` and `keito capture worker-status --json`. +Do not create duplicate manual entries for the same captured coding session. ", claude: "\ ## Keito Time Tracking Keito agent time tracking is required before billable coding work in this repository. Before starting, verify `keito skill status --json`. If the skill -or hooks are missing, stop and tell the user to run `keito skill install`. +or hooks are missing, stop and tell the user to run `keito skill install --agent `. If `.keito/config.yml` is missing for this worktree, stop and run `/track-time-keito` so the user can choose the Keito client, project, and task. Do not guess project or task IDs. Do not commit `.keito/config.yml`. -The lifecycle hooks create one `source=agent` time entry when a tracked session -ends. Do not create duplicate manual entries for the same coding session. +The lifecycle hooks save minimized observed-turn evidence in a private local queue. +A separately supervised worker sends canonical revisions for review; elapsed activity +is not permission to bill. Verify local consent, worker and delivery with +`keito capture status --json` and `keito capture worker-status --json`. +Do not create duplicate manual entries for the same captured coding session. ", }, } } -fn git_repo_root() -> Result { +pub(crate) fn git_repo_root() -> Result { let output = ProcessCommand::new("git") .args(["rev-parse", "--show-toplevel"]) .stdin(Stdio::null()) @@ -815,3 +1326,125 @@ fn relative_display(path: &Path) -> String { }) .unwrap_or_else(|| path.display().to_string()) } + +fn capture_diagnostics(global: &GlobalFlags) -> (serde_json::Value, serde_json::Value) { + if cfg!(not(unix)) { + // Doctor is available on this platform, but must not probe unsupported + // native storage/authority or imply repository approval and delivery. + return ( + serde_json::json!({"supported":false,"storage_paused":true,"reason":"UNSUPPORTED_PLATFORM", + "current_repository":{"approved":false,"mapping_current":false,"paused":true,"reason":"UNSUPPORTED_PLATFORM"}, + "delivery_verified":false,"historical_delivery_verified":null, + "usage":{"status":"UNAVAILABLE","reason":"UNSUPPORTED_PLATFORM"}}), + serde_json::json!({"installed":false,"loaded":false,"running":false,"stale":false,"state":"UNSUPPORTED_PLATFORM"}), + ); + } + let default_worker = serde_json::json!({"installed":false,"loaded":false,"running":false,"stale":false,"state":"UNKNOWN"}); + let directory = crate::capture_invocations::directory().ok(); + let Some(directory) = directory else { + return ( + serde_json::json!({"storage_paused":true,"reason":"STORAGE_UNAVAILABLE"}), + default_worker, + ); + }; + let Ok(mut store) = crate::capture::Store::open(&directory) else { + return ( + serde_json::json!({"storage_paused":true,"reason":"STORAGE_UNAVAILABLE"}), + default_worker, + ); + }; + let repository = std::env::current_dir() + .ok() + .and_then(|path| crate::capture::Repository::resolve(&path).ok()); + if let Some(repository) = &repository { + if store.observe_repository(repository).is_err() { + return ( + serde_json::json!({"storage_paused":true,"reason":"CAPTURE_AUTHORITY_UNAVAILABLE"}), + default_worker, + ); + } + } + let Ok(status) = store.status() else { + return ( + serde_json::json!({"storage_paused":true,"reason":"STORAGE_UNAVAILABLE"}), + default_worker, + ); + }; + let mut capture = + serde_json::to_value(status).unwrap_or_else(|_| serde_json::json!({"storage_paused":true})); + capture["historical_delivery_verified"] = capture["delivery_verified"].clone(); + capture["delivery_verified"] = serde_json::json!(false); + let auth = ResolvedAuth::resolve(global).ok(); + let origin = crate::config::AppConfig::load() + .ok() + .map(|config| crate::capture::hash(config.api_base_url().trim_end_matches('/'))); + let worker = if let Some(repository) = repository { + capture["current_repository"] = match store.binding(&repository.key) { + Ok(Some(binding)) => { + let local_auth_match = auth + .as_ref() + .is_some_and(|auth| auth.workspace_id == binding.workspace_id) + && origin.as_deref() == Some(binding.origin_hash.as_str()); + serde_json::json!({"approved":!binding.revoked,"paused":binding.paused,"mapping_current":repository.matches_binding(&binding), + "workspace_id":binding.workspace_id,"owner_id":binding.owner_id,"origin_hash":binding.origin_hash, + "delivery_history_verified":store.binding_delivery_history(&binding.id).unwrap_or(false), + "authentication_binding":if local_auth_match {"UNVERIFIED_OWNER"} else {"MISMATCH"}}) + } + _ => serde_json::json!({"approved":false,"reason":"LOCAL_APPROVAL_REQUIRED"}), + }; + crate::capture_supervisor::Supervisor::system() + .ok() + .and_then(|s| s.status(&repository.key, None).ok()) + .and_then(|s| serde_json::to_value(s).ok()) + .unwrap_or(default_worker) + } else { + capture["current_repository"] = + serde_json::json!({"approved":false,"reason":"REPOSITORY_UNAVAILABLE"}); + default_worker + }; + (capture, worker) +} + +#[cfg(test)] +mod bundle_tests { + use super::*; + use std::collections::BTreeSet; + fn collect(root: &Path, relative: &Path, paths: &mut BTreeSet) { + for item in fs::read_dir(root.join(relative)).unwrap() { + let item = item.unwrap(); + let next = relative.join(item.file_name()); + if item.file_name() == "__pycache__" + || item.path().extension().is_some_and(|ext| ext == "pyc") + { + continue; + } + if item.file_type().unwrap().is_dir() { + collect(root, &next, paths) + } else { + paths.insert(next.to_string_lossy().replace('\\', "/")); + } + } + } + #[test] + fn materialized_bundle_is_complete_and_byte_identical_to_all_shipped_sources() { + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("skills/keito-time-track"); + let mut source_paths = BTreeSet::new(); + collect(&source, Path::new(""), &mut source_paths); + let embedded: BTreeSet<_> = BUNDLED_SKILL_FILES + .iter() + .map(|f| f.path.to_owned()) + .collect(); + assert_eq!( + embedded, source_paths, + "A shipped adapter/test/manifest must never disappear from the binary bundle" + ); + let materialized = materialize_bundled_skill().unwrap(); + for path in source_paths { + assert_eq!( + fs::read(source.join(&path)).unwrap(), + fs::read(materialized.skill_root.join(&path)).unwrap(), + "{path}" + ); + } + } +} diff --git a/src/config/file.rs b/src/config/file.rs index da67998..826a99e 100644 --- a/src/config/file.rs +++ b/src/config/file.rs @@ -38,8 +38,12 @@ impl AppConfig { } let contents = std::fs::read_to_string(&path) .map_err(|e| AppError::Config(format!("Failed to read config: {e}")))?; - let config: AppConfig = toml::from_str(&contents) - .map_err(|e| AppError::Config(format!("Invalid config TOML: {e}")))?; + let config: AppConfig = toml::from_str(&contents).map_err(|_| { + AppError::Config( + "Invalid config TOML; repair the local configuration without sharing its contents" + .into(), + ) + })?; Ok(config) } diff --git a/src/error.rs b/src/error.rs index 2049e39..0f8186e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,6 +1,22 @@ use serde_json::json; use thiserror::Error; +/// Closed failure reasons: never retain arbitrary probe output or error text. +#[derive(Clone, Copy, Debug, Error, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CaptureProbeReason { + #[error("ownership admission refused")] + AdmissionRefused, + #[error("original deadline exceeded")] + Deadline, + #[error("monotonic clock unavailable")] + Clock, + #[error("ownership proof unavailable")] + Ownership, + #[error("probe unavailable")] + Unavailable, +} + #[derive(Error, Debug)] pub enum AppError { #[error("Authentication error: {0}")] @@ -26,6 +42,13 @@ pub enum AppError { #[error("Configuration error: {0}")] Config(String), + + #[error("Coding-agent version probe refused: {reason}")] + CaptureVersionProbe { + reason: CaptureProbeReason, + /// A later explicit finish failed; false means not reported, not clean. + cleanup_unverified: bool, + }, } impl AppError { @@ -39,6 +62,7 @@ impl AppError { AppError::ServerError(_) => 6, AppError::Network(_) => 7, AppError::Config(_) => 8, + AppError::CaptureVersionProbe { .. } => 8, } } @@ -66,6 +90,9 @@ impl AppError { } AppError::Auth(_) => Some("Set KEITO_API_KEY env var or run 'keito auth login'"), AppError::Config(_) => Some("Run 'keito auth login' to configure"), + AppError::CaptureVersionProbe { .. } => Some( + "Inspect 'keito capture status --json' and retained failure evidence before retrying", + ), AppError::RateLimited { .. } => Some("Retry after the server's Retry-After delay"), _ => None, } @@ -73,6 +100,14 @@ impl AppError { pub fn details(&self) -> Option { match self { + AppError::CaptureVersionProbe { + reason, + cleanup_unverified, + } => Some(json!({ + "kind": "capture_version_probe", "reason": reason, + "cleanup_unverified": cleanup_unverified, + "cleanup_status": if *cleanup_unverified { "unverified" } else { "not_reported" }, + })), AppError::NotFound(msg) => { if let Some(available_str) = msg .strip_suffix(|_: char| false) diff --git a/src/lib.rs b/src/lib.rs index 07661ba..7796da7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,70 @@ +mod adapter_files; pub mod api; +pub mod capture; +mod capture_authority; +mod capture_busy; +#[cfg(unix)] +mod capture_command_owner; +mod capture_invocations; +pub mod capture_mapping; +pub mod capture_runtime_pair; +pub mod capture_supervisor; +mod capture_usage; +mod capture_usage_consent; +mod capture_usage_ledger; +#[cfg(unix)] +mod capture_usage_origin; +#[cfg(unix)] +mod capture_usage_profile; +#[cfg(all(test, unix))] +mod capture_usage_test_io; pub mod cli; pub mod commands; pub mod config; pub mod error; pub mod output; +#[cfg(unix)] +#[doc(hidden)] +pub mod process_entry; +#[cfg(unix)] +#[doc(hidden)] +pub mod process_ownership; +#[cfg(all(feature = "dev-tools", unix))] +pub mod real_client_qa; +pub mod skill_adapter; +#[cfg(all(feature = "dev-tools", unix))] +pub mod source_qa_group; +#[cfg(all(feature = "dev-tools", unix))] +pub mod source_qa_protocol; +#[cfg(all(feature = "dev-tools", unix))] +pub mod source_qa_scope; pub mod types; + +#[cfg(all(unix, feature = "capture-profile"))] +#[doc(hidden)] +pub mod capture_profile; +/// Internal numeric profiling; disabled shipping builds evaluate only the body. +#[doc(hidden)] +#[macro_export] +macro_rules! capture_profile_measure { + (Ack, $body:expr, $accepted:expr) => {{ + #[cfg(all(unix, feature = "capture-profile"))] + { + $crate::capture_profile::measure_ack($accepted, || $body) + } + #[cfg(not(all(unix, feature = "capture-profile")))] + { + $body + } + }}; + ($phase:ident, $body:expr) => {{ + #[cfg(all(unix, feature = "capture-profile"))] + { + $crate::capture_profile::measure($crate::capture_profile::Phase::$phase, || $body) + } + #[cfg(not(all(unix, feature = "capture-profile")))] + { + $body + } + }}; +} diff --git a/src/main.rs b/src/main.rs index f12d774..e3c869c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,21 +1,126 @@ -mod api; -mod cli; -mod commands; -mod config; -mod error; -mod output; -mod types; - use clap::Parser; use cli::Cli; use error::AppError; +use keito_cli::{capture_runtime_pair, cli, commands, error, output}; use std::io::IsTerminal; -#[tokio::main] -async fn main() { - let cli = Cli::parse(); +fn local_command(cli: &Cli) -> bool { + match &cli.command { + cli::Command::Capture(command) => matches!( + &command.command, + cli::capture::CaptureSubcommand::Hook { .. } + | cli::capture::CaptureSubcommand::Status + | cli::capture::CaptureSubcommand::Usage { .. } + | cli::capture::CaptureSubcommand::Pause { .. } + | cli::capture::CaptureSubcommand::Resume { .. } + ), + cli::Command::Skill(command) => match &command.command { + cli::skill::SkillSubcommand::Runtime => true, + cli::skill::SkillSubcommand::Install { source, agent, .. } => { + cli.global.quiet && !agent.is_empty() && matches!(source.trim(), "" | "bundled") + } + _ => false, + }, + _ => false, + } +} - if let Err(e) = run(cli).await { +fn poll_local( + future: impl std::future::Future>, + hook: bool, +) -> Result<(), AppError> { + let mut future = std::pin::pin!(future); + let mut context = std::task::Context::from_waker(std::task::Waker::noop()); + match future.as_mut().poll(&mut context) { + std::task::Poll::Ready(result) => result, + std::task::Poll::Pending => Err(AppError::Config( + if hook { + "Capture hook required unsupported asynchronous work; collection remains paused" + } else { + "Local command required unsupported asynchronous work; operation refused" + } + .into(), + )), + } +} + +fn main() { + #[cfg(unix)] + let mut entry_scope = None; + let mut parser_exit = None; + let result = capture_runtime_pair::bootstrap_image().and_then(|()| { + #[cfg(unix)] + let pending = keito_cli::process_entry::PendingEntry::attach() + .map_err(|_| AppError::Config("Command ownership attachment refused".into()))?; + let parsed = Cli::try_parse(); + if let Err(error) = &parsed { + parser_exit = Some(error.exit_code()); + } + #[cfg(unix)] + { + let (scope, selection) = pending.select(parsed.as_ref().ok().map(|cli| &cli.command)); + entry_scope = scope; + selection.map_err(|_| AppError::Config("Command ownership policy refused".into()))?; + } + let cli = match parsed { + Ok(cli) => cli, + Err(error) => { + parser_exit = Some(error.exit_code()); + let _ = error.print(); + return Ok(()); + } + }; + if local_command(&cli) { + // These reviewed handlers perform only synchronous local work. + // Avoid the general worker pool and refuse an unexpected Pending. + // Network and unclassified commands retain the normal runtime. + let hook = matches!( + &cli.command, + cli::Command::Capture(cli::capture::CaptureCommand { + command: cli::capture::CaptureSubcommand::Hook { .. }, + }) + ); + return poll_local( + run( + cli, + #[cfg(unix)] + entry_scope.as_mut(), + ), + hook, + ); + } + tokio::runtime::Runtime::new() + .map_err(|_| AppError::Config("Cannot start command runtime".into()))? + .block_on(run( + cli, + #[cfg(unix)] + entry_scope.as_mut(), + )) + }); + #[cfg(unix)] + let result = if let Some(scope) = entry_scope.as_mut() { + let resources = scope.finish().clean; + if !scope.publish_terminal(resources && result.is_ok() && parser_exit.unwrap_or(0) == 0) + && result.is_ok() + { + Err(AppError::Config( + "Command ownership did not settle; collection remains paused".into(), + )) + } else { + result + } + } else { + result + }; + #[cfg(all(unix, feature = "capture-profile"))] + keito_cli::capture_profile::finish( + result.is_ok() && parser_exit.unwrap_or(0) == 0, + entry_scope.as_ref().map(|scope| scope.hard_end()), + ); + if let Some(code) = parser_exit { + std::process::exit(code); + } + if let Err(e) = result { let json_mode = std::env::args().any(|a| a == "--json") || !std::io::stdout().is_terminal(); if json_mode { eprintln!("{}", e.to_json()); @@ -27,7 +132,10 @@ async fn main() { } } -async fn run(cli: Cli) -> Result<(), AppError> { +async fn run( + cli: Cli, + #[cfg(unix)] scope: Option<&mut keito_cli::process_ownership::scope::Scope>, +) -> Result<(), AppError> { let output_mode = if cli.json || !std::io::stdout().is_terminal() { output::OutputMode::Json } else { @@ -35,10 +143,150 @@ async fn run(cli: Cli) -> Result<(), AppError> { }; match cli.command { + cli::Command::Capture(cmd) => { + #[cfg(unix)] + { + commands::capture::run_with_scope(cmd, &cli.global, output_mode, scope).await + } + #[cfg(not(unix))] + { + commands::capture::run(cmd, &cli.global, output_mode).await + } + } cli::Command::Auth(cmd) => commands::auth::run(cmd, &cli.global, output_mode).await, cli::Command::Clients(cmd) => commands::clients::run(cmd, &cli.global, output_mode).await, cli::Command::Time(cmd) => commands::time::run(cmd, &cli.global, output_mode).await, cli::Command::Projects(cmd) => commands::projects::run(cmd, &cli.global, output_mode).await, - cli::Command::Skill(cmd) => commands::skill::run(cmd, &cli.global, output_mode).await, + cli::Command::Skill(cmd) => { + #[cfg(unix)] + { + commands::skill::run_with_scope(cmd, &cli.global, output_mode, scope).await + } + #[cfg(not(unix))] + { + commands::skill::run(cmd, &cli.global, output_mode).await + } + } + } +} + +#[cfg(test)] +mod local_startup_tests { + use super::*; + + fn parsed(arguments: &[&str]) -> Cli { + Cli::try_parse_from(std::iter::once("keito").chain(arguments.iter().copied())).unwrap() + } + + #[test] + fn local_startup_known_local_commands_need_no_async_workers() { + for arguments in [ + vec!["skill", "runtime"], + vec![ + "--quiet", "skill", "install", "--source", "bundled", "--agent", "codex", + ], + vec!["capture", "status"], + vec!["capture", "pause", "--repo"], + vec!["capture", "resume", "--repo"], + vec!["capture", "usage", "status", "--repo", "--agent", "codex"], + vec![ + "capture", + "usage", + "enable", + "--repo", + "--agent", + "codex", + "--profile-home", + "/synthetic/home", + "--harness-executable", + "/synthetic/codex", + "--confirm", + ], + ] { + assert!(local_command(&parsed(&arguments)), "{arguments:?}"); + } + } + + #[test] + fn local_startup_general_and_network_commands_keep_async_workers() { + for arguments in [ + vec!["auth", "status"], + vec!["capture", "sync"], + vec!["capture", "worker"], + vec![ + "capture", + "setup", + "--agent", + "codex", + "--project", + "p", + "--task", + "t", + "--confirm", + ], + vec!["skill", "doctor", "--live"], + vec![ + "skill", "install", "--source", "bundled", "--agent", "codex", + ], + vec![ + "--quiet", + "skill", + "install", + "--source", + "external/repository", + "--agent", + "codex", + ], + vec!["--quiet", "skill", "install", "--source", "bundled"], + ] { + assert!(!local_command(&parsed(&arguments)), "{arguments:?}"); + } + } + + #[test] + fn local_startup_existing_hook_is_still_synchronous() { + assert!(local_command(&parsed(&[ + "capture", + "hook", + "--agent", + "codex", + "--event", + "prompt", + "--harness-version", + "0.167.0" + ]))); + } + + #[test] + fn local_startup_ready_future_does_not_enter_tokio() { + poll_local( + async { + assert!(tokio::runtime::Handle::try_current().is_err()); + Ok(()) + }, + false, + ) + .unwrap(); + } + + #[test] + fn local_startup_pending_future_is_polled_once_and_refused() { + let mut polls = 0; + let future = std::future::poll_fn(|_| { + polls += 1; + std::task::Poll::Pending + }); + assert!(matches!( + poll_local(future, false), + Err(AppError::Config(_)) + )); + assert_eq!(polls, 1); + } + + #[test] + fn local_startup_ready_failure_is_preserved() { + assert!( + matches!(poll_local(async { Err(AppError::Conflict("finite-refusal".into())) }, false), Err(AppError::Conflict(value)) if value == "finite-refusal") + ); } } diff --git a/src/native_capture_guard.rs b/src/native_capture_guard.rs new file mode 100644 index 0000000..d8c4a58 --- /dev/null +++ b/src/native_capture_guard.rs @@ -0,0 +1,994 @@ +//! Small, content-blind prelaunch guardian: std, libc and SHA-256 only. +#[cfg(any(target_os = "macos", target_os = "linux"))] +mod unix { + use sha2::{Digest, Sha256}; + use std::{ + ffi::{CStr, CString}, + fs::File, + io::{Read, Write}, + os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::{ffi::OsStrExt, fs::MetadataExt, process::CommandExt}, + }, + path::{Component, Path, PathBuf}, + process::{Command, Stdio}, + time::{Duration, Instant}, + }; + const PENDING: &[u8] = b"KEITO_CAPTURE_PENDING_V1\n"; + const ACK: &[u8] = b"KEITO_CAPTURE_DURABLE_V1\n"; + fn c(value: &std::ffi::OsStr) -> Result { + CString::new(value.as_bytes()).map_err(|_| ()) + } + fn root_path() -> Result { + if let Some(path) = std::env::var_os("KEITO_CAPTURE_HOME") { + return Ok(path.into()); + } + let mut buffer = vec![0u8; 65536]; + let mut entry = std::mem::MaybeUninit::::uninit(); + let mut result = std::ptr::null_mut(); + if unsafe { + libc::getpwuid_r( + libc::geteuid(), + entry.as_mut_ptr(), + buffer.as_mut_ptr().cast(), + buffer.len(), + &mut result, + ) + } != 0 + || result.is_null() + { + return Err(()); + } + let entry = unsafe { entry.assume_init() }; + if entry.pw_dir.is_null() { + return Err(()); + } + let home = PathBuf::from(std::ffi::OsStr::from_bytes( + unsafe { CStr::from_ptr(entry.pw_dir) }.to_bytes(), + )); + #[cfg(target_os = "macos")] + { + Ok(home.join("Library/Application Support/keito/capture")) + } + #[cfg(not(target_os = "macos"))] + { + Ok(home.join(".config/keito/capture")) + } + } + fn directory(path: &Path, private_last: usize) -> Result { + directory_open(path, private_last, true) + } + fn directory_open(path: &Path, private_last: usize, create: bool) -> Result { + if !path.is_absolute() + || path + .as_os_str() + .as_bytes() + .split(|b| *b == b'/') + .any(|p| p == b"." || p == b"..") + { + return Err(()); + } + let fd = unsafe { + libc::open( + c(Path::new("/").as_os_str())?.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(()); + } + let mut parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let parts: Vec<_> = path + .components() + .filter_map(|p| { + if let Component::Normal(p) = p { + Some(p) + } else { + None + } + }) + .collect(); + for (i, part) in parts.iter().enumerate() { + let name = c(part)?; + let mut fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + if create + && fd < 0 + && std::io::Error::last_os_error().kind() == std::io::ErrorKind::NotFound + { + if unsafe { libc::mkdirat(parent.as_raw_fd(), name.as_ptr(), 0o700) } != 0 + && std::io::Error::last_os_error().kind() != std::io::ErrorKind::AlreadyExists + { + return Err(()); + } + if unsafe { libc::fsync(parent.as_raw_fd()) } != 0 { + return Err(()); + } + fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + } + if fd < 0 { + return Err(()); + } + parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let meta = File::from(parent.try_clone().map_err(|_| ())?) + .metadata() + .map_err(|_| ())?; + let uid = unsafe { libc::geteuid() }; + if meta.uid() != 0 && meta.uid() != uid { + return Err(()); + } + if i + private_last >= parts.len() + && (meta.uid() != uid || meta.mode() & 0o777 != 0o700) + { + return Err(()); + } + } + Ok(parent.into()) + } + fn executable(path: &Path, expected: &str) -> Result { + if expected.len() != 64 + || !expected + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err(()); + } + let parent = directory_open(path.parent().ok_or(())?, 0, false)?; + let name = c(path.file_name().ok_or(())?)?; + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(()); + } + let mut file = unsafe { File::from_raw_fd(fd) }; + let before = file.metadata().map_err(|_| ())?; + if !before.is_file() + || before.nlink() != 1 + || before.mode() & 0o111 == 0 + || before.mode() & 0o022 != 0 + || before.len() > 128 * 1024 * 1024 + || before.uid() != 0 && before.uid() != unsafe { libc::geteuid() } + { + return Err(()); + } + let mut hash = Sha256::new(); + let mut buffer = [0u8; 65536]; + let mut length = 0; + loop { + let n = file.read(&mut buffer).map_err(|_| ())?; + if n == 0 { + break; + } + length += n; + if length > 128 * 1024 * 1024 { + return Err(()); + } + hash.update(&buffer[..n]); + } + let actual: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect(); + let after = file.metadata().map_err(|_| ())?; + if actual != expected + || before.len() != after.len() + || before.mode() != after.mode() + || before.uid() != after.uid() + || before.mtime() != after.mtime() + || before.mtime_nsec() != after.mtime_nsec() + { + return Err(()); + } + Ok(file) + } + fn open(parent: &File, name: &str, flags: i32) -> Result { + let name = CString::new(name).map_err(|_| ())?; + let started = Instant::now(); + let fd = loop { + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + flags | libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK, + 0o600, + ) + }; + if fd >= 0 { + break fd; + } + let error = std::io::Error::last_os_error(); + // APFS can report ENOENT for concurrent non-exclusive O_CREAT + // on this shared lockfile. Retry only that bounded creation path. + if flags & libc::O_CREAT == 0 + || flags & libc::O_EXCL != 0 + || !matches!( + error.raw_os_error(), + Some(libc::ENOENT | libc::EINTR | libc::EAGAIN) + ) + || started.elapsed() >= Duration::from_millis(25) + { + return Err(()); + } + std::thread::sleep(Duration::from_millis(1)); + }; + let file = unsafe { File::from_raw_fd(fd) }; + let m = file.metadata().map_err(|_| ())?; + if !m.is_file() + || m.nlink() != 1 + || m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != 0o600 + { + return Err(()); + } + Ok(file) + } + fn lock(file: &File) -> bool { + let start = Instant::now(); + loop { + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + return true; + } + if start.elapsed() >= Duration::from_millis(25) { + return false; + } + std::thread::sleep(Duration::from_millis(1)); + } + } + fn unlock(file: &File) { + unsafe { + libc::flock(file.as_raw_fd(), libc::LOCK_UN); + } + } + // Rust File::sync_all uses F_FULLFSYNC on Apple. This protocol specifies + // POSIX fsync, matching the existing capture ledger/adapter contract. + fn sync(file: &File) -> Result<(), ()> { + let started = Instant::now(); + loop { + if unsafe { libc::fsync(file.as_raw_fd()) } == 0 { + return Ok(()); + } + if std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted + || started.elapsed() >= Duration::from_millis(25) + || crate::process_ownership::signals::pending() + { + return Err(()); + } + } + } + fn flush_rename_publication_with( + publication: &File, + flags: &File, + flush: impl FnOnce(&File) -> Result<(), ()>, + ) -> Result<(), ()> { + // The preparing entry was already durable before rename. Namespace + // mutation stays exclusive, while its flush need not serialize other + // publishers. The marker remains EX-locked, and core launch still + // requires this flush to succeed. Unlink cleanup keeps its old barrier. + unlock(publication); + flush(flags) + } + fn set_errno(value: i32) { + #[cfg(target_os = "macos")] + unsafe { + *libc::__error() = value; + } + #[cfg(target_os = "linux")] + unsafe { + *libc::__errno_location() = value; + } + } + fn errno() -> i32 { + #[cfg(target_os = "macos")] + unsafe { + *libc::__error() + } + #[cfg(target_os = "linux")] + unsafe { + *libc::__errno_location() + } + } + fn count_entries(directory: &File, prefix: Option<&[u8]>) -> Result { + let fd = unsafe { libc::fcntl(directory.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) }; + if fd < 0 { + return Err(()); + } + let stream = unsafe { libc::fdopendir(fd) }; + if stream.is_null() { + unsafe { + libc::close(fd); + } + return Err(()); + } + let mut count = 0; + loop { + set_errno(0); + let entry = unsafe { libc::readdir(stream) }; + if entry.is_null() { + let failed = errno() != 0; + unsafe { + libc::closedir(stream); + } + return if failed { Err(()) } else { Ok(count) }; + } + let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }.to_bytes(); + if !matches!(name, b"." | b"..") && prefix.is_none_or(|p| name.starts_with(p)) { + count += 1; + } + if count >= 1024 { + break; + } + } + unsafe { + libc::closedir(stream); + } + Ok(count) + } + enum PrelaunchRefusal { + Capacity, + Boundary, + } + fn publish_prelaunch_refusal( + state: &File, + nonce: &str, + reason: PrelaunchRefusal, + ) -> Result<(), ()> { + // Existing refusal saturation already forces a paused core. Never + // evict another unresolved boundary to make room for this one. + if count_entries(state, Some(b"capture-refusal-"))? >= 1024 { + return Err(()); + } + let temporary = format!(".capture-refusal-{nonce}.tmp"); + let final_name = format!("capture-refusal-{nonce}.json"); + let mut file = open( + state, + &temporary, + libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL, + )?; + let now = unsafe { libc::time(std::ptr::null_mut()) }; + let reason = match reason { + PrelaunchRefusal::Capacity => "QUEUE_LIMIT_REACHED", + PrelaunchRefusal::Boundary => "BOUNDARY_REFUSED", + }; + let bytes = format!( + "{{\"reason\":\"{reason}\",\"boundary_id\":\"{nonce}\",\"observed_at\":{now}}}" + ); + file.write_all(bytes.as_bytes()).map_err(|_| ())?; + sync(&file)?; + if unsafe { + libc::renameat( + state.as_raw_fd(), + CString::new(temporary).unwrap().as_ptr(), + state.as_raw_fd(), + CString::new(final_name).unwrap().as_ptr(), + ) + } != 0 + { + return Err(()); + } + sync(state) + } + fn prepare_marker_with( + state: &File, + publication: &File, + nonce: &str, + serialize: bool, + create: impl FnOnce() -> Result, + ) -> Result, ()> { + // Darwin's O_EXLOCK makes create+ownership atomic. Linux has no such + // open flag: serialize ONLY visible creation and the original flock + // against the existing scanner's publication barrier. Never hold this + // barrier across marker writes/fsync or expensive core preparation. + if serialize && !lock(publication) { + // A bounded admission failure is still a lost boundary. Preserve + // immutable evidence without requiring the contended lock. + publish_prelaunch_refusal(state, nonce, PrelaunchRefusal::Boundary)?; + return Ok(None); + } + let result = create().and_then(|marker| if lock(&marker) { Ok(marker) } else { Err(()) }); + if serialize { + unlock(publication); + } + if !serialize { + return result.map(Some); // Retain the original atomic Darwin path. + } + match result { + Ok(marker) => Ok(Some(marker)), + Err(()) => { + publish_prelaunch_refusal(state, nonce, PrelaunchRefusal::Boundary)?; + Ok(None) + } + } + } + pub fn run(args: &[std::ffi::OsString]) -> Result<(), ()> { + // This entry owns no Child before publication. Signals only latch, + // and an interruption still reaches the durable marker check below. + let _prelaunch_signals = crate::process_ownership::signals::install().map_err(|_| ())?; + let started = Instant::now(); + // Share a CLOCK_MONOTONIC absolute bound with core leaf commands. This + // reserves work inside the existing guard budget, never after it. + let leaf_start = crate::process_ownership::scope::monotonic_now().ok(); + if args.len() != 8 { + return Err(()); + } + let mut core = None; + let mut agent = None; + let mut event = None; + let mut version = None; + for pair in args.as_chunks::<2>().0 { + match pair[0].to_str() { + Some("--core") if core.is_none() => core = Some(PathBuf::from(&pair[1])), + Some("--agent") if agent.is_none() => agent = pair[1].to_str(), + Some("--event") if event.is_none() => event = pair[1].to_str(), + Some("--harness-version") if version.is_none() => version = pair[1].to_str(), + _ => return Err(()), + } + } + let core = core.ok_or(())?; + let agent = agent.ok_or(())?; + let event = event.ok_or(())?; + let version = version.ok_or(())?; + if !core.is_absolute() + || !matches!(agent, "codex" | "claude-code") + || !matches!( + event, + "session-start" | "prompt" | "stop" | "interrupt" | "session-end" + ) + || version.is_empty() + || version.len() > 64 + || version.contains("..") + || !version + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._:-".contains(&b)) + { + return Err(()); + } + let root = root_path()?; + let state = directory(&root, 1).map_err(|_| ())?; + let flags = directory(&root.join("capture-invocations"), 2).map_err(|_| ())?; + let publication = open( + &state, + "capture-invocations-publication.lock", + libc::O_RDWR | libc::O_CREAT, + ) + .map_err(|_| ())?; + let mut random = [0u8; 32]; + if unsafe { libc::getentropy(random.as_mut_ptr().cast(), random.len()) } != 0 { + return Err(()); + } + let nonce: String = random.iter().map(|b| format!("{b:02x}")).collect(); + if count_entries(&flags, None).map_err(|_| ())? >= 1024 { + publish_prelaunch_refusal(&state, &nonce, PrelaunchRefusal::Capacity)?; + return Ok(()); + } + let preparing = format!("{nonce}.preparing"); + let pending = format!("{nonce}.pending"); + let marker_flags = libc::O_RDWR | libc::O_CREAT | libc::O_EXCL; + // Darwin can atomically create and lock the visible preparation. + #[cfg(target_os = "macos")] + let marker_flags = marker_flags | libc::O_EXLOCK; + let Some(mut marker) = prepare_marker_with( + &state, + &publication, + &nonce, + cfg!(not(target_os = "macos")), + || open(&flags, &preparing, marker_flags), + )? + else { + return Ok(()); + }; + marker.write_all(PENDING).map_err(|_| ())?; + sync(&marker)?; + sync(&flags)?; + // A live-locked preparing marker is already durable. Keep expensive + // preparation outside the bounded publication critical section. + if !lock(&publication) { + return Ok(()); + } + if unsafe { + libc::renameat( + flags.as_raw_fd(), + CString::new(preparing).unwrap().as_ptr(), + flags.as_raw_fd(), + CString::new(pending.as_str()).unwrap().as_ptr(), + ) + } != 0 + { + return Err(()); + } + flush_rename_publication_with(&publication, &flags, sync)?; + let initial = marker.metadata().map_err(|_| ())?; + if crate::process_ownership::signals::pending() + || started.elapsed() >= Duration::from_millis(600) + { + return Ok(()); + } + // Even a clock refusal must leave the already durable pending marker. + let leaf_end = leaf_start.ok_or(())?.saturating_add(500_000_000); + let hard_end = leaf_start.ok_or(())?.saturating_add(600_000_000); + // Parent validation/clock refusal and all executable preparation occur + // AFTER the durable pending marker. No failed entry loses the boundary. + // Declare the permit first: unwinding drops Scope (including fallback + // cleanup/terminal publication) before releasing scheduling ownership. + let mut core_admission = None; + let mut scope = + match crate::process_ownership::scope::Scope::entry_from_environment(600_000_000) + .map_err(|_| ())? + { + Some(mut scope) => { + scope.tighten_end(hard_end); + scope + } + None => { + crate::process_ownership::scope::Scope::local_entry(hard_end).map_err(|_| ())? + } + }; + let result = (|| { + // Queue before image hashing/descriptor preparation and before any + // core exists. The separate four-leaf pool remains unchanged, so + // cores never wait for leaf permits they themselves hold here. + core_admission = Some( + scope + .await_hook_core_admission(&state, leaf_end) + .map_err(|_| ())?, + ); + // This digest comes from the fixed managed registration, never stdin. + // Linux executes the descriptor. Darwin checks its managed pathname + // immediately before exec and carries this verified imageFD for a + // synchronous identity cross-check before Tokio/CLI parsing. + let expected = std::env::var("KEITO_CAPTURE_CORE_SHA256").map_err(|_| ())?; + let original = executable(&core, &expected)?; + let core_fd = unsafe { libc::fcntl(original.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 5) }; + if !(5..=1024).contains(&core_fd) { + if core_fd >= 0 { + unsafe { + libc::close(core_fd); + } + } + return Err(()); + } + let core_file = unsafe { File::from_raw_fd(core_fd) }; + drop(original); + let mut pipe = [-1; 2]; + if unsafe { libc::pipe(pipe.as_mut_ptr()) } != 0 { + return Err(()); + } + let reader = unsafe { OwnedFd::from_raw_fd(pipe[0]) }; + let writer = unsafe { OwnedFd::from_raw_fd(pipe[1]) }; + for fd in [reader.as_raw_fd(), writer.as_raw_fd()] { + if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 { + return Err(()); + } + } + if unsafe { libc::fcntl(reader.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) } < 0 { + return Err(()); + } + let write_fd = writer.as_raw_fd(); + // Inventory this single-threaded process before fork; Command's own + // later error pipe is CLOEXEC. Never scan or allocate after fork. + let inventory = unsafe { libc::opendir(CString::new("/dev/fd").unwrap().as_ptr()) }; + if inventory.is_null() { + return Err(()); + } + let inventory_fd = unsafe { libc::dirfd(inventory) }; + let mut inherited = Vec::new(); + loop { + set_errno(0); + let entry = unsafe { libc::readdir(inventory) }; + if entry.is_null() { + if errno() != 0 { + unsafe { + libc::closedir(inventory); + } + return Err(()); + } + break; + } + let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }; + if let Some(fd) = name.to_str().ok().and_then(|name| name.parse::().ok()) { + if fd >= 4 && fd != inventory_fd { + inherited.push(fd); + } + } + } + unsafe { + libc::closedir(inventory); + } + #[cfg(target_os = "macos")] + let mut command = Command::new(&core); + #[cfg(not(target_os = "macos"))] + let mut command = Command::new(format!("/dev/fd/{core_fd}")); + let core_name = c(core.as_os_str())?; + let core_identity = core_file.metadata().map_err(|_| ())?; + command + .args([ + "capture", + "hook", + "--agent", + agent, + "--event", + event, + "--harness-version", + version, + ]) + .env("KEITO_CAPTURE_INVOCATION_NONCE", nonce) + .env("KEITO_CAPTURE_ACK_FD", "3") + .env("KEITO_CAPTURE_IMAGE_FD", core_fd.to_string()) + .env("KEITO_CAPTURE_LEAF_END_NS", leaf_end.to_string()) + .stdin(Stdio::inherit()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + unsafe { + command.pre_exec(move || { + // Darwin has no public exec-by-fd. Verify the fixed managed + // path immediately before exec; synchronous core bootstrap + // cross-checks its actual executable inode against imageFD. + let mut current = std::mem::MaybeUninit::::uninit(); + if libc::lstat(core_name.as_ptr(), current.as_mut_ptr()) != 0 { + return Err(std::io::Error::last_os_error()); + } + let current = current.assume_init(); + if current.st_dev as u128 != u128::from(core_identity.dev()) + || u128::from(current.st_ino) != u128::from(core_identity.ino()) + || current.st_mode & libc::S_IFMT != libc::S_IFREG + { + return Err(std::io::Error::from_raw_os_error(libc::ESTALE)); + } + if libc::setsid() < 0 { + return Err(std::io::Error::last_os_error()); + } + if libc::dup2(write_fd, 3) < 0 { + return Err(std::io::Error::last_os_error()); + } + if libc::fcntl(core_fd, libc::F_SETFD, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + if libc::fcntl(3, libc::F_SETFD, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + for fd in &inherited { + if *fd >= 4 && *fd != core_fd { + libc::close(*fd); + } + } + Ok(()) + }); + } + let child = scope.start_hook_core(command, leaf_end).map_err(|_| ())?; + drop(writer); + let mut reader = File::from(reader); + let mut bytes = Vec::with_capacity(ACK.len() + 1); + let mut eof = false; + let mut status = None; + loop { + let mut part = [0u8; 64]; + match reader.read(&mut part) { + Ok(0) => eof = true, + Ok(n) => { + bytes.extend_from_slice(&part[..n]); + if bytes.len() > ACK.len() { + break; + } + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(_) => break, + } + scope.poll(); + status = scope.slot_status(&child); + if scope.slot_complete(&child) && eof { + break; + } + if scope.failed() + || crate::process_ownership::signals::pending() + || started.elapsed() >= Duration::from_millis(600) + { + break; + } + if scope + .wait_hook_core_progress( + &child, + (!eof).then(|| reader.as_raw_fd()), + &mut || Duration::from_millis(600).checked_sub(started.elapsed()), + ) + .is_err() + { + break; + } + } + if !scope.slot_complete(&child) || !eof || bytes != ACK { + scope.begin_cancel( + crate::process_ownership::protocol::ProtocolError("GUARD_CORE_INCOMPLETE"), + scope.hard_end(), + ); + } + let resources_clean = scope.finish().clean; + if resources_clean + && status.is_some_and(|s| s.success()) + && eof + && bytes == ACK + && !crate::process_ownership::signals::pending() + && started.elapsed() < Duration::from_millis(600) + && lock(&publication) + { + if let Ok(current) = open(&flags, &pending, libc::O_RDONLY) { + let m = current.metadata().map_err(|_| ())?; + let mut content = Vec::new(); + current + .take((PENDING.len() + 1) as u64) + .read_to_end(&mut content) + .map_err(|_| ())?; + if m.dev() == initial.dev() + && m.ino() == initial.ino() + && m.len() == PENDING.len() as u64 + && content == PENDING + && unsafe { + libc::unlinkat( + flags.as_raw_fd(), + CString::new(pending).unwrap().as_ptr(), + 0, + ) + } == 0 + { + sync(&flags)?; + } + } + unlock(&publication); + } + Ok(()) + })(); + let clean = scope.finish().clean && result.is_ok(); + scope.publish_terminal(clean); + // Even a failed core keeps its scheduling permit through the final + // cleanup attempt. Process exit/unproved cleanup grants no global bound. + drop(core_admission); + result + } + #[cfg(test)] + mod publication_tests { + use super::*; + use std::os::unix::fs::OpenOptionsExt; + fn owned_file(path: &Path) -> File { + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .unwrap() + } + #[test] + fn preparing_visibility_is_serialized_until_original_marker_is_locked() { + let temp = tempfile::tempdir().unwrap(); + let state = File::open(temp.path()).unwrap(); + let publication_path = temp.path().join("publication.lock"); + let publication = owned_file(&publication_path); + let nonce = "b".repeat(64); + let marker_path = temp.path().join("marker.preparing"); + let marker = prepare_marker_with(&state, &publication, &nonce, true, || { + let file = owned_file(&marker_path); + let observer = File::open(&publication_path).unwrap(); + assert_ne!( + unsafe { libc::flock(observer.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0, + "an observer must not classify the visible but not-yet-locked preparation as dead" + ); + assert_eq!( + std::io::Error::last_os_error().kind(), + std::io::ErrorKind::WouldBlock + ); + Ok(file) + }) + .unwrap() + .unwrap(); + let observer = File::open(&publication_path).unwrap(); + assert_eq!( + unsafe { libc::flock(observer.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0, + "publication must be released before writes/fsync or core preparation" + ); + let probe = File::open(&marker_path).unwrap(); + assert_ne!( + unsafe { libc::flock(probe.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) }, + 0 + ); + drop(marker); + assert_eq!( + unsafe { libc::flock(probe.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) }, + 0, + "an abandoned original marker remains dead, never ignored" + ); + } + #[test] + fn preparing_publication_contention_preserves_lock_independent_failure_evidence() { + let temp = tempfile::tempdir().unwrap(); + let state = File::open(temp.path()).unwrap(); + let path = temp.path().join("publication.lock"); + let held = owned_file(&path); + assert!(lock(&held)); + let publication = File::open(&path).unwrap(); + let nonce = "c".repeat(64); + let mut created = false; + let marker = prepare_marker_with(&state, &publication, &nonce, true, || { + created = true; + Err(()) + }) + .unwrap(); + assert!(marker.is_none()); + assert!( + !created, + "publication refusal must precede a visible unlocked preparation" + ); + let evidence: serde_json::Value = serde_json::from_slice( + &std::fs::read(temp.path().join(format!("capture-refusal-{nonce}.json"))).unwrap(), + ) + .unwrap(); + assert_eq!(evidence["reason"], "BOUNDARY_REFUSED"); + assert_eq!(evidence["boundary_id"], nonce); + } + #[test] + fn rename_flush_releases_publication_but_retains_guardian_marker_lock() { + let temp = tempfile::tempdir().unwrap(); + let flags = File::open(temp.path()).unwrap(); + let publication_path = temp.path().join("publication.lock"); + let marker_path = temp.path().join("pending"); + let publication = owned_file(&publication_path); + let marker = owned_file(&marker_path); + assert!(lock(&publication)); + assert!(lock(&marker)); + flush_rename_publication_with(&publication, &flags, |_| { + let next_publisher = File::open(&publication_path).unwrap(); + assert_eq!( + unsafe { + libc::flock(next_publisher.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) + }, + 0, + "directory flush must not serialize another atomic publication" + ); + let marker_probe = File::open(&marker_path).unwrap(); + assert_ne!( + unsafe { libc::flock(marker_probe.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + assert_eq!( + std::io::Error::last_os_error().kind(), + std::io::ErrorKind::WouldBlock + ); + Ok(()) + }) + .unwrap(); + } + #[test] + fn pending_rename_blocks_real_delivery_during_paused_and_failed_flush() { + use keito_cli::capture::{self, Binding, Clock, Repository, Signal, Store}; + use keito_cli::cli::capture::CaptureEvent::{Prompt, Stop}; + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let mut store = Store::open(&root).unwrap(); + let repository = Repository { + key: capture::hash("fixture"), + remote_hash: capture::hash("remote"), + hint_hash: capture::hash("hint"), + linked_without_hint: false, + disabled: false, + }; + let binding = store + .approve(Binding { + repository_key: repository.key.clone(), + remote_hash: repository.remote_hash.clone(), + hint_hash: repository.hint_hash.clone(), + id: String::new(), + version: 0, + workspace_id: "co_fixture".into(), + owner_id: "owner_fixture".into(), + origin_hash: capture::hash("origin"), + project_id: "project_fixture".into(), + task_id: "task_fixture".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }) + .unwrap(); + let clock = |n: i64| Clock { + wall: 1794067200 + n, + monotonic: 1000 + n, + boot: "fixture".into(), + }; + for (event, n) in [(Prompt, 0), (Stop, 30)] { + store + .event( + &repository, + Signal { + source: "codex", + resumed: false, + source_id: "session_fixture", + turn_id: Some("turn_fixture"), + version: "0.167.0", + event, + clock: &clock(n), + }, + ) + .unwrap(); + } + assert!(store.has_ready(&binding, clock(31).wall).unwrap()); + let flags_path = root.join("capture-invocations"); + std::fs::create_dir_all(&flags_path).unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&flags_path, std::fs::Permissions::from_mode(0o700)).unwrap(); + let flags = File::open(&flags_path).unwrap(); + let publication = owned_file(&root.join("capture-invocations-publication.lock")); + let nonce = capture::hash("unlaunched-guard"); + let preparing = flags_path.join(format!("{nonce}.preparing")); + let pending = flags_path.join(format!("{nonce}.pending")); + let mut marker = owned_file(&preparing); + assert!(lock(&marker)); + marker.write_all(PENDING).unwrap(); + sync(&marker).unwrap(); + sync(&flags).unwrap(); + assert!(lock(&publication)); + std::fs::rename(&preparing, &pending).unwrap(); + assert!(flush_rename_publication_with(&publication, &flags, |_| { + assert!(!store.has_ready(&binding, clock(31).wall).unwrap()); + assert!(store.claim(&binding, clock(31).wall).unwrap().is_none()); + Err(()) + }) + .is_err()); + assert_eq!(std::fs::read(&pending).unwrap(), PENDING); + assert!(!store.has_ready(&binding, clock(31).wall).unwrap()); + assert!(store.claim(&binding, clock(31).wall).unwrap().is_none()); + drop(marker); + assert!(!store.has_ready(&binding, clock(32).wall).unwrap()); + assert!(store.claim(&binding, clock(32).wall).unwrap().is_none()); + } + #[test] + fn rename_flush_failure_stays_failure_without_relocking_or_removing_marker() { + let temp = tempfile::tempdir().unwrap(); + let flags = File::open(temp.path()).unwrap(); + let publication_path = temp.path().join("publication.lock"); + let marker_path = temp.path().join("pending"); + let publication = owned_file(&publication_path); + let mut marker = owned_file(&marker_path); + marker.write_all(PENDING).unwrap(); + assert!(lock(&publication)); + assert!(lock(&marker)); + let mut called = 0; + assert!(flush_rename_publication_with(&publication, &flags, |_| { + called += 1; + let next_publisher = File::open(&publication_path).unwrap(); + assert_eq!( + unsafe { + libc::flock(next_publisher.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) + }, + 0 + ); + Err(()) + }) + .is_err()); + assert_eq!(called, 1); + assert_eq!(std::fs::read(&marker_path).unwrap(), PENDING); + } + } +} +#[cfg(unix)] +pub fn run(args: &[std::ffi::OsString]) -> Result<(), ()> { + #[cfg(any(target_os = "macos", target_os = "linux"))] + { + unix::run(args) + } + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + { + let _ = args; + Err(()) + } +} diff --git a/src/process_entry.rs b/src/process_entry.rs new file mode 100644 index 0000000..ef955bf --- /dev/null +++ b/src/process_entry.rs @@ -0,0 +1,115 @@ +//! Closed CLI entry classification; no child API is exposed before parsing. +use crate::{ + cli, + process_ownership::{ + protocol::ProtocolError, + scope::{self, Scope}, + }, +}; +use std::io; + +pub struct PendingEntry { + origin: u64, + ceiling: u64, + scope: Option, +} +fn direct_installer(command: Option<&cli::Command>) -> bool { + matches!( + command, + Some(cli::Command::Skill(cli::skill::SkillCommand { + command: cli::skill::SkillSubcommand::Install { .. }, + })) + ) +} +fn selected_end(origin: u64, ceiling: u64, installer: bool) -> io::Result { + origin + .checked_add(if installer { + scope::INSTALL_OPERATION_NS + } else { + 1_000_000_000 + }) + .map(|end| end.min(ceiling)) + .ok_or_else(|| io::Error::other("SCOPE_CLOCK")) +} +impl PendingEntry { + pub fn attach() -> io::Result { + let origin = scope::monotonic_now()?; + let ceiling = selected_end(origin, u64::MAX, true)?; + let scope = Scope::attach_at(origin, ceiling)?; + Ok(Self { + origin, + ceiling, + scope, + }) + } + /// Consumed once. A failed selection still returns its retained attachment. + pub fn select(mut self, command: Option<&cli::Command>) -> (Option, io::Result<()>) { + let installer = direct_installer(command); + let result = (|| { + let end = selected_end(self.origin, self.ceiling, installer)?; + if self.scope.is_none() && installer { + self.scope = Some(Scope::local_entry(end)?); + } + if let Some(scope) = self.scope.as_mut() { + scope.refine_entry(end)?; + } + Ok(()) + })(); + if result.is_err() { + if let Some(scope) = self.scope.as_mut() { + if !scope.failed() { + scope.begin_cancel(ProtocolError("SCOPE_ENTRY_SELECTION"), 0); + } + } + } + (self.scope.take(), result) + } +} +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + #[test] + fn installer_entry_classifier_is_typed_and_preserves_the_original_origin() { + let install = + cli::Cli::try_parse_from(["keito", "skill", "install", "--agent", "codex"]).unwrap(); + let auth = cli::Cli::try_parse_from(["keito", "auth", "status"]).unwrap(); + assert!(direct_installer(Some(&install.command))); + assert!(!direct_installer(Some(&auth.command))); + assert!(!direct_installer(None)); + assert_eq!( + selected_end(100_000_000, u64::MAX, true).unwrap(), + 30_100_000_000 + ); + assert_eq!( + selected_end(100_000_000, u64::MAX, false).unwrap(), + 1_100_000_000 + ); + assert_eq!( + selected_end(100_000_000, 300_000_000, true).unwrap(), + 300_000_000 + ); + assert!(selected_end(u64::MAX, u64::MAX, true).is_err()); + } + #[test] + fn installer_policy_preserves_earlier_parents_and_other_entry_limits() { + let origin = 100_000_000; + assert_eq!( + selected_end(origin, u64::MAX, true).unwrap(), + 30_100_000_000 + ); + assert_eq!( + selected_end(origin, 4_000_000_000, true).unwrap(), + 4_000_000_000 + ); + assert_eq!( + selected_end(origin, u64::MAX, false).unwrap(), + 1_100_000_000 + ); + assert_eq!( + selected_end(origin, 300_000_000, false).unwrap(), + 300_000_000 + ); + assert!(selected_end(u64::MAX - 20_000_000_000, u64::MAX, true).is_err()); + } +} diff --git a/src/process_ownership/attachment.rs b/src/process_ownership/attachment.rs new file mode 100644 index 0000000..2eec2ab --- /dev/null +++ b/src/process_ownership/attachment.rs @@ -0,0 +1,146 @@ +//! Complete-or-absent cancellation attachment. This is never capture authority. +use std::{ + io, + os::fd::{AsRawFd, FromRawFd}, + os::unix::net::UnixStream, +}; +pub(super) const KEYS: [&str; 5] = [ + "KEITO_PROCESS_OWNER_FD", + "KEITO_PROCESS_OWNER_NONCE", + "KEITO_PROCESS_OWNER_PID", + "KEITO_PROCESS_OWNER_END_NS", + "KEITO_PROCESS_OWNER_CONTRACT", +]; +pub(super) fn present() -> bool { + KEYS.into_iter() + .chain(["KEITO_SOURCE_OWNER_FD", "KEITO_SOURCE_OWNER_NONCE"]) + .any(|key| std::env::var_os(key).is_some()) +} +fn error() -> io::Error { + io::Error::other("OWNER_ATTACHMENT") +} +pub(super) struct Attachment { + pub nonce: String, + pub parent: u32, + pub end: u64, +} +fn number(value: &str) -> Option { + let n = value.parse::().ok()?; + (n > 0 && n.to_string() == value).then_some(n) +} +pub(super) fn parse( + values: &[Option; 5], + parent: u32, + at: u64, + end: u64, +) -> io::Result> { + if values.iter().all(Option::is_none) { + return Ok(None); + } + let values = values.each_ref().map(|v| v.as_deref().ok_or_else(error)); + let [fd, nonce, pid, inherited, contract] = values; + let (fd, nonce, pid, inherited, contract) = (fd?, nonce?, pid?, inherited?, contract?); + let inherited = number(inherited).filter(|n| *n > at).ok_or_else(error)?; + if fd != "4" + || contract != "2" + || number(pid) != Some(u64::from(parent)) + || parent == 0 + || parent > i32::MAX as u32 + || nonce.len() != 32 + || !nonce + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err(error()); + } + Ok(Some(Attachment { + nonce: nonce.into(), + parent, + end: end.min(inherited), + })) +} +pub(super) fn consume(at: u64, end: u64) -> io::Result> { + // Legacy metadata is a partial/incompatible attachment, never ignored. + if ["KEITO_SOURCE_OWNER_FD", "KEITO_SOURCE_OWNER_NONCE"] + .iter() + .any(|k| std::env::var_os(k).is_some()) + { + return Err(error()); + } + let mut values: [Option; 5] = Default::default(); + for (i, key) in KEYS.iter().enumerate() { + values[i] = match std::env::var(key) { + Ok(v) => Some(v), + Err(std::env::VarError::NotPresent) => None, + Err(_) => return Err(error()), + }; + } + let Some(attachment) = parse(&values, unsafe { libc::getppid() } as u32, at, end)? else { + return Ok(None); + }; + let mut kind = 0; + let mut length = std::mem::size_of::() as libc::socklen_t; + let mut address = unsafe { std::mem::zeroed::() }; + let mut size = std::mem::size_of_val(&address) as libc::socklen_t; + if unsafe { + libc::getsockopt( + 4, + libc::SOL_SOCKET, + libc::SO_TYPE, + (&mut kind as *mut i32).cast(), + &mut length, + ) + } != 0 + || kind != libc::SOCK_STREAM + || unsafe { + libc::getsockname( + 4, + (&mut address as *mut libc::sockaddr_storage).cast(), + &mut size, + ) + } != 0 + || i32::from(address.ss_family) != libc::AF_UNIX + { + return Err(error()); + } + let stream = unsafe { UnixStream::from_raw_fd(4) }; + if unsafe { libc::fcntl(stream.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } < 0 { + return Err(error()); + } + // Retain the tuple as a fail-closed sentinel for any convenience API that + // has not received the explicit owner. It cannot consume this CLOEXEC FD. + Ok(Some((attachment, stream))) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn r41_parent_tuple_is_complete_canonical_direct_and_cancellation_only() { + let good = + ["4", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "42", "1000", "2"].map(|s| Some(s.into())); + assert!(parse(&Default::default(), 42, 100, 900).unwrap().is_none()); + let a = parse(&good, 42, 100, 900).unwrap().unwrap(); + assert_eq!(a.end, 900); + assert_eq!(a.parent, 42); + for i in 0..5 { + let mut partial = good.clone(); + partial[i] = None; + assert!(parse(&partial, 42, 100, 900).is_err()); + } + for (i, invalid) in [ + (0, "3"), + (0, "04"), + (1, "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), + (2, "43"), + (2, "042"), + (3, "100"), + (3, "01000"), + (4, "1"), + ] { + let mut bad = good.clone(); + bad[i] = Some(invalid.into()); + assert!(parse(&bad, 42, 100, 900).is_err()); + } + } +} diff --git a/src/process_ownership/group.rs b/src/process_ownership/group.rs new file mode 100644 index 0000000..f817cf4 --- /dev/null +++ b/src/process_ownership/group.rs @@ -0,0 +1,4408 @@ +//! Shared Unix reserved group cleanup. Not connected to product commands yet. +//! +//! The keeper is a sibling, never a wrapper/ancestor of the workload. Only the +//! keeper queries or signals its own reserved PGID. An opaque same-session tool +//! may use this lease; the guardian's setsid core must be a cooperative owner. +use super::protocol::{ProtocolError, SharedOwner}; +use std::{ + ffi::OsStr, + fs, + io::{self, Read, Write}, + os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::{fs::MetadataExt, net::UnixStream, process::CommandExt}, + }, + path::Path, + process::{Child, Command, ExitStatus, Stdio}, + time::Duration, +}; + +const MAX_FRAME: usize = 256; +const MAX_WIRE: usize = 4096; +const CLEANUP_NS: u64 = 1_800_000_000; +const TERM_NS: u64 = 15_000_000; +const MAX_LIFETIME_NS: u64 = 900_000_000_000; + +/// Closed policies, not caller-supplied timeout extensions. The short policy +/// must fit inside an inherited product end; it is not a latency qualification. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CleanupPolicy { + Legacy, + HookShort, + CommandProbe, +} +impl CleanupPolicy { + fn reserve_ns(self) -> u64 { + match self { + Self::Legacy => CLEANUP_NS, + Self::HookShort | Self::CommandProbe => 50_000_000, + } + } + fn term_ns(self) -> u64 { + TERM_NS + } + fn setup_ns(self) -> u64 { + match self { + Self::Legacy => CLEANUP_NS, + Self::HookShort => 20_000_000, + // No independent relative setup interval; setup_end uses H-50ms. + Self::CommandProbe => 0, + } + } + fn keeper_tag(tag: Option<&str>) -> io::Result { + match tag { + None => Ok(Self::Legacy), + Some("hook-short-v1") => Ok(Self::HookShort), + Some("command-probe-v1") => Ok(Self::CommandProbe), + _ => Err(refused("KEEPER_POLICY")), + } + } + fn setup_end(self, at: u64, hard_end: u64) -> u64 { + let operation_end = hard_end.saturating_sub(self.reserve_ns()); + match self { + Self::CommandProbe => operation_end, + Self::Legacy | Self::HookShort => at.saturating_add(self.setup_ns()).min(operation_end), + } + } + fn observation_end(self, at: u64, inherited_end: u64) -> u64 { + at.saturating_add(self.reserve_ns()).min(inherited_end) + } +} + +fn refused(reason: &'static str) -> io::Error { + io::Error::other(reason) +} +fn now() -> io::Result { + let mut clock = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, clock.as_mut_ptr()) } != 0 { + return Err(refused("GROUP_CLOCK")); + } + let clock = unsafe { clock.assume_init() }; + u64::try_from(clock.tv_sec) + .ok() + .and_then(|seconds| seconds.checked_mul(1_000_000_000)) + .and_then(|seconds| seconds.checked_add(clock.tv_nsec as u64)) + .ok_or_else(|| refused("GROUP_CLOCK")) +} +fn number(value: &str) -> io::Result { + if value.is_empty() + || value.len() > 20 + || (value.len() > 1 && value.starts_with('0')) + || !value.bytes().all(|v| v.is_ascii_digit()) + { + return Err(refused("GROUP_INTEGER")); + } + value.parse().map_err(|_| refused("GROUP_INTEGER")) +} + +// The owning descriptor is retained through admission; invalid values close on refusal. +fn keeper_fd_allowed(value: u64) -> bool { + (4..=1024).contains(&value) +} + +fn admit_keeper_fd(owned: T, value: u64) -> io::Result { + if keeper_fd_allowed(value) { + Ok(owned) + } else { + Err(refused("GROUP_FD")) + } +} + +fn fixed_ready_frame( + ready_end: u64, + hard_end: u64, + policy: CleanupPolicy, + mut clock: impl FnMut() -> io::Result, + wait: impl FnOnce(u64) -> io::Result, +) -> io::Result { + let deadline = ready_end.min(hard_end.saturating_sub(policy.reserve_ns())); + if clock()? >= deadline { + return Err(refused("GROUP_DEADLINE")); + } + let body = wait(deadline)?; + if clock()? >= deadline { + return Err(refused("GROUP_DEADLINE")); + } + Ok(body) +} + +fn nonce_valid(value: &str) -> bool { + value.len() == 32 + && value + .bytes() + .all(|v| v.is_ascii_digit() || (b'a'..=b'f').contains(&v)) +} +fn pause() { + std::thread::sleep(Duration::from_millis(1)); +} + +#[derive(Default)] +struct ParkObservation { + #[cfg(feature = "dev-tools")] + before: Option, + #[cfg(feature = "dev-tools")] + frame_observed: bool, + #[cfg(feature = "dev-tools")] + deadline: Option<(&'static str, u64)>, +} +fn poll_park_frame( + channel: &mut Channel, + expected: impl FnOnce() -> String, + end: u64, + clock: &mut impl FnMut() -> io::Result, + observation: &mut ParkObservation, +) -> io::Result { + let before = clock()?; + #[cfg(feature = "dev-tools")] + { + observation.before = Some(before); + } + #[cfg(not(feature = "dev-tools"))] + let _ = observation; + if before >= end { + #[cfg(feature = "dev-tools")] + { + observation.deadline = Some(("PARK_BEFORE_RECEIVE", before)); + } + return Err(refused("GROUP_DEADLINE")); + } + let body = channel.receive()?; + let after = clock()?; + #[cfg(feature = "dev-tools")] + { + observation.frame_observed |= body.is_some(); + } + if after >= end { + #[cfg(feature = "dev-tools")] + { + observation.deadline = Some(("PARK_AFTER_RECEIVE", after)); + } + return Err(refused("GROUP_DEADLINE")); + } + let Some(body) = body else { + return if channel.eof { + Err(refused("GROUP_EOF")) + } else { + Ok(false) + }; + }; + if body != expected() { + return Err(refused("GROUP_PARK")); + } + Ok(true) +} + +/// No cached PID is a signalling capability. This machine permits GONE only +/// while the keeper reservation is held and forbids all operations afterward. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Phase { + AwaitReady, + Ready, + Joined, + Parked, + Cleaning, + Gone, + Released, + Failed, +} +struct Progress { + phase: Phase, + first_fault: Option<&'static str>, + deadline_ns: u64, + secondary_faults: Vec<&'static str>, +} +impl Progress { + fn new(deadline_ns: u64) -> Self { + Self { + phase: Phase::AwaitReady, + first_fault: None, + deadline_ns, + secondary_faults: Vec::new(), + } + } + fn advance(&mut self, from: Phase, to: Phase) -> io::Result<()> { + let valid = matches!( + (from, to), + (Phase::AwaitReady, Phase::Ready) + | (Phase::Ready, Phase::Joined) + | (Phase::Joined, Phase::Parked) + | (Phase::Parked, Phase::Cleaning) + | (Phase::Cleaning, Phase::Gone) + | (Phase::Gone, Phase::Released) + ); + if self.first_fault.is_some() || self.phase != from || !valid { + self.fail("GROUP_STATE"); + return Err(refused(self.first_fault.unwrap())); + } + self.phase = to; + Ok(()) + } + fn begin_cleanup(&mut self) -> io::Result<()> { + match self.phase { + Phase::AwaitReady | Phase::Ready | Phase::Joined | Phase::Parked => { + self.phase = Phase::Cleaning; + Ok(()) + } + Phase::Cleaning | Phase::Gone => Ok(()), + _ => Err(refused("GROUP_STATE")), + } + } + fn shorten(&mut self, deadline_ns: u64) { + self.deadline_ns = self.deadline_ns.min(deadline_ns); + } + fn fail(&mut self, reason: &'static str) { + if let Some(first) = self.first_fault { + if reason != first + && !self.secondary_faults.contains(&reason) + && self.secondary_faults.len() < 8 + { + self.secondary_faults.push(reason); + } + } else { + self.first_fault = Some(reason); + } + self.phase = Phase::Failed; + } + #[cfg(test)] + fn may_touch_group(&self) -> bool { + matches!(self.phase, Phase::Parked | Phase::Cleaning) && self.first_fault.is_none() + } +} + +/// No complete frame is different from a drained transport. A budget yield +/// must not authorize the keeper's next query/signal step. +enum Receive { + Frame(String), + // A whole rejected line was consumed; its known boundary permits bounded + // failure-only draining. This is NOT evidence of transport quiescence. + Rejected(&'static str), + Quiescent, + Eof, + BudgetYield, +} + +/// Separate closed keeper protocol. No paths/content/auth/capture fields. +struct Channel { + stream: S, + nonce: String, + pending: Vec, + wire: usize, + eof: bool, +} +impl Channel { + fn cleanup_wait_source(&self) -> Option { + (!self.eof).then(|| self.stream.as_raw_fd()) + } + fn new(stream: UnixStream, nonce: String) -> io::Result { + if !nonce_valid(&nonce) { + return Err(refused("GROUP_NONCE")); + } + stream.set_nonblocking(true)?; + if unsafe { libc::fcntl(stream.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } < 0 { + return Err(refused("GROUP_FD")); + } + Ok(Self { + stream, + nonce, + pending: Vec::new(), + wire: 0, + eof: false, + }) + } +} +impl Channel { + fn cleanup_buffered_event(&self) -> bool { + self.pending.contains(&b'\n') || (self.eof && !self.pending.is_empty()) + } + fn buffered_event(&self) -> bool { + self.eof || self.pending.contains(&b'\n') + } + fn charge(&mut self, bytes: usize) -> io::Result<()> { + self.wire = self + .wire + .checked_add(bytes) + .filter(|n| *n <= MAX_WIRE) + .ok_or_else(|| refused("GROUP_WIRE_LIMIT"))?; + Ok(()) + } + fn send(&mut self, body: &str) -> io::Result<()> { + if !body.is_ascii() + || body.contains(['\n', '\r']) + || body.len() + 34 > MAX_FRAME + || self.eof + { + return Err(refused("GROUP_FRAME")); + } + let bytes = format!("{}|{}\n", self.nonce, body); + self.charge(bytes.len())?; + if self + .stream + .write(bytes.as_bytes()) + .map_err(|_| refused("GROUP_WRITE"))? + != bytes.len() + { + return Err(refused("GROUP_SHORT_WRITE")); + } + Ok(()) + } + fn receive_event(&mut self) -> io::Result { + for _ in 0..8 { + if let Some(end) = self.pending.iter().position(|v| *v == b'\n') { + let line: Vec<_> = self.pending.drain(..=end).collect(); + if line.len() > MAX_FRAME || !line.is_ascii() { + return Ok(Receive::Rejected("GROUP_FRAME")); + } + let Ok(text) = std::str::from_utf8(&line[..line.len() - 1]) else { + return Ok(Receive::Rejected("GROUP_FRAME")); + }; + let Some((nonce, body)) = text.split_once('|') else { + return Ok(Receive::Rejected("GROUP_FRAME")); + }; + if nonce != self.nonce || body.contains('\r') { + return Ok(Receive::Rejected("GROUP_NONCE")); + } + return Ok(Receive::Frame(body.to_owned())); + } + if self.pending.len() >= MAX_FRAME { + return Err(refused("GROUP_FRAME_LIMIT")); + } + if self.eof { + return Ok(Receive::Eof); + } + let mut bytes = [0u8; MAX_FRAME]; + match self.stream.read(&mut bytes) { + Ok(0) => { + self.eof = true; + if !self.pending.is_empty() { + return Err(refused("GROUP_TRUNCATED")); + } + return Ok(Receive::Eof); + } + Ok(n) => { + self.charge(n)?; + self.pending.extend_from_slice(&bytes[..n]); + } + Err(error) if error.kind() == io::ErrorKind::WouldBlock => { + return Ok(if self.pending.is_empty() { + Receive::Quiescent + } else { + Receive::BudgetYield + }) + } + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(_) => return Err(refused("GROUP_READ")), + } + } + Ok(Receive::BudgetYield) + } + // Parent frame polling performs no group operations. Its EOF predicate is + // still separate; a budget yield cannot satisfy terminal+EOF proof. + fn receive(&mut self) -> io::Result> { + match self.receive_event()? { + Receive::Frame(body) => Ok(Some(body)), + Receive::Rejected(reason) => Err(refused(reason)), + Receive::Quiescent | Receive::Eof | Receive::BudgetYield => Ok(None), + } + } + fn wait_frame(&mut self, deadline: u64) -> io::Result { + while now()? < deadline { + if let Some(frame) = self.receive()? { + return Ok(frame); + } + if self.eof { + return Err(refused("GROUP_EOF")); + } + pause(); + } + Err(refused("GROUP_DEADLINE")) + } +} + +/// Cleanup is reserved INSIDE the admitted lifetime, never added after expiry. +#[derive(Clone, Copy)] +struct Lifetime { + operation_end: u64, + hard_end: u64, + policy: CleanupPolicy, +} +impl Lifetime { + fn new(at: u64, hard_end: u64) -> io::Result { + Self::with_policy(at, hard_end, CleanupPolicy::Legacy) + } + fn with_policy(at: u64, hard_end: u64, policy: CleanupPolicy) -> io::Result { + let remaining = hard_end + .checked_sub(at) + .ok_or_else(|| refused("GROUP_LIFETIME"))?; + if remaining <= policy.reserve_ns() || remaining > MAX_LIFETIME_NS { + return Err(refused("GROUP_LIFETIME")); + } + Ok(Self { + operation_end: hard_end - policy.reserve_ns(), + hard_end, + policy, + }) + } +} + +/// Returned even on failure by report(); waits do not rehabilitate clean proof. +#[derive(Clone, Debug)] +pub struct GroupReport { + /// Known direct handles only; these numbers are metadata, never authority + /// for a caller to query or signal a cached PID/group. + pub keeper_pid: u32, + pub workload_pid: Option, + pub first_fault: Option<&'static str>, + pub secondary_faults: Vec<&'static str>, + pub workload_spawned: bool, + pub workload_status: Option, + pub keeper_status: Option, + pub group_absent: bool, + pub release_sent: bool, + pub terminal_eof: bool, +} +/// Actual direct wait facts, separate from the keeper's group-absence evidence. +#[derive(Debug)] +pub struct GroupProof { + pub workload_status: Option, + pub keeper_status: ExitStatus, + pub group_absent: bool, +} + +// The same wait/protocol driver is exercised by finite fake handles; no child +// or group syscall is needed to test faulted/expired explicit finalization. +trait DirectWait { + fn try_wait(&mut self) -> io::Result>; +} +impl DirectWait for Child { + fn try_wait(&mut self) -> io::Result> { + Child::try_wait(self) + } +} +struct Settlement { + progress: Progress, + workload_status: Option, + keeper_status: Option, + cleanup_sent: bool, + release_sent: bool, + group_absent: bool, + expected_ready: Option, + expected_park: Option, + policy: CleanupPolicy, +} +impl Settlement { + fn progress_wait_end(&self) -> u64 { + self.progress.deadline_ns + } + fn new(hard_end: u64) -> Self { + Self::with_policy(hard_end, CleanupPolicy::Legacy) + } + fn with_policy(hard_end: u64, policy: CleanupPolicy) -> Self { + Self { + progress: Progress::new(hard_end), + workload_status: None, + keeper_status: None, + cleanup_sent: false, + release_sent: false, + group_absent: false, + expected_ready: None, + expected_park: None, + policy, + } + } + fn cap_failed_observation(&mut self, at: Option, requested: u64) { + // No usable clock means no newly granted observation interval. + let end = at + .map(|at| self.policy.observation_end(at, requested)) + .unwrap_or(0); + self.progress.shorten(end); + } + fn begin(&mut self, deadline_ns: u64, at: u64, channel: &mut Channel) -> io::Result<()> { + if let Some(first) = self.progress.first_fault { + return Err(refused(first)); + } + // RELEASE+write EOF seals the last shared bound. A later reduction + // is explicitly refused (never silently accepted only in parent). + if self.release_sent { + return if deadline_ns < self.progress.deadline_ns { + Err(refused("GROUP_BOUND_SEALED")) + } else { + Ok(()) + }; + } + let end = deadline_ns + .min(at.saturating_add(self.policy.reserve_ns())) + .min(self.progress.deadline_ns); + if !self.cleanup_sent || end < self.progress.deadline_ns { + channel.send(&format!("CLEAN|{end}"))?; + self.progress.shorten(end); + } + self.cleanup_sent = true; + // Includes explicit pre-READY cancellation. The queued READY must + // still be parsed and matched before a GONE can be accepted. + self.progress.begin_cleanup()?; + Ok(()) + } + fn collect(&mut self, keeper: &mut impl DirectWait, workload: Option<&mut impl DirectWait>) { + // Both known handles get an attempt, even after first failure/deadline. + if self.workload_status.is_none() { + if let Some(child) = workload { + match child.try_wait() { + Ok(status) => self.workload_status = status, + Err(_) => self.progress.fail("GROUP_WORKLOAD_WAIT"), + } + } + } + if self.keeper_status.is_none() { + match keeper.try_wait() { + Ok(status) => self.keeper_status = status, + Err(_) => self.progress.fail("GROUP_KEEPER_WAIT"), + } + } + } + fn poll( + &mut self, + clock: &mut impl FnMut() -> io::Result, + pid: libc::pid_t, + channel: &mut Channel, + keeper: &mut impl DirectWait, + workload: Option<&mut impl DirectWait>, + ) -> io::Result> { + let has_workload = workload.is_some(); + self.collect(keeper, workload); + if self.progress.phase == Phase::Released && self.progress.first_fault.is_none() { + return Ok(Some(GroupProof { + workload_status: self.workload_status, + keeper_status: self.keeper_status.unwrap(), + group_absent: true, + })); + } + let at = match clock() { + Ok(at) => at, + Err(_) => { + self.progress.fail("GROUP_CLOCK"); + return Err(refused(self.progress.first_fault.unwrap())); + } + }; + if !self.cleanup_sent { + self.progress.fail("GROUP_CLEANUP_NOT_STARTED"); + } + if at >= self.progress.deadline_ns { + self.progress.fail("GROUP_CLEANUP_DEADLINE"); + } + if let Some(reason) = self.progress.first_fault { + return Err(refused(reason)); + } + let outcome = (|| { + let body = channel.receive()?; + if clock()? >= self.progress.deadline_ns { + return Err(refused("GROUP_CLEANUP_DEADLINE")); + } + if let Some(body) = body { + if let Some(expected) = &self.expected_ready { + if body != *expected { + return Err(refused("GROUP_READY")); + } + self.expected_ready = None; + } else if let Some(expected) = &self.expected_park { + if body != *expected { + return Err(refused("GROUP_PARK")); + } + self.expected_park = None; + } else { + if body != format!("GONE|{pid}") || self.progress.phase != Phase::Cleaning { + return Err(refused("GROUP_TERMINAL")); + } + self.progress.advance(Phase::Cleaning, Phase::Gone)?; + self.group_absent = true; + } + } + if channel.eof && !self.release_sent { + return Err(refused("GROUP_EARLY_EOF")); + } + if self.progress.phase == Phase::Gone + && (!has_workload || self.workload_status.is_some()) + && !self.release_sent + { + if clock()? >= self.progress.deadline_ns { + return Err(refused("GROUP_CLEANUP_DEADLINE")); + } + channel.send("RELEASE")?; + channel + .stream + .shutdown(std::net::Shutdown::Write) + .map_err(|_| refused("GROUP_SHUTDOWN"))?; + self.release_sent = true; + } + if let Some(status) = self.keeper_status { + if !status.success() { + return Err(refused("GROUP_KEEPER_FAILED")); + } + if channel.eof && channel.pending.is_empty() && self.release_sent { + if clock()? >= self.progress.deadline_ns { + return Err(refused("GROUP_CLEANUP_DEADLINE")); + } + self.progress.advance(Phase::Gone, Phase::Released)?; + return Ok(Some(GroupProof { + workload_status: self.workload_status, + keeper_status: status, + group_absent: true, + })); + } + } + Ok(None) + })(); + if let Err(error) = &outcome { + self.progress.fail(safe_reason(error)); + } + outcome + } +} +// Only literals generated here enter durable diagnostics; never raw OS errors. +fn safe_reason(error: &io::Error) -> &'static str { + match error.to_string().as_str() { + "GROUP_CLEANUP_DEADLINE" => "GROUP_CLEANUP_DEADLINE", + "GROUP_NONCE" => "GROUP_NONCE", + "GROUP_FRAME" => "GROUP_FRAME", + "GROUP_FRAME_LIMIT" => "GROUP_FRAME_LIMIT", + "GROUP_WIRE_LIMIT" => "GROUP_WIRE_LIMIT", + "GROUP_TRUNCATED" => "GROUP_TRUNCATED", + "GROUP_READ" => "GROUP_READ", + "GROUP_WRITE" => "GROUP_WRITE", + "GROUP_SHORT_WRITE" => "GROUP_SHORT_WRITE", + "GROUP_TERMINAL" => "GROUP_TERMINAL", + "GROUP_SHUTDOWN" => "GROUP_SHUTDOWN", + "GROUP_EARLY_EOF" => "GROUP_EARLY_EOF", + "GROUP_KEEPER_FAILED" => "GROUP_KEEPER_FAILED", + "GROUP_EOF" => "GROUP_EOF", + "GROUP_DEADLINE" => "GROUP_DEADLINE", + "GROUP_CLOCK" => "GROUP_CLOCK", + "GROUP_STATE" => "GROUP_STATE", + "GROUP_ADMISSION" => "GROUP_ADMISSION", + "GROUP_READY" => "GROUP_READY", + "GROUP_PARK" => "GROUP_PARK", + "GROUP_SPAWN" => "GROUP_SPAWN", + "GROUP_START_STATE" => "GROUP_START_STATE", + "GROUP_BOUND_SEALED" => "GROUP_BOUND_SEALED", + _ => "GROUP_IO", + } +} + +/// Developer-only observations, never a timing or cleanup capability. +#[cfg(feature = "dev-tools")] +#[derive(Clone, Copy, Debug, Default)] +pub struct SetupTrace { + pub setup_start_ns: u64, + pub ready_end_ns: u64, + pub pre_spawn_ns: u64, + pub spawn_return_ns: Option, + pub first_ready_poll_ns: Option, + pub last_ready_before_ns: Option, + pub last_ready_after_ns: Option, + pub ready_frame_observed: bool, + pub ready_eof_observed: bool, + pub deadline_observed: Option<(&'static str, u64)>, + pub fault_origin: Option<(&'static str, &'static str)>, + pub park_end_ns: Option, + pub workload_spawn_return_ns: Option, + pub first_park_poll_ns: Option, + pub park_frame_observed: bool, +} + +#[cfg(feature = "dev-tools")] +impl SetupTrace { + fn note_fault_origin(&mut self, owner: &SharedOwner, phase: Phase, reason: &'static str) { + // Only the edge that first poisons the containing owner may claim it. + // Sibling cancellation and later cleanup cannot replace that origin. + if owner.borrow().first_fault.is_none() && self.fault_origin.is_none() { + let state = match phase { + Phase::AwaitReady => "AWAIT_READY", + Phase::Ready => "READY", + Phase::Joined => "JOINED", + Phase::Parked => "PARKED", + Phase::Cleaning => "CLEANING", + Phase::Gone => "GONE", + Phase::Released => "RELEASED", + Phase::Failed => "FAILED", + }; + self.fault_origin = Some((reason, state)); + } + } +} + +/// Register immediately after spawn_keeper, BEFORE await_ready/start/receipts. +/// Failed objects retain both handles and expose actual wait facts via report. +pub struct GroupLease { + keeper: Child, + workload: Option, + #[cfg(not(feature = "dev-tools"))] + settlement: Settlement, + #[cfg(feature = "dev-tools")] + settlement: Box, + channel: Channel, + owner: SharedOwner, + keeper_pid: libc::pid_t, + owner_pgid: libc::pid_t, + sid: libc::pid_t, + ready_end: u64, + park_end: Option, + #[cfg(feature = "dev-tools")] + setup_trace: Box, +} +#[derive(Clone, Copy)] +enum KeeperProgram<'a> { + Owned { root: &'a Path, image: &'a Path }, + Verified(&'a super::image::VerifiedKeeperImage), +} +impl GroupLease { + // Cleanup consumes this channel on its ORIGINAL next settlement turn. + // Known physical EOF is omitted: a remaining Child::try_wait has no FD. + pub(super) fn cleanup_wait_source(&self) -> Option { + self.channel.cleanup_wait_source() + } + pub(super) fn cleanup_buffered_event(&self) -> bool { + self.channel.cleanup_buffered_event() + } + pub(super) fn progress_wait_end(&self) -> u64 { + // Lifetime/actual shortened cleanup end, NEVER ready_end/park_end. + self.settlement.progress_wait_end() + } + pub(super) fn setup_buffered_event(&self) -> bool { + self.channel.buffered_event() + } + pub(super) fn setup_wait_source(&self) -> (i32, u64) { + ( + self.channel.stream.as_raw_fd(), + self.park_end.unwrap_or(self.ready_end), + ) + } + pub fn spawn_keeper( + owner: SharedOwner, + run_root: &Path, + keeper_image: &Path, + lifetime_deadline_ns: u64, + ) -> io::Result { + Self::spawn_keeper_with_policy( + owner, + run_root, + keeper_image, + lifetime_deadline_ns, + CleanupPolicy::Legacy, + ) + } + /// Explicit short policy for same-session leaves. Product image authority, + /// cooperative core and I/O wiring remain separate prerequisites. + pub fn spawn_keeper_with_policy( + owner: SharedOwner, + run_root: &Path, + keeper_image: &Path, + lifetime_deadline_ns: u64, + policy: CleanupPolicy, + ) -> io::Result { + // The public QA-owned image API must not grant ordinary-command setup + // policy to an arbitrary caller-supplied lifetime or image. + if policy == CleanupPolicy::CommandProbe { + return Err(refused("GROUP_POLICY")); + } + Self::spawn( + owner, + KeeperProgram::Owned { + root: run_root, + image: keeper_image, + }, + lifetime_deadline_ns, + policy, + ) + } + pub(crate) fn spawn_verified_keeper( + owner: SharedOwner, + image: &super::image::VerifiedKeeperImage, + lifetime_deadline_ns: u64, + ) -> io::Result { + Self::spawn_verified_keeper_with_policy( + owner, + image, + lifetime_deadline_ns, + CleanupPolicy::HookShort, + ) + } + pub(crate) fn spawn_verified_keeper_with_policy( + owner: SharedOwner, + image: &super::image::VerifiedKeeperImage, + lifetime_deadline_ns: u64, + policy: CleanupPolicy, + ) -> io::Result { + Self::spawn( + owner, + KeeperProgram::Verified(image), + lifetime_deadline_ns, + policy, + ) + } + fn spawn( + owner: SharedOwner, + program: KeeperProgram<'_>, + lifetime_deadline_ns: u64, + policy: CleanupPolicy, + ) -> io::Result { + owner + .borrow() + .check_admission() + .map_err(|_| refused("GROUP_ADMISSION"))?; + let current = now()?; + if Lifetime::with_policy(current, lifetime_deadline_ns, policy).is_err() { + return Err(refused("GROUP_LIFETIME")); + } + if let KeeperProgram::Owned { + root: run_root, + image: keeper_image, + } = program + { + for path in [run_root, keeper_image] { + if !path.is_absolute() || path.canonicalize().ok().as_deref() != Some(path) { + return Err(refused("GROUP_OWNED_PATH")); + } + } + let root = fs::symlink_metadata(run_root)?; + let image = fs::symlink_metadata(keeper_image)?; + if !root.is_dir() + || root.uid() != unsafe { libc::geteuid() } + || root.mode() & 0o777 != 0o700 + || !keeper_image.starts_with(run_root) + || !image.is_file() + || image.file_type().is_symlink() + || image.uid() != root.uid() + || image.nlink() != 1 + || image.mode() & 0o777 != 0o700 + { + return Err(refused("GROUP_OWNED_PATH")); + } + } + let mut random = [0u8; 16]; + if unsafe { libc::getentropy(random.as_mut_ptr().cast(), random.len()) } != 0 { + return Err(refused("GROUP_RANDOM")); + } + let nonce: String = random.iter().map(|v| format!("{v:02x}")).collect(); + let (parent, child_end) = UnixStream::pair()?; + let inherited = unsafe { libc::fcntl(child_end.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 4) }; + if inherited < 0 { + return Err(refused("GROUP_FD")); + } + let inherited = unsafe { OwnedFd::from_raw_fd(inherited) }; + let child_fd = inherited.as_raw_fd(); + let inherited = admit_keeper_fd(inherited, child_fd as u64)?; + let channel = Channel::new(parent, nonce.clone())?; + let owner_pid = std::process::id(); + let owner_pgid = unsafe { libc::getpgrp() }; + let sid = unsafe { libc::getsid(0) }; + let (mut command, image_descriptor, cwd) = match program { + KeeperProgram::Owned { root, image } => (Command::new(image), None, root), + KeeperProgram::Verified(image) => { + let (command, fd) = image.command(child_fd)?; + (command, Some(fd), Path::new("/")) + } + }; + command + .env_clear() + .current_dir(cwd) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .args([ + child_fd.to_string(), + nonce, + owner_pid.to_string(), + owner_pgid.to_string(), + sid.to_string(), + lifetime_deadline_ns.to_string(), + ]); + match policy { + CleanupPolicy::Legacy => {} + CleanupPolicy::HookShort => { + command.arg("hook-short-v1"); + } + CleanupPolicy::CommandProbe => { + command.arg("command-probe-v1"); + } + } + if let Some(image) = &image_descriptor { + command.env( + super::image::VerifiedKeeperImage::image_env(), + image.as_raw_fd().to_string(), + ); + } + // Core Foundation may initialize before this helper's main. Supply + // synthetic UID/zero encoding metadata instead of consulting the + // operator's encoding file. No auth/profile value is inherited. + #[cfg(target_os = "macos")] + command.env( + "__CF_USER_TEXT_ENCODING", + format!("0x{:X}:0:0", unsafe { libc::getuid() }), + ); + unsafe { + command.pre_exec(move || { + if libc::setpgid(0, 0) != 0 || libc::fcntl(child_fd, libc::F_SETFD, 0) < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + // Verification/inventory cannot consume an old admission timestamp and + // then start a keeper beyond its setup/operation end. + // Allocate developer metadata BEFORE the fresh pre-spawn check and + // BEFORE any Child exists; it does not extend the fixed setup end. + #[cfg(feature = "dev-tools")] + let mut setup_trace = Box::new(SetupTrace { + setup_start_ns: current, + ready_end_ns: policy.setup_end(current, lifetime_deadline_ns), + pre_spawn_ns: 0, + spawn_return_ns: None, + first_ready_poll_ns: None, + last_ready_before_ns: None, + last_ready_after_ns: None, + ready_frame_observed: false, + ready_eof_observed: false, + deadline_observed: None, + fault_origin: None, + ..Default::default() + }); + #[cfg(feature = "dev-tools")] + let mut settlement = Box::new(if policy == CleanupPolicy::Legacy { + Settlement::new(lifetime_deadline_ns) + } else { + Settlement::with_policy(lifetime_deadline_ns, policy) + }); + let pre_spawn = now()?; + #[cfg(feature = "dev-tools")] + { + setup_trace.pre_spawn_ns = pre_spawn; + } + if pre_spawn >= policy.setup_end(current, lifetime_deadline_ns) { + return Err(refused("GROUP_DEADLINE")); + } + let mask = super::signals::AdmissionMask::block(&mut command)?; + let keeper = command.spawn()?; + let keeper_pid = keeper.id() as libc::pid_t; + // The real handle is owned before any fallible read or publication. + #[cfg(not(feature = "dev-tools"))] + let mut settlement = if policy == CleanupPolicy::Legacy { + Settlement::new(lifetime_deadline_ns) + } else { + Settlement::with_policy(lifetime_deadline_ns, policy) + }; + settlement.expected_ready = Some(format!("READY|{keeper_pid}|{keeper_pid}|{sid}")); + let lease = Self { + keeper, + workload: None, + settlement, + channel, + owner, + keeper_pid, + owner_pgid, + sid, + ready_end: policy.setup_end(current, lifetime_deadline_ns), + park_end: None, + #[cfg(feature = "dev-tools")] + setup_trace, + }; + // Diagnostic only: the actual Child is already retained in the lease. + // An unavailable observation grants no new time and changes no check. + #[cfg(feature = "dev-tools")] + let lease = { + let mut lease = lease; + lease.setup_trace.spawn_return_ns = now().ok(); + lease + }; + drop(mask); + drop(image_descriptor); + drop(inherited); + drop(child_end); + // Return BEFORE READY I/O. The caller registers even a failing + // preparation in its owned registry before calling await_ready. + Ok(lease) + } + + fn fail(&mut self, reason: &'static str) { + #[cfg(feature = "dev-tools")] + self.setup_trace + .note_fault_origin(&self.owner, self.settlement.progress.phase, reason); + self.settlement.progress.fail(reason); + let first = self.settlement.progress.first_fault.unwrap(); + self.owner.borrow_mut().poison(ProtocolError(first)); + if let Some(child) = &mut self.workload { + child.stdin.take(); + } + // EOF requests failure-only keeper cleanup even when CLEAN cannot be + // sent. No parent group authority is acquired by this failure path. + if self + .channel + .stream + .shutdown(std::net::Shutdown::Write) + .is_err() + { + self.settlement.progress.fail("GROUP_SHUTDOWN"); + } + } + fn checked(&mut self, result: io::Result) -> io::Result { + if let Err(error) = &result { + self.fail(safe_reason(error)); + } + result + } + fn check_admission(&mut self) -> io::Result<()> { + if self.owner.borrow().check_admission().is_err() { + self.fail("GROUP_ADMISSION"); + return Err(refused("GROUP_ADMISSION")); + } + Ok(()) + } + pub fn await_ready(&mut self) -> io::Result<()> { + let result = (|| { + self.check_admission()?; + if self.settlement.progress.phase != Phase::AwaitReady { + return Err(refused("GROUP_STATE")); + } + let body = fixed_ready_frame( + self.ready_end, + self.settlement.progress.deadline_ns, + self.settlement.policy, + now, + |deadline| self.channel.wait_frame(deadline), + )?; + if body != format!("READY|{}|{}|{}", self.keeper_pid, self.keeper_pid, self.sid) { + return Err(refused("GROUP_READY")); + } + self.settlement.expected_ready = None; + self.settlement + .progress + .advance(Phase::AwaitReady, Phase::Ready)?; + self.check_admission() + })(); + self.checked(result) + } + /// One bounded READY turn for the product runner. The setup cap was fixed + /// before keeper spawn; an incomplete read never grants a fresh interval. + pub(super) fn poll_ready(&mut self) -> io::Result { + let result = (|| { + self.check_admission()?; + if self.settlement.progress.phase != Phase::AwaitReady { + return Err(refused("GROUP_STATE")); + } + let before = now()?; + #[cfg(feature = "dev-tools")] + { + self.setup_trace.first_ready_poll_ns.get_or_insert(before); + self.setup_trace.last_ready_before_ns = Some(before); + } + if before >= self.ready_end { + #[cfg(feature = "dev-tools")] + self.setup_trace + .deadline_observed + .get_or_insert(("READY_BEFORE_RECEIVE", before)); + return Err(refused("GROUP_DEADLINE")); + } + let body = self.channel.receive()?; + let after = now()?; + #[cfg(feature = "dev-tools")] + { + self.setup_trace.last_ready_after_ns = Some(after); + self.setup_trace.ready_frame_observed |= body.is_some(); + self.setup_trace.ready_eof_observed |= self.channel.eof; + } + if after >= self.ready_end { + #[cfg(feature = "dev-tools")] + self.setup_trace + .deadline_observed + .get_or_insert(("READY_AFTER_RECEIVE", after)); + return Err(refused("GROUP_DEADLINE")); + } + let Some(body) = body else { + if self.channel.eof { + return Err(refused("GROUP_EOF")); + } + return Ok(false); + }; + if Some(&body) != self.settlement.expected_ready.as_ref() { + return Err(refused("GROUP_READY")); + } + self.settlement.expected_ready = None; + self.settlement + .progress + .advance(Phase::AwaitReady, Phase::Ready)?; + Ok(true) + })(); + self.checked(result) + } + /// Consume the ORIGINAL prepared Command. Its join callback can never escape + /// back to a caller for reuse after release. No argv/env/FD reconstruction. + fn spawn_joined(&mut self, mut command: Command) -> io::Result<()> { + self.check_admission()?; + if self.settlement.progress.phase != Phase::Ready || self.workload.is_some() { + return Err(refused("GROUP_START_STATE")); + } + if now()? + >= self + .settlement + .progress + .deadline_ns + .saturating_sub(self.settlement.policy.reserve_ns()) + { + return Err(refused("GROUP_DEADLINE")); + } + let pgid = self.keeper_pid; + let sid = self.sid; + unsafe { + command.pre_exec(move || { + if libc::getsid(0) != sid || libc::setpgid(0, pgid) != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + let mask = super::signals::AdmissionMask::block(&mut command)?; + let child = command.spawn().map_err(|_| refused("GROUP_SPAWN"))?; + self.workload = Some(child); + drop(mask); + if super::signals::pending() { + return Err(refused("GROUP_INTERRUPTED")); + } + self.settlement + .progress + .advance(Phase::Ready, Phase::Joined)?; + Ok(()) + } + pub fn start(&mut self, command: Command) -> io::Result<()> { + let result = (|| { + self.spawn_joined(command)?; + self.check_admission()?; + self.channel.send("PARK")?; + let response = self.channel.wait_frame( + self.settlement + .policy + .setup_end(now()?, self.settlement.progress.deadline_ns), + )?; + if response + != format!( + "PARKED|{}|{}|{}", + self.keeper_pid, self.owner_pgid, self.sid + ) + { + return Err(refused("GROUP_PARK")); + } + self.settlement + .progress + .advance(Phase::Joined, Phase::Parked) + })(); + self.checked(result) + } + /// Retain the original workload and return before PARKED. Pipes can then + /// be owned/drained by Scope while this handshake remains pending. + pub(super) fn start_pending(&mut self, command: Command) -> io::Result<()> { + let result = (|| { + self.check_admission()?; + if self.settlement.progress.phase != Phase::Ready || self.workload.is_some() { + return Err(refused("GROUP_START_STATE")); + } + let at = now()?; + let end = self + .settlement + .policy + .setup_end(at, self.settlement.progress.deadline_ns); + if at >= end { + return Err(refused("GROUP_DEADLINE")); + } + #[cfg(feature = "dev-tools")] + { + self.setup_trace.park_end_ns = Some(end); + } + let joined = self.spawn_joined(command); + #[cfg(feature = "dev-tools")] + if self.workload.is_some() { + // The actual Child is already retained. This optional sample + // cannot change admission, time bounds or ownership on error. + self.setup_trace.workload_spawn_return_ns = now().ok(); + } + joined?; + self.park_end = Some(end); + self.settlement.expected_park = Some(format!( + "PARKED|{}|{}|{}", + self.keeper_pid, self.owner_pgid, self.sid + )); + self.check_admission()?; + self.channel.send("PARK") + })(); + self.checked(result) + } + pub(super) fn poll_parked(&mut self) -> io::Result { + let result = (|| { + self.check_admission()?; + if self.settlement.progress.phase != Phase::Joined { + return Err(refused("GROUP_STATE")); + } + let end = self.park_end.ok_or_else(|| refused("GROUP_STATE"))?; + let expected = (self.keeper_pid, self.owner_pgid, self.sid); + let mut observation = ParkObservation::default(); + let received = poll_park_frame( + &mut self.channel, + || format!("PARKED|{}|{}|{}", expected.0, expected.1, expected.2), + end, + &mut now, + &mut observation, + ); + #[cfg(feature = "dev-tools")] + { + if let Some(before) = observation.before { + self.setup_trace.first_park_poll_ns.get_or_insert(before); + } + self.setup_trace.park_frame_observed |= observation.frame_observed; + if let Some(deadline) = observation.deadline { + self.setup_trace.deadline_observed.get_or_insert(deadline); + } + } + if !received? { + return Ok(false); + } + self.settlement.expected_park = None; + self.settlement + .progress + .advance(Phase::Joined, Phase::Parked)?; + Ok(true) + })(); + self.checked(result) + } + pub(super) fn poll_workload(&mut self) -> io::Result> { + self.settlement + .collect(&mut self.keeper, self.workload.as_mut()); + if self.settlement.keeper_status.is_some() { + self.fail("GROUP_KEEPER_FAILED"); + } + if let Some(reason) = self.settlement.progress.first_fault { + return Err(refused(reason)); + } + Ok(self.settlement.workload_status) + } + /// Transferred pipes MUST have a caller-scoped close/drain/EOF owner. Neither + /// GroupProof nor terminal keeper EOF proves those output streams drained. + pub fn stdin(&mut self) -> Option { + self.workload.as_mut()?.stdin.take() + } + pub fn stdout(&mut self) -> Option { + self.workload.as_mut()?.stdout.take() + } + pub fn stderr(&mut self) -> Option { + self.workload.as_mut()?.stderr.take() + } + pub fn begin_cleanup(&mut self, deadline_ns: u64) -> io::Result<()> { + self.owner.borrow_mut().admission_closed = true; + self.begin_local_cleanup(deadline_ns) + } + /// Slot-local settlement does not close containing admission. An operation + /// fault still poisons Scope, but does not itself invalidate an intact + /// keeper channel's independent resource observations. + pub(super) fn begin_local_cleanup(&mut self, deadline_ns: u64) -> io::Result<()> { + if let Some(child) = &mut self.workload { + child.stdin.take(); + } + let clock = now(); + let at = clock.as_ref().ok().copied(); + let result = clock.and_then(|at| self.settlement.begin(deadline_ns, at, &mut self.channel)); + let result = self.checked(result); + if result.is_err() { + // Scope's common failed-observation bound still applies when a + // poisoned/sending-failed lease cannot form a clean wire proof. + // This is local failure retention only, never a clean bound ACK. + self.settlement.cap_failed_observation(at, deadline_ns); + } + result + } + pub fn poll_cleanup(&mut self) -> io::Result> { + // A sibling owner fault cannot be rehabilitated by this lease's trace. + let owner_fault = self.owner.borrow().first_fault; + if let Some(reason) = owner_fault { + self.fail(reason.0); + } + self.poll_local_cleanup() + } + pub(super) fn poll_local_cleanup(&mut self) -> io::Result> { + // Always collect available waits, including on clock failure/expiry. + let result = self.settlement.poll( + &mut now, + self.keeper_pid, + &mut self.channel, + &mut self.keeper, + self.workload.as_mut(), + ); + // Preserve first specific literal; never replace it with a wrapper. + if result.is_err() { + let reason = self + .settlement + .progress + .first_fault + .unwrap_or_else(|| safe_reason(result.as_ref().err().unwrap())); + self.fail(reason); + } + result + } + pub fn report(&self) -> GroupReport { + GroupReport { + keeper_pid: self.keeper.id(), + workload_pid: self.workload.as_ref().map(Child::id), + first_fault: self.settlement.progress.first_fault, + secondary_faults: self.settlement.progress.secondary_faults.clone(), + workload_spawned: self.workload.is_some(), + workload_status: self.settlement.workload_status, + keeper_status: self.settlement.keeper_status, + group_absent: self.settlement.group_absent, + release_sent: self.settlement.release_sent, + terminal_eof: self.channel.eof && self.channel.pending.is_empty(), + } + } + pub(super) fn registration_nonce(&self) -> &str { + &self.channel.nonce + } + #[cfg(feature = "dev-tools")] + pub(super) fn setup_trace(&self) -> SetupTrace { + *self.setup_trace + } +} +impl Drop for GroupLease { + fn drop(&mut self) { + if self.settlement.progress.phase == Phase::Released { + return; + } + self.fail("GROUP_DROPPED_WITHOUT_PROOF"); + // Failure fallback only. One nonblocking collection runs even if the + // proof deadline passed. Explicit owner must retain report/unknowns. + self.settlement + .collect(&mut self.keeper, self.workload.as_mut()); + let deadline = self + .settlement + .policy + .observation_end(now().unwrap_or(0), self.settlement.progress.deadline_ns); + while now().unwrap_or(deadline) < deadline { + self.settlement + .collect(&mut self.keeper, self.workload.as_mut()); + if self.settlement.keeper_status.is_some() + && (self.workload.is_none() || self.settlement.workload_status.is_some()) + { + break; + } + pause(); + } + } +} + +trait GroupOps { + fn park(&mut self) -> io::Result<()>; + fn absent(&mut self) -> io::Result; + fn signal(&mut self, signal: libc::c_int) -> io::Result<()>; + fn abandon_self_group(&mut self) -> io::Result<()>; + fn disable(&mut self); +} +struct KeeperGroup { + pid: libc::pid_t, + park: libc::pid_t, + parked: bool, + no_more_group_ops: bool, +} +impl GroupOps for KeeperGroup { + fn park(&mut self) -> io::Result<()> { + if !self.parked { + if self.no_more_group_ops || unsafe { libc::setpgid(0, self.park) } != 0 { + return Err(refused("KEEPER_PARK")); + } + self.parked = true; + } + Ok(()) + } + fn absent(&mut self) -> io::Result { + if !self.parked || self.no_more_group_ops { + return Err(refused("KEEPER_GROUP_AUTHORITY")); + } + if unsafe { libc::kill(-self.pid, 0) } == 0 { + return Ok(false); + } + if io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) { + return Ok(true); + } + Err(refused("KEEPER_GROUP_QUERY")) + } + fn signal(&mut self, signal: libc::c_int) -> io::Result<()> { + if !self.parked || self.no_more_group_ops { + return Err(refused("KEEPER_GROUP_AUTHORITY")); + } + if unsafe { libc::kill(-self.pid, signal) } != 0 + && io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) + { + return Err(refused("KEEPER_GROUP_SIGNAL")); + } + Ok(()) + } + fn abandon_self_group(&mut self) -> io::Result<()> { + // Failure only: parent parking group vanished before PARK. Our live PID + // still reserves THIS group, of which we are still a member. SIGKILL + // includes this keeper, so no GONE/proof or subsequent operation exists. + if self.parked + || self.no_more_group_ops + || unsafe { libc::getpid() } != self.pid + || unsafe { libc::getpgrp() } != self.pid + { + return Err(refused("KEEPER_SELF_GROUP_AUTHORITY")); + } + self.no_more_group_ops = true; + if unsafe { libc::kill(-self.pid, libc::SIGKILL) } != 0 { + return Err(refused("KEEPER_SELF_GROUP_SIGNAL")); + } + Err(refused("KEEPER_SELF_GROUP_UNPROVEN")) + } + fn disable(&mut self) { + self.no_more_group_ops = true; + } +} + +// Incremental cleanup: control reductions/EOF are consumed between steps; TERM +// grace is set once, never restarted. Every group syscall checks the same end. +struct KeeperSession { + group: G, + lifetime: Lifetime, + end: u64, + cleaning: bool, + parked: bool, + park_requested: bool, + term_end: Option, + killed: bool, + gone: bool, + released: bool, + abandoned: bool, + authority_stopped: bool, + first_fault: Option<&'static str>, +} +impl KeeperSession { + fn new(group: G, lifetime: Lifetime) -> Self { + Self { + group, + lifetime, + end: lifetime.hard_end, + cleaning: false, + parked: false, + park_requested: false, + term_end: None, + killed: false, + gone: false, + released: false, + abandoned: false, + authority_stopped: false, + first_fault: None, + } + } + fn fail(&mut self, reason: &'static str, at: u64) { + self.first_fault.get_or_insert(reason); + if !self.cleaning && !self.gone { + self.cleaning = true; + self.end = self + .end + .min(at.saturating_add(self.lifetime.policy.reserve_ns())); + } + } + fn check_authority(&self) -> io::Result<()> { + if self.authority_stopped { + return Err(refused( + self.first_fault.unwrap_or("KEEPER_AUTHORITY_STOPPED"), + )); + } + Ok(()) + } + fn stop_authority(&mut self, reason: &'static str, at: u64) { + self.fail(reason, at); + if !self.authority_stopped { + self.authority_stopped = true; + self.park_requested = false; + // Logical disable only: do not query/signal a group when a possibly + // unread stricter bound is unavailable. FAILED/unknown, not GONE. + self.group.disable(); + } + } + fn control(&mut self, body: &str, at: u64) -> io::Result<()> { + self.check_authority()?; + if at >= self.end { + return Err(refused("KEEPER_CLEANUP_DEADLINE")); + } + if self.released { + return Err(refused("KEEPER_TRAILING_RELEASE")); + } + if let Some(end) = body.strip_prefix("CLEAN|") { + self.end = self + .end + .min(number(end)?) + .min(at.saturating_add(self.lifetime.policy.reserve_ns())); + self.cleaning = true; + Ok(()) + } else if body == "RELEASE" && self.gone && self.first_fault.is_none() { + self.released = true; + Ok(()) + } else { + Err(refused("KEEPER_STATE")) + } + } + fn check_time(&self, clock: &mut impl FnMut() -> io::Result) -> io::Result { + self.check_authority()?; + let at = clock()?; + if at >= self.end { + return Err(refused("KEEPER_CLEANUP_DEADLINE")); + } + Ok(at) + } + fn park(&mut self, clock: &mut impl FnMut() -> io::Result) -> io::Result<()> { + self.check_time(clock)?; + if let Err(error) = self.group.park() { + self.first_fault.get_or_insert("KEEPER_PARK"); + // Check the bound again after the failed syscall. No extra grace. + self.check_time(clock)?; + self.abandoned = true; + self.group.abandon_self_group()?; + return Err(error); + } + self.parked = true; + Ok(()) + } + fn step(&mut self, clock: &mut impl FnMut() -> io::Result) -> io::Result { + self.check_authority()?; + if self.abandoned { + return Err(refused("KEEPER_SELF_GROUP_UNPROVEN")); + } + let at = clock()?; + if !self.cleaning && at >= self.lifetime.operation_end { + self.fail("KEEPER_LIFETIME", at); + } + if at >= self.end { + return Err(refused("KEEPER_CLEANUP_DEADLINE")); + } + if !self.cleaning || self.gone { + return Ok(false); + } + if !self.parked { + self.park(clock)?; + } + self.check_time(clock)?; + if self.group.absent()? { + self.group.disable(); + self.gone = true; + return Ok(true); + } + if let Some(term_end) = self.term_end { + if !self.killed && clock()? >= term_end { + self.check_time(clock)?; + self.killed = true; + self.group.signal(libc::SIGKILL)?; + } + } else { + let at = self.check_time(clock)?; + self.term_end = Some(at.saturating_add(self.lifetime.policy.term_ns())); + self.group.signal(libc::SIGTERM)?; + } + Ok(false) + } +} + +#[derive(Debug, PartialEq, Eq)] +enum Turn { + Again, + Finished, +} +fn keeper_turn( + session: &mut KeeperSession, + channel: &mut Channel, + pid: libc::pid_t, + park: u64, + sid: u64, + clock: &mut impl FnMut() -> io::Result, +) -> io::Result { + session.check_authority()?; + let at = clock()?; + if at >= session.end { + return Err(refused("KEEPER_CLEANUP_DEADLINE")); + } + // Drain bounded traffic BEFORE the next syscall step. When the parse + // cap is reached, yield without group ops; reductions cannot sit behind + // already-buffered control traffic while signalling proceeds. + let mut drained = false; + for _ in 0..8 { + match channel.receive_event() { + Ok(Receive::Frame(body)) + if session.first_fault.is_none() || body.starts_with("CLEAN|") => + { + let result = if body == "PARK" + && !session.parked + && !session.cleaning + && !session.park_requested + { + // Pure bounded intent only. Even membership changes and + // the failure self-kill must wait for the minimum drain. + session.park_requested = true; + Ok(()) + } else { + session.control(&body, clock()?) + }; + if result.is_err() { + session.fail("KEEPER_CONTROL", clock()?); + } + } + // Failure remains irreversible. Only canonical CLEAN can tighten + // its bound; no PARK/RELEASE/GONE/proof path is reopened. + Ok(Receive::Frame(_)) => (), + Ok(Receive::Rejected(_)) => session.fail("KEEPER_CHANNEL", clock()?), + Ok(Receive::BudgetYield) => return Ok(Turn::Again), + Ok(Receive::Quiescent | Receive::Eof) => { + drained = true; + break; + } + Err(_) => { + // No known frame boundary/drain fact: stop authority rather + // than act under an end that may have been superseded unread. + session.stop_authority("KEEPER_CHANNEL", clock()?); + return Err(refused(session.first_fault.unwrap())); + } + } + } + if channel.eof { + if session.released && session.first_fault.is_none() { + session.check_time(clock)?; + return Ok(Turn::Finished); + } + session.fail("KEEPER_OWNER_EOF", clock()?); + } + if !drained { + return Ok(Turn::Again); + } + if session.park_requested { + session.park_requested = false; + if session.first_fault.is_none() { + // All readable bounds are now reduced. Fresh end checks precede + // PARK and any own-group failure fallback inside park(). + session.park(clock)?; + session.check_time(clock)?; + if channel.send(&format!("PARKED|{pid}|{park}|{sid}")).is_err() { + // Preserve failure cleanup if the response itself fails after + // membership changed; never turn a send fault into a clean exit. + session.fail("KEEPER_CONTROL", clock()?); + } + } + } + match session.step(clock) { + Ok(true) if session.first_fault.is_none() => channel.send(&format!("GONE|{pid}"))?, + Ok(_) => (), + Err(error) => return Err(error), + } + if session.gone { + if let Some(reason) = session.first_fault { + return Err(refused(reason)); + } + } + Ok(Turn::Again) +} + +// Waiting only schedules the next original keeper_turn. It cannot advance +// protocol/group state, and none of the existing absolute ends is restarted. +fn wait_keeper_control( + session: &KeeperSession, + channel: &Channel, + clock: &mut impl FnMut() -> io::Result, + wait: &mut impl FnMut(i32) -> io::Result<()>, +) -> io::Result<()> { + session.check_authority()?; + let at = session.check_time(clock)?; + if channel.buffered_event() { + return Ok(()); + } + let mut end = session.end; + if !session.cleaning { + end = end.min(session.lifetime.operation_end); + } else if !session.gone && !session.killed { + if let Some(term_end) = session.term_end { + end = end.min(term_end); + } + } + if at >= end { + return Ok(()); + } + // Preserve the old 1ms cap; never round the original remainder up. + wait(((end - at) / 1_000_000).min(1) as i32) +} + +// Pure interpretation shared by the real poll adapter and injected tests. +fn keeper_poll_outcome( + count: libc::c_int, + revents: libc::c_short, + error_kind: Option, +) -> io::Result<()> { + if count < 0 { + return if error_kind == Some(io::ErrorKind::Interrupted) { + Ok(()) + } else { + Err(refused("KEEPER_CHANNEL")) + }; + } + if revents & libc::POLLNVAL != 0 { + return Err(refused("KEEPER_CHANNEL")); + } + Ok(()) +} + +/// Entry point of the dev-only keeper example. No product code calls this. +pub fn keeper_main(arguments: impl IntoIterator>) -> io::Result<()> { + let values: Vec = arguments + .into_iter() + .map(|v| { + v.as_ref() + .to_str() + .map(str::to_owned) + .ok_or_else(|| refused("KEEPER_ARG")) + }) + .collect::>()?; + if !matches!(values.len(), 6 | 7) || !nonce_valid(&values[1]) { + return Err(refused("KEEPER_ARGS")); + } + let fd = number(&values[0])?; + let parent = number(&values[2])?; + let park = number(&values[3])?; + let sid = number(&values[4])?; + let deadline = number(&values[5])?; + let policy = CleanupPolicy::keeper_tag(values.get(6).map(String::as_str))?; + let admitted_at = now()?; + let lifetime = if policy == CleanupPolicy::Legacy { + Lifetime::new(admitted_at, deadline)? + } else { + Lifetime::with_policy(admitted_at, deadline, policy)? + }; + if !keeper_fd_allowed(fd) + || parent != unsafe { libc::getppid() } as u64 + || park == 0 + || park > i32::MAX as u64 + || sid != unsafe { libc::getsid(0) } as u64 + || unsafe { libc::getpid() } != unsafe { libc::getpgrp() } + || unsafe { libc::getpid() } as u64 == sid + { + return Err(refused("KEEPER_IDENTITY")); + } + let mut kind: libc::c_int = 0; + let mut length = std::mem::size_of_val(&kind) as libc::socklen_t; + if unsafe { + libc::getsockopt( + fd as i32, + libc::SOL_SOCKET, + libc::SO_TYPE, + (&mut kind as *mut libc::c_int).cast(), + &mut length, + ) + } != 0 + || kind != libc::SOCK_STREAM + { + return Err(refused("KEEPER_FD")); + } + let stream = unsafe { UnixStream::from_raw_fd(fd as i32) }; + let mut channel = Channel::new(stream, values[1].clone())?; + let group = KeeperGroup { + pid: unsafe { libc::getpid() }, + park: park as libc::pid_t, + parked: false, + no_more_group_ops: false, + }; + let pid = group.pid; + let mut session = KeeperSession::new(group, lifetime); + let mut clock = now; + channel.send(&format!("READY|{pid}|{pid}|{sid}"))?; + loop { + match keeper_turn(&mut session, &mut channel, pid, park, sid, &mut clock)? { + Turn::Finished => return Ok(()), + Turn::Again => { + let fd = channel.stream.as_raw_fd(); + wait_keeper_control(&session, &channel, &mut clock, &mut |timeout| { + let mut source = libc::pollfd { + fd, + events: libc::POLLIN, + revents: 0, + }; + let count = unsafe { libc::poll(&mut source, 1, timeout) }; + let error_kind = (count < 0).then(|| io::Error::last_os_error().kind()); + keeper_poll_outcome(count, source.revents, error_kind) + })?; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + mod shipping_keeper_contract { + use super::*; + use std::{cell::Cell, rc::Rc}; + struct Owner(Rc>); + impl Drop for Owner { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + #[test] + fn invalid_fd_refuses_and_closes_the_owned_duplicate() { + for fd in [0, 3, 1025, u64::MAX] { + let drops = Rc::new(Cell::new(0)); + let result = admit_keeper_fd(Owner(drops.clone()), fd); + assert!(result.is_err(), "invalid inherited fd {fd} admitted"); + assert_eq!(drops.get(), 1); + } + } + #[test] + fn valid_fd_retains_ownership_until_explicit_release() { + for fd in [4, 1024] { + let drops = Rc::new(Cell::new(0)); + let owner = admit_keeper_fd(Owner(drops.clone()), fd).ok().unwrap(); + assert_eq!(drops.get(), 0); + drop(owner); + assert_eq!(drops.get(), 1); + } + } + #[test] + fn delayed_await_cannot_renew_original_ready_interval() { + let called = Cell::new(false); + let result = fixed_ready_frame( + 20, + 1_000_000_000, + CleanupPolicy::HookShort, + || Ok(21), + |_| { + called.set(true); + Ok("READY".into()) + }, + ); + assert!(result.is_err(), "late await renewed the fixed interval"); + assert!(!called.get()); + } + #[test] + fn returned_frame_at_original_deadline_is_refused() { + let mut clocks = [1, 20].into_iter(); + let result = fixed_ready_frame( + 20, + 1_000_000_000, + CleanupPolicy::HookShort, + || Ok(clocks.next().unwrap()), + |_| Ok("READY".into()), + ); + assert!(result.is_err(), "returned frame escaped deadline recheck"); + } + #[test] + fn reduced_hard_end_intersects_original_ready_end() { + let mut clocks = [1, 19].into_iter(); + let mut received_end = None; + let result = fixed_ready_frame( + 100, + 50_000_020, + CleanupPolicy::HookShort, + || Ok(clocks.next().unwrap()), + |end| { + received_end = Some(end); + Ok("READY".into()) + }, + ); + assert_eq!(received_end, Some(20)); + assert_eq!(result.unwrap(), "READY"); + } + #[test] + fn receive_fault_remains_the_original_fault() { + let result = fixed_ready_frame( + 20, + 1_000_000_000, + CleanupPolicy::HookShort, + || Ok(1), + |_| Err(refused("GROUP_EOF")), + ); + assert_eq!(result.unwrap_err().to_string(), "GROUP_EOF"); + } + } + + #[test] + fn no_group_operation_after_absence_or_release_or_fault() { + let mut state = Progress::new(100); + for (from, to) in [ + (Phase::AwaitReady, Phase::Ready), + (Phase::Ready, Phase::Joined), + (Phase::Joined, Phase::Parked), + (Phase::Parked, Phase::Cleaning), + ] { + state.advance(from, to).unwrap(); + } + assert!(state.may_touch_group()); + state.advance(Phase::Cleaning, Phase::Gone).unwrap(); + assert!(!state.may_touch_group()); + state.advance(Phase::Gone, Phase::Released).unwrap(); + assert!(!state.may_touch_group()); + state.fail("FIRST"); + state.fail("SECOND"); + assert_eq!(state.first_fault, Some("FIRST")); + assert!(!state.may_touch_group()); + } + #[test] + fn admission_cannot_skip_ready_join_or_park_and_deadline_never_extends() { + let mut state = Progress::new(100); + assert!(state.advance(Phase::AwaitReady, Phase::Parked).is_err()); + // A stale predecessor must never rehabilitate this machine after failure. + assert!(state.advance(Phase::Ready, Phase::Joined).is_err()); + assert!(state.advance(Phase::Failed, Phase::Ready).is_err()); + state.shorten(200); + assert_eq!(state.deadline_ns, 100); + state.shorten(50); + assert_eq!(state.deadline_ns, 50); + } + #[test] + fn every_unlisted_transition_is_refused_and_stays_failed() { + let phases = [ + Phase::AwaitReady, + Phase::Ready, + Phase::Joined, + Phase::Parked, + Phase::Cleaning, + Phase::Gone, + Phase::Released, + Phase::Failed, + ]; + for from in phases { + for to in phases { + let allowed = matches!( + (from, to), + (Phase::AwaitReady, Phase::Ready) + | (Phase::Ready, Phase::Joined) + | (Phase::Joined, Phase::Parked) + | (Phase::Parked, Phase::Cleaning) + | (Phase::Cleaning, Phase::Gone) + | (Phase::Gone, Phase::Released) + ); + let mut state = Progress::new(100); + state.phase = from; + assert_eq!(state.advance(from, to).is_ok(), allowed, "{from:?}->{to:?}"); + if !allowed { + assert_eq!(state.phase, Phase::Failed); + assert!(!state.may_touch_group()); + } + } + } + } + #[test] + fn content_free_channel_checks_nonce_and_bounds_partial_input() { + let (left, mut right) = UnixStream::pair().unwrap(); + right + .set_write_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + right + .write_all(format!("{}|PARK\n", "b".repeat(32)).as_bytes()) + .unwrap(); + assert_eq!(channel.receive().unwrap_err().to_string(), "GROUP_NONCE"); + let (left, mut right) = UnixStream::pair().unwrap(); + right + .set_write_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + right.write_all(&[b'x'; MAX_FRAME]).unwrap(); + assert_eq!( + channel.receive().unwrap_err().to_string(), + "GROUP_FRAME_LIMIT" + ); + } + #[test] + fn content_free_channel_preserves_split_frames_and_eof() { + let (left, mut right) = UnixStream::pair().unwrap(); + right + .set_write_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + right.write_all("a".repeat(32).as_bytes()).unwrap(); + assert!(channel.receive().unwrap().is_none()); + right.write_all(b"|PARK\n").unwrap(); + assert_eq!(channel.receive().unwrap().as_deref(), Some("PARK")); + right.shutdown(std::net::Shutdown::Write).unwrap(); + assert!(channel.receive().unwrap().is_none()); + assert!(channel.eof); + } + + // R19 regression drivers execute the actual settlement/session methods with + // finite fake wait/syscall results and Unix socketpairs, never child actors. + use std::{collections::VecDeque, os::unix::process::ExitStatusExt}; + #[derive(Default)] + struct FakeWait { + steps: VecDeque>>, + calls: usize, + } + impl DirectWait for FakeWait { + fn try_wait(&mut self) -> io::Result> { + self.calls += 1; + self.steps.pop_front().unwrap_or(Ok(None)) + } + } + fn exited() -> io::Result> { + Ok(Some(ExitStatus::from_raw(0))) + } + fn parent_fixture() -> (Settlement, Channel, UnixStream) { + let (left, right) = UnixStream::pair().unwrap(); + right + .set_write_timeout(Some(Duration::from_secs(1))) + .unwrap(); + right + .set_read_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let mut state = Settlement::new(1000); + state.cleanup_sent = true; + state.progress.phase = Phase::Cleaning; + (state, Channel::new(left, "a".repeat(32)).unwrap(), right) + } + fn frame(peer: &mut UnixStream, body: &str) { + peer.write_all(format!("{}|{body}\n", "a".repeat(32)).as_bytes()) + .unwrap(); + } + #[test] + fn consumed_command_type_cannot_return_a_stale_join_callback() { + let _: fn(&mut GroupLease, Command) -> io::Result<()> = GroupLease::start; + } + #[test] + fn pending_park_cleanup_requires_parked_before_gone() { + for skip_parked in [false, true] { + let (mut state, mut channel, mut peer) = parent_fixture(); + state.expected_park = Some("PARKED|42|7|7".to_owned()); + let mut keeper = FakeWait::default(); + if !skip_parked { + frame(&mut peer, "PARKED|42|7|7"); + } + frame(&mut peer, "GONE|42"); + let result = state.poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + None::<&mut FakeWait>, + ); + if skip_parked { + assert_eq!(result.unwrap_err().to_string(), "GROUP_PARK"); + assert!(!state.group_absent); + } else { + assert!(result.unwrap().is_none()); + assert!(state.expected_park.is_none()); + assert!(!state.group_absent); + assert!(state + .poll( + &mut || Ok(2), + 42, + &mut channel, + &mut keeper, + None::<&mut FakeWait> + ) + .unwrap() + .is_none()); + assert!(state.group_absent); + assert!(state.release_sent); + } + } + } + #[test] + fn duplicate_gone_between_pending_and_completed_wait_is_sticky() { + let (mut state, mut channel, mut peer) = parent_fixture(); + let mut keeper = FakeWait::default(); + let mut workload = FakeWait { + steps: [Ok(None), exited()].into(), + calls: 0, + }; + frame(&mut peer, "GONE|42"); + assert!(state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap() + .is_none()); + assert_eq!(state.progress.phase, Phase::Gone); + assert!(!state.release_sent); + frame(&mut peer, "GONE|42"); + assert_eq!( + state + .poll( + &mut || Ok(2), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap_err() + .to_string(), + "GROUP_TERMINAL" + ); + assert_eq!(state.progress.first_fault, Some("GROUP_TERMINAL")); + assert!(state.workload_status.is_some()); + assert!(!state.release_sent); + peer.shutdown(std::net::Shutdown::Write).unwrap(); + keeper.steps.push_back(exited()); + assert!(state + .poll( + &mut || Ok(3), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .is_err()); + assert!(state.keeper_status.is_some()); + assert_eq!(state.progress.first_fault, Some("GROUP_TERMINAL")); + } + #[test] + fn bad_nonce_cannot_be_rehabilitated_by_gone_and_available_waits() { + let (mut state, mut channel, mut peer) = parent_fixture(); + let mut keeper = FakeWait::default(); + let mut workload = FakeWait::default(); + peer.write_all(format!("{}|GONE|42\n", "b".repeat(32)).as_bytes()) + .unwrap(); + assert_eq!( + state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap_err() + .to_string(), + "GROUP_NONCE" + ); + frame(&mut peer, "GONE|42"); + keeper.steps.push_back(exited()); + workload.steps.push_back(exited()); + assert_eq!( + state + .poll( + &mut || Ok(2), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap_err() + .to_string(), + "GROUP_NONCE" + ); + assert!(state.keeper_status.is_some() && state.workload_status.is_some()); + assert!(!state.group_absent && !state.release_sent); + } + #[test] + fn park_failure_and_expiry_still_collect_both_direct_waits_and_first_reason() { + let (mut state, mut channel, _peer) = parent_fixture(); + state.progress.fail("GROUP_PARK"); + let mut keeper = FakeWait { + steps: [exited()].into(), + calls: 0, + }; + let mut workload = FakeWait { + steps: [exited()].into(), + calls: 0, + }; + assert_eq!( + state + .poll( + &mut || Ok(1000), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap_err() + .to_string(), + "GROUP_PARK" + ); + assert_eq!((keeper.calls, workload.calls), (1, 1)); + assert!(state.keeper_status.is_some() && state.workload_status.is_some()); + assert_eq!(state.progress.secondary_faults, ["GROUP_CLEANUP_DEADLINE"]); + } + #[test] + fn wait_error_does_not_skip_other_wait_or_erase_original_fault() { + let (mut state, mut channel, _peer) = parent_fixture(); + state.progress.fail("GROUP_PARK"); + let mut keeper = FakeWait { + steps: [exited()].into(), + calls: 0, + }; + let mut workload = FakeWait { + steps: [Err(refused("private OS text")), exited()].into(), + calls: 0, + }; + assert_eq!( + state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap_err() + .to_string(), + "GROUP_PARK" + ); + assert!(state.keeper_status.is_some() && state.workload_status.is_none()); + assert_eq!(state.progress.secondary_faults, ["GROUP_WORKLOAD_WAIT"]); + assert!(state + .poll( + &mut || Ok(2), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .is_err()); + assert!(state.workload_status.is_some()); + } + #[test] + fn expired_unfaulted_poll_collects_available_waits_but_never_proves_clean() { + let (mut state, mut channel, _peer) = parent_fixture(); + let mut keeper = FakeWait { + steps: [exited()].into(), + calls: 0, + }; + let mut workload = FakeWait { + steps: [exited()].into(), + calls: 0, + }; + assert_eq!( + state + .poll( + &mut || Ok(1000), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap_err() + .to_string(), + "GROUP_CLEANUP_DEADLINE" + ); + assert!(state.keeper_status.is_some() && state.workload_status.is_some()); + assert!(!state.group_absent); + } + #[test] + fn single_gone_waits_and_empty_eof_positive_control() { + let (mut state, mut channel, mut peer) = parent_fixture(); + let mut keeper = FakeWait { + steps: [Ok(None), exited()].into(), + calls: 0, + }; + let mut workload = FakeWait { + steps: [exited()].into(), + calls: 0, + }; + frame(&mut peer, "GONE|42"); + assert!(state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap() + .is_none()); + let mut bytes = [0; 128]; + let n = peer.read(&mut bytes).unwrap(); + assert_eq!( + &bytes[..n], + format!("{}|RELEASE\n", "a".repeat(32)).as_bytes() + ); + peer.shutdown(std::net::Shutdown::Write).unwrap(); + let proof = state + .poll( + &mut || Ok(2), + 42, + &mut channel, + &mut keeper, + Some(&mut workload), + ) + .unwrap() + .unwrap(); + assert!(proof.group_absent && proof.keeper_status.success()); + assert_eq!(state.progress.phase, Phase::Released); + } + #[test] + fn gone_without_clean_and_early_eof_are_refused() { + for clean in [false, true] { + let (mut state, mut channel, mut peer) = parent_fixture(); + state.cleanup_sent = clean; + if !clean { + frame(&mut peer, "GONE|42"); + } else { + peer.shutdown(std::net::Shutdown::Write).unwrap(); + } + assert!(state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut FakeWait::default(), + None::<&mut FakeWait> + ) + .is_err()); + assert_eq!( + state.progress.first_fault, + Some(if clean { + "GROUP_EARLY_EOF" + } else { + "GROUP_CLEANUP_NOT_STARTED" + }) + ); + } + } + #[test] + fn missing_eof_and_partial_trailing_bytes_never_prove_clean() { + for partial in [false, true] { + let (mut state, mut channel, mut peer) = parent_fixture(); + let mut keeper = FakeWait { + steps: [Ok(None), exited()].into(), + calls: 0, + }; + frame(&mut peer, "GONE|42"); + assert!(state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + None::<&mut FakeWait> + ) + .unwrap() + .is_none()); + if partial { + peer.write_all(b"partial").unwrap(); + peer.shutdown(std::net::Shutdown::Write).unwrap(); + } + let result = state.poll( + &mut || Ok(2), + 42, + &mut channel, + &mut keeper, + None::<&mut FakeWait>, + ); + if partial { + assert_eq!(result.unwrap_err().to_string(), "GROUP_TRUNCATED"); + } else { + assert!(result.unwrap().is_none()); + } + } + } + #[derive(Default)] + struct FakeGroup { + events: Vec<&'static str>, + absent: bool, + fail_park: bool, + disabled: bool, + } + impl GroupOps for FakeGroup { + fn park(&mut self) -> io::Result<()> { + self.events.push("park"); + if self.fail_park { + Err(refused("KEEPER_PARK")) + } else { + Ok(()) + } + } + fn absent(&mut self) -> io::Result { + assert!(!self.disabled); + self.events.push("query"); + Ok(self.absent) + } + fn signal(&mut self, sig: i32) -> io::Result<()> { + assert!(!self.disabled); + self.events + .push(if sig == libc::SIGTERM { "term" } else { "kill" }); + Ok(()) + } + fn abandon_self_group(&mut self) -> io::Result<()> { + assert!(!self.disabled); + self.events.push("self-kill"); + self.disabled = true; + Err(refused("KEEPER_SELF_GROUP_UNPROVEN")) + } + fn disable(&mut self) { + self.events.push("disable"); + self.disabled = true; + } + } + fn helper_fixture() -> KeeperSession { + KeeperSession::new( + FakeGroup::default(), + Lifetime::new(0, 10 * CLEANUP_NS).unwrap(), + ) + } + #[test] + fn lifetime_reserves_cleanup_and_equality_never_signals_after_hard_end() { + assert!(Lifetime::new(0, CLEANUP_NS).is_err()); + let mut state = helper_fixture(); + let trigger = state.lifetime.operation_end; + assert!(!state.step(&mut || Ok(trigger - 1)).unwrap()); + assert!(state.group.events.is_empty()); + assert!(!state.step(&mut || Ok(trigger)).unwrap()); + assert_eq!(state.group.events, ["park", "query", "term"]); + assert_eq!(state.first_fault, Some("KEEPER_LIFETIME")); + let saved = state.group.events.clone(); + assert!(state.step(&mut || Ok(10 * CLEANUP_NS)).is_err()); + assert_eq!(state.group.events, saved); + } + #[test] + fn pre_park_parent_loss_uses_failure_only_self_group_fallback_once() { + let mut state = helper_fixture(); + state.group.fail_park = true; + state.fail("KEEPER_OWNER_EOF", 1); + assert!(state.step(&mut || Ok(1)).is_err()); + assert_eq!(state.group.events, ["park", "self-kill"]); + assert!(!state.gone); + assert!(state.step(&mut || Ok(2)).is_err()); + assert_eq!(state.group.events, ["park", "self-kill"]); + assert_eq!(state.first_fault, Some("KEEPER_OWNER_EOF")); + } + #[test] + fn decreasing_bounds_during_term_do_not_restart_grace_or_extend_end() { + let mut state = helper_fixture(); + state.control("CLEAN|100000000", 1).unwrap(); + assert!(!state.step(&mut || Ok(2)).unwrap()); + let grace = state.term_end.unwrap(); + state.control("CLEAN|200000000", 3).unwrap(); + assert_eq!(state.end, 100000000); + state.control("CLEAN|100000000", 4).unwrap(); + state.control("CLEAN|1000", 5).unwrap(); + assert_eq!(state.end, 1000); + assert_eq!(state.term_end, Some(grace)); + let saved = state.group.events.clone(); + assert!(state.step(&mut || Ok(1000)).is_err()); + assert_eq!(state.group.events, saved); + } + #[test] + fn shortening_after_gone_bounds_release_and_never_touches_group() { + let mut state = helper_fixture(); + state.group.absent = true; + state.control("CLEAN|1000", 1).unwrap(); + assert!(state.step(&mut || Ok(2)).unwrap()); + let saved = state.group.events.clone(); + state.control("CLEAN|100", 3).unwrap(); + assert!(!state.step(&mut || Ok(4)).unwrap()); + assert_eq!(state.group.events, saved); + assert!(state.control("RELEASE", 100).is_err()); + assert!(!state.released); + } + #[test] + fn syscall_time_crossing_end_stops_before_next_group_operation() { + let mut state = helper_fixture(); + state.control("CLEAN|100", 1).unwrap(); + let mut times = VecDeque::from([Ok(2), Ok(2), Ok(100)]); + assert!(state.step(&mut || times.pop_front().unwrap()).is_err()); + assert_eq!(state.group.events, ["park"]); + } + #[test] + fn pre_ready_cancellation_requires_the_actual_ready_before_gone() { + for invalid in [false, true] { + let (mut state, mut channel, mut peer) = parent_fixture(); + state.progress.phase = Phase::AwaitReady; + state.expected_ready = Some("READY|42|42|7".to_owned()); + state.progress.begin_cleanup().unwrap(); + let mut keeper = FakeWait::default(); + if invalid { + frame(&mut peer, "GONE|42"); + assert_eq!( + state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + None::<&mut FakeWait> + ) + .unwrap_err() + .to_string(), + "GROUP_READY" + ); + assert!(!state.group_absent); + } else { + frame(&mut peer, "READY|42|42|7"); + frame(&mut peer, "GONE|42"); + assert!(state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + None::<&mut FakeWait> + ) + .unwrap() + .is_none()); + assert!(state.expected_ready.is_none()); + assert!(!state.group_absent); + assert!(state + .poll( + &mut || Ok(2), + 42, + &mut channel, + &mut keeper, + None::<&mut FakeWait> + ) + .unwrap() + .is_none()); + assert!(state.group_absent && state.release_sent); + } + } + } + #[test] + fn parent_driver_sends_each_decrease_and_explicitly_refuses_after_seal() { + let (mut state, mut channel, mut peer) = parent_fixture(); + state.cleanup_sent = false; + state.progress.phase = Phase::Parked; + state.begin(900, 1, &mut channel).unwrap(); + state.begin(800, 2, &mut channel).unwrap(); + state.begin(950, 3, &mut channel).unwrap(); + assert_eq!(state.progress.deadline_ns, 800); + let mut bytes = [0; 256]; + let n = peer.read(&mut bytes).unwrap(); + assert_eq!( + &bytes[..n], + format!("{0}|CLEAN|900\n{0}|CLEAN|800\n", "a".repeat(32)).as_bytes() + ); + state.release_sent = true; + assert_eq!( + state.begin(700, 4, &mut channel).unwrap_err().to_string(), + "GROUP_BOUND_SEALED" + ); + assert_eq!(state.progress.deadline_ns, 800); + state.begin(800, 5, &mut channel).unwrap(); + } + #[test] + fn peer_death_collects_direct_keeper_wait_and_cannot_look_clean() { + let (mut state, mut channel, peer) = parent_fixture(); + drop(peer); + let mut keeper = FakeWait { + steps: [exited()].into(), + calls: 0, + }; + let mut workload = FakeWait::default(); + assert_eq!( + state + .poll( + &mut || Ok(1), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .unwrap_err() + .to_string(), + "GROUP_EARLY_EOF" + ); + assert!(state.keeper_status.is_some()); + assert!(state.workload_status.is_none()); + workload.steps.push_back(exited()); + assert!(state + .poll( + &mut || Ok(1000), + 42, + &mut channel, + &mut keeper, + Some(&mut workload) + ) + .is_err()); + assert!(state.workload_status.is_some()); + assert_eq!(state.progress.first_fault, Some("GROUP_EARLY_EOF")); + } + #[test] + fn proof_and_release_recheck_clock_after_receiving_bytes() { + for final_proof in [false, true] { + let (mut state, mut channel, mut peer) = parent_fixture(); + let mut keeper = FakeWait::default(); + let mut times = if final_proof { + state.progress.phase = Phase::Gone; + state.group_absent = true; + state.release_sent = true; + keeper.steps.push_back(exited()); + peer.shutdown(std::net::Shutdown::Write).unwrap(); + VecDeque::from([Ok(1), Ok(1), Ok(1000)]) + } else { + frame(&mut peer, "GONE|42"); + VecDeque::from([Ok(1), Ok(1000)]) + }; + assert_eq!( + state + .poll( + &mut || times.pop_front().unwrap(), + 42, + &mut channel, + &mut keeper, + None::<&mut FakeWait> + ) + .unwrap_err() + .to_string(), + "GROUP_CLEANUP_DEADLINE" + ); + assert_eq!(state.progress.first_fault, Some("GROUP_CLEANUP_DEADLINE")); + assert_ne!(state.progress.phase, Phase::Released); + if !final_proof { + assert!(!state.release_sent); + } + } + } + // R20 drives the EXACT outer keeper turn called by keeper_main. The + // extracted baseline deliberately retains both reviewed defects for RED. + fn r20_failed_reduction(expiry: bool) { + let mut session = helper_fixture(); + let at = if expiry { + session.lifetime.operation_end + } else { + 2 + }; + if !expiry { + session.control("CLEAN|1000000000", 1).unwrap(); + } + session.step(&mut || Ok(at)).unwrap(); + if !expiry { + session.fail("KEEPER_CHANNEL", at); + } + let first = session.first_fault; + assert!(first.is_some()); + let events = session.group.events.clone(); + let grace = session.term_end; + let (left, right) = UnixStream::pair().unwrap(); + let mut parent_channel = Channel::new(left, "a".repeat(32)).unwrap(); + let mut keeper_channel = Channel::new(right, "a".repeat(32)).unwrap(); + let mut parent = Settlement::new(session.lifetime.hard_end); + parent.progress.phase = Phase::Parked; + let end = at + 5_000_000; + parent + .begin(end, at + 1_000_000, &mut parent_channel) + .unwrap(); + assert_eq!(parent.progress.deadline_ns, end); + let result = keeper_turn(&mut session, &mut keeper_channel, 42, 7, 7, &mut || { + Ok(at + 6_000_000) + }); + assert_eq!( + session.end, end, + "helper discarded the bound accepted by the actual parent driver" + ); + assert_eq!(session.first_fault, first); + assert_eq!(session.term_end, grace); + assert_eq!( + session.group.events, events, + "no group operation after accepted end" + ); + assert_eq!(result.unwrap_err().to_string(), "KEEPER_CLEANUP_DEADLINE"); + assert!(!session.gone && !session.released); + } + #[test] + fn r20_expiry_fault_still_consumes_parent_accepted_reduction() { + r20_failed_reduction(true); + } + #[test] + fn r20_prior_clean_then_fault_still_consumes_parent_accepted_reduction() { + r20_failed_reduction(false); + } + + enum ReadAction { + Bytes(Vec), + Interrupted, + Fault, + } + #[derive(Default)] + struct ScriptedIo { + actions: VecDeque, + reads: usize, + output: Vec, + } + impl Read for ScriptedIo { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.reads += 1; + match self.actions.pop_front() { + Some(ReadAction::Bytes(bytes)) => { + assert!(bytes.len() <= buffer.len()); + buffer[..bytes.len()].copy_from_slice(&bytes); + Ok(bytes.len()) + } + Some(ReadAction::Interrupted) => Err(io::Error::from(io::ErrorKind::Interrupted)), + Some(ReadAction::Fault) => Err(io::Error::other("scripted read fault")), + None => Err(io::Error::from(io::ErrorKind::WouldBlock)), + } + } + } + impl Write for ScriptedIo { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.output.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + mod setup_schedule_tests { + use super::*; + + #[test] + fn setup_schedule_unready_and_expired_polls_do_not_format_an_expected_frame() { + for expired in [false, true] { + let mut channel = scripted_channel(&[]); + if expired { + channel.pending = format!("{}|PARKED|42|7|7\n", "a".repeat(32)).into_bytes(); + } + let formatted = std::cell::Cell::new(0); + let result = poll_park_frame( + &mut channel, + || { + formatted.set(formatted.get() + 1); + "PARKED|42|7|7".to_owned() + }, + 20_000_000, + &mut || Ok(if expired { 20_000_000 } else { 1 }), + &mut ParkObservation::default(), + ); + assert_eq!(formatted.get(), 0); + if expired { + assert_eq!(result.unwrap_err().to_string(), "GROUP_DEADLINE"); + assert!(channel.buffered_event()); + assert_eq!(channel.stream.reads, 0); + } else { + assert!(!result.unwrap()); + assert_eq!(channel.stream.reads, 1); + } + } + } + + #[test] + fn setup_schedule_actual_eighth_read_frame_returns_to_original_park_parser() { + let nonce = "a".repeat(32); + let mut channel = scripted_channel(&[]); + channel + .stream + .actions + .extend((0..7).map(|_| ReadAction::Interrupted)); + channel.stream.actions.push_back(ReadAction::Bytes( + format!("{nonce}|PARKED|42|7|7\n").into_bytes(), + )); + assert!(matches!( + channel.receive_event().unwrap(), + Receive::BudgetYield + )); + assert_eq!(channel.stream.reads, 8); + assert!(channel.buffered_event()); + let reads = channel.stream.reads; + assert!(poll_park_frame( + &mut channel, + || "PARKED|42|7|7".to_owned(), + 20_000_000, + &mut || Ok(19_970_000), + &mut ParkObservation::default() + ) + .unwrap()); + assert_eq!( + channel.stream.reads, reads, + "already buffered frame needs no ninth read" + ); + assert!(!channel.buffered_event()); + assert!(channel.stream.output.is_empty()); + } + + #[test] + fn setup_schedule_actual_eighth_read_ready_frame_is_buffered_not_phantom_readiness() { + let mut channel = scripted_channel(&[]); + channel + .stream + .actions + .extend((0..7).map(|_| ReadAction::Interrupted)); + channel.stream.actions.push_back(ReadAction::Bytes( + format!("{}|READY|42|42|7\n", "a".repeat(32)).into_bytes(), + )); + assert!(matches!( + channel.receive_event().unwrap(), + Receive::BudgetYield + )); + assert_eq!(channel.stream.reads, 8); + assert!(channel.buffered_event()); + assert_eq!(channel.receive().unwrap().as_deref(), Some("READY|42|42|7")); + assert_eq!(channel.stream.reads, 8); + assert!(!channel.buffered_event()); + } + + #[test] + fn setup_schedule_one_quiescent_park_probe_is_nonblocking_without_retry() { + let mut channel = scripted_channel(&[]); + assert!(!poll_park_frame( + &mut channel, + || "PARKED|42|7|7".to_owned(), + 20_000_000, + &mut || Ok(1), + &mut ParkObservation::default() + ) + .unwrap()); + assert_eq!(channel.stream.reads, 1); + assert!(!channel.buffered_event()); + assert!(channel.stream.output.is_empty()); + } + + #[test] + fn setup_schedule_missing_post_receive_clock_does_not_accept_the_park_frame() { + let mut channel = scripted_channel(&[]); + channel.pending = format!("{}|PARKED|42|7|7\n", "a".repeat(32)).into_bytes(); + let mut reads = 0; + assert_eq!( + poll_park_frame( + &mut channel, + || "PARKED|42|7|7".to_owned(), + 20_000_000, + &mut || { + reads += 1; + if reads == 1 { + Ok(1) + } else { + Err(refused("GROUP_CLOCK")) + } + }, + &mut ParkObservation::default() + ) + .unwrap_err() + .to_string(), + "GROUP_CLOCK" + ); + assert_eq!(reads, 2); + assert_eq!(channel.stream.reads, 0); + } + + #[test] + fn setup_schedule_buffered_wrong_nonce_or_frame_does_not_authorize_park() { + for (line, reason) in [ + (format!("{}|PARKED|42|7|7\n", "b".repeat(32)), "GROUP_NONCE"), + (format!("{}|READY|42|42|7\n", "a".repeat(32)), "GROUP_PARK"), + ] { + let mut channel = scripted_channel(&[]); + channel.pending = line.into_bytes(); + assert!(channel.buffered_event()); + assert_eq!( + poll_park_frame( + &mut channel, + || "PARKED|42|7|7".to_owned(), + 20_000_000, + &mut || Ok(1), + &mut ParkObservation::default() + ) + .unwrap_err() + .to_string(), + reason + ); + assert_eq!(channel.stream.reads, 0); + assert!(channel.stream.output.is_empty()); + } + } + + #[test] + fn setup_schedule_partial_bytes_and_eof_are_distinct_from_park_acceptance() { + let mut partial = scripted_channel(format!("{}|PARKED|", "a".repeat(32)).as_bytes()); + assert!(matches!( + partial.receive_event().unwrap(), + Receive::BudgetYield + )); + assert!(!partial.buffered_event()); + assert!(!poll_park_frame( + &mut partial, + || "PARKED|42|7|7".to_owned(), + 20_000_000, + &mut || Ok(1), + &mut ParkObservation::default() + ) + .unwrap()); + let mut eof = scripted_channel(&[]); + eof.stream.actions.push_back(ReadAction::Bytes(vec![])); + assert!(matches!(eof.receive_event().unwrap(), Receive::Eof)); + assert!(eof.buffered_event()); + assert_eq!( + poll_park_frame( + &mut eof, + || "PARKED|42|7|7".to_owned(), + 20_000_000, + &mut || Ok(1), + &mut ParkObservation::default() + ) + .unwrap_err() + .to_string(), + "GROUP_EOF" + ); + } + + #[test] + fn setup_schedule_original_park_checks_refuse_exact_end_and_post_receive_expiry() { + for before_expired in [true, false] { + let mut channel = scripted_channel(&[]); + channel.pending = format!("{}|PARKED|42|7|7\n", "a".repeat(32)).into_bytes(); + let mut samples = if before_expired { + vec![20_000_000].into_iter() + } else { + vec![19_999_999, 20_000_000].into_iter() + }; + assert_eq!( + poll_park_frame( + &mut channel, + || "PARKED|42|7|7".to_owned(), + 20_000_000, + &mut || Ok(samples.next().expect("bounded clock samples")), + &mut ParkObservation::default() + ) + .unwrap_err() + .to_string(), + "GROUP_DEADLINE" + ); + assert_eq!(channel.stream.reads, 0); + if before_expired { + assert!(channel.buffered_event()); + } + assert!(channel.stream.output.is_empty()); + } + } + + #[test] + fn setup_schedule_missing_clock_leaves_buffered_frame_unparsed() { + let mut channel = scripted_channel(&[]); + channel.pending = format!("{}|PARKED|42|7|7\n", "a".repeat(32)).into_bytes(); + assert_eq!( + poll_park_frame( + &mut channel, + || "PARKED|42|7|7".to_owned(), + 20_000_000, + &mut || Err(refused("GROUP_CLOCK")), + &mut ParkObservation::default() + ) + .unwrap_err() + .to_string(), + "GROUP_CLOCK" + ); + assert!(channel.buffered_event()); + assert_eq!(channel.stream.reads, 0); + } + } + + mod keeper_readiness_tests { + use super::*; + use std::cell::Cell; + + fn short_session() -> KeeperSession { + KeeperSession::new( + FakeGroup::default(), + Lifetime::with_policy(0, 70_000_000, CleanupPolicy::HookShort).unwrap(), + ) + } + + #[test] + fn keeper_wait_buffered_eighth_read_control_runs_again_without_wait_or_group_work() { + let mut session = helper_fixture(); + let mut channel = scripted_channel(&[]); + channel + .stream + .actions + .extend((0..7).map(|_| ReadAction::Interrupted)); + channel.stream.actions.push_back(ReadAction::Bytes( + format!("{}|CLEAN|100\n", "a".repeat(32)).into_bytes(), + )); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(150)).unwrap(), + Turn::Again + ); + assert_eq!(channel.stream.reads, 8); + assert!(channel.pending.ends_with(b"\n")); + assert!(session.group.events.is_empty()); + wait_keeper_control(&session, &channel, &mut || Ok(150), &mut |_| { + panic!("already-buffered control must not wait") + }) + .unwrap(); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(150)) + .unwrap_err() + .to_string(), + "KEEPER_CLEANUP_DEADLINE" + ); + assert_eq!(session.end, 100); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + assert!(!session.gone && !session.released); + } + + #[test] + fn keeper_wait_partial_control_and_readiness_never_authorize_pending_park() { + let mut session = short_session(); + let mut channel = + scripted_channel(format!("{0}|PARK\n{0}|CLEAN|", "a".repeat(32)).as_bytes()); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(1)).unwrap(), + Turn::Again + ); + assert!(session.park_requested && !session.parked); + let end = session.end; + wait_keeper_control(&session, &channel, &mut || Ok(2), &mut |timeout| { + assert_eq!(timeout, 1); + keeper_poll_outcome(1, libc::POLLIN, None) + }) + .unwrap(); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(2)).unwrap(), + Turn::Again + ); + assert_eq!(session.end, end); + assert!(session.park_requested && !session.parked); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + channel + .stream + .actions + .push_back(ReadAction::Bytes(b"0\n".to_vec())); + assert!(keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(3)).is_err()); + assert_eq!(session.end, 0); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + } + + #[test] + fn keeper_wait_final_submillisecond_poll_keeps_a_timely_park_in_the_original_window() { + let mut session = short_session(); + let mut channel = scripted_channel(&[]); + let original_end = session.lifetime.operation_end; + let clock = Cell::new(original_end - 49_000); + wait_keeper_control( + &session, + &channel, + &mut || Ok(clock.get()), + &mut |timeout| { + assert_eq!(timeout, 0); + clock.set(original_end - 30_000); + keeper_poll_outcome(1, libc::POLLIN, None) + }, + ) + .unwrap(); + assert!(session.group.events.is_empty()); + channel.stream.actions.push_back(ReadAction::Bytes( + format!("{}|PARK\n", "a".repeat(32)).into_bytes(), + )); + assert_eq!( + keeper_turn( + &mut session, + &mut channel, + 42, + 7, + 7, + &mut || Ok(clock.get()) + ) + .unwrap(), + Turn::Again + ); + assert_eq!(session.group.events, ["park"]); + assert_eq!(session.lifetime.operation_end, original_end); + assert_eq!(session.end, 70_000_000); + assert!(clock.get() < original_end); + assert!(!session.cleaning && !session.gone && !session.released); + } + + #[test] + fn keeper_wait_existing_operation_session_and_term_ends_bound_every_wait() { + // (cleaning, gone, killed, session end, TERM end, now, wait timeout) + for (cleaning, gone, killed, end, term, at, expected) in [ + (false, false, false, 70_000_000, None, 10_000_000, Some(1)), + (false, false, false, 70_000_000, None, 19_950_000, Some(0)), + (false, false, false, 70_000_000, None, 20_000_000, None), + (true, false, false, 20_000_000, None, 19_950_000, Some(0)), + ( + true, + false, + false, + 20_000_000, + Some(19_960_000), + 19_000_000, + Some(0), + ), + ( + true, + false, + false, + 20_000_000, + Some(19_960_000), + 19_960_000, + None, + ), + (true, true, false, 20_000_000, Some(1), 10_000_000, Some(1)), + (true, false, true, 20_000_000, Some(1), 10_000_000, Some(1)), + ] { + let mut session = short_session(); + session.cleaning = cleaning; + session.gone = gone; + session.killed = killed; + session.end = end; + session.term_end = term; + let channel = scripted_channel(&[]); + let mut observed = None; + wait_keeper_control(&session, &channel, &mut || Ok(at), &mut |timeout| { + observed = Some(timeout); + Ok(()) + }) + .unwrap(); + assert_eq!(observed, expected); + assert_eq!(session.end, end); + assert_eq!(session.term_end, term); + assert_eq!(session.lifetime.operation_end, 20_000_000); + assert_eq!(session.lifetime.hard_end, 70_000_000); + assert!(session.group.events.is_empty()); + assert!(!session.released); + } + } + + #[test] + fn keeper_wait_exact_session_end_refuses_without_waiting_or_group_effect() { + let mut session = short_session(); + session.end = 20_000_000; + let mut channel = scripted_channel(&[]); + assert_eq!( + wait_keeper_control(&session, &channel, &mut || Ok(20_000_000), &mut |_| { + panic!("no waiting at the exact end") + }) + .unwrap_err() + .to_string(), + "KEEPER_CLEANUP_DEADLINE" + ); + assert!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(20_000_000)).is_err() + ); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + assert_eq!(session.end, 20_000_000); + } + + #[test] + fn keeper_wait_wait_results_only_schedule_original_turns() { + for (count, events, kind) in [ + (0, 0, None), + (1, libc::POLLIN, None), + (1, libc::POLLHUP, None), + (1, libc::POLLERR, None), + (-1, 0, Some(io::ErrorKind::Interrupted)), + ] { + let mut session = short_session(); + let mut channel = scripted_channel(&[]); + wait_keeper_control(&session, &channel, &mut || Ok(1), &mut |_| { + keeper_poll_outcome(count, events, kind) + }) + .unwrap(); + assert!(session.group.events.is_empty()); + assert_eq!(session.end, 70_000_000); + assert!(!session.parked && !session.cleaning && !session.gone && !session.released); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(2)).unwrap(), + Turn::Again + ); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + } + } + + #[test] + fn keeper_wait_fatal_wait_clock_and_stopped_authority_cannot_touch_group_or_extend_ends() { + for (count, events, kind) in [ + (-1, 0, Some(io::ErrorKind::Other)), + (-1, 0, None), + (1, libc::POLLNVAL, None), + (0, libc::POLLNVAL, None), + ] { + let session = short_session(); + let channel = scripted_channel(&[]); + assert_eq!( + wait_keeper_control(&session, &channel, &mut || Ok(1), &mut |_| { + keeper_poll_outcome(count, events, kind) + }) + .unwrap_err() + .to_string(), + "KEEPER_CHANNEL" + ); + assert!(session.group.events.is_empty()); + assert_eq!(session.end, 70_000_000); + assert!(!session.gone && !session.released); + } + let mut session = short_session(); + let channel = scripted_channel(&[]); + assert_eq!( + wait_keeper_control( + &session, + &channel, + &mut || Err(refused("GROUP_CLOCK")), + &mut |_| { panic!("unavailable clock must not wait") } + ) + .unwrap_err() + .to_string(), + "GROUP_CLOCK" + ); + session.stop_authority("KEEPER_CHANNEL", 1); + let events = session.group.events.clone(); + let end = session.end; + assert!(wait_keeper_control( + &session, + &channel, + &mut || { panic!("stopped authority must refuse before clock") }, + &mut |_| panic!("stopped authority must not wait") + ) + .is_err()); + assert_eq!(session.group.events, events); + assert_eq!(session.end, end); + assert!(!session.gone && !session.released); + } + + #[test] + fn keeper_wait_observed_eof_returns_to_original_failure_cleanup_without_wait() { + let session = short_session(); + let mut channel = scripted_channel(&[]); + channel.eof = true; + wait_keeper_control(&session, &channel, &mut || Ok(1), &mut |_| { + panic!("observed EOF must return immediately") + }) + .unwrap(); + assert!(session.group.events.is_empty()); + assert!(!session.gone && !session.released); + } + } + + fn r20_budget_yield(interrupted: bool) { + let mut session = helper_fixture(); + session.control("CLEAN|1000000000", 1).unwrap(); + session.step(&mut || Ok(2)).unwrap(); + let events = session.group.events.clone(); + let bytes = format!("{}|CLEAN|100\n", "a".repeat(32)).into_bytes(); + let actions = if interrupted { + (0..7) + .map(|_| ReadAction::Interrupted) + .chain([ReadAction::Bytes(bytes)]) + .collect() + } else { + bytes[..7] + .iter() + .map(|b| ReadAction::Bytes(vec![*b])) + .chain([ReadAction::Bytes(bytes[7..].to_vec())]) + .collect() + }; + let mut channel = Channel { + stream: ScriptedIo { + actions, + ..Default::default() + }, + nonce: "a".repeat(32), + pending: vec![], + wire: 0, + eof: false, + }; + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(150)).unwrap(), + Turn::Again + ); + assert_eq!(channel.stream.reads, 8, "no ninth read in a receive pass"); + assert!(channel.pending.ends_with(b"\n")); + assert_eq!( + session.group.events, events, + "budget yield must not authorize group operations" + ); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(150)) + .unwrap_err() + .to_string(), + "KEEPER_CLEANUP_DEADLINE" + ); + assert_eq!(session.end, 100); + assert_eq!(session.group.events, events); + assert!(channel.stream.output.is_empty()); + } + #[test] + fn r20_eighth_short_read_completion_yields_before_group_operations() { + r20_budget_yield(false); + } + #[test] + fn r20_seven_interruptions_then_completion_yields_before_group_operations() { + r20_budget_yield(true); + } + fn scripted_channel(bytes: &[u8]) -> Channel { + Channel { + stream: ScriptedIo { + actions: bytes + .chunks(MAX_FRAME) + .map(|b| ReadAction::Bytes(b.to_vec())) + .collect(), + ..Default::default() + }, + nonce: "a".repeat(32), + pending: vec![], + wire: 0, + eof: false, + } + } + #[test] + fn r20_failed_control_only_tightens_and_never_reopens_normal_trace() { + let mut session = helper_fixture(); + let at = session.lifetime.operation_end; + session.step(&mut || Ok(at)).unwrap(); + let first = session.first_fault; + let grace = session.term_end; + let end = at + 5_000_000; + let payload=format!("{0}|PARK\n{0}|RELEASE\n{0}|GONE|42\n{0}|CLEAN|{1}\n{0}|CLEAN|0001\n{0}|CLEAN|999999999999\n", "a".repeat(32),end); + let mut channel = scripted_channel(payload.as_bytes()); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + at + 1_000_000 + )) + .unwrap(), + Turn::Again + ); + assert_eq!(session.end, end); + assert_eq!(session.first_fault, first); + assert_eq!(session.term_end, grace); + assert!(!session.released && !session.gone); + assert!(channel.stream.output.is_empty()); + } + #[test] + fn r20_control_frame_cap_yields_until_last_buffered_minimum_is_consumed() { + let mut session = helper_fixture(); + session.control("CLEAN|1000000000", 1).unwrap(); + session.step(&mut || Ok(2)).unwrap(); + let events = session.group.events.clone(); + let payload = (1..=9) + .rev() + .map(|n| format!("{}|CLEAN|{}\n", "a".repeat(32), n * 100)) + .collect::(); + let mut channel = scripted_channel(payload.as_bytes()); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(150)).unwrap(), + Turn::Again + ); + assert_eq!(session.end, 200); + assert_eq!(session.group.events, events); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(150)) + .unwrap_err() + .to_string(), + "KEEPER_CLEANUP_DEADLINE" + ); + assert_eq!(session.end, 100); + assert_eq!(session.group.events, events); + } + #[test] + fn r20_interrupted_empty_budget_yields_before_proven_quiescence() { + let mut session = helper_fixture(); + session.control("CLEAN|1000", 1).unwrap(); + session.step(&mut || Ok(2)).unwrap(); + let events = session.group.events.clone(); + let mut channel = scripted_channel(&[]); + channel.stream.actions = (0..8).map(|_| ReadAction::Interrupted).collect(); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(3)).unwrap(), + Turn::Again + ); + assert_eq!(channel.stream.reads, 8); + assert_eq!(session.group.events, events); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(4)).unwrap(), + Turn::Again + ); + assert_eq!(channel.stream.reads, 9); + let mut expected = events; + expected.push("query"); + assert_eq!(session.group.events, expected); + } + #[test] + fn r20_actual_turn_normal_park_gone_release_eof_positive_control() { + let mut session = helper_fixture(); + session.group.absent = true; + let payload = format!("{0}|PARK\n{0}|CLEAN|1000\n", "a".repeat(32)); + let mut channel = scripted_channel(payload.as_bytes()); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(1)).unwrap(), + Turn::Again + ); + assert!(session.gone); + assert!(session.first_fault.is_none()); + assert_eq!( + channel.stream.output, + format!("{0}|PARKED|42|7|7\n{0}|GONE|42\n", "a".repeat(32)).as_bytes() + ); + let events = session.group.events.clone(); + channel.stream.actions.push_back(ReadAction::Bytes( + format!("{}|RELEASE\n", "a".repeat(32)).into_bytes(), + )); + channel.stream.actions.push_back(ReadAction::Bytes(vec![])); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(2)).unwrap(), + Turn::Finished + ); + assert!(session.released && channel.eof); + assert_eq!(session.group.events, events); + } + // R21 tests use the same keeper_turn and real parent reducer, not a second + // parser/state model. All group operations below are fake event recording. + fn r21_parent_frame(end: u64, at: u64) -> Vec { + let (left, mut right) = UnixStream::pair().unwrap(); + right + .set_read_timeout(Some(Duration::from_secs(1))) + .unwrap(); + right + .set_write_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + let mut parent = Settlement::new(20 * CLEANUP_NS); + parent.progress.phase = Phase::Parked; + parent.begin(end, at, &mut channel).unwrap(); + assert_eq!(parent.progress.deadline_ns, end); + let expected = format!("{}|CLEAN|{end}\n", "a".repeat(32)).into_bytes(); + let mut frame = vec![0; expected.len()]; + right.read_exact(&mut frame).unwrap(); + assert_eq!(frame, expected); + frame + } + fn r21_rejected_prefix(prior_fault: bool, invalid_number: bool) { + let mut session = helper_fixture(); + let base = if prior_fault { + session.lifetime.operation_end + } else { + 2 + }; + if !prior_fault { + session.control("CLEAN|1000000000", 1).unwrap(); + } + session.step(&mut || Ok(base)).unwrap(); + let original = session.first_fault; + let grace = session.term_end; + let events = session.group.events.clone(); + let end = base + 100_000_000; + let mut bytes = if invalid_number { + format!("{}|CLEAN|0001\n", "a".repeat(32)).into_bytes() + } else { + format!("{}|PARK\n", "b".repeat(32)).into_bytes() + }; + bytes.extend(r21_parent_frame(end, base + 10_000_000)); + assert!(bytes.len() < MAX_FRAME); + let mut channel = scripted_channel(&bytes); + let result = keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || { + Ok(base + 150_000_000) + }); + assert_eq!( + session.group.events, events, + "rejected line must not authorize a step before buffered CLEAN" + ); + assert_eq!(session.end, end); + assert_eq!(session.term_end, grace); + assert_eq!( + session.first_fault, + original.or(Some(if invalid_number { + "KEEPER_CONTROL" + } else { + "KEEPER_CHANNEL" + })) + ); + assert_eq!(result.unwrap_err().to_string(), "KEEPER_CLEANUP_DEADLINE"); + assert!(!session.gone && !session.released); + assert!(channel.stream.output.is_empty()); + } + #[test] + fn r21_wrong_nonce_before_accepted_minimum_does_not_authorize_a_group_step() { + r21_rejected_prefix(false, false); + } + #[test] + fn r21_prior_expiry_fault_survives_rejected_line_and_buffered_minimum() { + r21_rejected_prefix(true, false); + } + #[test] + fn r21_invalid_number_before_valid_minimum_preserves_control_fault() { + r21_rejected_prefix(false, true); + } + + fn r21_fatal_channel(mut channel: Channel) { + let mut session = helper_fixture(); + session.control("CLEAN|1000000000", 1).unwrap(); + session.step(&mut || Ok(2)).unwrap(); + let mut expected = session.group.events.clone(); + let grace = session.term_end; + let result = keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || { + Ok(150_000_000) + }); + assert!( + result.is_err(), + "unrecoverable transport must stop group authority rather than claim drain" + ); + expected.push("disable"); + assert_eq!(session.group.events, expected); + assert_eq!(session.first_fault, Some("KEEPER_CHANNEL")); + assert_eq!(session.term_end, grace); + assert!(!session.gone && !session.released); + assert!(channel.stream.output.is_empty()); + // Even an explicit later call with valid bytes cannot regain authority. + channel.stream.actions.push_back(ReadAction::Bytes( + format!("{}|CLEAN|100\n", "a".repeat(32)).into_bytes(), + )); + assert!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_001 + )) + .is_err() + ); + assert!(session.step(&mut || Ok(150_000_001)).is_err()); + assert_eq!(session.group.events, expected); + } + #[test] + fn r21_fatal_read_error_stops_group_authority() { + let mut channel = scripted_channel(&[]); + channel.stream.actions.push_back(ReadAction::Fault); + r21_fatal_channel(channel); + } + #[test] + fn r21_wire_overflow_stops_group_authority() { + let mut channel = scripted_channel(format!("{}|CLEAN|100\n", "a".repeat(32)).as_bytes()); + channel.wire = MAX_WIRE; + r21_fatal_channel(channel); + } + #[test] + fn r21_unterminated_frame_limit_stops_group_authority() { + r21_fatal_channel(scripted_channel(&[b'x'; MAX_FRAME])); + } + #[test] + fn r21_truncated_eof_stops_group_authority() { + let mut channel = scripted_channel(format!("{}|CLEAN|", "a".repeat(32)).as_bytes()); + channel.stream.actions.push_back(ReadAction::Bytes(vec![])); + r21_fatal_channel(channel); + } + #[test] + fn r21_partial_wouldblock_is_not_control_quiescence() { + let mut session = helper_fixture(); + session.control("CLEAN|1000000000", 1).unwrap(); + session.step(&mut || Ok(2)).unwrap(); + let events = session.group.events.clone(); + let mut channel = scripted_channel(format!("{}|CLEAN|", "a".repeat(32)).as_bytes()); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_000 + )) + .unwrap(), + Turn::Again + ); + assert_eq!(session.group.events, events); + assert!(!channel.pending.is_empty()); + channel + .stream + .actions + .push_back(ReadAction::Bytes(b"100000000\n".to_vec())); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_001 + )) + .unwrap_err() + .to_string(), + "KEEPER_CLEANUP_DEADLINE" + ); + assert_eq!(session.end, 100_000_000); + assert_eq!(session.group.events, events); + } + #[test] + fn r21_complete_rejected_line_alone_can_clean_after_proven_quiescence() { + let mut session = helper_fixture(); + session.control("CLEAN|1000", 1).unwrap(); + session.step(&mut || Ok(2)).unwrap(); + let mut expected = session.group.events.clone(); + let mut channel = scripted_channel(format!("{}|PARK\n", "b".repeat(32)).as_bytes()); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(3)).unwrap(), + Turn::Again + ); + expected.push("query"); + assert_eq!(session.group.events, expected); + assert_eq!(session.first_fault, Some("KEEPER_CHANNEL")); + assert!(!session.gone && !session.released); + assert!(channel.stream.output.is_empty()); + } + #[test] + fn r21_recoverable_line_errors_drain_suffix_under_the_same_frame_cap() { + let nonce = "a".repeat(32); + let variants = [ + b"missing-pipe\n".to_vec(), + vec![255, b'\n'], + format!("{nonce}|PARK\r\n").into_bytes(), + { + let mut b = vec![b'x'; 270]; + b.push(b'\n'); + b + }, + ]; + for bad in variants { + let mut session = helper_fixture(); + session.control("CLEAN|1000000000", 1).unwrap(); + session.step(&mut || Ok(2)).unwrap(); + let events = session.group.events.clone(); + let mut bytes = bad; + bytes.extend(r21_parent_frame(100_000_000, 10_000_000)); + let mut channel = scripted_channel(&[]); + // A complete oversized line can be rejected at its known boundary + // when a short prefix plus a second bounded read includes newline. + channel.stream.actions = bytes + .chunks(200) + .map(|b| ReadAction::Bytes(b.to_vec())) + .collect(); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_000 + )) + .unwrap_err() + .to_string(), + "KEEPER_CLEANUP_DEADLINE" + ); + assert_eq!(session.end, 100_000_000); + assert_eq!(session.group.events, events); + assert_eq!(session.first_fault, Some("KEEPER_CHANNEL")); + assert!(channel.stream.output.is_empty()); + } + } + #[test] + fn r21_rejected_frame_cap_yields_before_buffered_minimum() { + let mut session = helper_fixture(); + session.control("CLEAN|1000000000", 1).unwrap(); + session.step(&mut || Ok(2)).unwrap(); + let events = session.group.events.clone(); + let mut bytes = format!("{}|PARK\n", "b".repeat(32)).repeat(8).into_bytes(); + bytes.extend(r21_parent_frame(100_000_000, 10_000_000)); + let mut channel = scripted_channel(&bytes); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_000 + )) + .unwrap(), + Turn::Again + ); + assert_eq!(session.group.events, events); + assert_eq!(session.first_fault, Some("KEEPER_CHANNEL")); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_001 + )) + .unwrap_err() + .to_string(), + "KEEPER_CLEANUP_DEADLINE" + ); + assert_eq!(session.end, 100_000_000); + assert_eq!(session.group.events, events); + } + #[test] + fn r21_fatal_stop_preserves_prior_expiry_reason() { + let mut session = helper_fixture(); + let at = session.lifetime.operation_end; + session.step(&mut || Ok(at)).unwrap(); + let mut events = session.group.events.clone(); + let mut channel = scripted_channel(&[]); + channel.stream.actions.push_back(ReadAction::Fault); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(at + 1)) + .unwrap_err() + .to_string(), + "KEEPER_LIFETIME" + ); + events.push("disable"); + assert_eq!(session.group.events, events); + assert_eq!(session.first_fault, Some("KEEPER_LIFETIME")); + assert!(!session.gone && !session.released); + } + #[test] + fn r21_fatal_error_after_absence_never_reports_terminal_success() { + let mut session = helper_fixture(); + session.group.absent = true; + session.control("CLEAN|1000", 1).unwrap(); + assert!(session.step(&mut || Ok(2)).unwrap()); + let mut channel = scripted_channel(&[]); + channel.stream.actions.push_back(ReadAction::Fault); + assert!(keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(3)).is_err()); + assert!(session.gone); + assert!(!session.released); + assert!(session.authority_stopped); + assert_eq!(session.first_fault, Some("KEEPER_CHANNEL")); + assert!(channel.stream.output.is_empty()); + assert!(session.control("RELEASE", 4).is_err()); + assert!(session.park(&mut || Ok(4)).is_err()); + } + // R22: no group side effect, including initial PARK and its self-kill + // fallback, can precede the same turn's bounded control drain. + fn r22_park_with_expired_minimum(fail_park: bool) { + let mut session = helper_fixture(); + session.group.fail_park = fail_park; + let mut bytes = format!("{}|PARK\n", "a".repeat(32)).into_bytes(); + bytes.extend(r21_parent_frame(100_000_000, 10_000_000)); + let mut channel = scripted_channel(&bytes); + let result = keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || { + Ok(150_000_000) + }); + assert!( + session.group.events.is_empty(), + "PARK/self-kill must not precede the buffered minimum" + ); + assert_eq!(session.end, 100_000_000); + assert!(channel.stream.output.is_empty()); + assert_eq!(result.unwrap_err().to_string(), "KEEPER_CLEANUP_DEADLINE"); + assert!(!session.gone && !session.released && !session.abandoned); + } + #[test] + fn r22_initial_park_consumes_expired_buffered_minimum_before_membership_change() { + r22_park_with_expired_minimum(false); + } + #[test] + fn r22_failed_initial_park_cannot_self_kill_before_buffered_minimum() { + r22_park_with_expired_minimum(true); + } + fn r22_pending_park_channel() -> (KeeperSession, Channel) { + let session = helper_fixture(); + let bytes = format!("{}|PARK\n", "a".repeat(32)).into_bytes(); + (session, scripted_channel(&bytes)) + } + #[test] + fn r22_park_intent_survives_read_budget_yield_without_group_work() { + let (mut session, mut channel) = r22_pending_park_channel(); + channel + .stream + .actions + .extend((0..7).map(|_| ReadAction::Interrupted)); + channel + .stream + .actions + .push_back(ReadAction::Bytes(r21_parent_frame(100_000_000, 10_000_000))); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_000 + )) + .unwrap(), + Turn::Again + ); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_001 + )) + .unwrap_err() + .to_string(), + "KEEPER_CLEANUP_DEADLINE" + ); + assert_eq!(session.end, 100_000_000); + assert!(session.group.events.is_empty()); + } + #[test] + fn r22_park_intent_survives_partial_wouldblock_without_group_work() { + let (mut session, mut channel) = r22_pending_park_channel(); + channel.stream.actions.push_back(ReadAction::Bytes( + format!("{}|CLEAN|", "a".repeat(32)).into_bytes(), + )); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_000 + )) + .unwrap(), + Turn::Again + ); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + channel + .stream + .actions + .push_back(ReadAction::Bytes(b"100000000\n".to_vec())); + assert!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_001 + )) + .is_err() + ); + assert_eq!(session.end, 100_000_000); + assert!(session.group.events.is_empty()); + } + #[test] + fn r22_park_intent_is_not_executed_before_fatal_transport_stop() { + let (mut session, mut channel) = r22_pending_park_channel(); + channel.stream.actions.push_back(ReadAction::Fault); + assert!(keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(1)).is_err()); + assert_eq!(session.group.events, ["disable"]); + assert!(channel.stream.output.is_empty()); + assert!(session.authority_stopped); + assert_eq!(session.first_fault, Some("KEEPER_CHANNEL")); + } + #[test] + fn r22_duplicate_pending_park_cannot_bypass_minimum_on_failure_cleanup() { + let mut session = helper_fixture(); + let mut bytes = format!("{0}|PARK\n{0}|PARK\n", "a".repeat(32)).into_bytes(); + bytes.extend(r21_parent_frame(100_000_000, 10_000_000)); + let mut channel = scripted_channel(&bytes); + assert!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_000 + )) + .is_err() + ); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + assert_eq!(session.end, 100_000_000); + assert_eq!(session.first_fault, Some("KEEPER_CONTROL")); + } + #[test] + fn r22_timely_lone_park_preserves_original_handshake() { + let (mut session, mut channel) = r22_pending_park_channel(); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(1)).unwrap(), + Turn::Again + ); + assert_eq!(session.group.events, ["park"]); + assert!(session.parked); + assert_eq!( + channel.stream.output, + format!("{}|PARKED|42|7|7\n", "a".repeat(32)).as_bytes() + ); + assert!(!session.cleaning && !session.gone && session.first_fault.is_none()); + } + #[test] + fn r22_pre_park_eof_retains_failure_cleanup_and_parking_loss_fallback() { + for fail_park in [false, true] { + let mut session = helper_fixture(); + session.group.fail_park = fail_park; + let mut channel = scripted_channel(&[]); + channel.stream.actions.push_back(ReadAction::Bytes(vec![])); + let result = keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(1)); + assert_eq!(session.first_fault, Some("KEEPER_OWNER_EOF")); + assert!(!session.gone && !session.released); + assert!(channel.stream.output.is_empty()); + if fail_park { + assert!(result.is_err()); + assert_eq!(session.group.events, ["park", "self-kill"]); + } else { + assert_eq!(result.unwrap(), Turn::Again); + assert_eq!(session.group.events, ["park", "query", "term"]); + } + } + } + #[test] + fn r22_pending_park_survives_frame_cap_before_ninth_minimum() { + let (mut session, mut channel) = r22_pending_park_channel(); + let mut rest = (0..7) + .map(|n| format!("{}|CLEAN|{}\n", "a".repeat(32), 1_000_000_000 - n)) + .collect::() + .into_bytes(); + rest.extend(r21_parent_frame(100_000_000, 10_000_000)); + channel.stream.actions.extend( + rest.chunks(MAX_FRAME) + .map(|b| ReadAction::Bytes(b.to_vec())), + ); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_000 + )) + .unwrap(), + Turn::Again + ); + assert!(session.park_requested); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + assert!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_001 + )) + .is_err() + ); + assert_eq!(session.end, 100_000_000); + assert!(session.group.events.is_empty()); + } + #[test] + fn r22_pending_park_is_executed_once_after_later_true_quiescence() { + let (mut session, mut channel) = r22_pending_park_channel(); + channel + .stream + .actions + .extend((0..8).map(|_| ReadAction::Interrupted)); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(1)).unwrap(), + Turn::Again + ); + assert!(session.park_requested); + assert!(session.group.events.is_empty()); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(2)).unwrap(), + Turn::Again + ); + assert!(!session.park_requested); + assert_eq!(session.group.events, ["park"]); + let output = channel.stream.output.clone(); + assert_eq!( + output, + format!("{}|PARKED|42|7|7\n", "a".repeat(32)).as_bytes() + ); + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(3)).unwrap(), + Turn::Again + ); + assert_eq!(channel.stream.output, output); + assert_eq!(session.group.events, ["park"]); + } + #[test] + fn r22_parked_response_failure_still_starts_bounded_failure_cleanup() { + let (mut session, mut channel) = r22_pending_park_channel(); + let bytes = channel + .stream + .actions + .front() + .map(|a| match a { + ReadAction::Bytes(b) => b.len(), + _ => 0, + }) + .unwrap(); + channel.wire = MAX_WIRE - bytes; + assert_eq!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(1)).unwrap(), + Turn::Again + ); + assert_eq!(session.group.events, ["park", "query", "term"]); + assert_eq!(session.first_fault, Some("KEEPER_CONTROL")); + assert!(!session.gone && !session.released); + assert!(channel.stream.output.is_empty()); + assert!(session.end <= 1 + CLEANUP_NS); + } + #[test] + fn r22_timely_park_loss_retains_one_failure_only_self_group_fallback() { + let (mut session, mut channel) = r22_pending_park_channel(); + session.group.fail_park = true; + assert!(keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok(1)).is_err()); + assert_eq!(session.group.events, ["park", "self-kill"]); + assert_eq!(session.first_fault, Some("KEEPER_PARK")); + assert!(session.abandoned); + assert!(!session.gone && !session.released); + assert!(channel.stream.output.is_empty()); + } + #[test] + fn r22_rejected_line_after_park_intent_does_not_bypass_buffered_minimum() { + let (mut session, mut channel) = r22_pending_park_channel(); + let mut bytes = format!("{}|PARK\n", "b".repeat(32)).into_bytes(); + bytes.extend(r21_parent_frame(100_000_000, 10_000_000)); + channel.stream.actions.push_back(ReadAction::Bytes(bytes)); + assert!( + keeper_turn(&mut session, &mut channel, 42, 7, 7, &mut || Ok( + 150_000_000 + )) + .is_err() + ); + assert_eq!(session.end, 100_000_000); + assert_eq!(session.first_fault, Some("KEEPER_CHANNEL")); + assert!(session.group.events.is_empty()); + assert!(channel.stream.output.is_empty()); + } +} + +// Short-policy acceptance runs the actual lifetime, settlement and keeper +// machines with finite clocks/socketpairs/GroupOps; no second cleanup model. +#[cfg(test)] +mod short_policy_tests { + use super::*; + #[test] + #[cfg(feature = "dev-tools")] + fn failure_setup_trace_origin_is_sticky_and_excludes_sibling_cancellation() { + let owner: SharedOwner = Default::default(); + let mut first = SetupTrace::default(); + let mut sibling = SetupTrace::default(); + first.note_fault_origin(&owner, Phase::Joined, "GROUP_DEADLINE"); + owner.borrow_mut().poison(ProtocolError("GROUP_DEADLINE")); + first.note_fault_origin(&owner, Phase::Cleaning, "GROUP_IO"); + sibling.note_fault_origin(&owner, Phase::AwaitReady, "GROUP_DEADLINE"); + assert_eq!(first.fault_origin, Some(("GROUP_DEADLINE", "JOINED"))); + assert!(sibling.fault_origin.is_none()); + assert_eq!( + owner.borrow().first_fault, + Some(ProtocolError("GROUP_DEADLINE")) + ); + } + + use std::os::unix::net::UnixStream; + struct Group { + actions: Vec<&'static str>, + absent: bool, + } + impl GroupOps for Group { + fn park(&mut self) -> io::Result<()> { + self.actions.push("park"); + Ok(()) + } + fn absent(&mut self) -> io::Result { + self.actions.push("query"); + Ok(self.absent) + } + fn signal(&mut self, signal: i32) -> io::Result<()> { + self.actions.push(if signal == libc::SIGTERM { + "term" + } else { + "kill" + }); + Ok(()) + } + fn abandon_self_group(&mut self) -> io::Result<()> { + panic!("not a failure parking case") + } + fn disable(&mut self) { + self.actions.push("disable"); + } + } + fn session() -> KeeperSession { + KeeperSession::new( + Group { + actions: vec![], + absent: false, + }, + Lifetime::with_policy(0, 550_000_000, CleanupPolicy::HookShort).unwrap(), + ) + } + #[test] + fn admitted_hook_lifetime_reserves_fifty_ms_inside_original_end() { + let lifetime = Lifetime::with_policy(0, 550_000_000, CleanupPolicy::HookShort).unwrap(); + assert_eq!(lifetime.operation_end, 500_000_000); + assert_eq!(lifetime.hard_end, 550_000_000); + assert_eq!(lifetime.policy, CleanupPolicy::HookShort); + assert!(Lifetime::with_policy(0, 50_000_000, CleanupPolicy::HookShort).is_err()); + assert!(Lifetime::with_policy(1, 0, CleanupPolicy::HookShort).is_err()); + } + #[test] + fn parent_clean_is_capped_to_the_short_reserve_not_legacy_tail() { + let (left, _right) = UnixStream::pair().unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + let mut state = Settlement::with_policy(550_000_000, CleanupPolicy::HookShort); + state.begin(550_000_000, 100_000_000, &mut channel).unwrap(); + assert_eq!(state.progress.deadline_ns, 150_000_000); + state.begin(500_000_000, 110_000_000, &mut channel).unwrap(); + assert_eq!(state.progress.deadline_ns, 150_000_000); + state.begin(140_000_000, 120_000_000, &mut channel).unwrap(); + assert_eq!(state.progress.deadline_ns, 140_000_000); + } + #[test] + fn keeper_failure_and_control_share_the_same_short_minimum() { + let mut s = session(); + s.fail("ORIGINAL", 100_000_000); + assert_eq!(s.end, 150_000_000); + s.control("CLEAN|140000000", 110_000_000).unwrap(); + s.control("CLEAN|500000000", 120_000_000).unwrap(); + assert_eq!(s.end, 140_000_000); + assert_eq!(s.first_fault, Some("ORIGINAL")); + } + #[test] + fn expiry_starts_cleanup_inside_end_and_signals_never_after_end() { + let mut s = session(); + s.parked = true; + s.step(&mut || Ok(500_000_000)).unwrap(); + assert_eq!(s.end, 550_000_000); + assert_eq!(s.term_end, Some(515_000_000)); + assert_eq!(s.group.actions, ["query", "term"]); + s.step(&mut || Ok(515_000_000)).unwrap(); + assert_eq!(s.group.actions, ["query", "term", "query", "kill"]); + let before = s.group.actions.clone(); + assert!(s.step(&mut || Ok(550_000_000)).is_err()); + assert_eq!(s.group.actions, before); + assert_eq!(s.first_fault, Some("KEEPER_LIFETIME")); + } + #[test] + fn short_handshake_and_failed_drop_never_restart_the_inherited_budget() { + let p = CleanupPolicy::HookShort; + assert_eq!(p.setup_end(100_000_000, 550_000_000), 120_000_000); + assert_eq!(p.setup_end(490_000_000, 550_000_000), 500_000_000); + assert_eq!(p.observation_end(100_000_000, 140_000_000), 140_000_000); + assert_eq!(p.observation_end(200_000_000, 140_000_000), 140_000_000); + assert_eq!(p.observation_end(u64::MAX - 1, u64::MAX), u64::MAX); + assert_eq!( + CleanupPolicy::Legacy.setup_end(0, 3_000_000_000), + 1_200_000_000 + ); + } + #[test] + fn faulted_parent_caps_retention_to_short_end_without_clearing_first_fault() { + let (left, _right) = UnixStream::pair().unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + let mut state = Settlement::with_policy(550_000_000, CleanupPolicy::HookShort); + state.progress.fail("ORIGINAL"); + assert!(state.begin(550_000_000, 100_000_000, &mut channel).is_err()); + state.cap_failed_observation(Some(100_000_000), 550_000_000); + assert_eq!(state.progress.deadline_ns, 150_000_000); + state.cap_failed_observation(Some(110_000_000), 500_000_000); + assert_eq!(state.progress.deadline_ns, 150_000_000); + state.cap_failed_observation(None, 500_000_000); + assert_eq!(state.progress.deadline_ns, 0); + assert_eq!(state.progress.first_fault, Some("ORIGINAL")); + } + #[test] + fn failed_control_send_keeps_failed_observation_within_same_short_policy() { + let (left, right) = UnixStream::pair().unwrap(); + left.shutdown(std::net::Shutdown::Write).unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + let mut state = Settlement::with_policy(550_000_000, CleanupPolicy::HookShort); + assert!(state.begin(550_000_000, 100_000_000, &mut channel).is_err()); + state.progress.fail("SEND_FAILED"); + state.cap_failed_observation(Some(100_000_000), 550_000_000); + assert_eq!(state.progress.deadline_ns, 150_000_000); + assert!(!state.cleanup_sent); + assert_eq!(state.progress.first_fault, Some("SEND_FAILED")); + drop(right); + } + #[test] + fn keeper_policy_tag_is_closed_not_a_caller_supplied_allowance() { + assert_eq!( + CleanupPolicy::keeper_tag(None).unwrap(), + CleanupPolicy::Legacy + ); + assert_eq!( + CleanupPolicy::keeper_tag(Some("hook-short-v1")).unwrap(), + CleanupPolicy::HookShort + ); + for invalid in [ + "", + "legacy", + "hook-short-v2", + "5000000000", + "hook-short-v1\n", + ] { + assert_eq!( + CleanupPolicy::keeper_tag(Some(invalid)) + .unwrap_err() + .to_string(), + "KEEPER_POLICY" + ); + } + } + #[test] + fn legacy_policy_values_and_admission_remain_unchanged() { + let life = Lifetime::new(0, 3_000_000_000).unwrap(); + assert_eq!(life.policy, CleanupPolicy::Legacy); + assert_eq!(life.operation_end, 1_200_000_000); + assert!(Lifetime::new(0, CLEANUP_NS).is_err()); + assert_eq!(CleanupPolicy::Legacy.reserve_ns(), CLEANUP_NS); + assert_eq!(CleanupPolicy::Legacy.term_ns(), 15_000_000); + assert_eq!(CleanupPolicy::HookShort.reserve_ns(), 50_000_000); + assert_eq!(CleanupPolicy::HookShort.term_ns(), 15_000_000); + assert_eq!(CleanupPolicy::HookShort.setup_ns(), 20_000_000); + } + #[test] + fn command_probe_setup_uses_the_same_original_operation_end() { + let policy = CleanupPolicy::CommandProbe; + let hard = 1_000_000_000; + assert_eq!(policy.setup_end(100_000_000, hard), 950_000_000); + assert_eq!(policy.setup_end(300_000_000, hard), 950_000_000); + assert_eq!(policy.setup_end(960_000_000, hard), 950_000_000); + let lifetime = Lifetime::with_policy(100_000_000, hard, policy).unwrap(); + assert_eq!(lifetime.operation_end, 950_000_000); + assert_eq!(lifetime.hard_end, hard); + } + #[test] + fn command_probe_cleanup_never_renews_original_or_tighter_end() { + let (left, _right) = UnixStream::pair().unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + let mut state = Settlement::with_policy(1_000_000_000, CleanupPolicy::CommandProbe); + state + .begin(1_000_000_000, 100_000_000, &mut channel) + .unwrap(); + assert_eq!(state.progress.deadline_ns, 150_000_000); + state + .begin(1_000_000_000, 120_000_000, &mut channel) + .unwrap(); + assert_eq!(state.progress.deadline_ns, 150_000_000); + state.begin(140_000_000, 125_000_000, &mut channel).unwrap(); + assert_eq!(state.progress.deadline_ns, 140_000_000); + assert_eq!(CleanupPolicy::CommandProbe.term_ns(), 15_000_000); + assert!(Lifetime::with_policy(0, 50_000_000, CleanupPolicy::CommandProbe).is_err()); + } + #[test] + fn command_probe_keeper_tag_is_closed_and_does_not_change_hook_policy() { + assert_eq!( + CleanupPolicy::keeper_tag(Some("command-probe-v1")).unwrap(), + CleanupPolicy::CommandProbe + ); + for invalid in [ + "command-probe-v2", + "command-probe-v1\n", + "1000000000", + "command-probe-v1:1000000000", + ] { + assert!(CleanupPolicy::keeper_tag(Some(invalid)).is_err()); + } + assert_eq!( + CleanupPolicy::HookShort.setup_end(100_000_000, 550_000_000), + 120_000_000 + ); + assert_eq!(CleanupPolicy::HookShort.reserve_ns(), 50_000_000); + assert_eq!(CleanupPolicy::HookShort.term_ns(), 15_000_000); + } + #[test] + fn command_probe_is_refused_by_public_owned_image_gateway_before_preparation() { + let result = GroupLease::spawn_keeper_with_policy( + Default::default(), + Path::new("not-an-absolute-root"), + Path::new("not-an-image"), + 1_000_000_000, + CleanupPolicy::CommandProbe, + ); + assert_eq!(result.err().unwrap().to_string(), "GROUP_POLICY"); + } + #[test] + fn command_probe_ready_and_park_share_inherited_minimum_and_reject_equality() { + let policy = CleanupPolicy::CommandProbe; + assert_eq!(policy.setup_end(0, 180_000_000), 130_000_000); + assert_eq!(policy.setup_end(120_000_000, 180_000_000), 130_000_000); + assert_eq!(policy.setup_end(130_000_000, 180_000_000), 130_000_000); + assert!(Lifetime::with_policy(130_000_000, 180_000_000, policy).is_err()); + assert_eq!( + policy.setup_end(u64::MAX - 1, u64::MAX), + u64::MAX - 50_000_000 + ); + let mut session = KeeperSession::new( + Group { + actions: vec![], + absent: false, + }, + Lifetime::with_policy(0, 1_000_000_000, policy).unwrap(), + ); + session.parked = true; + session.step(&mut || Ok(950_000_000)).unwrap(); + assert_eq!(session.end, 1_000_000_000); + assert_eq!(session.term_end, Some(965_000_000)); + session.step(&mut || Ok(965_000_000)).unwrap(); + let actions = session.group.actions.clone(); + assert!(session.step(&mut || Ok(1_000_000_000)).is_err()); + assert_eq!(session.group.actions, actions); + assert_eq!(session.first_fault, Some("KEEPER_LIFETIME")); + } +} + +#[cfg(all(test, feature = "dev-tools"))] +mod dev_client_keeper_policy_tests { + use super::*; + fn selected() -> CleanupPolicy { + super::super::scope::dev_client_keeper_policy() + } + #[test] + fn dev_client_keeper_policy_uses_remaining_ordinary_setup_before_cleanup() { + let admitted = 100_000_000; + let hard = 1_100_000_000; + let setup_end = selected().setup_end(admitted, hard); + assert_eq!(setup_end, 1_050_000_000); + // A READY observation after the hook window can be timely for a + // one-second native command, but never beyond that command's end. + assert!(admitted + 30_000_000 < setup_end); + assert_eq!(selected().reserve_ns(), 50_000_000); + assert_eq!(selected().term_ns(), 15_000_000); + } + #[test] + fn dev_client_keeper_policy_honors_earlier_parent_without_restarting_setup() { + let hard = 180_000_000; + assert_eq!(selected().setup_end(100_000_000, hard), 130_000_000); + assert_eq!(selected().setup_end(120_000_000, hard), 130_000_000); + assert!(Lifetime::with_policy(130_000_000, hard, selected()).is_err()); + } + #[test] + fn dev_client_keeper_policy_is_closed_and_keeps_hook_policy_unchanged() { + assert_eq!(selected(), CleanupPolicy::CommandProbe); + assert_eq!( + CleanupPolicy::keeper_tag(Some("command-probe-v1")).unwrap(), + selected() + ); + assert_eq!( + CleanupPolicy::HookShort.setup_end(100_000_000, 1_100_000_000), + 120_000_000 + ); + assert_eq!(CleanupPolicy::HookShort.reserve_ns(), 50_000_000); + assert_eq!(CleanupPolicy::HookShort.term_ns(), 15_000_000); + } +} + +#[cfg(test)] +mod progress_readiness_getter_tests { + use super::*; + #[test] + fn cleanup_readiness_getters_preserve_partial_and_complete_buffered_frames() { + let (left, mut right) = UnixStream::pair().unwrap(); + right.set_nonblocking(true).unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + let fd = channel.stream.as_raw_fd(); + right.write_all("a".repeat(32).as_bytes()).unwrap(); + assert!(channel.receive().unwrap().is_none()); + assert!(!channel.cleanup_buffered_event()); + assert_eq!(channel.cleanup_wait_source(), Some(fd)); + let partial = channel.pending.clone(); + assert_eq!(channel.cleanup_wait_source(), Some(fd)); + assert_eq!( + channel.pending, partial, + "hint consumed partial protocol bytes" + ); + right + .write_all(format!("|PARK|7\n{}|GONE|7\n", "a".repeat(32)).as_bytes()) + .unwrap(); + assert_eq!(channel.receive().unwrap().as_deref(), Some("PARK|7")); + assert!(channel.cleanup_buffered_event()); + let complete = channel.pending.clone(); + assert_eq!(channel.cleanup_wait_source(), Some(fd)); + assert!(channel.cleanup_buffered_event()); + assert_eq!(channel.pending, complete, "hint consumed a complete GONE"); + assert!(!channel.eof); + assert_eq!(channel.receive().unwrap().as_deref(), Some("GONE|7")); + assert!(!channel.cleanup_buffered_event()); + assert_eq!(channel.cleanup_wait_source(), Some(fd)); + } + #[test] + fn cleanup_readiness_omits_only_physically_observed_eof_not_peer_shutdown_hint() { + let (left, right) = UnixStream::pair().unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + let fd = channel.stream.as_raw_fd(); + right.shutdown(std::net::Shutdown::Write).unwrap(); + // A physical hangup can wake the next read, but is not yet read(0). + assert_eq!(channel.cleanup_wait_source(), Some(fd)); + assert!(!channel.eof); + assert!(channel.receive().unwrap().is_none()); + assert!(channel.eof); + assert_eq!(channel.cleanup_wait_source(), None); + assert!(!channel.cleanup_buffered_event()); + // All wait-only turns now use the original no-usefulFD cadence. + assert_eq!(channel.cleanup_wait_source(), None); + assert!(channel.pending.is_empty()); + } + #[test] + fn cleanup_readiness_end_is_actual_shortened_settlement_end_not_setup_window() { + let (left, _right) = UnixStream::pair().unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + let mut settlement = Settlement::with_policy(500_000_000, CleanupPolicy::HookShort); + assert_eq!(settlement.progress_wait_end(), 500_000_000); + assert_eq!( + CleanupPolicy::HookShort.setup_end(0, 500_000_000), + 20_000_000 + ); + settlement.progress.phase = Phase::Parked; + settlement + .begin(300_000_000, 100_000_000, &mut channel) + .unwrap(); + assert_eq!(settlement.progress_wait_end(), 150_000_000); + settlement + .begin(120_000_000, 110_000_000, &mut channel) + .unwrap(); + assert_eq!(settlement.progress_wait_end(), 120_000_000); + settlement + .begin(300_000_000, 115_000_000, &mut channel) + .unwrap(); + assert_eq!(settlement.progress_wait_end(), 120_000_000); + assert!(settlement.workload_status.is_none() && settlement.keeper_status.is_none()); + assert!(!settlement.group_absent && !settlement.release_sent); + assert_eq!(settlement.progress.phase, Phase::Cleaning); + } + + #[test] + fn cleanup_readiness_partial_at_physical_eof_remains_original_truncation_fault() { + let (left, mut right) = UnixStream::pair().unwrap(); + right.set_nonblocking(true).unwrap(); + let mut channel = Channel::new(left, "a".repeat(32)).unwrap(); + right.write_all("a".repeat(32).as_bytes()).unwrap(); + right.shutdown(std::net::Shutdown::Write).unwrap(); + assert_eq!( + channel.receive().unwrap_err().to_string(), + "GROUP_TRUNCATED" + ); + assert!(channel.eof && !channel.pending.is_empty()); + assert_eq!(channel.cleanup_wait_source(), None); + assert!(channel.cleanup_buffered_event()); + let pending = channel.pending.clone(); + assert!(channel.cleanup_buffered_event()); + assert_eq!(channel.pending, pending); + } +} diff --git a/src/process_ownership/image.rs b/src/process_ownership/image.rs new file mode 100644 index 0000000..5be2e2d --- /dev/null +++ b/src/process_ownership/image.rs @@ -0,0 +1,731 @@ +//! Retained guard-image identity for internal resource ownership only. +//! A private Rust constructor is not an OS file seal: snapshot/exec races remain +//! subject to the same inode checks as the existing core bootstrap. +use sha2::{Digest, Sha256}; +use std::{ + ffi::CString, + fs::{self, File}, + io::{self, Read}, + os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::{ffi::OsStrExt, fs::MetadataExt, process::CommandExt}, + }, + path::{Component, Path, PathBuf}, + process::Command, +}; + +const MAX_IMAGE: u64 = 128 * 1024 * 1024; +const IMAGE_ENV: &str = "KEITO_CAPTURE_KEEPER_IMAGE_FD"; +pub(crate) const KEEPER_ROLE: &str = "--internal-keeper-v1"; +#[allow(dead_code)] // Used by the standalone guard's shared-source inclusion. +pub(crate) const DISPATCH_ROLE: &str = "--internal-dispatch-v2"; +#[allow(dead_code)] +pub(crate) const GUARDIAN_ROLE: &str = "--internal-guardian-v2"; +fn refused() -> io::Error { + io::Error::other("KEEPER_IMAGE") +} +fn open_path(path: &Path) -> io::Result { + if !path.is_absolute() + || path + .components() + .any(|p| matches!(p, Component::ParentDir | Component::CurDir)) + { + return Err(refused()); + } + let root = CString::new("/").unwrap(); + let fd = unsafe { + libc::open( + root.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + let mut parent = unsafe { OwnedFd::from_raw_fd(fd) }; + let parts: Vec<_> = path + .components() + .filter_map(|p| { + if let Component::Normal(p) = p { + Some(p) + } else { + None + } + }) + .collect(); + let (leaf, ancestors) = parts.split_last().ok_or_else(refused)?; + for part in ancestors { + let name = CString::new(part.as_bytes()).map_err(|_| refused())?; + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + parent = unsafe { OwnedFd::from_raw_fd(fd) }; + } + let name = CString::new(leaf.as_bytes()).map_err(|_| refused())?; + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return Err(refused()); + } + Ok(unsafe { File::from_raw_fd(fd) }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +struct Stamp { + device: u64, + inode: u64, + size: u64, + mode: u32, + uid: u32, + links: u64, + modified: i64, + modified_ns: i64, + changed: i64, + changed_ns: i64, +} +impl Stamp { + fn of(m: &fs::Metadata) -> Self { + Self { + device: m.dev(), + inode: m.ino(), + size: m.len(), + mode: m.mode(), + uid: m.uid(), + links: m.nlink(), + modified: m.mtime(), + modified_ns: m.mtime_nsec(), + changed: m.ctime(), + changed_ns: m.ctime_nsec(), + } + } +} + +/// The only product caller is the compiled-anchor HookRuntime factory. Public +/// runtime descriptors and caller-supplied manifests cannot construct this type. +pub(crate) struct VerifiedKeeperImage { + file: File, + path: PathBuf, + stamp: Stamp, +} +impl VerifiedKeeperImage { + /// Resource-only self-image authority in the already-running guard. This + /// does not create a release/source/capture proof or accept another path. + #[allow(dead_code)] + pub(crate) fn running_guard() -> io::Result { + let path = std::env::current_exe()?; + // This is resource-only self-image admission, not a compiled-anchor + // check. Retain the same opened image through its single hash pass. + Self::open_hashed(&path, |file, bytes| file.read(bytes)).map(|(image, _)| image) + } + pub(crate) fn open(path: &Path, expected: &str) -> io::Result { + if expected.len() != 64 + || !expected + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + || !path.is_absolute() + || path + .components() + .any(|p| matches!(p, Component::ParentDir | Component::CurDir)) + { + return Err(refused()); + } + let (image, actual) = Self::open_hashed(path, |file, bytes| file.read(bytes))?; + // Anchored admission always compares the supplied compiled digest. + if actual != expected { + return Err(refused()); + } + Ok(image) + } + fn open_hashed( + path: &Path, + mut read: impl FnMut(&mut File, &mut [u8]) -> io::Result, + ) -> io::Result<(Self, String)> { + let mut file = open_path(path)?; + let before = file.metadata().map_err(|_| refused())?; + // Separate product policy; the legacy QA constructor still requires700. + if !before.is_file() + || before.mode() & 0o111 == 0 + || before.mode() & 0o022 != 0 + || before.nlink() != 1 + || (before.uid() != 0 && before.uid() != unsafe { libc::geteuid() }) + || before.len() > MAX_IMAGE + { + return Err(refused()); + } + let stamp = Stamp::of(&before); + let mut digest = Sha256::new(); + let mut bytes = [0u8; 65536]; + let mut length = 0u64; + loop { + let n = read(&mut file, &mut bytes).map_err(|_| refused())?; + if n == 0 { + break; + } + // Real File::read respects the buffer; the explicit check also + // keeps injected faults from indexing outside the admitted block. + if n > bytes.len() { + return Err(refused()); + } + length = length + .checked_add(n as u64) + .filter(|n| *n <= MAX_IMAGE) + .ok_or_else(refused)?; + digest.update(&bytes[..n]); + } + let actual: String = digest + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + if length != before.len() || Stamp::of(&file.metadata().map_err(|_| refused())?) != stamp { + return Err(refused()); + } + let result = Self { + file, + path: path.into(), + stamp, + }; + result.check_current()?; + Ok((result, actual)) + } + fn check_current(&self) -> io::Result<()> { + let file = self.file.metadata().map_err(|_| refused())?; + let path = open_path(&self.path)?.metadata().map_err(|_| refused())?; + if Stamp::of(&file) != self.stamp || Stamp::of(&path) != self.stamp { + return Err(refused()); + } + Ok(()) + } + // Keep the duplicated image FD alive in the parent until spawn has returned + // its real Child. All descriptor inventory/allocation occurs before fork. + pub(super) fn command(&self, control: i32) -> io::Result<(Command, OwnedFd)> { + self.command_role(control, KEEPER_ROLE) + } + #[allow(dead_code)] + pub(crate) fn guardian_command(&self, control: i32) -> io::Result<(Command, OwnedFd)> { + self.command_role(control, GUARDIAN_ROLE) + } + fn command_role(&self, control: i32, role: &'static str) -> io::Result<(Command, OwnedFd)> { + if !(4..=1024).contains(&control) { + return Err(refused()); + } + self.check_current()?; + let fd = unsafe { libc::fcntl(self.file.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 5) }; + if fd < 0 { + return Err(refused()); + } + let image = unsafe { OwnedFd::from_raw_fd(fd) }; + if fd > 1024 || fd == control { + return Err(refused()); + } + let inherited = inventory(control, fd)?; + let path = CString::new(self.path.as_os_str().as_bytes()).map_err(|_| refused())?; + let stamp = self.stamp; + #[cfg(target_os = "linux")] + let mut command = Command::new(format!("/dev/fd/{fd}")); + #[cfg(not(target_os = "linux"))] + let mut command = Command::new(&self.path); + command.arg(role); + unsafe { + command.pre_exec(move || { + let mut current = std::mem::MaybeUninit::::uninit(); + if libc::lstat(path.as_ptr(), current.as_mut_ptr()) != 0 { + return Err(io::Error::last_os_error()); + } + let current = current.assume_init(); + if current.st_dev as u128 != u128::from(stamp.device) + || u128::from(current.st_ino) != u128::from(stamp.inode) + || current.st_mode & libc::S_IFMT != libc::S_IFREG + { + return Err(io::Error::from_raw_os_error(libc::ESTALE)); + } + if libc::fcntl(fd, libc::F_SETFD, 0) < 0 { + return Err(io::Error::last_os_error()); + } + for other in &inherited { + libc::close(*other); + } + Ok(()) + }); + } + Ok((command, image)) + } + pub(crate) fn image_env() -> &'static str { + IMAGE_ENV + } +} + +#[cfg(any(target_os = "macos", target_os = "linux"))] +fn inventory(control: i32, image: i32) -> io::Result> { + use std::ffi::CStr; + let directory = CString::new("/dev/fd").unwrap(); + let raw = unsafe { libc::opendir(directory.as_ptr()) }; + if raw.is_null() { + return Err(refused()); + } + let own = unsafe { libc::dirfd(raw) }; + let mut descriptors = Vec::new(); + let failed = loop { + #[cfg(target_os = "macos")] + unsafe { + *libc::__error() = 0; + } + #[cfg(target_os = "linux")] + unsafe { + *libc::__errno_location() = 0; + } + let entry = unsafe { libc::readdir(raw) }; + if entry.is_null() { + break io::Error::last_os_error().raw_os_error().unwrap_or(0) != 0; + } + let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }; + if name.to_bytes() == b"." || name.to_bytes() == b".." { + continue; + } + let Some(fd) = name.to_str().ok().and_then(|n| n.parse::().ok()) else { + break true; + }; + if fd >= 3 && fd != own && fd != control && fd != image { + if descriptors.len() >= 4096 || descriptors.try_reserve(1).is_err() { + break true; + } + descriptors.push(fd); + } + }; + unsafe { + libc::closedir(raw); + } + if failed { + Err(refused()) + } else { + Ok(descriptors) + } +} +#[cfg(not(any(target_os = "macos", target_os = "linux")))] +fn inventory(_: i32, _: i32) -> io::Result> { + Err(refused()) +} + +/// Private keeper role entry, before parsing keeper controls or touching capture +/// state. The descriptor is consumed/closed, never turned into capture authority. +#[allow(dead_code)] // Called by the standalone guard's inclusion, not by libkeito. +pub(crate) fn bootstrap_keeper_image(control: i32) -> io::Result<()> { + let encoding = std::env::var("__CF_USER_TEXT_ENCODING").ok(); + if !closed_environment( + std::env::vars_os().map(|(key, _)| key), + encoding.as_deref(), + unsafe { libc::getuid() }, + ) { + return Err(refused()); + } + bootstrap_role_image(control) +} +pub(crate) fn bootstrap_role_image(control: i32) -> io::Result<()> { + let raw = std::env::var(IMAGE_ENV).map_err(|_| refused())?; + std::env::remove_var(IMAGE_ENV); + let fd = bootstrap_fd(&raw, control)?; + let file = unsafe { File::from_raw_fd(fd) }; + if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 { + return Err(refused()); + } + let metadata = file.metadata().map_err(|_| refused())?; + let running = + fs::metadata(std::env::current_exe().map_err(|_| refused())?).map_err(|_| refused())?; + if !metadata.is_file() + || metadata.len() > MAX_IMAGE + || metadata.nlink() != 1 + || metadata.mode() & 0o022 != 0 + || metadata.mode() & 0o111 == 0 + || (metadata.uid() != 0 && metadata.uid() != unsafe { libc::geteuid() }) + || unsafe { libc::fcntl(fd, libc::F_GETFL) } & libc::O_ACCMODE != libc::O_RDONLY + || metadata.dev() != running.dev() + || metadata.ino() != running.ino() + { + return Err(refused()); + } + Ok(()) +} +fn closed_environment( + keys: impl IntoIterator>, + encoding: Option<&str>, + uid: u32, +) -> bool { + let mut count = 0; + #[cfg(target_os = "macos")] + let expected = 2; + #[cfg(not(target_os = "macos"))] + let expected = 1; + for key in keys { + count += 1; + if count > expected { + return false; + } + let key = key.as_ref(); + if key == IMAGE_ENV { + continue; + } + #[cfg(target_os = "macos")] + if key == "__CF_USER_TEXT_ENCODING" { + continue; + } + return false; + } + #[cfg(target_os = "macos")] + { + count == expected && encoding == Some(format!("0x{uid:X}:0:0").as_str()) + } + #[cfg(not(target_os = "macos"))] + { + let _ = uid; + count == expected && encoding.is_none() + } +} +fn bootstrap_fd(raw: &str, control: i32) -> io::Result { + raw.parse::() + .ok() + .filter(|fd| (5..=1024).contains(fd) && *fd != control && fd.to_string() == raw) + .ok_or_else(refused) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::{symlink, PermissionsExt}; + struct Inert { + _temp: tempfile::TempDir, + path: PathBuf, + hash: String, + } + impl Inert { + fn new(mode: u32) -> Self { + let temp = tempfile::tempdir().unwrap(); + let path = temp + .path() + .canonicalize() + .unwrap() + .join("keito-capture-guard"); + fs::write(&path, b"inert guard bytes; MUST NEVER EXECUTE").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap(); + let hash = Sha256::digest(fs::read(&path).unwrap()) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + Self { + _temp: temp, + path, + hash, + } + } + } + // Inert files only. The injected reads execute the same constructor used + // by running_guard; no process, native role or capture authority is run. + #[test] + fn resource_image_single_hash_retains_the_original_readonly_descriptor() { + for mode in [0o700, 0o755] { + let fixture = Inert::new(mode); + let expected = fs::read(&fixture.path).unwrap(); + let mut observed_fd = None; + let mut bytes_read = 0; + let mut eof_reads = 0; + let (image, digest) = VerifiedKeeperImage::open_hashed(&fixture.path, |file, bytes| { + let fd = file.as_raw_fd(); + assert!(observed_fd.is_none_or(|original| original == fd)); + observed_fd = Some(fd); + let n = file.read(bytes)?; + bytes_read += n; + eof_reads += usize::from(n == 0); + Ok(n) + }) + .unwrap(); + assert_eq!(bytes_read, expected.len()); + assert_eq!(eof_reads, 1); + assert_eq!(digest, fixture.hash); + assert_eq!(observed_fd, Some(image.file.as_raw_fd())); + assert!(image.check_current().is_ok()); + assert_eq!( + unsafe { libc::fcntl(image.file.as_raw_fd(), libc::F_GETFL) } & libc::O_ACCMODE, + libc::O_RDONLY + ); + assert_eq!( + unsafe { libc::fcntl(image.file.as_raw_fd(), libc::F_GETFD) } & libc::FD_CLOEXEC, + libc::FD_CLOEXEC + ); + } + } + + #[test] + fn resource_image_single_hash_short_reads_keep_the_exact_digest() { + let fixture = Inert::new(0o700); + let (image, digest) = VerifiedKeeperImage::open_hashed(&fixture.path, |file, bytes| { + file.read(&mut bytes[..1]) + }) + .unwrap(); + assert_eq!(digest, fixture.hash); + assert!(image.check_current().is_ok()); + assert!(VerifiedKeeperImage::open(&fixture.path, &fixture.hash).is_ok()); + assert!(VerifiedKeeperImage::open(&fixture.path, &"0".repeat(64)).is_err()); + } + + #[test] + fn resource_image_single_hash_early_eof_and_read_fault_never_admit() { + let fixture = Inert::new(0o700); + assert!(VerifiedKeeperImage::open_hashed(&fixture.path, |_, _| Ok(0)).is_err()); + for kind in [io::ErrorKind::Interrupted, io::ErrorKind::Other] { + assert!(VerifiedKeeperImage::open_hashed(&fixture.path, |_, _| { + Err(io::Error::from(kind)) + }) + .is_err()); + } + assert!(VerifiedKeeperImage::open_hashed(&fixture.path, |_, bytes| { + Ok(bytes.len() + 1) + }) + .is_err()); + } + + #[test] + fn resource_image_single_hash_replacement_at_first_read_or_eof_refuses() { + for at_eof in [false, true] { + for same_bytes in [false, true] { + let fixture = Inert::new(0o700); + let original = fs::read(&fixture.path).unwrap(); + let mut replaced = false; + let result = VerifiedKeeperImage::open_hashed(&fixture.path, |file, bytes| { + let n = file.read(bytes)?; + if !replaced && (!at_eof || n == 0) { + replaced = true; + fs::rename(&fixture.path, fixture.path.with_extension("old"))?; + fs::write( + &fixture.path, + if same_bytes { + original.as_slice() + } else { + b"replacement" + }, + )?; + fs::set_permissions(&fixture.path, fs::Permissions::from_mode(0o700))?; + } + Ok(n) + }); + assert!(replaced); + assert!( + result.is_err(), + "replaced named image must not inherit the retained file" + ); + } + } + } + + #[test] + fn resource_image_single_hash_edit_or_mode_change_during_read_refuses() { + for change_mode in [false, true] { + let fixture = Inert::new(0o700); + let mut changed = false; + let result = VerifiedKeeperImage::open_hashed(&fixture.path, |file, bytes| { + let n = file.read(&mut bytes[..1])?; + if !changed && n != 0 { + changed = true; + if change_mode { + fs::set_permissions(&fixture.path, fs::Permissions::from_mode(0o755))?; + } else { + // Same inode; a length change cannot be hidden by a + // digest of an earlier prefix or a later EOF. + let mut output = fs::OpenOptions::new().append(true).open(&fixture.path)?; + std::io::Write::write_all(&mut output, b"changed")?; + } + } + Ok(n) + }); + assert!(changed); + assert!(result.is_err()); + } + } + + #[test] + fn resource_image_single_hash_same_size_edit_with_changed_mtime_refuses() { + for at_eof in [false, true] { + let fixture = Inert::new(0o700); + let original = fs::read(&fixture.path).unwrap(); + let before = fs::metadata(&fixture.path).unwrap(); + let before_modified = before.modified().unwrap(); + let changed_modified = before_modified + .checked_add(std::time::Duration::from_secs(60)) + .unwrap(); + let mut changed = false; + let result = VerifiedKeeperImage::open_hashed(&fixture.path, |file, bytes| { + let n = file.read(bytes)?; + if !changed && (!at_eof || n == 0) { + changed = true; + let mut output = fs::OpenOptions::new().write(true).open(&fixture.path)?; + std::io::Write::write_all(&mut output, &[original[0] ^ 0xff])?; + output.set_times(fs::FileTimes::new().set_modified(changed_modified))?; + } + Ok(n) + }); + let after = fs::metadata(&fixture.path).unwrap(); + assert!(changed); + assert_eq!(after.len(), before.len()); + assert_eq!(after.ino(), before.ino()); + assert_eq!(after.mode(), before.mode()); + assert_ne!(after.modified().unwrap(), before_modified); + assert_eq!(fs::read(&fixture.path).unwrap()[0], original[0] ^ 0xff); + assert!( + result.is_err(), + "same-size mutation must not inherit a prior hash snapshot" + ); + } + } + #[test] + fn resource_image_single_hash_policy_refuses_before_any_payload_read() { + for mode in [0o600, 0o777] { + let fixture = Inert::new(mode); + assert!(VerifiedKeeperImage::open_hashed(&fixture.path, |_, _| { + panic!("invalid image mode must refuse before reading") + }) + .is_err()); + } + let fixture = Inert::new(0o700); + fs::hard_link(&fixture.path, fixture.path.with_extension("link")).unwrap(); + assert!(VerifiedKeeperImage::open_hashed(&fixture.path, |_, _| { + panic!("multiply-linked image must refuse before reading") + }) + .is_err()); + let fixture = Inert::new(0o700); + let output = fs::OpenOptions::new() + .write(true) + .open(&fixture.path) + .unwrap(); + output.set_len(MAX_IMAGE + 1).unwrap(); + assert!(VerifiedKeeperImage::open_hashed(&fixture.path, |_, _| { + panic!("oversized image must refuse before reading") + }) + .is_err()); + } + + #[test] + fn resource_image_single_hash_later_replacement_edit_and_link_still_refuse() { + for change in ["replace", "edit", "link", "symlink"] { + let fixture = Inert::new(0o700); + let (image, _) = + VerifiedKeeperImage::open_hashed(&fixture.path, |file, bytes| file.read(bytes)) + .unwrap(); + match change { + "replace" => { + let original = fs::read(&fixture.path).unwrap(); + fs::rename(&fixture.path, fixture.path.with_extension("old")).unwrap(); + fs::write(&fixture.path, original).unwrap(); + fs::set_permissions(&fixture.path, fs::Permissions::from_mode(0o700)).unwrap(); + } + "edit" => fs::write(&fixture.path, b"changed bytes").unwrap(), + "link" => { + fs::hard_link(&fixture.path, fixture.path.with_extension("link")).unwrap() + } + _ => { + let old = fixture.path.with_extension("old"); + fs::rename(&fixture.path, &old).unwrap(); + symlink(old, &fixture.path).unwrap(); + } + } + assert!(image.check_current().is_err()); + } + } + + #[test] + fn r40_official_755_guard_has_distinct_verified_image_admission() { + let f = Inert::new(0o755); + let image = VerifiedKeeperImage::open(&f.path, &f.hash).unwrap(); + assert!(image.check_current().is_ok()); + assert_eq!( + unsafe { libc::fcntl(image.file.as_raw_fd(), libc::F_GETFD) } & libc::FD_CLOEXEC, + libc::FD_CLOEXEC + ); + } + #[test] + fn r40_unsigned_wrong_hash_writable_and_symlink_images_refuse() { + let f = Inert::new(0o700); + assert!(VerifiedKeeperImage::open(&f.path, &"0".repeat(64)).is_err()); + assert!(VerifiedKeeperImage::open(&f.path, "").is_err()); + for mode in [0o600, 0o777] { + fs::set_permissions(&f.path, fs::Permissions::from_mode(mode)).unwrap(); + assert!(VerifiedKeeperImage::open(&f.path, &f.hash).is_err()); + } + let f = Inert::new(0o700); + let link = f.path.with_extension("link"); + symlink(&f.path, &link).unwrap(); + assert!(VerifiedKeeperImage::open(&link, &f.hash).is_err()); + } + #[test] + fn r40_retained_descriptor_detects_replacement_edit_and_hardlink() { + for change in ["replace", "edit", "link"] { + let f = Inert::new(0o700); + let image = VerifiedKeeperImage::open(&f.path, &f.hash).unwrap(); + match change { + "replace" => { + fs::rename(&f.path, f.path.with_extension("old")).unwrap(); + fs::write(&f.path, b"replacement").unwrap(); + } + "edit" => fs::write(&f.path, b"different size").unwrap(), + _ => fs::hard_link(&f.path, f.path.with_extension("link")).unwrap(), + } + assert!(image.check_current().is_err()); + } + let f = Inert::new(0o700); + fs::hard_link(&f.path, f.path.with_extension("link")).unwrap(); + assert!(VerifiedKeeperImage::open(&f.path, &f.hash).is_err()); + } + #[test] + fn r40_image_bootstrap_fd_is_canonical_and_never_the_control_socket() { + assert_eq!(bootstrap_fd("5", 4).unwrap(), 5); + for raw in ["0", "3", "4", "05", "+5", " 5", "1025", "-1", ""] { + assert!(bootstrap_fd(raw, 4).is_err()); + } + assert!(bootstrap_fd("5", 5).is_err()); + } + #[test] + fn r40_image_parent_replaced_with_symlink_is_not_a_live_managed_path() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let managed = root.join("managed"); + fs::create_dir(&managed).unwrap(); + let path = managed.join("keito-capture-guard"); + fs::write(&path, b"inert; never execute").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + let hash: String = Sha256::digest(fs::read(&path).unwrap()) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + let image = VerifiedKeeperImage::open(&path, &hash).unwrap(); + let old = root.join("old"); + fs::rename(&managed, &old).unwrap(); + symlink(&old, &managed).unwrap(); + assert!(image.check_current().is_err()); + } + #[test] + fn r40_private_keeper_environment_is_closed_without_auth_or_home() { + #[cfg(target_os = "macos")] + let (keys, encoding) = ( + vec![IMAGE_ENV, "__CF_USER_TEXT_ENCODING"], + Some("0x1F5:0:0"), + ); + #[cfg(not(target_os = "macos"))] + let (keys, encoding) = (vec![IMAGE_ENV], None); + assert!(closed_environment(keys.clone(), encoding, 501)); + let mut extra = keys.clone(); + extra.push("HOME"); + assert!(!closed_environment(extra, encoding, 501)); + assert!(!closed_environment(Vec::<&str>::new(), encoding, 501)); + #[cfg(target_os = "macos")] + assert!(!closed_environment(keys, Some("0x1F5:1:0"), 501)); + } +} diff --git a/src/process_ownership/io.rs b/src/process_ownership/io.rs new file mode 100644 index 0000000..0e297d8 --- /dev/null +++ b/src/process_ownership/io.rs @@ -0,0 +1,585 @@ +//! Bounded transient pipes. Only read(0) establishes output EOF. +//! Buffers deliberately have no Debug/Serialize implementation. +use std::{ + io::{self, Read, Write}, + os::fd::AsRawFd, + process::{ChildStderr, ChildStdin, ChildStdout}, +}; + +pub const MAX_STREAM_BYTES: usize = 1024 * 1024; +const TURN_BYTES: usize = 4096; + +pub struct IoPlan { + input: Vec, + stdout_cap: usize, + stderr_cap: usize, +} +impl IoPlan { + pub fn new(input: Vec, stdout_cap: usize, stderr_cap: usize) -> io::Result { + if input.capacity() > MAX_STREAM_BYTES + || stdout_cap > MAX_STREAM_BYTES + || stderr_cap > MAX_STREAM_BYTES + { + return Err(io::Error::other("IO_LIMIT")); + } + Ok(Self { + input, + stdout_cap, + stderr_cap, + }) + } + pub(super) fn capacity(&self) -> usize { + // Retained slots keep this allocation even after input is consumed. + // Initialized bytes alone are not the owned-buffer reservation. + self.input.capacity() + self.stdout_cap + self.stderr_cap + } + pub(super) fn prepare(self) -> io::Result { + Ok(PipeIo { + input: Input { + bytes: self.input, + offset: 0, + closed: false, + }, + stdout: Output::new(self.stdout_cap)?, + stderr: Output::new(self.stderr_cap)?, + stdin_pipe: None, + stdout_pipe: None, + stderr_pipe: None, + stdin_ready: false, + stdout_ready: false, + stderr_ready: false, + fault: None, + }) + } +} + +struct Input { + bytes: Vec, + offset: usize, + closed: bool, +} +impl Input { + fn poll(&mut self, writer: &mut impl Write) -> Option<&'static str> { + if self.closed { + return None; + } + if self.offset == self.bytes.len() { + self.closed = true; + return None; + } + let end = (self.offset + TURN_BYTES).min(self.bytes.len()); + match writer.write(&self.bytes[self.offset..end]) { + Ok(0) => { + self.closed = true; + Some("IO_STDIN_ZERO") + } + Ok(count) if count <= end - self.offset => { + self.offset += count; + if self.offset == self.bytes.len() { + self.closed = true; + } + None + } + Ok(_) => { + self.closed = true; + Some("IO_STDIN_WRITE") + } + Err(e) + if matches!( + e.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted + ) => + { + None + } + Err(_) => { + self.closed = true; + Some("IO_STDIN_WRITE") + } + } + } +} +struct Output { + bytes: Vec, + cap: usize, + count: usize, + eof: bool, + fault: Option<&'static str>, +} +impl Output { + fn new(cap: usize) -> io::Result { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(cap) + .map_err(|_| io::Error::other("IO_ALLOCATION"))?; + // A reserve_exact implementation may overallocate. Refuse before any + // child exists unless the retained capacity fits the charged budget. + if bytes.capacity() > cap { + return Err(io::Error::other("IO_ALLOCATION")); + } + Ok(Self { + bytes, + cap, + count: 0, + eof: false, + fault: None, + }) + } + fn poll(&mut self, reader: &mut impl Read) -> Option<&'static str> { + if self.eof { + return self.fault; + } + let mut scratch = [0u8; TURN_BYTES]; + match reader.read(&mut scratch) { + Ok(0) => self.eof = true, + Ok(count) if count <= scratch.len() => { + self.count = self.count.saturating_add(count); + let room = self.cap - self.bytes.len(); + self.bytes.extend_from_slice(&scratch[..count.min(room)]); + if count > room { + self.fault.get_or_insert("IO_OUTPUT_LIMIT"); + } + } + Ok(_) => { + self.fault.get_or_insert("IO_OUTPUT_READ"); + } + Err(e) + if matches!( + e.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted + ) => {} + Err(_) => { + self.fault.get_or_insert("IO_OUTPUT_READ"); + } + } + self.fault + } +} + +#[derive(Clone, Copy, Debug, Default)] +pub struct IoFacts { + pub stdin_closed: bool, + pub stdout_eof: bool, + pub stderr_eof: bool, + pub stdout_bytes: usize, + pub stderr_bytes: usize, + pub first_fault: Option<&'static str>, +} +impl IoFacts { + pub fn complete(&self) -> bool { + self.stdin_closed && self.stdout_eof && self.stderr_eof + } +} + +pub struct CommandOutput { + pub stdout: Vec, + pub stderr: Vec, +} +pub(super) struct PipeIo { + input: Input, + stdout: Output, + stderr: Output, + stdin_pipe: Option, + stdout_pipe: Option, + stderr_pipe: Option, + stdin_ready: bool, + stdout_ready: bool, + stderr_ready: bool, + fault: Option<&'static str>, +} +fn flags(pipe: &impl AsRawFd) -> io::Result<()> { + let fd = pipe.as_raw_fd(); + let old = unsafe { libc::fcntl(fd, libc::F_GETFL) }; + if old < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, old | libc::O_NONBLOCK) } < 0 { + return Err(io::Error::other("IO_FLAGS")); + } + let old = unsafe { libc::fcntl(fd, libc::F_GETFD) }; + if old < 0 || unsafe { libc::fcntl(fd, libc::F_SETFD, old | libc::FD_CLOEXEC) } < 0 { + return Err(io::Error::other("IO_FLAGS")); + } + Ok(()) +} +impl PipeIo { + // Move ALL handles in before any fallible flags operation. Failure leaves + // them retained; callers must continue collection under their original end. + pub(super) fn attach( + &mut self, + input: Option, + output: Option, + error: Option, + ) -> io::Result<()> { + self.stdin_pipe = input; + self.stdout_pipe = output; + self.stderr_pipe = error; + self.stdin_ready = self.stdin_pipe.as_ref().is_some_and(|p| flags(p).is_ok()); + self.stdout_ready = self.stdout_pipe.as_ref().is_some_and(|p| flags(p).is_ok()); + self.stderr_ready = self.stderr_pipe.as_ref().is_some_and(|p| flags(p).is_ok()); + if !(self.stdin_ready && self.stdout_ready && self.stderr_ready) { + self.fault.get_or_insert("IO_FLAGS"); + self.cancel_input(); + // Failed descriptors remain retained but are not read with unknown + // flags. Other independently configured streams continue draining. + return Err(io::Error::other("IO_FLAGS")); + } + Ok(()) + } + pub(super) fn cancel_input(&mut self) { + self.stdin_pipe.take(); + self.input.closed = true; + } + pub(super) fn poll(&mut self) { + if let Some(pipe) = self.stdin_pipe.as_mut().filter(|_| self.stdin_ready) { + if let Some(reason) = self.input.poll(pipe) { + self.fault.get_or_insert(reason); + } + if self.input.closed { + self.stdin_pipe.take(); + } + } + if let Some(pipe) = self.stdout_pipe.as_mut().filter(|_| self.stdout_ready) { + if let Some(reason) = self.stdout.poll(pipe) { + self.fault.get_or_insert(reason); + } + } + if let Some(pipe) = self.stderr_pipe.as_mut().filter(|_| self.stderr_ready) { + if let Some(reason) = self.stderr.poll(pipe) { + self.fault.get_or_insert(reason); + } + } + } + // Scheduling hints from the SAME retained, independently configured pipes. + // Only their original read/write operations can change closure/EOF facts. + pub(super) fn progress_wait_sources(&self, descriptors: &mut Vec) { + if self.stdin_ready && !self.input.closed && self.input.offset < self.input.bytes.len() { + if let Some(pipe) = &self.stdin_pipe { + descriptors.push(libc::pollfd { + fd: pipe.as_raw_fd(), + events: libc::POLLOUT, + revents: 0, + }); + } + } + for (pipe, ready, eof) in [ + ( + self.stdout_pipe.as_ref().map(AsRawFd::as_raw_fd), + self.stdout_ready, + self.stdout.eof, + ), + ( + self.stderr_pipe.as_ref().map(AsRawFd::as_raw_fd), + self.stderr_ready, + self.stderr.eof, + ), + ] { + if ready && !eof { + if let Some(fd) = pipe { + descriptors.push(libc::pollfd { + fd, + events: libc::POLLIN, + revents: 0, + }); + } + } + } + } + pub(super) fn facts(&self) -> IoFacts { + IoFacts { + stdin_closed: self.input.closed, + stdout_eof: self.stdout.eof, + stderr_eof: self.stderr.eof, + stdout_bytes: self.stdout.count, + stderr_bytes: self.stderr.count, + first_fault: self.fault, + } + } + pub(super) fn take_output(&mut self) -> CommandOutput { + CommandOutput { + stdout: std::mem::take(&mut self.stdout.bytes), + stderr: std::mem::take(&mut self.stderr.bytes), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::VecDeque; + enum ReadStep { + Data(Vec), + Block, + Interrupt, + Fail, + Eof, + } + struct Reader { + steps: VecDeque, + calls: usize, + } + impl Read for Reader { + fn read(&mut self, out: &mut [u8]) -> io::Result { + self.calls += 1; + match self.steps.pop_front().unwrap_or(ReadStep::Block) { + ReadStep::Data(bytes) => { + assert!(bytes.len() <= out.len()); + out[..bytes.len()].copy_from_slice(&bytes); + Ok(bytes.len()) + } + ReadStep::Block => Err(io::ErrorKind::WouldBlock.into()), + ReadStep::Interrupt => Err(io::ErrorKind::Interrupted.into()), + ReadStep::Fail => Err(io::ErrorKind::BrokenPipe.into()), + ReadStep::Eof => Ok(0), + } + } + } + fn reader(steps: Vec) -> Reader { + Reader { + steps: steps.into(), + calls: 0, + } + } + #[test] + fn output_requires_read_zero_not_wouldblock_interruption_or_error() { + let mut output = Output::new(8).unwrap(); + let mut input = reader(vec![ + ReadStep::Block, + ReadStep::Interrupt, + ReadStep::Fail, + ReadStep::Eof, + ]); + for _ in 0..3 { + output.poll(&mut input); + assert!(!output.eof); + } + output.poll(&mut input); + assert!(output.eof); + assert_eq!(output.fault, Some("IO_OUTPUT_READ")); + assert_eq!(input.calls, 4); + } + #[test] + fn exact_cap_is_valid_cap_plus_one_remains_failed_after_drain_and_eof() { + let mut output = Output::new(3).unwrap(); + let mut input = reader(vec![ + ReadStep::Data(b"abc".to_vec()), + ReadStep::Block, + ReadStep::Data(b"d".to_vec()), + ReadStep::Data(vec![0; TURN_BYTES]), + ReadStep::Eof, + ]); + output.poll(&mut input); + assert_eq!(output.fault, None); + assert!(!output.eof); + output.poll(&mut input); + assert!(!output.eof); + output.poll(&mut input); + assert_eq!(output.fault, Some("IO_OUTPUT_LIMIT")); + output.poll(&mut input); + output.poll(&mut input); + assert!(output.eof); + assert_eq!(output.bytes, b"abc"); + assert_eq!(output.count, TURN_BYTES + 4); + assert_eq!(output.fault, Some("IO_OUTPUT_LIMIT")); + } + struct Writer { + bytes: Vec, + block: bool, + fail: bool, + calls: usize, + } + impl Write for Writer { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.calls += 1; + if self.fail { + return Err(io::ErrorKind::BrokenPipe.into()); + } + if self.block { + self.block = false; + return Err(io::ErrorKind::WouldBlock.into()); + } + let count = bytes.len().min(2); + self.bytes.extend_from_slice(&bytes[..count]); + Ok(count) + } + fn flush(&mut self) -> io::Result<()> { + panic!("no blocking flush") + } + } + #[test] + fn stdin_partial_backpressure_and_epipe_preserve_offset_and_close() { + let mut state = Input { + bytes: b"abcde".to_vec(), + offset: 0, + closed: false, + }; + let mut writer = Writer { + bytes: vec![], + block: true, + fail: false, + calls: 0, + }; + assert_eq!(state.poll(&mut writer), None); + assert_eq!(state.offset, 0); + assert_eq!(state.poll(&mut writer), None); + assert_eq!(state.offset, 2); + writer.fail = true; + assert_eq!(state.poll(&mut writer), Some("IO_STDIN_WRITE")); + assert!(state.closed); + state.poll(&mut writer); + assert_eq!(writer.calls, 3); + assert_eq!(writer.bytes, b"ab"); + } + #[test] + fn input_completion_and_cancellation_are_separate_from_output_eof() { + let mut io = IoPlan::new(vec![], 0, 0).unwrap().prepare().unwrap(); + io.cancel_input(); + assert!(io.facts().stdin_closed); + assert!(!io.facts().complete()); + assert!(!io.facts().stdout_eof); + assert!(!io.facts().stderr_eof); + assert!(IoPlan::new(vec![], MAX_STREAM_BYTES + 1, 0).is_err()); + } + #[test] + fn each_output_turn_is_one_bounded_read_and_zero_cap_still_needs_eof() { + let mut output = Output::new(0).unwrap(); + let mut input = reader(vec![ReadStep::Data(vec![0; TURN_BYTES]), ReadStep::Eof]); + output.poll(&mut input); + assert_eq!(input.calls, 1); + assert!(!output.eof); + assert_eq!(output.bytes.len(), 0); + assert_eq!(output.fault, Some("IO_OUTPUT_LIMIT")); + output.poll(&mut input); + assert!(output.eof); + } + #[test] + fn r38_unused_input_allocation_cannot_bypass_the_limit() { + let mut input = Vec::with_capacity(MAX_STREAM_BYTES + 1); + input.push(b'x'); + assert_eq!(input.len(), 1); + assert!(input.capacity() > MAX_STREAM_BYTES); + assert!(IoPlan::new(input, 0, 0).is_err()); + let empty = Vec::with_capacity(MAX_STREAM_BYTES + 1); + assert!(empty.is_empty()); + assert!(IoPlan::new(empty, 0, 0).is_err()); + } + #[test] + fn retained_input_capacity_is_charged_without_changing_bytes() { + let mut input = Vec::with_capacity(4096); + input.push(b'x'); + let capacity = input.capacity(); + let plan = IoPlan::new(input, 7, 11).unwrap(); + assert_eq!(plan.capacity(), capacity + 18); + let pipes = plan.prepare().unwrap(); + assert_eq!(pipes.input.bytes, b"x"); + assert_eq!(pipes.input.bytes.capacity(), capacity); + } + // Inert retained descriptors only: these tests create no process. + fn socket_pipe_io( + input: Vec, + ) -> ( + PipeIo, + std::os::unix::net::UnixStream, + std::os::unix::net::UnixStream, + std::os::unix::net::UnixStream, + [i32; 3], + ) { + use std::os::{fd::OwnedFd, unix::net::UnixStream}; + let (stdin, input_peer) = UnixStream::pair().unwrap(); + let (stdout, output_peer) = UnixStream::pair().unwrap(); + let (stderr, error_peer) = UnixStream::pair().unwrap(); + for peer in [&input_peer, &output_peer, &error_peer] { + peer.set_nonblocking(true).unwrap(); + } + let fds = [stdin.as_raw_fd(), stdout.as_raw_fd(), stderr.as_raw_fd()]; + let mut pipes = IoPlan::new(input, 32, 32).unwrap().prepare().unwrap(); + let stdin: OwnedFd = stdin.into(); + let stdout: OwnedFd = stdout.into(); + let stderr: OwnedFd = stderr.into(); + pipes + .attach( + Some(ChildStdin::from(stdin)), + Some(ChildStdout::from(stdout)), + Some(ChildStderr::from(stderr)), + ) + .unwrap(); + (pipes, input_peer, output_peer, error_peer, fds) + } + #[test] + fn retained_pipe_readiness_matches_pending_fd_directions_without_advancing_io() { + let (mut pipes, mut input_peer, mut output_peer, mut error_peer, fds) = + socket_pipe_io(b"in".to_vec()); + let mut descriptors = Vec::new(); + pipes.progress_wait_sources(&mut descriptors); + assert_eq!( + descriptors + .iter() + .map(|fd| (fd.fd, fd.events)) + .collect::>(), + [ + (fds[0], libc::POLLOUT), + (fds[1], libc::POLLIN), + (fds[2], libc::POLLIN) + ] + ); + let mut bytes = [0u8; 8]; + assert_eq!( + input_peer.read(&mut bytes).unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); + output_peer.write_all(b"out").unwrap(); + error_peer.write_all(b"err").unwrap(); + descriptors.clear(); + pipes.progress_wait_sources(&mut descriptors); + assert_eq!(pipes.facts().stdout_bytes, 0); + assert_eq!(pipes.facts().stderr_bytes, 0); + assert!(!pipes.facts().stdout_eof && !pipes.facts().stderr_eof); + assert!(!pipes.facts().stdin_closed); + pipes.poll(); + assert_eq!(input_peer.read(&mut bytes).unwrap(), 2); + assert_eq!(&bytes[..2], b"in"); + assert_eq!(pipes.facts().stdout_bytes, 3); + assert_eq!(pipes.facts().stderr_bytes, 3); + assert!(pipes.facts().stdin_closed); + descriptors.clear(); + pipes.progress_wait_sources(&mut descriptors); + assert!(descriptors.iter().all(|fd| fd.fd != fds[0])); + assert_eq!(descriptors.len(), 2); + output_peer.shutdown(std::net::Shutdown::Write).unwrap(); + error_peer.shutdown(std::net::Shutdown::Write).unwrap(); + descriptors.clear(); + pipes.progress_wait_sources(&mut descriptors); + assert_eq!( + descriptors.len(), + 2, + "HUP was mistaken for physical read(0)" + ); + assert!(!pipes.facts().stdout_eof && !pipes.facts().stderr_eof); + pipes.poll(); + assert!(pipes.facts().stdout_eof && pipes.facts().stderr_eof); + descriptors.clear(); + pipes.progress_wait_sources(&mut descriptors); + assert!( + descriptors.is_empty(), + "known EOF would cause repeated HUP wakeups" + ); + assert!(pipes.facts().complete()); + } + #[test] + fn retained_pipe_readiness_omits_empty_input_before_original_close_then_keeps_it_closed() { + let (mut pipes, mut input_peer, _output_peer, _error_peer, fds) = + socket_pipe_io(Vec::new()); + let mut descriptors = Vec::new(); + pipes.progress_wait_sources(&mut descriptors); + assert!( + !pipes.facts().stdin_closed, + "hint performed original stdin close" + ); + assert!(descriptors.iter().all(|fd| fd.fd != fds[0])); + assert_eq!(descriptors.len(), 2); + pipes.poll(); + assert!(pipes.facts().stdin_closed); + assert_eq!(input_peer.read(&mut [0u8; 1]).unwrap(), 0); + descriptors.clear(); + pipes.progress_wait_sources(&mut descriptors); + assert!(descriptors.iter().all(|fd| fd.fd != fds[0])); + assert_eq!(descriptors.len(), 2); + } +} diff --git a/src/process_ownership/mod.rs b/src/process_ownership/mod.rs new file mode 100644 index 0000000..81d3d07 --- /dev/null +++ b/src/process_ownership/mod.rs @@ -0,0 +1,14 @@ +//! Unix process ownership shared by product and developer tools. +//! +//! Shared group/protocol code includes closed legacy and short cleanup policies. +//! Product probes and cooperative core use this source. Merely compiling this +//! module in a default artifact is not runtime or real-harness qualification. +//! This code grants no capture, profile, billing or authentication authority. +mod attachment; +pub mod group; +pub(crate) mod image; +pub mod io; +pub(crate) mod probes; +pub mod protocol; +pub mod scope; +pub(crate) mod signals; diff --git a/src/process_ownership/probes.rs b/src/process_ownership/probes.rs new file mode 100644 index 0000000..1f30334 --- /dev/null +++ b/src/process_ownership/probes.rs @@ -0,0 +1,72 @@ +//! Tool result interpretation after ownership, never a process-spawn fallback. +use super::scope::CommandResult; +use std::{io, process::Command}; + +pub(crate) trait LeafRunner { + /// Optional fixed repository cohort. None preserves the original sequential + /// resolver, including short-circuiting before later commands are executed. + fn repository_outputs( + &mut self, + _commands: [Command; 2], + ) -> Option> { + None + } + fn output( + &mut self, + command: Command, + stdout_cap: usize, + stderr_cap: usize, + ) -> io::Result; +} +/// Git config --get-regexp uses exit1 with empty output for no matches. Every +/// ownership/read/deadline error is propagated BEFORE reaching this classifier. +pub(crate) fn text(result: CommandResult, allow_empty_exit_one: bool) -> io::Result { + text_untrimmed(result, allow_empty_exit_one).map(|s| s.trim().to_owned()) +} +/// Retain framing until a multi-value caller has checked raw field boundaries +/// and byte limits. Scalar callers keep their existing trimming through text(). +pub(crate) fn text_untrimmed( + result: CommandResult, + allow_empty_exit_one: bool, +) -> io::Result { + if !result.status.success() + && !(allow_empty_exit_one + && result.status.code() == Some(1) + && result.output.stdout.is_empty() + && result.output.stderr.is_empty()) + { + return Err(io::Error::other("PROBE_EXIT")); + } + String::from_utf8(result.output.stdout).map_err(|_| io::Error::other("PROBE_UTF8")) +} +#[cfg(test)] +mod tests { + use super::*; + use crate::process_ownership::io::CommandOutput; + use std::os::unix::process::ExitStatusExt; + fn result(code: i32, out: &[u8], err: &[u8]) -> CommandResult { + CommandResult { + status: std::process::ExitStatus::from_raw(code << 8), + output: CommandOutput { + stdout: out.into(), + stderr: err.into(), + }, + } + } + #[test] + fn r40_only_the_known_empty_git_exit_can_be_an_empty_identity_result() { + assert_eq!(text(result(1, b"", b""), true).unwrap(), ""); + assert!(text(result(1, b"", b"error"), true).is_err()); + assert!(text(result(1, b"unexpected", b""), true).is_err()); + assert!(text(result(128, b"", b""), true).is_err()); + assert!(text(result(1, b"", b""), false).is_err()); + assert_eq!(text(result(0, b" root\n", b""), false).unwrap(), "root"); + } + #[test] + fn r40_invalid_text_and_signals_are_not_valid_empty_remotes() { + assert!(text(result(0, &[255], b""), true).is_err()); + let mut r = result(0, b"", b""); + r.status = std::process::ExitStatus::from_raw(15); + assert!(text(r, true).is_err()); + } +} diff --git a/src/process_ownership/protocol.rs b/src/process_ownership/protocol.rs new file mode 100644 index 0000000..bf02dab --- /dev/null +++ b/src/process_ownership/protocol.rs @@ -0,0 +1,625 @@ +//! Shared Unix cancellation metadata. No capture, profile or auth authority. +//! Included in default library/guard builds and their real process owners. +//! Protocol proof alone is not a wait or process-group absence proof. +use std::{ + cell::RefCell, + collections::BTreeMap, + fmt, + io::{Read, Write}, + net::Shutdown, + os::{fd::AsRawFd, unix::net::UnixStream}, + rc::Rc, +}; + +pub const MAX_FRAME: usize = 256; +pub const MAX_PENDING: usize = 1024; +pub const MAX_READS: usize = 8; +pub const MAX_PARSE: usize = 32; +pub const MAX_REGISTRATIONS: usize = 4096; +pub const MAX_FRAMES: usize = 16384; +pub const MAX_WIRE: usize = 4 * 1024 * 1024; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProtocolError(pub &'static str); +impl fmt::Display for ProtocolError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.0) + } +} +impl std::error::Error for ProtocolError {} +type Result = std::result::Result; +pub(super) type Registration = (u32, u32, String); + +#[derive(Default, Debug)] +pub struct OwnerState { + pub first_fault: Option, + pub admission_closed: bool, + wire: usize, + frames: usize, + registrations: usize, + budget_fault: Option, +} +pub type SharedOwner = Rc>; +impl OwnerState { + pub fn check_admission(&self) -> Result<()> { + if let Some(error) = self.first_fault { + return Err(error); + } + if self.admission_closed { + return Err(ProtocolError("OWNER_ADMISSION_CLOSED")); + } + Ok(()) + } + pub fn poison(&mut self, error: ProtocolError) { + self.first_fault.get_or_insert(error); + self.admission_closed = true; + } + pub(super) fn charge(&mut self, kind: &'static str, amount: usize) -> Result<()> { + if let Some(error) = self.budget_fault { + return Err(error); + } + let (counter, cap, reason) = match kind { + "wire" => (&mut self.wire, MAX_WIRE, "LIMIT_WIRE"), + "frames" => (&mut self.frames, MAX_FRAMES, "LIMIT_FRAMES"), + "registrations" => ( + &mut self.registrations, + MAX_REGISTRATIONS, + "LIMIT_REGISTRATIONS", + ), + _ => unreachable!("closed internal budget kind"), + }; + match counter.checked_add(amount).filter(|n| *n <= cap) { + Some(next) => *counter = next, + None => { + let error = ProtocolError(reason); + self.budget_fault = Some(error); + self.poison(error); + return Err(error); + } + } + Ok(()) + } +} + +fn nonce_valid(value: &str) -> bool { + value.len() == 32 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} +fn unsigned(value: &str) -> Result { + if value.is_empty() + || value.len() > 20 + || (value.len() > 1 && value.starts_with('0')) + || !value.bytes().all(|b| b.is_ascii_digit()) + { + return Err(ProtocolError("INTEGER_SCHEMA")); + } + value.parse().map_err(|_| ProtocolError("INTEGER_RANGE")) +} +fn pid(value: &str) -> Result { + let value = unsigned(value)?; + if value == 0 || value > i32::MAX as u64 { + return Err(ProtocolError("PID_SCHEMA")); + } + Ok(value as u32) +} +fn wait_status(value: &str) -> Result<()> { + if value == "-0" { + return Err(ProtocolError("INTEGER_SCHEMA")); + } + unsigned(value.strip_prefix('-').unwrap_or(value))?; + value + .parse::() + .map_err(|_| ProtocolError("INTEGER_RANGE"))?; + Ok(()) +} + +#[derive(Default, Debug)] +pub struct PollWork { + pub reads: usize, + pub parsed: usize, +} + +pub struct Endpoint { + socket: UnixStream, + nonce: String, + expected_pid: Option, + pub owner: SharedOwner, + pending: Vec, + live: bool, + terminal: bool, + eof: bool, + settled: bool, + cancelled: bool, + first_fault: Option, + cancel_deadline_ns: Option, + parent_role: Option, + events: Vec, + registrations: BTreeMap, + sent_registrations: BTreeMap, + sent_live: bool, + sent_terminal: bool, + sent_cancel: bool, + sent_cancel_end: Option, + failed_attempted: bool, + pub last_poll: PollWork, +} +impl Endpoint { + // Readiness metadata only. The original receive() remains the sole parser + // and physical EOF observer; a known EOF cannot wake another Child wait. + pub(super) fn progress_wait_source(&self) -> Option { + (!self.eof).then(|| self.socket.as_raw_fd()) + } + pub(super) fn progress_buffered_event(&self) -> bool { + !self.eof + && (self.pending.contains(&b'\n') + || self.last_poll.reads >= MAX_READS + || self.last_poll.parsed >= MAX_PARSE) + } + /// Nonterminal metadata predicate only; never sends proof or closes a peer. + pub(super) fn sent_resources_complete(&self) -> bool { + self.sent_live + && !self.sent_terminal + && !self.cancelled + && self.first_fault.is_none() + && self.owner.borrow().first_fault.is_none() + && self.pending.is_empty() + && self.events.is_empty() + && self.last_poll.reads < MAX_READS + && self.last_poll.parsed < MAX_PARSE + && self.sent_registrations.values().all(|waited| *waited) + } + pub(super) fn set_expected_child(&mut self, pid: u32) -> Result<()> { + if self.live || self.expected_pid.is_some() || pid == 0 || pid > i32::MAX as u32 { + return Err(self.poison(ProtocolError("PEER_IDENTITY"))); + } + self.expected_pid = Some(pid); + Ok(()) + } + pub fn new(socket: UnixStream, nonce: String, expected_pid: Option) -> Result { + Self::with_owner(socket, nonce, expected_pid, Rc::default()) + } + pub fn with_owner( + socket: UnixStream, + nonce: String, + expected_pid: Option, + owner: SharedOwner, + ) -> Result { + if !nonce_valid(&nonce) || expected_pid.is_some_and(|p| p == 0 || p > i32::MAX as u32) { + let error = ProtocolError("ENDPOINT_SCHEMA"); + owner.borrow_mut().poison(error); + return Err(error); + } + if socket.set_nonblocking(true).is_err() + || unsafe { libc::fcntl(socket.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } < 0 + { + let error = ProtocolError("SOCKET_FLAGS"); + owner.borrow_mut().poison(error); + return Err(error); + } + Ok(Self { + socket, + nonce, + expected_pid, + owner, + pending: Vec::new(), + live: false, + terminal: false, + eof: false, + settled: false, + cancelled: false, + first_fault: None, + cancel_deadline_ns: None, + parent_role: None, + events: Vec::new(), + registrations: BTreeMap::new(), + sent_registrations: BTreeMap::new(), + sent_live: false, + sent_terminal: false, + sent_cancel: false, + sent_cancel_end: None, + failed_attempted: false, + last_poll: PollWork::default(), + }) + } + fn poison(&mut self, error: ProtocolError) -> ProtocolError { + let first = *self.first_fault.get_or_insert(error); + self.settled = false; + self.owner.borrow_mut().poison(first); + first + } + fn check(&mut self) -> Result<()> { + if let Some(error) = self.first_fault { + return Err(error); + } + let budget_fault = self.owner.borrow().budget_fault; + if let Some(error) = budget_fault { + return Err(self.poison(error)); + } + Ok(()) + } + fn write_frame(&mut self, value: &str) -> Result<()> { + let result = (|| { + if !value.is_ascii() || value.len() + 34 > MAX_FRAME || value.contains(['\n', '\r']) { + return Err(ProtocolError("FRAME_SCHEMA")); + } + let frame = format!("{}|{}\n", self.nonce, value); + { + let mut owner = self.owner.borrow_mut(); + owner.charge("wire", frame.len())?; + owner.charge("frames", 1)?; + } + if self + .socket + .write(frame.as_bytes()) + .map_err(|_| ProtocolError("WRITE_FAILED"))? + != frame.len() + { + return Err(ProtocolError("SHORT_WRITE")); + } + Ok(()) + })(); + result.map_err(|e| self.poison(e)) + } + pub fn send_live(&mut self) -> Result<()> { + self.check()?; + if self.sent_live || self.sent_terminal || self.sent_cancel { + return Err(self.poison(ProtocolError("SEND_STATE"))); + } + self.sent_live = true; + self.write_frame(&format!("LIVE|{}", std::process::id())) + } + pub fn send_cancel(&mut self, deadline_ns: u64) -> Result<()> { + self.check()?; + if deadline_ns == 0 || self.sent_live || self.sent_terminal || self.sent_cancel { + return Err(self.poison(ProtocolError("CANCEL_STATE"))); + } + self.sent_cancel = true; + self.sent_cancel_end = Some(deadline_ns); + self.write_frame(&format!("CANCEL|{}|{}", std::process::id(), deadline_ns)) + } + pub fn send_cancel_tighter(&mut self, deadline_ns: u64) -> Result<()> { + self.check()?; + if deadline_ns == 0 || self.sent_terminal || self.sent_live { + return Err(self.poison(ProtocolError("CANCEL_STATE"))); + } + match self.sent_cancel_end { + None => self.send_cancel(deadline_ns), + Some(previous) if deadline_ns >= previous => Ok(()), + Some(_) => { + self.sent_cancel_end = Some(deadline_ns); + self.write_frame(&format!("CANCEL|{}|{}", std::process::id(), deadline_ns)) + } + } + } + pub fn send_terminal(&mut self, clean: bool) -> Result<()> { + if clean { + self.check()?; + if self.owner.borrow().first_fault.is_some() + || !self.sent_live + || self.sent_registrations.values().any(|w| !w) + { + return Err(self.poison(ProtocolError("OWNER_FAULT_OR_ACTIVE_REGISTRATION"))); + } + } else if self.failed_attempted { + return Err(self.poison(ProtocolError("DUPLICATE_TERMINAL"))); + } + if self.sent_terminal { + return Err(self.poison(ProtocolError("DUPLICATE_TERMINAL"))); + } + self.failed_attempted |= !clean; + self.sent_terminal = true; + self.write_frame(&format!( + "{}|{}", + if clean { "SETTLED" } else { "FAILED" }, + std::process::id() + ))?; + self.socket + .shutdown(Shutdown::Write) + .map_err(|_| self.poison(ProtocolError("SHUTDOWN_FAILED"))) + } + pub fn metadata(&mut self, value: &str) -> Result<()> { + self.check()?; + let result = (|| { + if !self.sent_live + || self.sent_terminal + || value.len() + 34 > MAX_FRAME + || !value.is_ascii() + { + return Err(ProtocolError("METADATA_SEND_STATE")); + } + if Self::record_metadata(&mut self.sent_registrations, std::process::id(), value)? { + self.owner.borrow_mut().charge("registrations", 1)?; + } + self.write_frame(value) + })(); + result.map_err(|e| self.poison(e)) + } + // The no-upstream root uses this SAME ledger validation as wire senders. + // A missing observer does not mean registrations may be forgotten. + pub(super) fn record_metadata( + registrations: &mut BTreeMap, + root: u32, + value: &str, + ) -> Result { + let fields: Vec<_> = value.split('|').collect(); + if fields.len() != 5 + || !matches!(fields[0], "REGISTER" | "WAITED") + || !nonce_valid(fields[3]) + || value.len() + 34 > MAX_FRAME + { + return Err(ProtocolError("METADATA_SCHEMA")); + } + let key = (pid(fields[1])?, pid(fields[2])?, fields[3].to_owned()); + if fields[0] == "REGISTER" { + unsigned(fields[4])?; + Self::validate_registration(registrations, root, &key)?; + if registrations.len() >= MAX_REGISTRATIONS { + return Err(ProtocolError("LIMIT_REGISTRATIONS")); + } + registrations.insert(key, false); + Ok(true) + } else { + wait_status(fields[4])?; + let waited = registrations + .get_mut(&key) + .filter(|w| !**w) + .ok_or(ProtocolError("UNMATCHED_WAIT"))?; + *waited = true; + Ok(false) + } + } + fn validate_registration( + registrations: &BTreeMap, + root: u32, + key: &Registration, + ) -> Result<()> { + if key.0 != root + && !registrations + .iter() + .any(|(k, waited)| k.1 == key.0 && !waited) + { + return Err(ProtocolError("OWNER_EDGE")); + } + if key.0 == key.1 + || key.1 == root + || registrations.contains_key(key) + || registrations + .iter() + .any(|(k, waited)| k.1 == key.1 && !waited) + { + return Err(ProtocolError("DUPLICATE_OR_CYCLIC_REGISTRATION")); + } + Ok(()) + } + fn frame(&mut self, line: &[u8], parent: bool) -> Result<()> { + if self.terminal || line.len() + 1 > MAX_FRAME { + return Err(ProtocolError("POST_TERMINAL_OR_FRAME_LIMIT")); + } + self.owner.borrow_mut().charge("frames", 1)?; + if !line.is_ascii() { + return Err(ProtocolError("FRAME_ENCODING")); + } + let text = std::str::from_utf8(line).map_err(|_| ProtocolError("FRAME_ENCODING"))?; + let fields: Vec<_> = text.split('|').collect(); + if !matches!(fields.len(), 3 | 4 | 6) || fields[0] != self.nonce { + return Err(ProtocolError("NONCE_OR_SCHEMA")); + } + if fields.len() == 6 { + if parent + || !self.live + || !matches!(fields[1], "REGISTER" | "WAITED") + || !nonce_valid(fields[4]) + { + return Err(ProtocolError("METADATA_STATE")); + } + let key = (pid(fields[2])?, pid(fields[3])?, fields[4].to_owned()); + if fields[1] == "REGISTER" { + unsigned(fields[5])?; + Self::validate_registration( + &self.registrations, + self.expected_pid.ok_or(ProtocolError("MISSING_PEER"))?, + &key, + )?; + self.owner.borrow_mut().charge("registrations", 1)?; + self.registrations.insert(key, false); + } else { + wait_status(fields[5])?; + let waited = self + .registrations + .get_mut(&key) + .filter(|w| !**w) + .ok_or(ProtocolError("UNMATCHED_WAIT"))?; + *waited = true; + } + self.events.push(fields[1..].join("|")); + return Ok(()); + } + let peer = pid(fields[2])?; + if self.expected_pid.is_some_and(|p| p != peer) { + return Err(ProtocolError("PEER_IDENTITY")); + } + if parent { + if fields.len() != 4 || fields[1] != "CANCEL" { + return Err(ProtocolError("PARENT_STATE")); + } + let deadline = unsigned(fields[3])?; + if deadline == 0 { + return Err(ProtocolError("CANCEL_DEADLINE")); + } + self.cancel_deadline_ns = + Some(self.cancel_deadline_ns.unwrap_or(deadline).min(deadline)); + self.cancelled = true; + self.owner.borrow_mut().admission_closed = true; + self.expected_pid = Some(peer); + } else if fields.len() != 3 { + return Err(ProtocolError("CHILD_SCHEMA")); + } else { + match fields[1] { + "LIVE" if !self.live => { + self.live = true; + self.expected_pid = Some(peer); + } + "SETTLED" if self.live && self.registrations.values().all(|w| *w) => { + self.terminal = true + } + "FAILED" => return Err(ProtocolError("PEER_FAILED")), + _ => return Err(ProtocolError("CHILD_STATE")), + } + } + Ok(()) + } + pub fn receive(&mut self, parent: bool) -> Result { + self.check()?; + if self.parent_role.is_some_and(|role| role != parent) { + return Err(self.poison(ProtocolError("ROLE_CHANGED"))); + } + self.parent_role = Some(parent); + if self.eof { + return Ok(self.cancelled); + } + self.last_poll = PollWork::default(); + let result = self.receive_inner(parent); + result.map_err(|e| self.poison(e)) + } + fn receive_inner(&mut self, parent: bool) -> Result { + loop { + while self.last_poll.parsed < MAX_PARSE { + let Some(end) = self.pending.iter().position(|b| *b == b'\n') else { + break; + }; + let line: Vec<_> = self.pending.drain(..=end).collect(); + self.frame(&line[..line.len() - 1], parent)?; + self.last_poll.parsed += 1; + } + if self.terminal && !self.pending.is_empty() { + return Err(ProtocolError("POST_TERMINAL_DATA")); + } + if !self.pending.contains(&b'\n') && self.pending.len() >= MAX_FRAME { + return Err(ProtocolError("FRAME_LIMIT")); + } + if self.last_poll.parsed == MAX_PARSE || self.last_poll.reads == MAX_READS { + break; + } + self.last_poll.reads += 1; + let mut block = [0u8; MAX_FRAME]; + match self.socket.read(&mut block) { + Ok(0) => { + self.eof = true; + if !self.pending.is_empty() { + return Err(ProtocolError("TRUNCATED_FRAME")); + } + if parent { + self.cancelled = true; + self.owner.borrow_mut().admission_closed = true; + } else if self.terminal { + self.settled = true; + } else { + return Err(ProtocolError("EOF_WITHOUT_TERMINAL")); + } + break; + } + Ok(n) => { + self.owner.borrow_mut().charge("wire", n)?; + if self.pending.len() + n > MAX_PENDING { + return Err(ProtocolError("PENDING_LIMIT")); + } + self.pending.extend_from_slice(&block[..n]); + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => return Err(ProtocolError("READ_FAILED")), + } + } + Ok(self.cancelled) + } + pub fn is_settled(&self) -> bool { + self.settled && self.first_fault.is_none() + } + pub fn cancel_deadline_ns(&self) -> Option { + self.cancel_deadline_ns + } + pub fn take_events(&mut self) -> Vec { + std::mem::take(&mut self.events) + } +} + +#[cfg(test)] +mod installer_metadata_tests { + use super::*; + #[test] + fn installer_sent_ledger_predicate_is_nonterminal_and_requires_every_wait() { + let (socket, _peer) = UnixStream::pair().unwrap(); + let mut endpoint = Endpoint::new(socket, "ab".repeat(16), None).unwrap(); + assert!(!endpoint.sent_resources_complete()); + endpoint.send_live().unwrap(); + assert!(endpoint.sent_resources_complete()); + let root = std::process::id(); + let child = if root == 42 { 43 } else { 42 }; + endpoint + .metadata(&format!("REGISTER|{root}|{child}|{}|0", "cd".repeat(16))) + .unwrap(); + assert!(!endpoint.sent_resources_complete()); + endpoint + .metadata(&format!("WAITED|{root}|{child}|{}|0", "cd".repeat(16))) + .unwrap(); + assert!(endpoint.sent_resources_complete()); + assert!(!endpoint.sent_terminal); + endpoint.send_terminal(true).unwrap(); + assert!(!endpoint.sent_resources_complete()); + } +} + +#[cfg(test)] +#[path = "../../tests/unit/source_qa_protocol.rs"] +mod tests; + +#[cfg(test)] +mod readiness_metadata_tests { + use super::*; + #[test] + fn child_readiness_hints_do_not_parse_partial_frames_or_accept_budget_yield() { + let (socket, _peer) = UnixStream::pair().unwrap(); + let mut endpoint = Endpoint::new(socket, "ab".repeat(16), None).unwrap(); + let fd = endpoint.socket.as_raw_fd(); + endpoint.pending = b"partial".to_vec(); + assert_eq!(endpoint.progress_wait_source(), Some(fd)); + assert!(!endpoint.progress_buffered_event()); + let pending = endpoint.pending.clone(); + endpoint.last_poll.reads = MAX_READS; + assert!(endpoint.progress_buffered_event()); + endpoint.last_poll = PollWork { + reads: 0, + parsed: MAX_PARSE, + }; + assert!(endpoint.progress_buffered_event()); + assert_eq!(endpoint.pending, pending); + assert!(!endpoint.live && !endpoint.terminal && !endpoint.eof && !endpoint.is_settled()); + endpoint.last_poll = PollWork::default(); + endpoint.pending.push(b'\n'); + assert!(endpoint.progress_buffered_event()); + assert!(!endpoint.is_settled()); + } + #[test] + fn child_readiness_omits_only_original_receive_eof_even_after_terminal_hup() { + let (socket, peer_socket) = UnixStream::pair().unwrap(); + let mut endpoint = Endpoint::new(socket, "ab".repeat(16), None).unwrap(); + let mut peer = Endpoint::new(peer_socket, "ab".repeat(16), None).unwrap(); + peer.send_live().unwrap(); + peer.send_terminal(true).unwrap(); + assert!(endpoint.progress_wait_source().is_some()); + assert!(!endpoint.eof && !endpoint.is_settled()); + assert!(!endpoint.receive(false).unwrap()); + assert!(endpoint.eof && endpoint.is_settled()); + endpoint.last_poll = PollWork { + reads: MAX_READS, + parsed: MAX_PARSE, + }; + assert_eq!(endpoint.progress_wait_source(), None); + assert!( + !endpoint.progress_buffered_event(), + "stale cap after EOF would spin on Child wait" + ); + } +} diff --git a/src/process_ownership/scope.rs b/src/process_ownership/scope.rs new file mode 100644 index 0000000..f77bdcb --- /dev/null +++ b/src/process_ownership/scope.rs @@ -0,0 +1,5323 @@ +//! Explicit entry-thread command owner. No implicit/TLS runner or positive +//! capture authority. Cooperative children require terminal, physical EOF and +//! retained direct waits; opaque leaves use the paired guard's reserved groups. +use super::{ + group::{CleanupPolicy, GroupLease}, + io::{CommandOutput, IoFacts, IoPlan, PipeIo}, + protocol::{Endpoint, ProtocolError, Registration, SharedOwner, MAX_REGISTRATIONS}, +}; +use std::{ + collections::BTreeMap, + fs::File, + io, + os::{ + fd::{AsRawFd, FromRawFd, OwnedFd}, + unix::{ + net::UnixStream, + process::{CommandExt, ExitStatusExt}, + }, + }, + path::Path, + process::{Child, Command, ExitStatus, Stdio}, + rc::Rc, +}; + +const RESERVE_NS: u64 = 50_000_000; +const MAX_IO_BYTES: usize = 4 * 1024 * 1024; +const SLOTS_PER_TURN: usize = 8; +/// Original maximum for one selected installation; an earlier parent always wins. +pub const INSTALL_OPERATION_NS: u64 = 30_000_000_000; +const ORDINARY_OPERATION_NS: u64 = 1_000_000_000; + +// The fixed developer version/help lane has the ordinary one-second owner. +// Keep the selector closed; callers cannot supply a keeper policy or duration. +#[cfg(feature = "dev-tools")] +pub(super) fn dev_client_keeper_policy() -> CleanupPolicy { + CleanupPolicy::CommandProbe +} + +fn error(reason: &'static str) -> io::Error { + io::Error::other(reason) +} +fn spawn_cooperative_before( + hard_end: u64, + admission_ceiling: Option, + fresh: u64, + spawn: impl FnOnce() -> io::Result, +) -> io::Result { + let admission_end = admission_ceiling + .unwrap_or(hard_end) + .min(hard_end) + .saturating_sub(RESERVE_NS); + if fresh >= admission_end || super::signals::pending() { + return Err(error("SCOPE_ADMISSION")); + } + spawn() +} +fn clear_parent_environment(command: &mut Command) { + for key in [ + "KEITO_PROCESS_OWNER_FD", + "KEITO_PROCESS_OWNER_NONCE", + "KEITO_PROCESS_OWNER_PID", + "KEITO_PROCESS_OWNER_END_NS", + "KEITO_PROCESS_OWNER_CONTRACT", + "KEITO_SOURCE_OWNER_FD", + "KEITO_SOURCE_OWNER_NONCE", + "KEITO_CAPTURE_ACK_FD", + "KEITO_CAPTURE_IMAGE_FD", + "KEITO_CAPTURE_INVOCATION_NONCE", + "KEITO_CAPTURE_LEAF_END_NS", + "KEITO_CAPTURE_KEEPER_IMAGE_FD", + "KEITO_CAPTURE_CORE_SHA256", + ] { + command.env_remove(key); + } +} +fn now() -> io::Result { + let mut clock = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, clock.as_mut_ptr()) } != 0 { + return Err(error("SCOPE_CLOCK")); + } + let clock = unsafe { clock.assume_init() }; + u64::try_from(clock.tv_sec) + .ok() + .and_then(|s| s.checked_mul(1_000_000_000)) + .and_then(|s| s.checked_add(clock.tv_nsec as u64)) + .ok_or_else(|| error("SCOPE_CLOCK")) +} +pub(crate) fn monotonic_now() -> io::Result { + now() +} + +#[derive(Clone)] +pub struct SlotId { + index: usize, + scope: Rc<()>, +} +#[derive(Clone, Copy, Debug, Default)] +struct EdgeFacts { + status: Option, + waits_known: bool, + group_absent: bool, + terminal_eof: bool, + resource_proof: bool, + io_required: bool, + io: IoFacts, + first_fault: Option<&'static str>, +} +impl EdgeFacts { + fn resources_complete(&self) -> bool { + self.resource_proof && self.waits_known && (!self.io_required || self.io.complete()) + } +} +trait Edge { + fn begin(&mut self, end: u64) -> io::Result<()>; + fn poll(&mut self) -> io::Result<()>; + fn facts(&self) -> EdgeFacts; + #[cfg(feature = "capture-profile")] + fn repository_profile_stage(&self) -> Option { + None + } + fn setup_pending(&self) -> bool { + false + } + fn setup_wait_source(&self) -> Option<(i32, u64)> { + None + } + fn progress_wait_sources(&self, _descriptors: &mut Vec) -> Option { + None + } + fn progress_buffered_event(&self) -> bool { + false + } + fn setup_buffered_event(&self) -> bool { + false + } + fn post_join_pending(&self) -> bool { + false + } + #[cfg(feature = "dev-tools")] + fn setup_trace(&self) -> Option { + None + } + fn take_output(&mut self) -> CommandOutput; + fn take_events(&mut self) -> Vec { + Vec::new() + } +} +enum Stage { + Ready, + Park, + Running, + Cleaning, + Done, +} +impl Stage { + #[cfg(feature = "capture-profile")] + fn repository_profile_stage(&self) -> crate::capture_profile::Phase { + use crate::capture_profile::Phase; + match self { + Self::Ready => Phase::RepoReadyPoll, + Self::Park => Phase::RepoParkPoll, + Self::Running => Phase::RepoRunningPoll, + Self::Cleaning => Phase::RepoCleaningPoll, + Self::Done => Phase::RepoDonePoll, + } + } + fn setup_pending(&self) -> bool { + matches!(self, Self::Ready | Self::Park) + } +} +// Scheduling only: this lock never proves command identity, consent or success. +// Retain each slot through group and pipe finality, so a parked command cannot +// admit another live Git group into the same four-slot pool. This is not an +// absolute process bound after owner death or unproved cleanup. +// Each admission opens an independent description; never duplicate the lock FD. +const HOOK_SETUP_SLOTS: usize = 4; +#[derive(Clone, Copy)] +enum HookCapacityKind { + Leaf, + Core, +} +struct HookSetupAdmission { + file: File, + name: &'static [u8], +} +impl HookSetupAdmission { + #[cfg(test)] + fn open(directory: &File, slot: usize) -> io::Result { + Self::open_kind(directory, slot, HookCapacityKind::Leaf) + } + fn open_kind(directory: &File, slot: usize, kind: HookCapacityKind) -> io::Result { + use std::os::unix::fs::MetadataExt; + let parent = directory + .metadata() + .map_err(|_| error("SCOPE_SETUP_GATE"))?; + if !parent.is_dir() + || parent.uid() != unsafe { libc::geteuid() } + || parent.mode() & 0o777 != 0o700 + { + return Err(error("SCOPE_SETUP_GATE")); + } + let name: &'static [u8] = match (kind, slot) { + (HookCapacityKind::Leaf, 0) => b"capture-hook-setup-0.lock\0", + (HookCapacityKind::Leaf, 1) => b"capture-hook-setup-1.lock\0", + (HookCapacityKind::Leaf, 2) => b"capture-hook-setup-2.lock\0", + (HookCapacityKind::Leaf, 3) => b"capture-hook-setup-3.lock\0", + (HookCapacityKind::Core, 0) => b"capture-hook-core-0.lock\0", + (HookCapacityKind::Core, 1) => b"capture-hook-core-1.lock\0", + (HookCapacityKind::Core, 2) => b"capture-hook-core-2.lock\0", + (HookCapacityKind::Core, 3) => b"capture-hook-core-3.lock\0", + _ => return Err(error("SCOPE_SETUP_GATE")), + }; + let fd = unsafe { + libc::openat( + directory.as_raw_fd(), + name.as_ptr().cast(), + libc::O_RDWR + | libc::O_CREAT + | libc::O_NONBLOCK + | libc::O_NOFOLLOW + | libc::O_CLOEXEC, + 0o600, + ) + }; + if fd < 0 { + return Err(error("SCOPE_SETUP_GATE")); + } + let admission = Self { + file: unsafe { File::from_raw_fd(fd) }, + name, + }; + admission.check(directory)?; + Ok(admission) + } + fn check(&self, directory: &File) -> io::Result<()> { + use std::os::unix::fs::MetadataExt; + let metadata = self + .file + .metadata() + .map_err(|_| error("SCOPE_SETUP_GATE"))?; + let name = self.name; + let mut current = std::mem::MaybeUninit::::uninit(); + if unsafe { + libc::fstatat( + directory.as_raw_fd(), + name.as_ptr().cast(), + current.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { + return Err(error("SCOPE_SETUP_GATE")); + } + let current = unsafe { current.assume_init() }; + if !metadata.is_file() + || metadata.uid() != unsafe { libc::geteuid() } + || metadata.mode() & 0o777 != 0o600 + || metadata.nlink() != 1 + || metadata.len() != 0 + || current.st_dev as u128 != u128::from(metadata.dev()) + || current.st_ino as u128 != u128::from(metadata.ino()) + || current.st_mode & libc::S_IFMT != libc::S_IFREG + { + return Err(error("SCOPE_SETUP_GATE")); + } + Ok(()) + } + fn try_lock(&mut self, directory: &File) -> io::Result { + self.check(directory)?; + if unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + self.check(directory)?; + return Ok(true); + } + if io::Error::last_os_error().kind() == io::ErrorKind::WouldBlock { + Ok(false) + } else { + Err(error("SCOPE_SETUP_GATE")) + } + } +} + +// Guard-only scheduling ownership. It grants no capture authority. CLOEXEC and +// the guard's child descriptor inventory keep the lock in the owning guard. +// A guard retains it through its final Scope::finish and terminal publication; +// as with leaf permits, this is not an after-crash/unproved-cleanup bound. +#[allow(dead_code)] // Also compiled into the standalone guard from shared source. +pub(crate) struct HookCoreAdmission { + _permit: HookSetupAdmission, +} + +struct GroupEdge { + lease: GroupLease, + command: Option, + pipes: PipeIo, + stage: Stage, + proof: bool, + first_fault: Option<&'static str>, + published: [bool; 4], + setup_admission: Option, + post_join_pending: bool, +} +fn release_hook_admission( + stage: &Stage, + facts: EdgeFacts, + admission: &mut Option, +) { + if matches!(stage, Stage::Done) + && facts.resources_complete() + && facts.group_absent + && facts.terminal_eof + { + admission.take(); + } +} +// Attach all retained handles before propagating even a post-spawn error. +// Success schedules ONE later PARK observation after the upstream drain. +fn retain_group_start( + stage: &mut Stage, + pending: &mut bool, + started: io::Result<()>, + attach: impl FnOnce() -> io::Result<()>, +) -> io::Result<()> { + let attached = attach(); + *stage = Stage::Park; + *pending = false; + started?; + attached?; + *pending = true; + Ok(()) +} + +impl GroupEdge { + fn progress(&mut self) -> io::Result<()> { + // Outputs progress even while PARK is pending. Each pipe has a fixed + // per-turn byte/syscall cap, and no WouldBlock is accepted as EOF. + self.pipes.poll(); + if let Some(reason) = self.pipes.facts().first_fault { + self.first_fault.get_or_insert(reason); + if !matches!(self.stage, Stage::Cleaning | Stage::Done) { + return Err(error(reason)); + } + } + match self.stage { + Stage::Ready => { + if self.lease.poll_ready()? { + let command = self.command.take().ok_or_else(|| error("SCOPE_COMMAND"))?; + let started = self.lease.start_pending(command); + // Even an error AFTER spawn must transfer every available + // pipe to this retained slot before returning the fault. + let workload_spawned = self.lease.report().workload_spawned; + let lease = &mut self.lease; + let pipes = &mut self.pipes; + retain_group_start( + &mut self.stage, + &mut self.post_join_pending, + started, + || { + if workload_spawned { + pipes.attach(lease.stdin(), lease.stdout(), lease.stderr()) + } else { + Ok(()) + } + }, + )?; + } + } + Stage::Park => { + self.post_join_pending = false; + if self.lease.poll_parked()? { + self.stage = Stage::Running; + } + } + Stage::Running => { + self.lease.poll_workload()?; + } + Stage::Cleaning => { + if self.lease.poll_local_cleanup()?.is_some() { + self.proof = true; + self.stage = Stage::Done; + } + } + Stage::Done => {} + } + if self.setup_admission.is_some() && matches!(self.stage, Stage::Done) { + let facts = self.facts(); + release_hook_admission(&self.stage, facts, &mut self.setup_admission); + } + Ok(()) + } +} +impl Edge for GroupEdge { + fn progress_wait_sources(&self, descriptors: &mut Vec) -> Option { + if self.stage.setup_pending() { + return None; + } + self.pipes.progress_wait_sources(descriptors); + if matches!(self.stage, Stage::Cleaning) { + if let Some(fd) = self.lease.cleanup_wait_source() { + descriptors.push(libc::pollfd { + fd, + events: libc::POLLIN, + revents: 0, + }); + } + } + Some(self.lease.progress_wait_end()) + } + fn progress_buffered_event(&self) -> bool { + matches!(self.stage, Stage::Cleaning) && self.lease.cleanup_buffered_event() + } + #[cfg(feature = "capture-profile")] + fn repository_profile_stage(&self) -> Option { + Some(self.stage.repository_profile_stage()) + } + #[cfg(feature = "dev-tools")] + fn setup_trace(&self) -> Option { + Some(self.lease.setup_trace()) + } + fn setup_pending(&self) -> bool { + self.stage.setup_pending() + } + fn setup_buffered_event(&self) -> bool { + self.stage.setup_pending() && self.lease.setup_buffered_event() + } + fn post_join_pending(&self) -> bool { + self.post_join_pending && matches!(self.stage, Stage::Park) + } + fn setup_wait_source(&self) -> Option<(i32, u64)> { + self.stage + .setup_pending() + .then(|| self.lease.setup_wait_source()) + } + fn begin(&mut self, end: u64) -> io::Result<()> { + self.command.take(); + self.pipes.cancel_input(); + if matches!(self.stage, Stage::Done) { + return Ok(()); + } + self.stage = Stage::Cleaning; + self.post_join_pending = false; + self.lease.begin_local_cleanup(end) + } + fn poll(&mut self) -> io::Result<()> { + #[cfg(feature = "capture-profile")] + let result = { + let _span = crate::capture_profile::Span::start(self.stage.repository_profile_stage()); + self.progress() + }; + #[cfg(not(feature = "capture-profile"))] + let result = self.progress(); + if result.is_err() { + self.first_fault.get_or_insert( + self.lease + .report() + .first_fault + .or(self.pipes.facts().first_fault) + .unwrap_or("SCOPE_EDGE"), + ); + } + if let Some(reason) = self.first_fault { + Err(error(reason)) + } else { + result + } + } + fn facts(&self) -> EdgeFacts { + let facts = self.lease.report(); + EdgeFacts { + status: facts.workload_status, + waits_known: facts.keeper_status.is_some() + && (!facts.workload_spawned || facts.workload_status.is_some()), + group_absent: facts.group_absent, + terminal_eof: facts.terminal_eof, + resource_proof: self.proof, + io_required: facts.workload_spawned, + io: self.pipes.facts(), + first_fault: self + .first_fault + .or(facts.first_fault) + .or(self.pipes.facts().first_fault), + } + } + fn take_output(&mut self) -> CommandOutput { + self.pipes.take_output() + } + fn take_events(&mut self) -> Vec { + let facts = self.lease.report(); + let parent = std::process::id(); + let nonce = self.lease.registration_nonce(); + let mut events = Vec::new(); + for (index, pid, status) in [ + (0, Some(facts.keeper_pid), None), + (1, facts.workload_pid, None), + (2, Some(facts.keeper_pid), facts.keeper_status), + (3, facts.workload_pid, facts.workload_status), + ] { + let Some(pid) = pid else { + continue; + }; + if !self.published[index] && (index < 2 || status.is_some()) { + self.published[index] = true; + let kind = if index < 2 { "REGISTER" } else { "WAITED" }; + let value = status.map(ExitStatus::into_raw).unwrap_or(0); + events.push(format!("{kind}|{parent}|{pid}|{nonce}|{value}")); + } + } + events + } +} + +struct CooperativeEdge { + child: Child, + endpoint: Endpoint, + nonce: String, + status: Option, + cancel_sent: Option, + registered: bool, + waited: bool, + first_fault: Option<&'static str>, + pipes: Option, +} +impl Edge for CooperativeEdge { + fn progress_wait_sources(&self, descriptors: &mut Vec) -> Option { + if let Some(pipes) = &self.pipes { + pipes.progress_wait_sources(descriptors); + } + if let Some(fd) = self.endpoint.progress_wait_source() { + descriptors.push(libc::pollfd { + fd, + events: libc::POLLIN, + revents: 0, + }); + } + self.cancel_sent + } + fn progress_buffered_event(&self) -> bool { + self.endpoint.progress_buffered_event() + } + fn begin(&mut self, end: u64) -> io::Result<()> { + if let Some(pipes) = &mut self.pipes { + pipes.cancel_input(); + } + if self.status.is_none() + && !self.endpoint.is_settled() + && self.cancel_sent.is_none_or(|previous| end < previous) + { + self.cancel_sent = Some(end); + // V1's cancellation grammar requires a positive absolute end. + // Zero is an already-expired local end, never a fresh allowance. + if let Err(e) = self.endpoint.send_cancel_tighter(end.max(1)) { + self.first_fault.get_or_insert(e.0); + return Err(error(e.0)); + } + } + Ok(()) + } + fn poll(&mut self) -> io::Result<()> { + if let Some(pipes) = &mut self.pipes { + pipes.poll(); + if let Some(reason) = pipes.facts().first_fault { + self.first_fault.get_or_insert(reason); + } + } + // Endpoint faults never skip the independently retained direct wait. + if let Err(e) = self.endpoint.receive(false) { + self.first_fault.get_or_insert(e.0); + } + if self.status.is_none() { + match self.child.try_wait() { + Ok(status) => self.status = status, + Err(_) => { + self.first_fault.get_or_insert("SCOPE_CHILD_WAIT"); + } + } + } + self.first_fault.map_or(Ok(()), |e| Err(error(e))) + } + fn facts(&self) -> EdgeFacts { + EdgeFacts { + status: self.status, + waits_known: self.status.is_some(), + terminal_eof: self.endpoint.is_settled(), + resource_proof: self.status.is_some() + && self.endpoint.is_settled() + && self.first_fault.is_none(), + first_fault: self.first_fault, + io_required: self.pipes.is_some(), + io: self.pipes.as_ref().map(PipeIo::facts).unwrap_or_default(), + ..Default::default() + } + } + fn take_output(&mut self) -> CommandOutput { + self.pipes + .as_mut() + .map(PipeIo::take_output) + .unwrap_or_else(|| CommandOutput { + stdout: Vec::new(), + stderr: Vec::new(), + }) + } + fn take_events(&mut self) -> Vec { + let mut events = Vec::new(); + let parent = std::process::id(); + let child = self.child.id(); + if !self.registered { + self.registered = true; + events.push(format!("REGISTER|{parent}|{child}|{}|0", self.nonce)); + } + events.extend(self.endpoint.take_events()); + // A direct WAITED is published after all currently received descendant + // records. Terminal+EOF remains a separate acceptance requirement. + if let Some(status) = self + .status + .filter(|_| !self.waited && (self.endpoint.is_settled() || self.first_fault.is_some())) + { + self.waited = true; + events.push(format!( + "WAITED|{parent}|{child}|{}|{}", + self.nonce, + status.into_raw() + )); + } + events + } +} +enum ProductEdge { + Group(GroupEdge), + Cooperative(CooperativeEdge), +} +impl Edge for ProductEdge { + fn progress_wait_sources(&self, descriptors: &mut Vec) -> Option { + match self { + Self::Group(edge) => edge.progress_wait_sources(descriptors), + Self::Cooperative(edge) => edge.progress_wait_sources(descriptors), + } + } + fn progress_buffered_event(&self) -> bool { + match self { + Self::Group(edge) => edge.progress_buffered_event(), + Self::Cooperative(edge) => edge.progress_buffered_event(), + } + } + #[cfg(feature = "capture-profile")] + fn repository_profile_stage(&self) -> Option { + match self { + Self::Group(edge) => edge.repository_profile_stage(), + Self::Cooperative(edge) => edge.repository_profile_stage(), + } + } + fn setup_buffered_event(&self) -> bool { + match self { + Self::Group(edge) => edge.setup_buffered_event(), + Self::Cooperative(edge) => edge.setup_buffered_event(), + } + } + fn post_join_pending(&self) -> bool { + match self { + Self::Group(edge) => edge.post_join_pending(), + Self::Cooperative(edge) => edge.post_join_pending(), + } + } + fn setup_wait_source(&self) -> Option<(i32, u64)> { + match self { + Self::Group(edge) => edge.setup_wait_source(), + Self::Cooperative(edge) => edge.setup_wait_source(), + } + } + #[cfg(feature = "dev-tools")] + fn setup_trace(&self) -> Option { + match self { + Self::Group(edge) => edge.setup_trace(), + Self::Cooperative(edge) => edge.setup_trace(), + } + } + fn setup_pending(&self) -> bool { + match self { + Self::Group(edge) => edge.setup_pending(), + Self::Cooperative(edge) => edge.setup_pending(), + } + } + fn begin(&mut self, end: u64) -> io::Result<()> { + match self { + Self::Group(e) => e.begin(end), + Self::Cooperative(e) => e.begin(end), + } + } + fn poll(&mut self) -> io::Result<()> { + match self { + Self::Group(e) => e.poll(), + Self::Cooperative(e) => e.poll(), + } + } + fn facts(&self) -> EdgeFacts { + match self { + Self::Group(e) => e.facts(), + Self::Cooperative(e) => e.facts(), + } + } + fn take_output(&mut self) -> CommandOutput { + match self { + Self::Group(e) => e.take_output(), + Self::Cooperative(e) => e.take_output(), + } + } + fn take_events(&mut self) -> Vec { + match self { + Self::Group(e) => e.take_events(), + Self::Cooperative(e) => e.take_events(), + } + } +} +struct Slot { + edge: E, + hard_end: u64, + completion_end: Option, + accepted_at: Option, + output_taken: bool, +} +#[derive(Clone, Copy, PartialEq, Eq)] +enum InstallerState { + Preflight, + Publishing, +} +struct InstallerPhase { + end: u64, + expected: usize, + state: InstallerState, +} +struct Core { + owner: SharedOwner, + identity: Rc<()>, + slots: Vec>, + hard_end: u64, + cancel_end: Option, + io_reserved: usize, + cursor: usize, + finish_called: bool, + finished: bool, + installer: Option, + unfinished_end: u64, + entry_selected: bool, +} +impl Core { + fn new(owner: SharedOwner, hard_end: u64) -> Self { + Self { + owner, + identity: Rc::new(()), + slots: vec![], + hard_end, + cancel_end: None, + io_reserved: 0, + cursor: 0, + finish_called: false, + finished: false, + installer: None, + unfinished_end: hard_end, + entry_selected: false, + } + } + #[cfg(feature = "dev-tools")] + fn first_fault_setup_trace(&self) -> Option { + let first = self.owner.borrow().first_fault?; + self.slots + .iter() + .filter_map(|slot| slot.edge.setup_trace()) + .find(|trace| { + trace + .fault_origin + .is_some_and(|(reason, _)| reason == first.0) + }) + } + fn poison(&mut self, reason: &'static str) { + self.owner.borrow_mut().poison(ProtocolError(reason)); + } + fn admission_clock(&mut self, clock: &mut impl FnMut() -> io::Result) -> io::Result { + match clock() { + Ok(at) => Ok(at), + Err(_) => { + self.cancel(Some("SCOPE_CLOCK"), 0, 0); + Err(error("SCOPE_CLOCK")) + } + } + } + fn admit( + &mut self, + at: u64, + capacity: usize, + create: impl FnOnce(SharedOwner) -> io::Result, + ) -> io::Result { + if self.installer.is_some() { + self.poison("SCOPE_INSTALLER_PHASE"); + return Err(error("SCOPE_INSTALLER_PHASE")); + } + self.admit_before(at, capacity, self.hard_end, |owner, _| create(owner)) + } + fn admit_before( + &mut self, + at: u64, + capacity: usize, + requested_end: u64, + create: impl FnOnce(SharedOwner, u64) -> io::Result, + ) -> io::Result { + let hard_end = requested_end.min(self.hard_end); + let admission = self.owner.borrow().check_admission(); + if let Err(reason) = admission { + return Err(error(reason.0)); + } + if self.finished || self.cancel_end.is_some() || at >= hard_end.saturating_sub(RESERVE_NS) { + self.poison("SCOPE_ADMISSION"); + return Err(error("SCOPE_ADMISSION")); + } + let reserved = self + .io_reserved + .checked_add(capacity) + .filter(|n| *n <= MAX_IO_BYTES); + if self.slots.len() >= MAX_REGISTRATIONS + || reserved.is_none() + || self.slots.try_reserve(1).is_err() + { + self.poison("SCOPE_LIMIT"); + return Err(error("SCOPE_LIMIT")); + } + let edge = match create(self.owner.clone(), hard_end) { + Ok(edge) => edge, + Err(_) => { + self.poison("SCOPE_SPAWN"); + return Err(error("SCOPE_SPAWN")); + } + }; + let id = SlotId { + index: self.slots.len(), + scope: self.identity.clone(), + }; + // Capacity exists before factory spawn; the returned edge/handles are + // retained before any subsequent publication or flags operation. + self.slots.push(Slot { + edge, + hard_end, + completion_end: None, + accepted_at: None, + output_taken: false, + }); + self.io_reserved = reserved.unwrap(); + self.unfinished_end = self.unfinished_end.min(hard_end); + Ok(id) + } + #[cfg(feature = "dev-tools")] + fn admit_dev_client( + &mut self, + at: u64, + capacity: usize, + selected_end: u64, + create: impl FnOnce(SharedOwner, u64) -> io::Result, + ) -> io::Result { + if self.installer.is_some() + || self.slots.len() >= 4 + || self.slots.iter().any(|slot| slot.accepted_at.is_none()) + { + self.poison("DEV_CLIENT_ADMISSION"); + return Err(error("DEV_CLIENT_ADMISSION")); + } + let local = match at.checked_add(1_000_000_000) { + Some(end) => end, + None => { + self.cancel(Some("SCOPE_CLOCK"), 0, 0); + return Err(error("SCOPE_CLOCK")); + } + }; + self.admit_before(at, capacity, selected_end.min(local), create) + } + #[cfg(feature = "dev-tools")] + fn release_dev_completed(&mut self, ledgers_complete: bool) -> io::Result<()> { + if !ledgers_complete + || self.installer.is_some() + || self.slots.is_empty() + || self.cancel_end.is_some() + || self.finish_called + || self.owner.borrow().check_admission().is_err() + || self.slots.iter().any(|slot| { + !slot.output_taken + || !slot.edge.facts().resources_complete() + || slot.accepted_at.is_none_or(|at| at >= slot.hard_end) + }) + { + self.poison("DEV_CLIENT_COLLECTION"); + return Err(error("DEV_CLIENT_COLLECTION")); + } + // Only the cache of UNFINISHED ends is released. Original owner/slot + // ends and all immutable acceptance facts remain unchanged. + self.unfinished_end = self.hard_end; + Ok(()) + } + fn begin_installer(&mut self, at: u64, expected: usize) -> io::Result<()> { + if self.installer.is_some() + || !self.slots.is_empty() + || !(1..=2).contains(&expected) + || self.finished + || self.finish_called + || self.cancel_end.is_some() + || self.owner.borrow().check_admission().is_err() + { + self.cancel(Some("SCOPE_INSTALLER_PHASE"), at, self.hard_end); + return Err(error("SCOPE_INSTALLER_PHASE")); + } + let Some(operation_end) = at.checked_add(INSTALL_OPERATION_NS) else { + self.cancel(Some("SCOPE_CLOCK"), 0, 0); + return Err(error("SCOPE_CLOCK")); + }; + // Library callers may supply a more generous containing owner. This + // operation can only restrict it; main's earlier entry bound still wins. + self.hard_end = self.hard_end.min(operation_end); + self.unfinished_end = self.unfinished_end.min(self.hard_end); + let Some(local_end) = at.checked_add(ORDINARY_OPERATION_NS) else { + self.cancel(Some("SCOPE_CLOCK"), 0, 0); + return Err(error("SCOPE_CLOCK")); + }; + let end = self.hard_end.min(local_end); + self.installer = Some(InstallerPhase { + end, + expected, + state: InstallerState::Preflight, + }); + if at >= end.saturating_sub(RESERVE_NS) { + self.cancel(Some("SCOPE_ADMISSION"), at, end); + return Err(error("SCOPE_ADMISSION")); + } + Ok(()) + } + fn installer_end(&self) -> io::Result { + self.installer + .as_ref() + .filter(|phase| { + phase.state == InstallerState::Preflight && self.slots.len() < phase.expected + }) + .map(|phase| phase.end) + .ok_or_else(|| error("SCOPE_INSTALLER_PHASE")) + } + fn admit_installer( + &mut self, + at: u64, + capacity: usize, + create: impl FnOnce(SharedOwner, u64) -> io::Result, + ) -> io::Result { + let end = match self.installer_end() { + Ok(end) => end, + Err(error) => { + self.cancel(Some("SCOPE_INSTALLER_PHASE"), at, self.hard_end); + return Err(error); + } + }; + self.admit_before(at, capacity, end, create) + } + fn refine_entry(&mut self, end: u64, at: u64) -> io::Result<()> { + self.hard_end = self.hard_end.min(end); + if self.entry_selected + || !self.slots.is_empty() + || self.installer.is_some() + || self.finished + || self.cancel_end.is_some() + || self.owner.borrow().check_admission().is_err() + || at >= self.hard_end.saturating_sub(RESERVE_NS) + { + self.cancel(Some("SCOPE_ENTRY_SELECTION"), at, self.hard_end); + return Err(error("SCOPE_ENTRY_SELECTION")); + } + self.entry_selected = true; + Ok(()) + } + fn active_end(&self) -> u64 { + let mut end = self.hard_end; + if let Some(phase) = &self.installer { + if phase.state == InstallerState::Preflight { + end = end.min(phase.end); + } + } + end.min(self.unfinished_end) + } + fn seal_installer( + &mut self, + ledgers_complete: bool, + clock: &mut impl FnMut() -> io::Result, + ) -> io::Result<()> { + let valid = self.installer.as_ref().is_some_and(|phase| { + phase.state == InstallerState::Preflight + && self.slots.len() == phase.expected + && self.slots.iter().all(|slot| { + let facts = slot.edge.facts(); + slot.output_taken + && slot + .accepted_at + .is_some_and(|at| at < slot.hard_end && at < phase.end) + && slot.hard_end <= phase.end + && facts.resources_complete() + && facts.status.is_some() + && facts.group_absent + && facts.terminal_eof + && facts.first_fault.is_none() + && facts.io.first_fault.is_none() + }) + }) && ledgers_complete + && !self.finished + && !self.finish_called + && self.cancel_end.is_none() + && self.owner.borrow().check_admission().is_ok(); + let at = self.admission_clock(clock)?; + let end = self.active_end(); + if !valid || at >= end || at >= self.hard_end.saturating_sub(RESERVE_NS) { + self.cancel(Some("SCOPE_PREFLIGHT"), at, end); + return Err(error("SCOPE_PREFLIGHT")); + } + self.installer.as_mut().unwrap().state = InstallerState::Publishing; + // No unaccepted cohort slot remains. Retain every immutable slot end; + // only its now-inactive timer stops restricting the parent operation. + self.unfinished_end = self.hard_end; + Ok(()) + } + fn publication_live( + &mut self, + ledgers_complete: bool, + clock: &mut impl FnMut() -> io::Result, + ) -> io::Result<()> { + let valid = self + .installer + .as_ref() + .is_some_and(|phase| phase.state == InstallerState::Publishing) + && ledgers_complete + && self.all_resources() + && !self.finished + && !self.finish_called + && self.cancel_end.is_none() + && self.owner.borrow().check_admission().is_ok(); + let at = self.admission_clock(clock)?; + if !valid || at >= self.hard_end.saturating_sub(RESERVE_NS) { + self.cancel(Some("SCOPE_PUBLICATION"), at, self.hard_end); + return Err(error("SCOPE_PUBLICATION")); + } + Ok(()) + } + fn terminal_fresh(&mut self, clock: &mut impl FnMut() -> io::Result) -> bool { + let at = match self.admission_clock(clock) { + Ok(at) => at, + Err(_) => return false, + }; + let end = self.hard_end.min(self.cancel_end.unwrap_or(self.hard_end)); + if at >= end { + self.cancel(Some("SCOPE_TERMINAL_DEADLINE"), at, end); + return false; + } + self.finished + && self.finish_called + && self.all_resources() + && self.owner.borrow().first_fault.is_none() + && self + .installer + .as_ref() + .is_some_and(|phase| phase.state == InstallerState::Publishing) + } + fn index(&mut self, id: &SlotId) -> io::Result { + if !Rc::ptr_eq(&id.scope, &self.identity) || id.index >= self.slots.len() { + self.poison("SCOPE_SLOT_ID"); + return Err(error("SCOPE_SLOT_ID")); + } + Ok(id.index) + } + fn request_complete(&mut self, id: &SlotId, at: u64) -> io::Result<()> { + let index = self.index(id)?; + if self.slots[index].completion_end.is_some() { + return Ok(()); + } + // Completing this slot must leave its containing owner open. Global + // cancellation/final finish use cancel(), never this local transition. + let end = self + .hard_end + .min(self.slots[index].hard_end) + .min(at.saturating_add(RESERVE_NS)); + self.slots[index].completion_end = Some(end); + let result = self.slots[index].edge.begin(end); + if result.is_err() { + self.poison( + self.slots[index] + .edge + .facts() + .first_fault + .unwrap_or("SCOPE_BEGIN"), + ); + } + result + } + fn cancel(&mut self, reason: Option<&'static str>, at: u64, requested: u64) { + if let Some(reason) = reason { + self.poison(reason); + } + self.owner.borrow_mut().admission_closed = true; + let end = self + .cancel_end + .unwrap_or(u64::MAX) + .min(self.hard_end) + .min(self.active_end()) + .min(requested) + .min(at.saturating_add(RESERVE_NS)); + if self.cancel_end == Some(end) { + return; + } + self.cancel_end = Some(end); + // Broadcast ALL intents before any poll/wait, even when begin fails. + for index in 0..self.slots.len() { + let slot = &mut self.slots[index]; + if slot.accepted_at.is_some() { + continue; + } + slot.completion_end = Some(slot.completion_end.unwrap_or(u64::MAX).min(end)); + if slot.edge.begin(slot.completion_end.unwrap()).is_err() { + let reason = slot.edge.facts().first_fault.unwrap_or("SCOPE_BEGIN"); + self.poison(reason); + } + } + } + fn poll(&mut self, clock: &mut impl FnMut() -> io::Result) { + let at = match clock() { + Ok(at) => at, + Err(_) => { + self.cancel(Some("SCOPE_CLOCK"), 0, 0); + 0 + } + }; + let fault = self.owner.borrow().first_fault; + if fault.is_some() && self.cancel_end.is_none() { + self.cancel(None, at, self.hard_end); + } + if at >= self.active_end().saturating_sub(RESERVE_NS) && self.cancel_end.is_none() { + self.cancel(Some("SCOPE_OPERATION_DEADLINE"), at, self.active_end()); + } + let len = self.slots.len(); + for _ in 0..len.min(SLOTS_PER_TURN) { + let index = self.cursor % len; + self.cursor = (index + 1) % len; + self.poll_slot(index, clock); + } + } + fn poll_slot(&mut self, index: usize, clock: &mut impl FnMut() -> io::Result) { + if self.slots[index].accepted_at.is_some() { + return; + } + if self.slots[index].edge.poll().is_err() { + self.poison( + self.slots[index] + .edge + .facts() + .first_fault + .unwrap_or("SCOPE_POLL"), + ); + match clock() { + Ok(at) => self.cancel(None, at, self.hard_end), + Err(_) => self.cancel(Some("SCOPE_CLOCK"), 0, 0), + } + } + let facts = self.slots[index].edge.facts(); + if facts.status.is_some() && self.slots[index].completion_end.is_none() { + match clock() { + Err(_) => self.cancel(Some("SCOPE_CLOCK"), 0, 0), + Ok(at) => { + let id = SlotId { + index, + scope: self.identity.clone(), + }; + if self.request_complete(&id, at).is_err() { + self.cancel(None, at, self.hard_end); + } + } + } + } + if facts.resources_complete() { + let end = self.slots[index] + .completion_end + .unwrap_or(0) + .min(self.slots[index].hard_end) + .min(self.hard_end); + match clock() { + Ok(at) if at < end => self.slots[index].accepted_at = Some(at), + _ => { + self.poison("SCOPE_PROOF_DEADLINE"); + self.cancel(None, 0, 0); + } + } + } + } + fn poll_post_joined( + &mut self, + start: usize, + clock: &mut impl FnMut() -> io::Result, + ) -> bool { + let mut observed = false; + // Only the edges visited by the containing fair turn can be newly + // joined. No recursion, new child, cursor reset or second setup loop. + let len = self.slots.len(); + for offset in 0..len.min(SLOTS_PER_TURN) { + let index = (start + offset) % len; + if self.slots[index].accepted_at.is_some() + || !self.slots[index].edge.post_join_pending() + { + continue; + } + if self.finished || self.cancel_end.is_some() { + return observed; + } + let at = match self.admission_clock(clock) { + Ok(at) => at, + Err(_) => return observed, + }; + let admission = self.owner.borrow().check_admission(); + if let Err(reason) = admission { + self.cancel(Some(reason.0), at, self.hard_end); + return observed; + } + if at >= self.active_end().saturating_sub(RESERVE_NS) { + self.cancel(Some("SCOPE_OPERATION_DEADLINE"), at, self.active_end()); + return observed; + } + // GroupEdge's existing Stage::Park path clears its flag and uses + // the original poll_parked parser and before/after end checks. + observed = true; + self.poll_slot(index, clock); + } + observed + } + fn all_resources(&self) -> bool { + self.slots.iter().all(|s| s.accepted_at.is_some()) + } + fn finish_at(&mut self, at: u64) -> bool { + if self.finished { + return true; + } + if at >= self.cancel_end.unwrap_or(0) { + self.poison("SCOPE_CLEANUP_DEADLINE"); + self.finished = true; + } else if self.all_resources() { + self.finished = true; + } + self.finished + } + // The public finish entrypoint and finite regressions use this SAME + // envelope. Clock injection does not replace any ownership transitions. + #[cfg(test)] + fn finish_with( + &mut self, + clock: &mut impl FnMut() -> io::Result, + pause: &mut impl FnMut(), + ) { + self.finish_with_progress(clock, pause, &mut |_| {}); + } + fn finish_with_progress( + &mut self, + clock: &mut impl FnMut() -> io::Result, + pause: &mut impl FnMut(), + progress: &mut impl FnMut(&mut Self), + ) { + self.finish_called = true; + if self.finished { + return; + } + match clock() { + Ok(at) => self.cancel(None, at, self.hard_end), + Err(_) => self.cancel(Some("SCOPE_CLOCK"), 0, 0), + } + loop { + progress(self); + self.poll(clock); + progress(self); + let at = match clock() { + Ok(at) => at, + Err(_) => { + // Broadcast the irreversible zero end BEFORE marking + // finished, including the final fresh-clock placement. + self.cancel(Some("SCOPE_CLOCK"), 0, 0); + 0 + } + }; + if self.finish_at(at) { + break; + } + #[cfg(feature = "capture-profile")] + { + let _span = crate::capture_profile::Span::wait( + crate::capture_profile::Phase::RepoFinishWait, + 1_000_000, + ); + pause(); + } + #[cfg(not(feature = "capture-profile"))] + pause(); + } + self.finished = true; + } + // No sibling preparation/spawn while a prior short READY/PARK handshake + // still requires this same entry thread. Running/cleanup may overlap. + fn repository_admission_ready(&mut self) -> io::Result { + let admission = self.owner.borrow().check_admission(); + if let Err(reason) = admission { + return Err(error(reason.0)); + } + if self.finished || self.cancel_end.is_some() { + self.poison("SCOPE_ADMISSION"); + return Err(error("SCOPE_ADMISSION")); + } + Ok(!self + .slots + .iter() + .any(|slot| slot.accepted_at.is_none() && slot.edge.setup_pending())) + } + fn wait_repository_setup( + &mut self, + clock: &mut impl FnMut() -> io::Result, + poll: &mut impl FnMut(&mut [libc::pollfd], i32) -> io::Result, + ) -> io::Result<()> { + self.repository_admission_ready()?; + let sources: Vec<_> = self + .slots + .iter() + .filter(|slot| slot.accepted_at.is_none() && slot.edge.setup_pending()) + .filter_map(|slot| slot.edge.setup_wait_source()) + .collect(); + if sources.is_empty() || sources.iter().any(|(fd, _)| *fd < 0) { + self.poison("SCOPE_SETUP_WAIT"); + return Err(error("SCOPE_SETUP_WAIT")); + } + let end = sources + .iter() + .map(|(_, end)| *end) + .min() + .unwrap() + .min(self.active_end().saturating_sub(RESERVE_NS)); + let mut descriptors: Vec<_> = sources + .iter() + .map(|(fd, _)| libc::pollfd { + fd: *fd, + events: libc::POLLIN, + revents: 0, + }) + .collect(); + let at = self.admission_clock(clock)?; + if at >= end { + return Ok(()); + } + if self.slots.iter().any(|slot| { + slot.accepted_at.is_none() + && slot.edge.setup_pending() + && slot.edge.setup_buffered_event() + }) { + return Ok(()); + } + // Block only while at least a full millisecond remains. Readable + // protocol traffic wakes immediately; the original last submillisecond + // remains nonblocking, and no absolute end is reset or extended. + let timeout = ((end - at) / 1_000_000).min(1) as i32; + #[cfg(feature = "capture-profile")] + let outcome = { + let _span = crate::capture_profile::Span::wait( + crate::capture_profile::Phase::RepoSetupWait, + timeout as u64 * 1_000_000, + ); + poll(&mut descriptors, timeout) + }; + #[cfg(not(feature = "capture-profile"))] + let outcome = poll(&mut descriptors, timeout); + match outcome { + Err(error) if error.kind() == io::ErrorKind::Interrupted => Ok(()), + Ok(count) + if count >= 0 + && descriptors + .iter() + .all(|fd| fd.revents & libc::POLLNVAL == 0) => + { + Ok(()) + } + _ => { + self.poison("SCOPE_SETUP_WAIT"); + Err(error("SCOPE_SETUP_WAIT")) + } + } + // Readiness/timeout/HUP/EINTR never advance a protocol state. The next + // original progress turn parses frames and checks deadlines/signals. + } + #[cfg(feature = "capture-profile")] + fn repository_wait_phase(&self) -> crate::capture_profile::Phase { + use crate::capture_profile::Phase; + let mut mask = 0u8; + for slot in self.slots.iter().filter(|slot| slot.accepted_at.is_none()) { + mask |= match slot.edge.repository_profile_stage() { + Some(Phase::RepoRunningPoll) => 1, + // Done can retain physical pipe EOF collection. Keep it in the + // cleanup wait category; its poll time has a distinct counter. + Some(Phase::RepoCleaningPoll | Phase::RepoDonePoll) => 2, + Some(Phase::RepoReadyPoll | Phase::RepoParkPoll) => 4, + _ => 8, + }; + } + match mask { + 1 => Phase::RepoRunningWait, + 2 => Phase::RepoCleaningWait, + 0 | 8 => Phase::RepoUnknownWait, + _ => Phase::RepoMixedWait, + } + } + fn progress_wait_clock( + &mut self, + clock: &mut impl FnMut() -> io::Result, + end: u64, + ) -> io::Result { + let at = self.admission_clock(clock)?; + if super::signals::pending() { + self.cancel(Some("SCOPE_INTERRUPTED"), at, self.hard_end); + return Err(error("SCOPE_INTERRUPTED")); + } + self.repository_admission_ready()?; + if at >= self.active_end().saturating_sub(RESERVE_NS) { + self.cancel(Some("SCOPE_OPERATION_DEADLINE"), at, self.active_end()); + return Err(error("SCOPE_OPERATION_DEADLINE")); + } + if at >= end { + // The local end caps waiting only. Preserve every sibling + // cleanup allowance in the original scope cancellation envelope. + self.cancel(Some("SCOPE_PROOF_DEADLINE"), at, self.hard_end); + return Err(error("SCOPE_PROOF_DEADLINE")); + } + Ok(at) + } + fn wait_running_progress( + &mut self, + clock: &mut impl FnMut() -> io::Result, + poll: &mut impl FnMut(&mut [libc::pollfd], i32) -> io::Result, + pause: &mut impl FnMut(), + ) -> io::Result<()> { + self.wait_progress_with_external(clock, poll, pause, None, &mut || { + Some(std::time::Duration::from_millis(1)) + }) + } + fn wait_progress_with_external( + &mut self, + clock: &mut impl FnMut() -> io::Result, + poll: &mut impl FnMut(&mut [libc::pollfd], i32) -> io::Result, + pause: &mut impl FnMut(), + external_read_fd: Option, + remaining_limit: &mut impl FnMut() -> Option, + ) -> io::Result<()> { + let mut end = self.active_end().saturating_sub(RESERVE_NS); + let mut descriptors = Vec::new(); + if descriptors + .try_reserve( + self.slots.len().min(MAX_REGISTRATIONS) * 4 + + usize::from(external_read_fd.is_some()), + ) + .is_err() + { + self.poison("SCOPE_LIMIT"); + return Err(error("SCOPE_LIMIT")); + } + if let Some(fd) = external_read_fd { + descriptors.push(libc::pollfd { + fd, + events: libc::POLLIN, + revents: 0, + }); + } + let mut buffered = false; + for slot in self.slots.iter().filter(|slot| slot.accepted_at.is_none()) { + end = end + .min(slot.hard_end) + .min(slot.completion_end.unwrap_or(u64::MAX)); + if let Some(edge_end) = slot.edge.progress_wait_sources(&mut descriptors) { + end = end.min(edge_end); + } + buffered |= slot.edge.progress_buffered_event(); + } + if descriptors.iter().any(|fd| fd.fd < 0) { + self.poison("SCOPE_POLL"); + return Err(error("SCOPE_POLL")); + } + let at = self.progress_wait_clock(clock, end)?; + if buffered { + return Ok(()); + } + // This external bound limits waiting only. Expiry schedules the + // original next turn, NEVER shortens the owner's cleanup allowance. + let Some(limit) = remaining_limit() else { + return Ok(()); + }; + if limit.is_zero() { + return Ok(()); + } + let timeout = ((end - at) / 1_000_000) + .min(1) + .min(limit.as_millis().min(1) as u64) as i32; + #[cfg(feature = "capture-profile")] + let phase = self.repository_wait_phase(); + if descriptors.is_empty() { + // EOF/HUP already consumed: sockets cannot wake a Child::try_wait. + // Retain the old short polling cadence rather than spin on HUP. + if timeout == 0 { + return Ok(()); + } + #[cfg(feature = "capture-profile")] + let _span = crate::capture_profile::Span::wait(phase, 1_000_000); + pause(); + } else { + #[cfg(feature = "capture-profile")] + let outcome = { + let _span = crate::capture_profile::Span::wait(phase, timeout as u64 * 1_000_000); + poll(&mut descriptors, timeout) + }; + #[cfg(not(feature = "capture-profile"))] + let outcome = poll(&mut descriptors, timeout); + match outcome { + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Ok(count) + if count >= 0 + && descriptors + .iter() + .all(|fd| fd.revents & libc::POLLNVAL == 0) => {} + _ => { + self.poison("SCOPE_POLL"); + return Err(error("SCOPE_POLL")); + } + } + } + self.progress_wait_clock(clock, end)?; + // Readiness/timeout/HUP/EINTR only schedule the original next fair + // turn (including upstream CANCEL pumping); NONE is resource proof. + Ok(()) + } + fn wait_command_progress( + &mut self, + clock: &mut impl FnMut() -> io::Result, + poll: &mut impl FnMut(&mut [libc::pollfd], i32) -> io::Result, + pause: &mut impl FnMut(), + ) -> io::Result<()> { + // The final admitted edge still owns its original short READY/PARK + // window. Do not return to a blind timer while its socket can wake us. + if self.repository_admission_ready()? { + self.wait_running_progress(clock, poll, pause) + } else { + self.wait_repository_setup(clock, poll) + } + } + // Validate the entire fixed cohort BEFORE consuming any result. An earlier + // accepted sibling cannot leak output while another is pending or invalid. + fn take_repository_results( + &mut self, + slots: &[SlotId; 2], + ) -> io::Result> { + let fault = self.owner.borrow().first_fault; + if let Some(reason) = fault { + return Err(error(reason.0)); + } + let mut pending = false; + for (position, id) in slots.iter().enumerate() { + let index = self.index(id)?; + if slots[..position].iter().any(|other| other.index == index) { + self.poison("SCOPE_RESULT"); + return Err(error("SCOPE_RESULT")); + } + let slot = &self.slots[index]; + if slot.output_taken { + self.poison("SCOPE_RESULT"); + return Err(error("SCOPE_RESULT")); + } + if slot.accepted_at.is_none() { + pending = true; + } else { + let facts = slot.edge.facts(); + if !facts.resources_complete() + || !facts.group_absent + || !facts.terminal_eof + || facts.status.is_none() + || facts.first_fault.is_some() + || facts.io.first_fault.is_some() + { + self.poison("SCOPE_RESULT"); + return Err(error("SCOPE_RESULT")); + } + } + } + if pending { + return Ok(None); + } + Ok(Some([ + self.take_result(&slots[0])?, + self.take_result(&slots[1])?, + ])) + } + fn take_result(&mut self, id: &SlotId) -> io::Result { + let index = self.index(id)?; + let fault = self.owner.borrow().first_fault; + if let Some(reason) = fault { + return Err(error(reason.0)); + } + let slot = &self.slots[index]; + let status = slot.edge.facts().status; + if slot.accepted_at.is_none() || slot.output_taken || status.is_none() { + self.poison("SCOPE_RESULT"); + return Err(error("SCOPE_RESULT")); + } + let slot = &mut self.slots[index]; + slot.output_taken = true; + Ok(CommandResult { + status: status.unwrap(), + output: slot.edge.take_output(), + }) + } +} + +fn upstream_park_probe_allowed(work: Option<&super::protocol::PollWork>) -> bool { + work.is_none_or(|work| { + work.reads < super::protocol::MAX_READS && work.parsed < super::protocol::MAX_PARSE + }) +} + +fn wait_with_upstream_budget( + work: Option<&super::protocol::PollWork>, + wait: impl FnOnce() -> io::Result<()>, +) -> io::Result<()> { + if !upstream_park_probe_allowed(work) { + return Ok(()); + } + wait() +} + +fn poll_joined_after_drain( + core: &mut Core, + start: usize, + clock: &mut impl FnMut() -> io::Result, + drain: &mut impl FnMut(&mut Core) -> bool, +) -> bool { + if !drain(core) { + return false; + } + core.poll_post_joined(start, clock) +} + +fn await_repository_admission( + core: &mut Core, + progress: &mut impl FnMut(&mut Core), + pause: &mut impl FnMut(&mut Core) -> io::Result<()>, +) -> io::Result<()> { + loop { + progress(core); + if core.repository_admission_ready()? { + return Ok(()); + } + pause(core)?; + } +} + +// Queue only inside the original containing end. Actual keeper preparation +// still begins at GroupLease::spawn's unchanged timestamp and setup policy. +#[cfg(test)] +fn await_hook_setup_capacity( + core: &mut Core, + progress: &mut impl FnMut(&mut Core), + clock: &mut impl FnMut() -> io::Result, + attempt: &mut impl FnMut() -> io::Result, + pause: &mut impl FnMut(), +) -> io::Result<()> { + await_hook_setup_capacity_until(core, progress, clock, attempt, pause, None) +} + +fn await_hook_setup_capacity_until( + core: &mut Core, + progress: &mut impl FnMut(&mut Core), + clock: &mut impl FnMut() -> io::Result, + attempt: &mut impl FnMut() -> io::Result, + pause: &mut impl FnMut(), + admission_ceiling: Option, +) -> io::Result<()> { + loop { + progress(core); + let at = core.admission_clock(clock)?; + let ready = core.repository_admission_ready()?; + let admission_end = core.active_end().min(admission_ceiling.unwrap_or(u64::MAX)); + if at >= admission_end.saturating_sub(RESERVE_NS) { + core.cancel(Some("SCOPE_SETUP_DEADLINE"), at, core.active_end()); + return Err(error("SCOPE_SETUP_DEADLINE")); + } + if ready + && attempt().map_err(|_| { + core.poison("SCOPE_SETUP_GATE"); + error("SCOPE_SETUP_GATE") + })? + { + // Parent cancellation, clock failure or shortening during flock + // cannot grant a stale admission after the descriptor was acquired. + progress(core); + let fresh = core.admission_clock(clock)?; + let ready = core.repository_admission_ready()?; + let admission_end = core.active_end().min(admission_ceiling.unwrap_or(u64::MAX)); + if !ready || fresh >= admission_end.saturating_sub(RESERVE_NS) { + core.cancel(Some("SCOPE_SETUP_DEADLINE"), fresh, core.active_end()); + return Err(error("SCOPE_SETUP_DEADLINE")); + } + return Ok(()); + } + pause(); + } +} + +#[derive(Clone, Debug)] +pub struct SlotReport { + pub slot: usize, + pub status: Option, + pub waits_known: bool, + pub group_absent: bool, + pub terminal_eof: bool, + pub io_required: bool, + pub io: IoFacts, + pub accepted_at: Option, + pub completion_end: Option, + pub first_fault: Option<&'static str>, + #[cfg(feature = "dev-tools")] + pub setup_trace: Option, +} +#[derive(Clone, Debug)] +pub struct ScopeReport { + pub first_fault: Option, + pub admission_closed: bool, + pub finish_called: bool, + pub all_resources: bool, + pub clean: bool, + pub slots: Vec, +} +pub struct CommandResult { + pub status: ExitStatus, + pub output: CommandOutput, +} +pub struct Scope { + core: Core, + upstream: Option, + ledger: BTreeMap, + terminal_sent: bool, + hook_setup_directory: Option, + _signals: Option, +} + +impl Scope { + /// Called on the entry thread after image bootstrap and before CLI parsing + /// or runtime construction. Absence and malformed metadata are distinct. + pub fn entry_from_environment(local_ns: u64) -> io::Result> { + if !super::attachment::present() { + return Ok(None); + } + let at = now()?; + let end = at + .checked_add(local_ns) + .ok_or_else(|| error("SCOPE_CLOCK"))?; + Self::attach_at(at, end) + } + pub(crate) fn attach_at(at: u64, end: u64) -> io::Result> { + let Some((attachment, stream)) = super::attachment::consume(at, end)? else { + return Ok(None); + }; + let signals = super::signals::install()?; + let owner: SharedOwner = Default::default(); + let mut endpoint = Endpoint::with_owner( + stream, + attachment.nonce, + Some(attachment.parent), + owner.clone(), + ) + .map_err(|e| error(e.0))?; + endpoint.send_live().map_err(|e| error(e.0))?; + Ok(Some(Self { + core: Core::new(owner, attachment.end), + upstream: Some(endpoint), + ledger: BTreeMap::new(), + terminal_sent: false, + hook_setup_directory: None, + _signals: Some(signals), + })) + } + pub(crate) fn refine_entry(&mut self, end: u64) -> io::Result<()> { + self.poll(); + let at = self.core.admission_clock(&mut now)?; + self.core.refine_entry(end, at)?; + self.poll(); + if self.failed() { + Err(error("SCOPE_ENTRY_SELECTION")) + } else { + Ok(()) + } + } + pub fn local_entry(hard_end: u64) -> io::Result { + let signals = super::signals::install()?; + let mut scope = Self::with_owner(Default::default(), hard_end); + scope._signals = Some(signals); + Ok(scope) + } + pub fn hard_end(&self) -> u64 { + self.core.hard_end + } + pub fn slot_status(&self, id: &SlotId) -> Option { + if !Rc::ptr_eq(&id.scope, &self.core.identity) { + return None; + } + self.core + .slots + .get(id.index) + .and_then(|slot| slot.edge.facts().status) + } + pub fn slot_complete(&self, id: &SlotId) -> bool { + Rc::ptr_eq(&id.scope, &self.core.identity) + && self + .core + .slots + .get(id.index) + .is_some_and(|slot| slot.accepted_at.is_some()) + && self.core.owner.borrow().first_fault.is_none() + } + pub fn failed(&self) -> bool { + self.core.owner.borrow().first_fault.is_some() + } + pub(crate) fn tighten_end(&mut self, end: u64) { + self.core.hard_end = self.core.hard_end.min(end); + } + pub(crate) fn owner_state(&self) -> SharedOwner { + self.core.owner.clone() + } + pub(crate) fn set_hook_setup_directory(&mut self, directory: File) -> io::Result<()> { + if self.hook_setup_directory.is_some() || !self.core.slots.is_empty() || self.core.finished + { + return Err(error("SCOPE_SETUP_GATE")); + } + self.core + .owner + .borrow() + .check_admission() + .map_err(|e| error(e.0))?; + self.hook_setup_directory = Some(directory); + Ok(()) + } + fn await_hook_setup_admission(&mut self) -> io::Result> { + let Some(directory) = self.hook_setup_directory.as_ref() else { + return Ok(None); + }; + // Duplicating the directory descriptor does not duplicate a lock. + let directory = directory + .try_clone() + .map_err(|_| error("SCOPE_SETUP_GATE"))?; + self.await_hook_capacity(directory, HookCapacityKind::Leaf, None) + .map(Some) + } + #[allow(dead_code)] // Called by the standalone guard, not ordinary product scopes. + pub(crate) fn await_hook_core_admission( + &mut self, + directory: &File, + leaf_end: u64, + ) -> io::Result { + if !self.core.slots.is_empty() || self.core.finished || self.hook_setup_directory.is_some() + { + return Err(error("SCOPE_SETUP_GATE")); + } + let directory = directory + .try_clone() + .map_err(|_| error("SCOPE_SETUP_GATE"))?; + self.await_hook_capacity(directory, HookCapacityKind::Core, Some(leaf_end)) + .map(|permit| HookCoreAdmission { _permit: permit }) + } + fn await_hook_capacity( + &mut self, + directory: File, + kind: HookCapacityKind, + admission_ceiling: Option, + ) -> io::Result { + let mut candidates = (0..HOOK_SETUP_SLOTS) + .map(|slot| HookSetupAdmission::open_kind(&directory, slot, kind).map(Some)) + .collect::>>()?; + let mut selected = None; + let upstream = &mut self.upstream; + let ledger = &mut self.ledger; + await_hook_setup_capacity_until( + &mut self.core, + &mut |core| Self::poll_turn(core, upstream, ledger), + &mut now, + &mut || { + for candidate in &mut candidates { + if candidate.as_mut().unwrap().try_lock(&directory)? { + selected = candidate.take(); + return Ok(true); + } + } + Ok(false) + }, + &mut || std::thread::sleep(std::time::Duration::from_millis(1)), + admission_ceiling, + )?; + selected.ok_or_else(|| error("SCOPE_SETUP_GATE")) + } + pub(crate) fn first_fault(&self) -> Option { + self.core.owner.borrow().first_fault + } + #[cfg(feature = "dev-tools")] + pub(crate) fn first_fault_setup_trace(&self) -> Option { + self.core.first_fault_setup_trace() + } + pub(crate) fn begin_installer_preflight(&mut self, expected: usize) -> io::Result<()> { + self.poll(); + let at = self.core.admission_clock(&mut now)?; + self.core.begin_installer(at, expected) + } + fn ledgers_complete(&self) -> bool { + self.ledger.values().all(|waited| *waited) + && self + .upstream + .as_ref() + .is_none_or(Endpoint::sent_resources_complete) + } + pub(crate) fn seal_installer_preflight(&mut self) -> io::Result<()> { + self.poll(); + if self.terminal_sent { + self.begin_cancel(ProtocolError("SCOPE_PREFLIGHT"), 0); + } + // A selected cohort has at most two slots; one fair turn visits all. + let complete = self.ledgers_complete(); + self.core.seal_installer(complete, &mut now) + } + pub(crate) fn check_installer_publication(&mut self) -> io::Result<()> { + self.poll(); + if self.terminal_sent { + self.begin_cancel(ProtocolError("SCOPE_PUBLICATION"), 0); + } + let complete = self.ledgers_complete(); + self.core.publication_live(complete, &mut now) + } + pub fn with_owner(owner: SharedOwner, hard_end: u64) -> Self { + Self { + core: Core::new(owner, hard_end), + upstream: None, + ledger: BTreeMap::new(), + terminal_sent: false, + hook_setup_directory: None, + _signals: None, + } + } + fn pump( + core: &mut Core, + upstream: &mut Option, + ledger: &mut BTreeMap, + turn_start: usize, + ) { + if super::signals::pending() { + match now() { + Ok(at) => core.cancel(Some("SCOPE_INTERRUPTED"), at, core.hard_end), + Err(_) => core.cancel(Some("SCOPE_CLOCK"), 0, 0), + } + } + if let Some(endpoint) = upstream { + match endpoint.receive(true) { + Ok(false) => {} + result => { + let reason = result + .err() + .map(|e| e.0) + .unwrap_or("SCOPE_PARENT_CANCELLED"); + let end = endpoint.cancel_deadline_ns().unwrap_or(core.hard_end); + match now() { + Ok(at) => core.cancel(Some(reason), at, end), + Err(_) => core.cancel(Some("SCOPE_CLOCK"), 0, 0), + } + } + } + } + let len = core.slots.len(); + for offset in 0..len.min(SLOTS_PER_TURN) { + let slot = &mut core.slots[(turn_start + offset) % len]; + for event in slot.edge.take_events() { + let result = if let Some(endpoint) = upstream { + endpoint.metadata(&event) + } else { + Endpoint::record_metadata(ledger, std::process::id(), &event).and_then( + |registered| { + if registered { + core.owner.borrow_mut().charge("registrations", 1)?; + } + Ok(()) + }, + ) + }; + if let Err(e) = result { + core.owner.borrow_mut().poison(e); + } + } + } + } + /// Retain an ORIGINAL cooperative Command without setpgid or cached-PID + /// signals. Its own entry owner must settle descendants and close the wire. + /// Caller-specified stdin/stdout/stderr and pre_exec are preserved. + pub fn start_cooperative(&mut self, mut command: Command) -> io::Result { + self.start_cooperative_inner(&mut command, None, None) + } + /// Guardian-only admission ceiling. This cannot lengthen the containing + /// owner or shorten its retained-child cleanup budget. + #[allow(dead_code)] // The standalone guardian links its own copy of Scope. + pub(crate) fn start_hook_core( + &mut self, + mut command: Command, + leaf_end: u64, + ) -> io::Result { + self.start_cooperative_inner(&mut command, None, Some(leaf_end)) + } + pub fn start_cooperative_with_io( + &mut self, + mut command: Command, + plan: IoPlan, + ) -> io::Result { + command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + self.start_cooperative_inner(&mut command, Some(plan), None) + } + fn start_cooperative_inner( + &mut self, + command: &mut Command, + plan: Option, + admission_ceiling: Option, + ) -> io::Result { + self.poll(); + let at = self.core.admission_clock(&mut now)?; + let mut random = [0u8; 16]; + if unsafe { libc::getentropy(random.as_mut_ptr().cast(), random.len()) } != 0 { + return Err(error("SCOPE_RANDOM")); + } + let nonce: String = random.iter().map(|b| format!("{b:02x}")).collect(); + let (parent, child_end) = UnixStream::pair()?; + let fd = unsafe { libc::fcntl(child_end.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 5) }; + if !(5..=1024).contains(&fd) { + if fd >= 0 { + unsafe { + libc::close(fd); + } + } + return Err(error("SCOPE_FD")); + } + let inherited = unsafe { OwnedFd::from_raw_fd(fd) }; + for key in super::attachment::KEYS + .into_iter() + .chain(["KEITO_SOURCE_OWNER_FD", "KEITO_SOURCE_OWNER_NONCE"]) + { + command.env_remove(key); + } + command + .env("KEITO_PROCESS_OWNER_FD", "4") + .env("KEITO_PROCESS_OWNER_NONCE", &nonce) + .env("KEITO_PROCESS_OWNER_PID", std::process::id().to_string()) + .env("KEITO_PROCESS_OWNER_END_NS", self.core.hard_end.to_string()) + .env("KEITO_PROCESS_OWNER_CONTRACT", "2"); + unsafe { + command.pre_exec(move || { + if libc::dup2(fd, 4) < 0 || libc::fcntl(4, libc::F_SETFD, 0) < 0 { + return Err(io::Error::last_os_error()); + } + if fd != 4 { + libc::close(fd); + } + Ok(()) + }); + } + let mask = super::signals::AdmissionMask::block(command)?; + let hard_end = self.core.hard_end; + let capacity = plan.as_ref().map(IoPlan::capacity).unwrap_or(0); + let mut clock_failed = false; + let result = self.core.admit(at, capacity, |owner| { + let endpoint = Endpoint::with_owner(parent, nonce.clone(), None, owner.clone()) + .map_err(|e| error(e.0))?; + let pipes = plan.map(IoPlan::prepare).transpose()?; + let fresh = match now() { + Ok(at) => at, + Err(_) => { + clock_failed = true; + owner.borrow_mut().poison(ProtocolError("SCOPE_CLOCK")); + return Err(error("SCOPE_CLOCK")); + } + }; + let child = + spawn_cooperative_before(hard_end, admission_ceiling, fresh, || command.spawn())?; + // The edge owns the actual handle before identity publication. + let mut edge = CooperativeEdge { + child, + endpoint, + nonce, + status: None, + cancel_sent: None, + registered: false, + waited: false, + first_fault: None, + pipes, + }; + if let Some(pipes) = &mut edge.pipes { + if pipes + .attach( + edge.child.stdin.take(), + edge.child.stdout.take(), + edge.child.stderr.take(), + ) + .is_err() + { + edge.first_fault = Some("SCOPE_IO_ATTACH"); + } + } + if let Err(e) = edge.endpoint.set_expected_child(edge.child.id()) { + edge.first_fault = Some(e.0); + } + Ok(ProductEdge::Cooperative(edge)) + }); + drop(mask); + drop(inherited); + drop(child_end); + if clock_failed { + self.core.cancel(Some("SCOPE_CLOCK"), 0, 0); + return result; + } + self.poll(); + if result.is_err() { + self.begin_cancel(ProtocolError("SCOPE_COOPERATIVE_SPAWN"), self.core.hard_end); + } + result + } + /// QA-owned700 image constructor only. Product callers use the separate + /// compiled-pair verified-image entry and cannot supply this QA authority. + pub fn start_owned_opaque( + &mut self, + command: Command, + plan: IoPlan, + root: &Path, + image: &Path, + ) -> io::Result { + self.start_with_lease(command, plan, false, |owner, end| { + GroupLease::spawn_keeper_with_policy(owner, root, image, end, CleanupPolicy::HookShort) + }) + } + pub(crate) fn start_verified_opaque( + &mut self, + command: Command, + plan: IoPlan, + image: &super::image::VerifiedKeeperImage, + ) -> io::Result { + self.start_verified_opaque_with_policy(command, plan, image, CleanupPolicy::HookShort) + } + pub(crate) fn start_verified_opaque_with_policy( + &mut self, + command: Command, + plan: IoPlan, + image: &super::image::VerifiedKeeperImage, + policy: CleanupPolicy, + ) -> io::Result { + self.start_with_lease(command, plan, false, |owner, end| { + if policy == CleanupPolicy::HookShort { + GroupLease::spawn_verified_keeper(owner, image, end) + } else { + GroupLease::spawn_verified_keeper_with_policy(owner, image, end, policy) + } + }) + } + /// Closed developer offline-client caller only; not a product policy. + #[cfg(feature = "dev-tools")] + pub(crate) fn start_dev_client_opaque_until( + &mut self, + mut command: Command, + plan: IoPlan, + image: &super::image::VerifiedKeeperImage, + selected_end: u64, + ) -> io::Result { + clear_parent_environment(&mut command); + let at = match now() { + Ok(at) => at, + Err(_) => { + self.core.cancel(Some("SCOPE_CLOCK"), 0, 0); + return Err(error("SCOPE_CLOCK")); + } + }; + let capacity = plan.capacity(); + command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let result = self + .core + .admit_dev_client(at, capacity, selected_end, |owner, end| { + let pipes = plan.prepare().map_err(|_| error("SCOPE_IO_PREPARE"))?; + let lease = GroupLease::spawn_verified_keeper_with_policy( + owner, + image, + end, + dev_client_keeper_policy(), + )?; + Ok(ProductEdge::Group(GroupEdge { + lease, + command: Some(command), + pipes, + stage: Stage::Ready, + proof: false, + first_fault: None, + published: [false; 4], + setup_admission: None, + post_join_pending: false, + })) + }); + if result.is_err() { + self.begin_cancel(ProtocolError("DEV_CLIENT_ADMISSION"), selected_end); + } + result + } + #[cfg(feature = "dev-tools")] + pub(crate) fn take_dev_client_result(&mut self, id: &SlotId) -> io::Result { + let result = self.take_result(id)?; + let complete = self.ledgers_complete(); + if self.core.release_dev_completed(complete).is_err() { + self.begin_cancel(ProtocolError("DEV_CLIENT_COLLECTION"), self.core.hard_end); + return Err(error("DEV_CLIENT_COLLECTION")); + } + Ok(result) + } + fn start_with_lease( + &mut self, + mut command: Command, + plan: IoPlan, + installer: bool, + create: impl FnOnce(SharedOwner, u64) -> io::Result, + ) -> io::Result { + clear_parent_environment(&mut command); + let setup_admission = match self.await_hook_setup_admission() { + Ok(admission) => admission, + Err(error) => { + self.begin_cancel(ProtocolError("SCOPE_SETUP_GATE"), self.core.hard_end); + return Err(error); + } + }; + let at = match now() { + Ok(at) => at, + Err(_) => { + self.core.cancel(Some("SCOPE_CLOCK"), 0, 0); + return Err(error("SCOPE_CLOCK")); + } + }; + let capacity = plan.capacity(); + command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let hook_setup = setup_admission.is_some(); + let hard_end = if installer || hook_setup { + self.core.active_end() + } else { + self.core.hard_end + }; + let create_edge = |owner: SharedOwner, end| { + // Scope capacity/slot admission precedes buffer allocation, and + // all buffers exist before spawning the first owned handle. + let pipes = match plan.prepare() { + Ok(pipes) => pipes, + Err(_) => { + owner.borrow_mut().poison(ProtocolError("SCOPE_IO_PREPARE")); + return Err(error("SCOPE_IO_PREPARE")); + } + }; + let lease = create(owner, end)?; + Ok(ProductEdge::Group(GroupEdge { + lease, + command: Some(command), + pipes, + stage: Stage::Ready, + proof: false, + first_fault: None, + published: [false; 4], + setup_admission, + post_join_pending: false, + })) + }; + let result = if installer { + self.core.admit_installer(at, capacity, create_edge) + } else if hook_setup { + self.core.admit_before(at, capacity, hard_end, create_edge) + } else { + self.core + .admit(at, capacity, |owner| create_edge(owner, hard_end)) + }; + if result.is_err() { + if self.core.owner.borrow().first_fault.is_none() { + self.core.poison("SCOPE_ADMISSION"); + } + match now() { + Ok(at) => self.core.cancel(None, at, hard_end), + Err(_) => self.core.cancel(Some("SCOPE_CLOCK"), 0, 0), + } + } + result + } + pub(crate) fn run_verified( + &mut self, + command: Command, + plan: IoPlan, + image: &super::image::VerifiedKeeperImage, + ) -> io::Result { + self.run_verified_with_policy(command, plan, image, CleanupPolicy::HookShort) + } + pub(crate) fn run_verified_with_policy( + &mut self, + command: Command, + plan: IoPlan, + image: &super::image::VerifiedKeeperImage, + policy: CleanupPolicy, + ) -> io::Result { + let started = if policy == CleanupPolicy::HookShort { + self.start_verified_opaque(command, plan, image) + } else { + self.start_verified_opaque_with_policy(command, plan, image, policy) + }; + self.run_started(started) + } + pub(crate) fn run_installer_verified( + &mut self, + command: Command, + plan: IoPlan, + image: &super::image::VerifiedKeeperImage, + ) -> io::Result { + let started = self.start_with_lease(command, plan, true, |owner, end| { + GroupLease::spawn_verified_keeper_with_policy( + owner, + image, + end, + CleanupPolicy::CommandProbe, + ) + }); + self.run_started(started) + } + /// Fixed read-only repository cohort, used only by the HookShort owner. + /// Three Git facts use two commands; no shell or worker thread. + pub(crate) fn run_verified_repository( + &mut self, + commands: [Command; 2], + image: &super::image::VerifiedKeeperImage, + ) -> io::Result<[CommandResult; 2]> { + let result = (|| { + // All IO plans exist before the first child. Actual allocation and + // capacity reservation still precede each registered edge's spawn. + let plans = [ + IoPlan::new(Vec::new(), 16384, 8192)?, + IoPlan::new(Vec::new(), 1024 * 1024, 8192)?, + ]; + let mut slots = [None, None]; + for ((command, plan), slot) in commands.into_iter().zip(plans).zip(&mut slots) { + // The private fixed cohort has at most two edges here. + // A blocking sibling spawn must not consume an earlier + // keeper's already-running short setup window. + let upstream = &mut self.upstream; + let ledger = &mut self.ledger; + await_repository_admission( + &mut self.core, + &mut |core| Self::poll_turn(core, upstream, ledger), + &mut |core| { + core.wait_repository_setup(&mut now, &mut |fds, timeout| { + let result = unsafe { + libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, timeout) + }; + if result < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(result) + } + }) + }, + )?; + *slot = Some(self.start_verified_opaque(command, plan, image)?); + self.poll(); + if let Some(reason) = self.core.owner.borrow().first_fault { + return Err(error(reason.0)); + } + } + let slots = slots.map(|slot| slot.expect("two admitted repository slots")); + loop { + self.poll(); + if let Some(results) = self.core.take_repository_results(&slots)? { + return Ok(results); + } + self.wait_command_progress()?; + } + })(); + if result.is_err() { + // Includes partial admission and result validation faults. All + // returned handles remain retained in this same cancelled Scope. + self.finish(); + } + result + } + fn run_started(&mut self, started: io::Result) -> io::Result { + let slot = match started { + Ok(slot) => slot, + Err(error) => { + self.finish(); + return Err(error); + } + }; + loop { + self.poll(); + let fault = self.core.owner.borrow().first_fault; + if let Some(reason) = fault { + self.finish(); + return Err(error(reason.0)); + } + if self.core.slots[slot.index].accepted_at.is_some() { + return self.take_result(&slot); + } + if let Err(error) = self.wait_command_progress() { + self.finish(); + return Err(error); + } + } + } + fn wait_command_progress(&mut self) -> io::Result<()> { + // Exhausted upstream read/parse budgets require the next ORIGINAL + // pump/turn before any additional wait, with no cursor reset. + let work = self.upstream.as_ref().map(|endpoint| &endpoint.last_poll); + wait_with_upstream_budget(work, || { + self.core.wait_command_progress( + &mut now, + &mut |fds, timeout| { + let result = + unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, timeout) }; + if result < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(result) + } + }, + &mut || std::thread::sleep(std::time::Duration::from_millis(1)), + ) + }) + } + /// Guardian-only scheduling hint. No ACK, wait, EOF or resource fact is + /// accepted here. The caller retains the ACK File throughout this call. + #[allow(dead_code)] // Standalone guard includes this same Scope source. + pub(crate) fn wait_hook_core_progress( + &mut self, + child: &SlotId, + ack_read_fd: Option, + guard_remaining: &mut impl FnMut() -> Option, + ) -> io::Result<()> { + let index = self.core.index(child)?; + if !matches!(&self.core.slots[index].edge, ProductEdge::Cooperative(_)) { + self.core.poison("SCOPE_SLOT_ID"); + return Err(error("SCOPE_SLOT_ID")); + } + let work = self.upstream.as_ref().map(|endpoint| &endpoint.last_poll); + wait_with_upstream_budget(work, || { + self.core.wait_progress_with_external( + &mut now, + &mut |fds, timeout| { + let result = + unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, timeout) }; + if result < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(result) + } + }, + &mut || std::thread::sleep(std::time::Duration::from_millis(1)), + ack_read_fd, + guard_remaining, + ) + }) + } + /// A bounded hot-path turn. Full retained reports are explicit snapshots, + /// never an allocation/whole-registry scan on every command I/O poll. + pub fn poll(&mut self) { + Self::poll_turn(&mut self.core, &mut self.upstream, &mut self.ledger); + } + fn poll_turn( + core: &mut Core, + upstream: &mut Option, + ledger: &mut BTreeMap, + ) { + let start = core.cursor; + Self::pump(core, upstream, ledger, start); + core.poll(&mut now); + if poll_joined_after_drain(core, start, &mut now, &mut |core| { + Self::pump(core, upstream, ledger, start); + upstream_park_probe_allowed(upstream.as_ref().map(|endpoint| &endpoint.last_poll)) + }) { + Self::pump(core, upstream, ledger, start); + } + } + pub fn request_complete(&mut self, id: &SlotId) -> io::Result<()> { + let result = match now() { + Ok(at) => self.core.request_complete(id, at), + Err(_) => { + self.core.cancel(Some("SCOPE_CLOCK"), 0, 0); + return Err(error("SCOPE_CLOCK")); + } + }; + if result.is_err() { + match now() { + Ok(at) => self.core.cancel(None, at, self.core.hard_end), + Err(_) => self.core.cancel(Some("SCOPE_CLOCK"), 0, 0), + } + } + result + } + pub fn take_result(&mut self, id: &SlotId) -> io::Result { + let result = self.core.take_result(id); + if result.is_err() { + match now() { + Ok(at) => self.core.cancel(None, at, self.core.hard_end), + Err(_) => self.core.cancel(Some("SCOPE_CLOCK"), 0, 0), + } + } + result + } + pub fn begin_cancel(&mut self, reason: ProtocolError, requested_end: u64) { + match now() { + Ok(at) => self.core.cancel(Some(reason.0), at, requested_end), + Err(_) => self.core.cancel(Some("SCOPE_CLOCK"), 0, 0), + } + } + pub fn finish(&mut self) -> ScopeReport { + let upstream = &mut self.upstream; + let ledger = &mut self.ledger; + let mut before = true; + let mut turn_start = self.core.cursor; + self.core.finish_with_progress( + &mut now, + &mut || { + std::thread::sleep(std::time::Duration::from_millis(1)); + }, + &mut |core| { + if before { + turn_start = core.cursor; + } + Self::pump(core, upstream, ledger, turn_start); + before = !before; + }, + ); + if self.ledger.values().any(|waited| !*waited) { + self.core.poison("SCOPE_ACTIVE_REGISTRATION"); + } + self.report() + } + /// Separate from finish so the existing durable ACK is written only after + /// resources settle, and BEFORE the ownership terminal/physical EOF. + pub fn publish_terminal(&mut self, operation_clean: bool) -> bool { + self.publish_terminal_with_clock(operation_clean, &mut now) + } + fn publish_terminal_with_clock( + &mut self, + operation_clean: bool, + clock: &mut impl FnMut() -> io::Result, + ) -> bool { + if self.terminal_sent { + return false; + } + let start = self.core.cursor; + Self::pump(&mut self.core, &mut self.upstream, &mut self.ledger, start); + self.terminal_sent = true; + let timed_installer = self.core.installer.is_some(); + let gate = !timed_installer || (self.ledgers_complete() && self.core.terminal_fresh(clock)); + let clean = gate && self.report().clean && operation_clean; + if !clean { + self.core.poison("SCOPE_OPERATION_FAILED"); + } + if let Some(endpoint) = &mut self.upstream { + if let Err(e) = endpoint.send_terminal(clean) { + self.core.owner.borrow_mut().poison(e); + return false; + } + } + clean && (!timed_installer || self.core.terminal_fresh(clock)) + } + pub fn report(&self) -> ScopeReport { + let first_fault = self.core.owner.borrow().first_fault; + let all_resources = self.core.all_resources(); + ScopeReport { + first_fault, + admission_closed: self.core.owner.borrow().admission_closed, + finish_called: self.core.finish_called, + all_resources, + clean: self.core.finished + && self.core.finish_called + && all_resources + && first_fault.is_none(), + slots: self + .core + .slots + .iter() + .enumerate() + .map(|(slot, s)| { + let facts = s.edge.facts(); + SlotReport { + slot, + status: facts.status, + waits_known: facts.waits_known, + group_absent: facts.group_absent, + terminal_eof: facts.terminal_eof, + io_required: facts.io_required, + io: facts.io, + accepted_at: s.accepted_at, + completion_end: s.completion_end, + first_fault: facts.first_fault, + #[cfg(feature = "dev-tools")] + setup_trace: s.edge.setup_trace(), + } + }) + .collect(), + } + } +} +impl Drop for Scope { + fn drop(&mut self) { + if !self.core.finished { + self.begin_cancel(ProtocolError("SCOPE_DROPPED"), self.core.hard_end); + self.finish(); + } + if self.upstream.is_some() && !self.terminal_sent { + self.publish_terminal(false); + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn cooperative_late_preparation_cannot_lose_a_tighter_hook_admission_ceiling() { + use std::cell::Cell; + let spawned = Cell::new(false); + // Preparation began within the leaf window but returned after its + // admission ceiling, still before the longer guard's admission end. + let result = spawn_cooperative_before(600_000_000, Some(500_000_000), 450_000_000, || { + spawned.set(true); + Ok(()) + }); + assert!(result.is_err()); + assert!(!spawned.get(), "late prepared command was spawned"); + for (hard, selected, fresh, allowed) in [ + (600_000_000, Some(500_000_000), 449_999_999, true), + (600_000_000, Some(500_000_000), 525_000_000, false), + (400_000_000, Some(500_000_000), 350_000_000, false), + (400_000_000, Some(u64::MAX), 350_000_000, false), + (600_000_000, None, 549_999_999, true), + (600_000_000, None, 550_000_000, false), + (600_000_000, Some(0), 0, false), + ] { + spawned.set(false); + let result = spawn_cooperative_before(hard, selected, fresh, || { + spawned.set(true); + Ok(()) + }); + assert_eq!(result.is_ok(), allowed); + assert_eq!(spawned.get(), allowed); + } + } + #[cfg(feature = "dev-tools")] + #[test] + fn offline_client_completed_leaf_cache_releases_only_after_proven_collection() { + let mut core = Core::new(std::rc::Rc::default(), 4_000_000_000); + let slot = core + .admit_dev_client(100, 0, 1_000_000_100, |_, _| { + Ok(fake("collected", std::rc::Rc::default())) + }) + .unwrap(); + core.request_complete(&slot, 200).unwrap(); + core.poll(&mut || Ok(201)); + core.take_result(&slot).unwrap(); + core.release_dev_completed(true).unwrap(); + assert_eq!(core.hard_end, 4_000_000_000); + assert_eq!(core.slots[0].hard_end, 1_000_000_100); + assert_eq!(core.active_end(), 4_000_000_000); + assert!(core + .admit_dev_client(1_500_000_000, 0, 2_500_000_000, |_, _| Ok(fake( + "next", + std::rc::Rc::default() + ))) + .is_ok()); + } + #[cfg(feature = "dev-tools")] + #[test] + fn offline_client_incomplete_or_unforwarded_collection_cannot_release_cache() { + let mut core = Core::new(std::rc::Rc::default(), 4_000_000_000); + core.admit_dev_client(100, 0, 1_000_000_100, |_, _| { + Ok(fake("unproved", std::rc::Rc::default())) + }) + .unwrap(); + assert!(core.release_dev_completed(false).is_err()); + assert_eq!(core.active_end(), 1_000_000_100); + } + #[cfg(feature = "dev-tools")] + #[test] + fn offline_client_slot_and_keeper_share_the_earlier_leaf_end() { + let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let captured = std::cell::Cell::new(0); + let mut core = Core::new(std::rc::Rc::default(), 4_000_000_000); + core.admit_dev_client(100, 8, 1_000_000_100, |_, end| { + captured.set(end); + Ok(fake("offline", events.clone())) + }) + .unwrap(); + assert_eq!(core.hard_end, 4_000_000_000); + assert_eq!(core.slots[0].hard_end, 1_000_000_100); + assert_eq!(captured.get(), 1_000_000_100); + } + #[cfg(feature = "dev-tools")] + #[test] + fn offline_client_does_not_admit_a_successor_with_unsettled_previous_slot() { + let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut core = Core::new(std::rc::Rc::default(), 4_000_000_000); + core.admit_dev_client(100, 0, 1_000_000_100, |_, _| { + Ok(fake("first", events.clone())) + }) + .unwrap(); + let created = std::cell::Cell::new(false); + assert!(core + .admit_dev_client(200, 0, 1_000_000_200, |_, _| { + created.set(true); + Ok(fake("second", events.clone())) + }) + .is_err()); + assert!(!created.get()); + assert_eq!(core.slots.len(), 1); + } + #[cfg(feature = "dev-tools")] + #[test] + fn offline_client_parent_end_and_closed_four_slot_maximum_are_enforced() { + let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut core = Core::new(std::rc::Rc::default(), 700_000_000); + for i in 0..4 { + core.admit_dev_client(100, 0, 1_000_000_100, |_, end| { + assert_eq!(end, 700_000_000); + Ok(fake("parent", events.clone())) + }) + .unwrap(); + core.slots[i].accepted_at = Some(101); + } + assert!(core + .admit_dev_client(100, 0, 1_000_000_100, |_, _| Ok(fake( + "fifth", + events.clone() + ))) + .is_err()); + } + use super::*; + use std::{cell::RefCell, os::unix::process::ExitStatusExt}; + #[test] + fn native_repair_admission_clock_failure_zeroes_retained_sibling() { + let events = Rc::new(RefCell::new(Vec::new())); + let mut core = Core::new(Rc::default(), 500_000_000); + core.admit(1, 0, |_| Ok(fake("a", events.clone()))).unwrap(); + assert!(core + .admission_clock(&mut || Err(error("INERT_CLOCK"))) + .is_err()); + assert_eq!(core.cancel_end, Some(0)); + assert_eq!(core.slots[0].completion_end, Some(0)); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_CLOCK")) + ); + } + #[test] + fn native_repair_unattached_entry_does_not_install_signal_handlers() { + let source = include_str!("scope.rs") + .split("#[cfg(test)]\nmod tests") + .next() + .unwrap(); + let entry = source + .split("pub fn entry_from_environment") + .nth(1) + .unwrap() + .split("pub fn hard_end") + .next() + .unwrap(); + assert!( + entry.find("attachment::consume").unwrap() < entry.find("signals::install").unwrap() + ); + } + #[test] + fn native_repair_public_metadata_turn_does_not_scan_all_history() { + let source = include_str!("scope.rs") + .split("#[cfg(test)]\nmod tests") + .next() + .unwrap(); + assert!(!source.contains("for slot in &mut core.slots")); + } + #[test] + fn native_repair_dispatch_enters_durable_guard_without_preparation_child() { + let source = include_str!("../bin/keito-capture-guard.rs"); + assert!(!source.contains("fn dispatch_guard(")); + let guardian = include_str!("../native_capture_guard.rs"); + assert!( + guardian.find("let initial = marker.metadata()").unwrap() + < guardian.find("Scope::entry_from_environment").unwrap() + ); + } + #[test] + fn native_repair_actual_public_turn_bounds_metadata_and_resource_visits_together() { + let events = Rc::new(RefCell::new(Vec::new())); + let mut core = Core::new(Rc::default(), now().unwrap() + 500_000_000); + for name in ["a", "b", "c", "d", "e", "f", "g", "h", "i"] { + core.admit(1, 0, |_| Ok(fake(name, events.clone()))) + .unwrap(); + } + core.slots[2].accepted_at = Some(1); + Scope::poll_turn(&mut core, &mut None, &mut BTreeMap::new()); + let first = events.borrow().clone(); + assert!(!first.iter().any(|event| event.ends_with(":i"))); + assert_eq!( + first + .iter() + .filter(|event| event.starts_with("metadata:")) + .count(), + 16 + ); + assert_eq!( + first + .iter() + .filter(|event| event.starts_with("poll:")) + .count(), + 7 + ); + assert_eq!(core.cursor, 8); + events.borrow_mut().clear(); + Scope::poll_turn(&mut core, &mut None, &mut BTreeMap::new()); + assert!(events.borrow().iter().any(|event| event == "metadata:i")); + assert!(events.borrow().iter().any(|event| event == "poll:i")); + assert_eq!(core.slots.len(), 9); + assert_eq!(core.slots[2].accepted_at, Some(1)); + } + struct Fake { + progress_sources: Vec<(i32, i16)>, + progress_end: Option, + progress_buffered: bool, + #[cfg(feature = "capture-profile")] + repository_stage: Option, + events: Rc>>, + name: &'static str, + facts: EdgeFacts, + begun: bool, + fail_begin: bool, + begin_ends: Vec, + setup_pending: bool, + setup_wait_source: Option<(i32, u64)>, + setup_buffered_event: bool, + post_join_pending: bool, + post_join_fault: Option<&'static str>, + #[cfg(feature = "dev-tools")] + setup_trace: Option, + } + impl Edge for Fake { + fn progress_wait_sources(&self, descriptors: &mut Vec) -> Option { + descriptors.extend( + self.progress_sources + .iter() + .map(|(fd, events)| libc::pollfd { + fd: *fd, + events: *events, + revents: 0, + }), + ); + self.progress_end + } + fn progress_buffered_event(&self) -> bool { + self.progress_buffered + } + #[cfg(feature = "capture-profile")] + fn repository_profile_stage(&self) -> Option { + self.repository_stage + } + #[cfg(feature = "dev-tools")] + fn setup_trace(&self) -> Option { + self.setup_trace + } + fn setup_pending(&self) -> bool { + self.setup_pending + } + fn setup_wait_source(&self) -> Option<(i32, u64)> { + self.setup_wait_source + } + fn setup_buffered_event(&self) -> bool { + self.setup_buffered_event + } + fn post_join_pending(&self) -> bool { + self.post_join_pending + } + fn take_events(&mut self) -> Vec { + self.events + .borrow_mut() + .push(format!("metadata:{}", self.name)); + Vec::new() + } + fn begin(&mut self, end: u64) -> io::Result<()> { + self.events + .borrow_mut() + .push(format!("begin:{}", self.name)); + self.begun = true; + self.begin_ends.push(end); + if self.fail_begin { + Err(error("SCOPE_BEGIN")) + } else { + Ok(()) + } + } + fn poll(&mut self) -> io::Result<()> { + self.events.borrow_mut().push(format!("poll:{}", self.name)); + self.post_join_pending = false; + if let Some(reason) = self.post_join_fault { + self.facts.first_fault = Some(reason); + return Err(error(reason)); + } + if self.begun { + self.facts.status = Some(ExitStatus::from_raw(0)); + self.facts.waits_known = true; + self.facts.resource_proof = true; + self.facts.group_absent = true; + self.facts.terminal_eof = true; + } + Ok(()) + } + fn facts(&self) -> EdgeFacts { + self.facts + } + fn take_output(&mut self) -> CommandOutput { + CommandOutput { + stdout: vec![], + stderr: vec![], + } + } + } + fn fake(name: &'static str, events: Rc>>) -> Fake { + Fake { + progress_sources: Vec::new(), + progress_end: None, + progress_buffered: false, + #[cfg(feature = "capture-profile")] + repository_stage: None, + name, + events, + facts: EdgeFacts::default(), + begun: false, + fail_begin: false, + begin_ends: vec![], + setup_pending: false, + setup_wait_source: None, + setup_buffered_event: false, + post_join_pending: false, + post_join_fault: None, + #[cfg(feature = "dev-tools")] + setup_trace: None, + } + } + #[test] + #[cfg(feature = "dev-tools")] + fn failure_setup_trace_never_substitutes_a_healthy_sibling_or_unmatched_fault() { + use super::super::group::SetupTrace; + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let healthy = core + .admit(1, 32, |_| Ok(fake("healthy", Rc::default()))) + .unwrap(); + core.slots[healthy.index].edge.setup_trace = Some(SetupTrace { + setup_start_ns: 10, + ready_frame_observed: true, + ..Default::default() + }); + assert!(core.first_fault_setup_trace().is_none()); + core.poison("GROUP_DEADLINE"); + assert!(core.first_fault_setup_trace().is_none()); + core.slots[healthy.index] + .edge + .setup_trace + .as_mut() + .unwrap() + .fault_origin = Some(("GROUP_IO", "JOINED")); + assert!(core.first_fault_setup_trace().is_none()); + } + + #[test] + #[cfg(feature = "dev-tools")] + fn failure_setup_trace_selects_the_origin_after_a_healthy_first_slot() { + use super::super::group::SetupTrace; + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let healthy = core + .admit(1, 32, |_| Ok(fake("healthy", Rc::default()))) + .unwrap(); + let failed = core + .admit(2, 32, |_| Ok(fake("failed", Rc::default()))) + .unwrap(); + core.slots[healthy.index].edge.setup_trace = Some(SetupTrace { + setup_start_ns: 10, + ready_frame_observed: true, + ..Default::default() + }); + core.slots[failed.index].edge.setup_trace = Some(SetupTrace { + setup_start_ns: 20, + fault_origin: Some(("GROUP_DEADLINE", "AWAIT_READY")), + ..Default::default() + }); + core.poison("GROUP_DEADLINE"); + let selected = core.first_fault_setup_trace().unwrap(); + assert_eq!(selected.setup_start_ns, 20); + assert_eq!( + selected.fault_origin, + Some(("GROUP_DEADLINE", "AWAIT_READY")) + ); + assert!(!selected.ready_frame_observed); + } + + #[test] + fn hook_setup_gate_is_exclusive_cloexec_and_rejects_replaced_or_unsafe_files() { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let directory = std::fs::File::open(temp.path()).unwrap(); + let mut first = HookSetupAdmission::open(&directory, 0).unwrap(); + assert!(first.try_lock(&directory).unwrap()); + assert_ne!( + unsafe { libc::fcntl(first.file.as_raw_fd(), libc::F_GETFD) } & libc::FD_CLOEXEC, + 0 + ); + let mut second = HookSetupAdmission::open(&directory, 0).unwrap(); + assert!(!second.try_lock(&directory).unwrap()); + drop(first); + assert!(second.try_lock(&directory).unwrap()); + let path = temp.path().join("capture-hook-setup-0.lock"); + std::fs::rename(&path, temp.path().join("old-lock")).unwrap(); + let replacement = HookSetupAdmission::open(&directory, 0).unwrap(); + assert!(second.try_lock(&directory).is_err()); + drop(second); + drop(replacement); + std::fs::remove_file(&path).unwrap(); + let target = temp.path().join("owned-target"); + std::fs::write(&target, b"PRIVATE_UNREAD_TARGET").unwrap(); + std::os::unix::fs::symlink(&target, &path).unwrap(); + assert!(HookSetupAdmission::open(&directory, 0).is_err()); + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, b"not-empty").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert!(HookSetupAdmission::open(&directory, 0).is_err()); + std::fs::write(&path, b"").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(HookSetupAdmission::open(&directory, 0).is_err()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + std::fs::hard_link(&path, temp.path().join("extra-link")).unwrap(); + assert!(HookSetupAdmission::open(&directory, 0).is_err()); + std::fs::remove_file(temp.path().join("extra-link")).unwrap(); + std::fs::remove_file(&path).unwrap(); + let cpath = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(cpath.as_ptr(), 0o600) }, 0); + assert!(HookSetupAdmission::open(&directory, 0).is_err()); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + assert!(HookSetupAdmission::open(&directory, 0).is_err()); + } + + #[test] + fn hook_setup_pool_has_exactly_four_independent_slots_and_releases_each_on_drop() { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let directory = File::open(temp.path()).unwrap(); + let mut held = Vec::new(); + for slot in 0..HOOK_SETUP_SLOTS { + let mut admission = HookSetupAdmission::open(&directory, slot).unwrap(); + assert!(admission.try_lock(&directory).unwrap()); + held.push(admission); + } + assert!(HookSetupAdmission::open(&directory, HOOK_SETUP_SLOTS).is_err()); + for slot in 0..HOOK_SETUP_SLOTS { + let mut waiter = HookSetupAdmission::open(&directory, slot).unwrap(); + assert!(!waiter.try_lock(&directory).unwrap()); + } + drop(held.remove(2)); + let mut released = HookSetupAdmission::open(&directory, 2).unwrap(); + assert!(released.try_lock(&directory).unwrap()); + let mut still_held = HookSetupAdmission::open(&directory, 0).unwrap(); + assert!(!still_held.try_lock(&directory).unwrap()); + } + + #[test] + fn guard_core_pool_is_four_independent_cloexec_locks_without_consuming_leaf_capacity() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let temp = tempfile::tempdir().unwrap(); + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let directory = File::open(temp.path()).unwrap(); + let mut held = Vec::new(); + for slot in 0..HOOK_SETUP_SLOTS { + let mut permit = + HookSetupAdmission::open_kind(&directory, slot, HookCapacityKind::Core).unwrap(); + assert!(permit.try_lock(&directory).unwrap()); + assert_ne!( + unsafe { libc::fcntl(permit.file.as_raw_fd(), libc::F_GETFD) } & libc::FD_CLOEXEC, + 0 + ); + let mut leaf = HookSetupAdmission::open(&directory, slot).unwrap(); + assert_ne!( + permit.file.metadata().unwrap().ino(), + leaf.file.metadata().unwrap().ino() + ); + assert!( + leaf.try_lock(&directory).unwrap(), + "core holder consumed a leaf permit" + ); + held.push(permit); + } + assert!(HookSetupAdmission::open_kind( + &directory, + HOOK_SETUP_SLOTS, + HookCapacityKind::Core + ) + .is_err()); + for attempt in 0..20 { + let mut waiter = HookSetupAdmission::open_kind( + &directory, + attempt % HOOK_SETUP_SLOTS, + HookCapacityKind::Core, + ) + .unwrap(); + assert!( + !waiter.try_lock(&directory).unwrap(), + "fifth core admitted into a full pool" + ); + } + drop(held.remove(2)); + let mut next = + HookSetupAdmission::open_kind(&directory, 2, HookCapacityKind::Core).unwrap(); + assert!(next.try_lock(&directory).unwrap()); + let mut blocked = + HookSetupAdmission::open_kind(&directory, 0, HookCapacityKind::Core).unwrap(); + assert!(!blocked.try_lock(&directory).unwrap()); + } + + #[test] + fn guard_core_capacity_ceiling_preserves_earlier_parent_and_clock_failure() { + let mut core: Core = Core::new(Rc::default(), 100_000_000); + assert!(await_hook_setup_capacity_until( + &mut core, + &mut |_| {}, + &mut || Ok(50_000_000), + &mut || panic!("earlier parent ignored"), + &mut || panic!("expired parent wait"), + Some(500_000_000) + ) + .is_err()); + assert_eq!(core.hard_end, 100_000_000); + let mut core: Core = Core::new(Rc::default(), 600_000_000); + assert!(await_hook_setup_capacity_until( + &mut core, + &mut |_| {}, + &mut || Err(error("SCOPE_CLOCK")), + &mut || panic!("clock failure admitted"), + &mut || panic!("failed clock wait"), + Some(500_000_000) + ) + .is_err()); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_CLOCK")) + ); + assert_eq!(core.cancel_end, Some(0)); + assert!(core.owner.borrow().admission_closed); + } + + fn completed_hook_facts() -> EdgeFacts { + EdgeFacts { + waits_known: true, + group_absent: true, + terminal_eof: true, + resource_proof: true, + io_required: true, + io: IoFacts { + stdin_closed: true, + stdout_eof: true, + stderr_eof: true, + ..Default::default() + }, + ..Default::default() + } + } + + #[test] + fn hook_admission_remains_locked_through_running_and_cleanup() { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let directory = File::open(temp.path()).unwrap(); + let mut admission = Some(HookSetupAdmission::open(&directory, 0).unwrap()); + assert!(admission.as_mut().unwrap().try_lock(&directory).unwrap()); + let mut waiter = HookSetupAdmission::open(&directory, 0).unwrap(); + for stage in [Stage::Ready, Stage::Park, Stage::Running, Stage::Cleaning] { + release_hook_admission(&stage, completed_hook_facts(), &mut admission); + assert!(admission.is_some(), "live command released capacity"); + assert!(!waiter.try_lock(&directory).unwrap()); + } + release_hook_admission(&Stage::Done, completed_hook_facts(), &mut admission); + assert!(admission.is_none()); + assert!(waiter.try_lock(&directory).unwrap()); + // Completion polling cannot release a second description's lock. + release_hook_admission(&Stage::Done, completed_hook_facts(), &mut admission); + let mut next = HookSetupAdmission::open(&directory, 0).unwrap(); + assert!(!next.try_lock(&directory).unwrap()); + } + + #[test] + fn hook_admission_requires_full_wait_group_and_pipe_finality() { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let directory = File::open(temp.path()).unwrap(); + let mut admission = Some(HookSetupAdmission::open(&directory, 0).unwrap()); + assert!(admission.as_mut().unwrap().try_lock(&directory).unwrap()); + let mut waiter = HookSetupAdmission::open(&directory, 0).unwrap(); + for missing in 0..7 { + let mut facts = completed_hook_facts(); + match missing { + 0 => facts.resource_proof = false, + 1 => facts.waits_known = false, + 2 => facts.group_absent = false, + 3 => facts.terminal_eof = false, + 4 => facts.io.stdin_closed = false, + 5 => facts.io.stdout_eof = false, + _ => facts.io.stderr_eof = false, + } + release_hook_admission(&Stage::Done, facts, &mut admission); + assert!(admission.is_some(), "incomplete cleanup released capacity"); + assert!(!waiter.try_lock(&directory).unwrap()); + } + release_hook_admission(&Stage::Done, completed_hook_facts(), &mut admission); + assert!(admission.is_none()); + assert!(waiter.try_lock(&directory).unwrap()); + } + + #[test] + fn hook_setup_capacity_progresses_and_never_renews_an_expired_or_tighter_end() { + use std::cell::Cell; + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let polls = Cell::new(0); + let attempts = Cell::new(0); + let pauses = Cell::new(0); + await_hook_setup_capacity( + &mut core, + &mut |_| polls.set(polls.get() + 1), + &mut || Ok(100), + &mut || { + attempts.set(attempts.get() + 1); + Ok(attempts.get() == 2) + }, + &mut || pauses.set(pauses.get() + 1), + ) + .unwrap(); + assert!(polls.get() >= 3); + assert_eq!(attempts.get(), 2); + assert_eq!(pauses.get(), 1); + assert_eq!(core.hard_end, 500_000_000); + for (hard_end, at) in [(500_000_000, 450_000_000), (100_000_000, 50_000_000)] { + let mut core: Core = Core::new(Rc::default(), hard_end); + await_hook_setup_capacity( + &mut core, + &mut |_| {}, + &mut || Ok(at), + &mut || panic!("expired setup admission attempted"), + &mut || panic!("expired pause"), + ) + .unwrap_err(); + assert_eq!(core.hard_end, hard_end); + assert!(core.owner.borrow().first_fault.is_some()); + } + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let reads = Cell::new(0); + await_hook_setup_capacity( + &mut core, + &mut |_| {}, + &mut || { + reads.set(reads.get() + 1); + Ok(if reads.get() == 1 { 1 } else { 450_000_000 }) + }, + &mut || Ok(true), + &mut || panic!("locked pause"), + ) + .unwrap_err(); + assert!(core.owner.borrow().first_fault.is_some()); + } + + #[test] + fn guard_core_capacity_refuses_at_the_original_leaf_ceiling_before_lock() { + let mut core: Core = Core::new(Rc::default(), 600_000_000); + let attempts = std::cell::Cell::new(0); + let result = await_hook_setup_capacity_until( + &mut core, + &mut |_| {}, + &mut || Ok(450_000_000), + &mut || { + attempts.set(attempts.get() + 1); + Ok(true) + }, + &mut || panic!("expired core capacity wait"), + Some(500_000_000), + ); + assert!( + result.is_err(), + "guard's longer end admitted an expired leaf" + ); + assert_eq!(attempts.get(), 0); + assert_eq!(core.hard_end, 600_000_000); + } + + #[test] + fn guard_core_capacity_rechecks_leaf_ceiling_after_lock() { + let mut core: Core = Core::new(Rc::default(), 600_000_000); + let reads = std::cell::Cell::new(0); + let result = await_hook_setup_capacity_until( + &mut core, + &mut |_| {}, + &mut || { + reads.set(reads.get() + 1); + Ok(if reads.get() == 1 { 1 } else { 450_000_000 }) + }, + &mut || Ok(true), + &mut || panic!("late acquired core permit"), + Some(500_000_000), + ); + assert!( + result.is_err(), + "lock wait renewed the original leaf ceiling" + ); + assert_eq!(reads.get(), 2); + assert_eq!(core.hard_end, 600_000_000); + } + + #[test] + fn hook_setup_capacity_rechecks_parent_after_lock_and_preserves_gate_errors() { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let owner = core.owner.clone(); + await_hook_setup_capacity( + &mut core, + &mut |_| {}, + &mut || Ok(1), + &mut || { + owner.borrow_mut().poison(ProtocolError("PARENT_CANCELLED")); + Ok(true) + }, + &mut || panic!("post-lock cancelled pause"), + ) + .unwrap_err(); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("PARENT_CANCELLED")) + ); + let mut core: Core = Core::new(Rc::default(), 500_000_000); + await_hook_setup_capacity( + &mut core, + &mut |_| {}, + &mut || Ok(1), + &mut || Err(error("PRIVATE_IO_CANARY")), + &mut || panic!("failed gate pause"), + ) + .unwrap_err(); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_SETUP_GATE")) + ); + } + + #[test] + fn hook_setup_capacity_preserves_parent_fault_clock_failure_and_poll_shortening() { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + core.poison("PARENT_CANCELLED"); + await_hook_setup_capacity( + &mut core, + &mut |_| {}, + &mut || Ok(1), + &mut || panic!("cancelled lock attempt"), + &mut || {}, + ) + .unwrap_err(); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("PARENT_CANCELLED")) + ); + let mut core: Core = Core::new(Rc::default(), 500_000_000); + await_hook_setup_capacity( + &mut core, + &mut |_| {}, + &mut || Err(error("SCOPE_CLOCK")), + &mut || panic!("clock-failed lock attempt"), + &mut || {}, + ) + .unwrap_err(); + assert_eq!(core.cancel_end, Some(0)); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_CLOCK")) + ); + let mut core: Core = Core::new(Rc::default(), 500_000_000); + await_hook_setup_capacity( + &mut core, + &mut |core| core.hard_end = 50_000_001, + &mut || Ok(1), + &mut || panic!("shortened lock attempt"), + &mut || {}, + ) + .unwrap_err(); + assert_eq!(core.hard_end, 50_000_001); + } + + mod setup_schedule_tests { + use super::*; + use std::cell::Cell; + + fn pending_core(buffered: bool, fd: i32) -> (Core, SlotId) { + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core + .admit(1, 32, |_| Ok(fake("joined", Rc::default()))) + .unwrap(); + core.slots[id.index].edge.setup_pending = true; + core.slots[id.index].edge.setup_wait_source = Some((fd, 20_000_000)); + core.slots[id.index].edge.setup_buffered_event = buffered; + (core, id) + } + + #[test] + fn setup_schedule_buffered_event_skips_wait_without_advancing_or_taking_output() { + let (mut core, id) = pending_core(true, 7); + let mut clocks = 0; + core.wait_repository_setup( + &mut || { + clocks += 1; + Ok(10_000_000) + }, + &mut |_, _| panic!("complete buffered frame must return to original parser"), + ) + .unwrap(); + assert_eq!(clocks, 1); + assert!(core.slots[id.index].edge.setup_pending); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(core.slots[id.index].completion_end.is_none()); + assert!(!core.slots[id.index].output_taken); + assert_eq!(core.hard_end, 500_000_000); + } + + #[test] + fn setup_schedule_partial_bytes_still_wait_on_the_original_fd_and_end() { + let (mut core, id) = pending_core(false, 7); + let mut calls = 0; + core.wait_repository_setup(&mut || Ok(19_950_000), &mut |fds, timeout| { + calls += 1; + assert_eq!( + (fds.len(), fds[0].fd, fds[0].events, timeout), + (1, 7, libc::POLLIN, 0) + ); + Ok(0) + }) + .unwrap(); + assert_eq!(calls, 1); + assert!(core.slots[id.index].edge.setup_pending); + assert!(core.slots[id.index].accepted_at.is_none()); + } + + #[test] + fn setup_schedule_buffer_shortcut_cannot_bypass_invalid_fd_clock_or_owner() { + let (mut invalid, _) = pending_core(true, -1); + assert_eq!( + invalid + .wait_repository_setup( + &mut || panic!("invalid FD refuses first"), + &mut |_, _| { panic!("invalid FD must not poll") } + ) + .unwrap_err() + .to_string(), + "SCOPE_SETUP_WAIT" + ); + let (mut no_clock, id) = pending_core(true, 7); + assert!(no_clock + .wait_repository_setup(&mut || Err(error("INJECTED_CLOCK")), &mut |_, _| { + panic!("clock failure must not poll") + }) + .is_err()); + assert_eq!(no_clock.cancel_end, Some(0)); + assert_eq!(no_clock.slots[id.index].completion_end, Some(0)); + for state in ["fault", "cancelled", "finished"] { + let (mut core, id) = pending_core(true, 7); + match state { + "fault" => core.poison("ORIGINAL_FAULT"), + "cancelled" => core.cancel_end = Some(10), + _ => core.finished = true, + } + assert!(core + .wait_repository_setup( + &mut || panic!("closed owner must refuse"), + &mut |_, _| { panic!("closed owner must not poll") } + ) + .is_err()); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + } + } + + #[test] + fn setup_schedule_exact_end_returns_to_deadline_parser_without_fake_acceptance() { + let (mut core, id) = pending_core(true, 7); + let mut clocks = 0; + core.wait_repository_setup( + &mut || { + clocks += 1; + Ok(20_000_000) + }, + &mut |_, _| panic!("no wait beyond original end"), + ) + .unwrap(); + assert_eq!(clocks, 1); + assert_eq!( + core.slots[id.index].edge.setup_wait_source, + Some((7, 20_000_000)) + ); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + } + + #[test] + fn setup_schedule_join_retains_all_pipes_before_first_error_and_only_schedules_success() { + for state in ["success", "start_error", "attach_error", "both_errors"] { + let mut stage = Stage::Ready; + let mut pending = true; + let attached = Cell::new(false); + let started = if state == "start_error" || state == "both_errors" { + Err(error("ORIGINAL_START")) + } else { + Ok(()) + }; + let result = retain_group_start(&mut stage, &mut pending, started, || { + attached.set(true); + if state == "attach_error" || state == "both_errors" { + Err(error("PIPE_ATTACH")) + } else { + Ok(()) + } + }); + assert!( + attached.get(), + "post-spawn error must not bypass handle retention" + ); + assert!(matches!(stage, Stage::Park)); + assert_eq!(pending, state == "success"); + match state { + "success" => assert!(result.is_ok()), + "attach_error" => assert_eq!(result.unwrap_err().to_string(), "PIPE_ATTACH"), + _ => assert_eq!(result.unwrap_err().to_string(), "ORIGINAL_START"), + } + } + } + + #[test] + fn setup_schedule_postjoin_observes_once_after_drain_without_sleep_or_result_acceptance() { + let (mut core, id) = pending_core(false, 7); + core.slots[id.index].edge.post_join_pending = true; + let events = core.slots[id.index].edge.events.clone(); + let original_cursor = core.cursor; + assert!(poll_joined_after_drain( + &mut core, + 0, + &mut || Ok(19_970_000), + &mut |_| { + events.borrow_mut().push("drain".into()); + true + } + )); + assert_eq!(events.borrow().as_slice(), ["drain", "poll:joined"]); + assert!(!core.slots[id.index].edge.post_join_pending); + assert!(!poll_joined_after_drain( + &mut core, + 0, + &mut || panic!("no second observation"), + &mut |_| true + )); + assert_eq!(core.cursor, original_cursor); + assert_eq!(core.hard_end, 500_000_000); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + } + + #[test] + fn setup_schedule_parent_cancel_after_spawn_wins_before_extra_park_observation() { + let (mut core, id) = pending_core(false, 7); + core.slots[id.index].edge.post_join_pending = true; + let events = core.slots[id.index].edge.events.clone(); + assert!(!poll_joined_after_drain( + &mut core, + 0, + &mut || panic!("cancelled pass must stop"), + &mut |core| { + core.cancel(Some("PARENT_CANCELLED"), 2, 3); + true + } + )); + assert!(!events + .borrow() + .iter() + .any(|event| event.starts_with("poll:"))); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("PARENT_CANCELLED")) + ); + assert_eq!(core.slots[id.index].completion_end, Some(3)); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + } + + #[test] + fn setup_schedule_exhausted_upstream_drain_defers_extra_probe_without_acceptance() { + for (reads, parsed, allowed) in [ + (0, 0, true), + ( + super::super::super::protocol::MAX_READS - 1, + super::super::super::protocol::MAX_PARSE - 1, + true, + ), + (super::super::super::protocol::MAX_READS, 0, false), + (0, super::super::super::protocol::MAX_PARSE, false), + ] { + let work = super::super::super::protocol::PollWork { reads, parsed }; + assert_eq!(upstream_park_probe_allowed(Some(&work)), allowed); + if allowed { + continue; + } + let (mut core, id) = pending_core(false, 7); + core.slots[id.index].edge.post_join_pending = true; + let events = core.slots[id.index].edge.events.clone(); + assert!(!poll_joined_after_drain( + &mut core, + 0, + &mut || { + panic!("an exhausted upstream drain must precede any extra observation") + }, + &mut |_| upstream_park_probe_allowed(Some(&work)) + )); + assert!(core.slots[id.index].edge.post_join_pending); + assert!(events.borrow().is_empty()); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + // A later proved drain schedules the original Park path once. + assert!(poll_joined_after_drain( + &mut core, + 0, + &mut || Ok(2), + &mut |_| { upstream_park_probe_allowed(None) } + )); + assert!(!core.slots[id.index].edge.post_join_pending); + assert_eq!( + events + .borrow() + .iter() + .filter(|event| event.starts_with("poll:")) + .count(), + 1 + ); + } + } + + #[test] + fn setup_schedule_postjoin_failure_clock_and_exact_operation_end_remain_closed() { + for state in ["poll", "clock", "deadline", "owner", "closed"] { + let (mut core, id) = pending_core(false, 7); + core.slots[id.index].edge.post_join_pending = true; + if state == "poll" { + core.slots[id.index].edge.post_join_fault = Some("ORIGINAL_PARK_FAULT"); + } + if state == "owner" { + core.poison("ORIGINAL_OWNER_FAULT"); + } + if state == "closed" { + core.owner.borrow_mut().admission_closed = true; + } + let events = core.slots[id.index].edge.events.clone(); + poll_joined_after_drain( + &mut core, + 0, + &mut || match state { + "clock" => Err(error("INJECTED_CLOCK")), + "deadline" => Ok(450_000_000), + _ => Ok(2), + }, + &mut |_| true, + ); + assert!(core.owner.borrow().first_fault.is_some()); + assert!(core.cancel_end.is_some()); + assert_eq!( + events + .borrow() + .iter() + .filter(|event| event.starts_with("poll:")) + .count(), + usize::from(state == "poll") + ); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + assert_eq!(core.hard_end, 500_000_000); + } + } + + #[test] + fn setup_schedule_targeted_pass_keeps_the_original_fair_window_and_skips_ordinary_edges() { + let events = Rc::new(RefCell::new(vec![])); + let mut core = Core::new(Rc::default(), 500_000_000); + let mut ids = vec![]; + for _ in 0..(SLOTS_PER_TURN + 2) { + let id = core + .admit(1, 0, |_| Ok(fake("edge", events.clone()))) + .unwrap(); + core.slots[id.index].edge.post_join_pending = true; + ids.push(id); + } + core.slots[ids[2].index].edge.post_join_pending = false; + let cursor = core.cursor; + assert!(core.poll_post_joined(0, &mut || Ok(2))); + assert_eq!( + events + .borrow() + .iter() + .filter(|event| event.starts_with("poll:")) + .count(), + SLOTS_PER_TURN - 1 + ); + assert!(core.slots[ids[SLOTS_PER_TURN].index].edge.post_join_pending); + assert_eq!(core.cursor, cursor); + assert!(core + .slots + .iter() + .all(|slot| slot.accepted_at.is_none() && !slot.output_taken)); + } + } + + #[test] + fn repository_admission_pending_setup_blocks_without_waiting_for_workload_completion() { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + assert!(core.repository_admission_ready().unwrap()); + let slot = core + .admit(1, 32, |_| Ok(fake("first", Rc::default()))) + .unwrap(); + core.slots[slot.index].edge.setup_pending = true; + let original_end = core.hard_end; + assert!(!core.repository_admission_ready().unwrap()); + assert_eq!(core.hard_end, original_end); + assert_eq!(core.slots.len(), 1); + assert!(!core.slots[0].output_taken); + assert!(core.owner.borrow().first_fault.is_none()); + core.slots[slot.index].edge.setup_pending = false; + assert!(core.repository_admission_ready().unwrap()); + assert!(core.slots[0].accepted_at.is_none()); + assert!(core.slots[0].edge.facts.status.is_none()); + } + #[test] + fn repository_admission_actual_stage_mapping_only_waits_for_ready_and_park() { + assert!(Stage::Ready.setup_pending()); + assert!(Stage::Park.setup_pending()); + assert!(!Stage::Running.setup_pending()); + assert!(!Stage::Cleaning.setup_pending()); + assert!(!Stage::Done.setup_pending()); + } + #[test] + fn repository_setup_wait_observes_a_response_inside_the_original_final_poll_period() { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let slot = core + .admit(1, 32, |_| Ok(fake("ready", Rc::default()))) + .unwrap(); + core.slots[slot.index].edge.setup_pending = true; + let end = 20_000_000u64; + core.slots[slot.index].edge.setup_wait_source = Some((7, end)); + let ready_at = end - 30_000; + let clock = std::cell::Cell::new(end - 49_000); + let mut turns = 0; + let result = await_repository_admission( + &mut core, + &mut |core| { + turns += 1; + assert!(turns <= 64, "finite scheduling counterexample"); + if clock.get() >= end { + core.poison("GROUP_DEADLINE"); + } else if clock.get() >= ready_at { + core.slots[slot.index].edge.setup_pending = false; + } + }, + &mut |core| { + core.wait_repository_setup(&mut || Ok(clock.get()), &mut |_, timeout| { + assert_eq!(timeout, 0, "do not round up a submillisecond remainder"); + clock.set(clock.get() + 1_000); + Ok(0) + }) + }, + ); + assert!(result.is_ok(), "READY before original deadline was missed"); + assert!(clock.get() >= ready_at && clock.get() < end); + assert_eq!(core.hard_end, 500_000_000); + assert!(core.slots[slot.index].completion_end.is_none()); + assert!(core.slots[slot.index].accepted_at.is_none()); + assert!(!core.slots[slot.index].output_taken); + } + #[test] + fn repository_setup_wait_progress_fault_stops_before_another_pause() { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let slot = core + .admit(1, 32, |_| Ok(fake("ready", Rc::default()))) + .unwrap(); + core.slots[slot.index].edge.setup_pending = true; + let mut turns = 0; + let mut pauses = 0; + let result = await_repository_admission( + &mut core, + &mut |core| { + turns += 1; + if turns == 2 { + core.poison("ORIGINAL_WAIT_FAULT"); + } + }, + &mut |_| { + pauses += 1; + Ok(()) + }, + ); + assert!(result.is_err()); + assert_eq!((turns, pauses), (2, 1)); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("ORIGINAL_WAIT_FAULT")) + ); + assert_eq!(core.slots.len(), 1); + assert!(!core.slots[slot.index].output_taken); + } + #[test] + fn repository_setup_wait_expiry_refuses_without_a_pause_or_new_interval() { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let slot = core + .admit(1, 32, |_| Ok(fake("ready", Rc::default()))) + .unwrap(); + core.slots[slot.index].edge.setup_pending = true; + let end = core.hard_end; + let result = await_repository_admission( + &mut core, + &mut |core| core.poison("GROUP_DEADLINE"), + &mut |_| panic!("expired setup must not wait again"), + ); + assert!(result.is_err()); + assert_eq!(core.hard_end, end); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("GROUP_DEADLINE")) + ); + assert!(core.slots[slot.index].completion_end.is_none()); + assert!(core.slots[slot.index].accepted_at.is_none()); + } + #[test] + fn repository_setup_readiness_wait_blocks_only_within_original_ends() { + for (setup_end, parent_end, at, expected) in [ + (20_000_000, 500_000_000, 10_000_000, Some(1)), + (20_000_000, 500_000_000, 19_000_001, Some(0)), + (20_000_000, 50_500_000, 0, Some(0)), + (20_000_000, 50_000_000, 0, None), + (20_000_000, 500_000_000, 20_000_000, None), + ] { + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core + .admit(0, 0, |_| Ok(fake("wait", Rc::default()))) + .unwrap(); + core.hard_end = parent_end; + core.slots[id.index].edge.setup_pending = true; + core.slots[id.index].edge.setup_wait_source = Some((7, setup_end)); + let mut observed = None; + core.wait_repository_setup(&mut || Ok(at), &mut |fds, timeout| { + assert_eq!(fds.len(), 1); + assert_eq!((fds[0].fd, fds[0].events), (7, libc::POLLIN)); + observed = Some(timeout); + fds[0].revents = libc::POLLIN | libc::POLLHUP; + Ok(1) + }) + .unwrap(); + assert_eq!(observed, expected); + assert_eq!(core.hard_end, parent_end); + assert!(core.slots[id.index].edge.setup_pending); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + } + } + #[test] + fn repository_setup_readiness_wait_interrupt_returns_to_progress_and_faults_refuse() { + for condition in ["interrupt", "invalid", "error"] { + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core + .admit(1, 0, |_| Ok(fake("wait", Rc::default()))) + .unwrap(); + core.slots[id.index].edge.setup_pending = true; + core.slots[id.index].edge.setup_wait_source = Some((7, 20_000_000)); + let result = + core.wait_repository_setup(&mut || Ok(10_000_000), &mut |fds, _| match condition { + "interrupt" => Err(io::Error::from_raw_os_error(libc::EINTR)), + "invalid" => { + fds[0].revents = libc::POLLNVAL; + Ok(1) + } + _ => Err(io::Error::from_raw_os_error(libc::EIO)), + }); + assert_eq!(result.is_ok(), condition == "interrupt"); + assert_eq!( + core.owner.borrow().first_fault.is_none(), + condition == "interrupt" + ); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + } + } + #[test] + fn repository_setup_readiness_wait_clock_failure_cancels_existing_owner_at_zero() { + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core + .admit(1, 0, |_| Ok(fake("wait", Rc::default()))) + .unwrap(); + core.slots[id.index].edge.setup_pending = true; + core.slots[id.index].edge.setup_wait_source = Some((7, 20_000_000)); + assert!(core + .wait_repository_setup(&mut || Err(error("INJECTED_CLOCK")), &mut |_, _| panic!( + "clock failure cannot wait" + ),) + .is_err()); + assert_eq!(core.cancel_end, Some(0)); + assert_eq!(core.slots[id.index].completion_end, Some(0)); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_CLOCK")) + ); + } + #[test] + fn scope_wait_final_pending_setup_uses_readiness_in_the_original_last_fraction() { + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core + .admit(0, 0, |_| Ok(fake("last", Rc::default()))) + .unwrap(); + core.slots[id.index].edge.setup_pending = true; + core.slots[id.index].edge.setup_wait_source = Some((7, 20_000_000)); + let mut polls = 0; + let mut pauses = 0; + core.wait_command_progress( + &mut || Ok(19_950_000), + &mut |fds, timeout| { + polls += 1; + assert_eq!(timeout, 0); + assert_eq!((fds.len(), fds[0].fd, fds[0].events), (1, 7, libc::POLLIN)); + fds[0].revents = libc::POLLIN; + Ok(1) + }, + &mut || pauses += 1, + ) + .unwrap(); + assert_eq!((polls, pauses), (1, 0)); + assert_eq!(core.hard_end, 500_000_000); + assert_eq!( + core.slots[id.index].edge.setup_wait_source, + Some((7, 20_000_000)) + ); + assert!(core.slots[id.index].edge.setup_pending); + assert!(core.slots[id.index].accepted_at.is_none()); + } + #[test] + fn scope_wait_repository_final_sibling_keeps_its_own_pending_socket() { + let mut core = Core::new(Rc::default(), 500_000_000); + let a = core + .admit(0, 0, |_| Ok(fake("running", Rc::default()))) + .unwrap(); + let b = core + .admit(0, 0, |_| Ok(fake("pending", Rc::default()))) + .unwrap(); + core.slots[b.index].edge.setup_pending = true; + core.slots[b.index].edge.setup_wait_source = Some((9, 20_000_000)); + assert!(core.take_repository_results(&[a, b]).unwrap().is_none()); + let mut polls = 0; + let mut pauses = 0; + core.wait_command_progress( + &mut || Ok(10_000_000), + &mut |fds, timeout| { + polls += 1; + assert_eq!((fds.len(), fds[0].fd, timeout), (1, 9, 1)); + Ok(0) + }, + &mut || pauses += 1, + ) + .unwrap(); + assert_eq!((polls, pauses), (1, 0)); + assert!(core + .slots + .iter() + .all(|slot| slot.accepted_at.is_none() && !slot.output_taken)); + } + #[test] + fn scope_wait_running_edges_keep_the_existing_ordinary_pause() { + let mut core = Core::new(Rc::default(), 500_000_000); + core.admit(0, 0, |_| Ok(fake("running", Rc::default()))) + .unwrap(); + let mut polls = 0; + let mut pauses = 0; + core.wait_command_progress( + &mut || Ok(10_000_000), + &mut |_, _| { + polls += 1; + Ok(0) + }, + &mut || pauses += 1, + ) + .unwrap(); + assert_eq!((polls, pauses), (0, 1)); + assert_eq!(core.hard_end, 500_000_000); + } + #[test] + fn scope_wait_failed_or_retired_owner_does_not_wait_or_renew() { + for state in ["fault", "finished", "cancelled"] { + let mut core = Core::new(Rc::default(), 500_000_000); + core.admit(0, 0, |_| Ok(fake("pending", Rc::default()))) + .unwrap(); + match state { + "fault" => core.poison("ORIGINAL_FAULT"), + "finished" => core.finished = true, + _ => core.cancel_end = Some(100), + } + let mut polls = 0; + let mut pauses = 0; + assert!(core + .wait_command_progress( + &mut || Ok(10), + &mut |_, _| { + polls += 1; + Ok(0) + }, + &mut || pauses += 1 + ) + .is_err()); + assert_eq!((polls, pauses), (0, 0)); + assert_eq!(core.hard_end, 500_000_000); + if state == "fault" { + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("ORIGINAL_FAULT")) + ); + } + } + } + #[test] + fn scope_wait_pending_clock_failure_broadcasts_zero_without_a_pause() { + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core + .admit(0, 0, |_| Ok(fake("pending", Rc::default()))) + .unwrap(); + core.slots[id.index].edge.setup_pending = true; + core.slots[id.index].edge.setup_wait_source = Some((7, 20_000_000)); + let mut polls = 0; + let mut pauses = 0; + assert!(core + .wait_command_progress( + &mut || Err(error("INJECTED_CLOCK")), + &mut |_, _| { + polls += 1; + Ok(0) + }, + &mut || pauses += 1 + ) + .is_err()); + assert_eq!((polls, pauses), (0, 0)); + assert_eq!(core.cancel_end, Some(0)); + assert_eq!(core.slots[id.index].completion_end, Some(0)); + } + #[test] + fn repository_admission_sticky_fault_never_reopens_for_a_ready_sibling() { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + core.admit(1, 32, |_| Ok(fake("first", Rc::default()))) + .unwrap(); + core.poison("ORIGINAL_FAULT"); + assert!(core.repository_admission_ready().is_err()); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("ORIGINAL_FAULT")) + ); + assert_eq!(core.slots.len(), 1); + assert!(!core.slots[0].output_taken); + } + #[test] + fn repository_admission_cancelled_and_finished_owners_refuse_without_renewal() { + for kind in ["zero", "cancel", "finished"] { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let slot = core + .admit(1, 32, |_| Ok(fake("first", Rc::default()))) + .unwrap(); + if kind == "finished" { + core.finished = true; + } else { + core.cancel(None, 10, if kind == "zero" { 0 } else { 100 }); + } + let end = core.slots[slot.index].completion_end; + assert!(core.repository_admission_ready().is_err()); + assert_eq!(core.slots[slot.index].completion_end, end); + assert_eq!(core.slots.len(), 1); + } + } + fn repository_cohort() -> (Core, [SlotId; 2]) { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + let slots = ["identity", "remotes"].map(|name| { + let id = core + .admit(1, 32, |_| Ok(fake(name, Rc::default()))) + .unwrap(); + core.slots[id.index].accepted_at = Some(2); + core.slots[id.index].edge.facts = EdgeFacts { + status: Some(ExitStatus::from_raw((id.index as i32) << 8)), + waits_known: true, + group_absent: true, + terminal_eof: true, + resource_proof: true, + ..Default::default() + }; + id + }); + (core, slots) + } + #[test] + fn repository_cohort_pending_sibling_consumes_no_outputs_or_authority() { + let (mut core, slots) = repository_cohort(); + core.slots[1].accepted_at = None; + assert!(matches!(core.take_repository_results(&slots), Ok(None))); + assert!(core.slots.iter().all(|slot| !slot.output_taken)); + assert!(core.owner.borrow().first_fault.is_none()); + core.slots[1].accepted_at = Some(3); + assert!(core.take_repository_results(&slots).unwrap().is_some()); + } + #[test] + fn repository_cohort_preserves_request_order_and_consumes_exactly_once() { + let (mut core, slots) = repository_cohort(); + let reordered = [slots[1].clone(), slots[0].clone()]; + let results = core.take_repository_results(&reordered).unwrap().unwrap(); + assert_eq!(results.map(|r| r.status.code()), [Some(1), Some(0)]); + assert!(core.slots.iter().all(|slot| slot.output_taken)); + assert!(core.take_repository_results(&slots).is_err()); + } + #[test] + fn repository_cohort_foreign_duplicate_and_consumed_slots_take_nothing() { + for invalid in ["foreign", "duplicate", "consumed"] { + let (mut core, mut slots) = repository_cohort(); + match invalid { + "foreign" => slots[1].scope = Rc::new(()), + "duplicate" => slots[1] = slots[0].clone(), + _ => core.slots[1].output_taken = true, + } + assert!(core.take_repository_results(&slots).is_err()); + assert!(!core.slots[0].output_taken); + assert_eq!(core.slots[1].output_taken, invalid == "consumed"); + assert!(core.owner.borrow().first_fault.is_some()); + } + } + #[test] + fn repository_cohort_missing_proof_or_sticky_fault_never_yields_outputs() { + for missing in ["proof", "wait", "status", "group", "terminal", "fault"] { + let (mut core, slots) = repository_cohort(); + match missing { + "proof" => core.slots[1].edge.facts.resource_proof = false, + "wait" => core.slots[1].edge.facts.waits_known = false, + "status" => core.slots[1].edge.facts.status = None, + "group" => core.slots[1].edge.facts.group_absent = false, + "terminal" => core.slots[1].edge.facts.terminal_eof = false, + _ => core.poison("ORIGINAL_FAULT"), + } + assert!(core.take_repository_results(&slots).is_err()); + assert!(core.slots.iter().all(|slot| !slot.output_taken)); + if missing == "fault" { + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("ORIGINAL_FAULT")) + ); + } + } + } + fn installer_ready() -> Core { + let events = Rc::default(); + let mut core: Core = Core::new(Rc::default(), INSTALL_OPERATION_NS); + core.begin_installer(100_000_000, 2).unwrap(); + for name in ["a", "b"] { + let id = core + .admit_installer(200_000_000, 32, |_, end| { + assert_eq!(end, 1_100_000_000); + let mut edge = fake(name, Rc::clone(&events)); + edge.facts = EdgeFacts { + status: Some(ExitStatus::from_raw(0)), + waits_known: true, + group_absent: true, + terminal_eof: true, + resource_proof: true, + io_required: true, + io: IoFacts { + stdin_closed: true, + stdout_eof: true, + stderr_eof: true, + ..Default::default() + }, + first_fault: None, + }; + Ok(edge) + }) + .unwrap(); + core.slots[id.index].accepted_at = Some(250_000_000); + core.take_result(&id).unwrap(); + } + core + } + #[test] + fn installer_cohort_uses_one_end_in_actual_factory_and_refuses_equality() { + let mut core: Core = Core::new(Rc::default(), INSTALL_OPERATION_NS); + core.begin_installer(100_000_000, 2).unwrap(); + let parent = core.hard_end; + let events = Rc::default(); + core.admit_installer(200_000_000, 1, |_, end| { + assert_eq!(end, 1_100_000_000); + Ok(fake("a", Rc::clone(&events))) + }) + .unwrap(); + let mut called = false; + assert!(core + .admit_installer(1_050_000_000, 1, |_, _| { + called = true; + Ok(fake("b", Rc::clone(&events))) + }) + .is_err()); + assert!(!called); + assert_eq!(core.hard_end, parent); + assert_eq!(core.slots[0].hard_end, 1_100_000_000); + let mut earlier: Core = Core::new(Rc::default(), 350_000_000); + earlier.begin_installer(100_000_000, 1).unwrap(); + assert_eq!(earlier.installer_end().unwrap(), 350_000_000); + } + #[test] + fn installer_borrowed_parent_cannot_grant_more_than_one_local_operation() { + let mut core: Core = Core::new(Rc::default(), 900_000_000_000); + core.begin_installer(100_000_000, 2).unwrap(); + assert_eq!(core.hard_end, 30_100_000_000); + assert_eq!(core.installer_end().unwrap(), 1_100_000_000); + assert!(core.begin_installer(500_000_000, 2).is_err()); + assert_eq!(core.hard_end, 30_100_000_000); + let mut overflow: Core = Core::new(Rc::default(), u64::MAX); + assert!(overflow.begin_installer(u64::MAX - 1, 1).is_err()); + assert_eq!(overflow.cancel_end, Some(0)); + } + #[test] + fn installer_policy_allows_publication_after_four_seconds_without_renewal() { + let mut core = installer_ready(); + core.seal_installer(true, &mut || Ok(300_000_000)).unwrap(); + let original = core.hard_end; + assert!(core + .publication_live(true, &mut || Ok(5_000_000_000)) + .is_ok()); + assert_eq!(original, 30_000_000_000); + assert_eq!(core.hard_end, original); + assert!(core.publication_live(true, &mut || Ok(original)).is_err()); + assert_eq!(core.hard_end, original); + } + #[test] + fn installer_policy_keeps_earlier_four_second_parent_and_one_second_preflight() { + let mut core: Core = Core::new(Rc::default(), 4_000_000_000); + core.begin_installer(100_000_000, 2).unwrap(); + assert_eq!(core.hard_end, 4_000_000_000); + assert_eq!(core.installer_end().unwrap(), 1_100_000_000); + assert!(core.begin_installer(200_000_000, 2).is_err()); + assert_eq!(core.hard_end, 4_000_000_000); + } + #[test] + fn installer_cohort_expiry_broadcasts_all_before_poll_and_keeps_first_fault() { + let events = Rc::default(); + let mut core: Core = Core::new(Rc::default(), INSTALL_OPERATION_NS); + core.begin_installer(0, 2).unwrap(); + for name in ["a", "b"] { + core.admit_installer(100_000_000, 0, |_, _| { + let mut edge = fake(name, Rc::clone(&events)); + edge.fail_begin = name == "a"; + Ok(edge) + }) + .unwrap(); + } + core.poll(&mut || Ok(950_000_000)); + assert_eq!(&events.borrow()[..2], ["begin:a", "begin:b"]); + assert!(core + .slots + .iter() + .all(|slot| slot.completion_end.unwrap() <= 1_000_000_000)); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_OPERATION_DEADLINE")) + ); + core.cancel(Some("LATER"), 970_000_000, 4_000_000_000); + assert!(core.cancel_end.unwrap() <= 1_000_000_000); + core.poll(&mut || Err(error("clock"))); + assert_eq!(core.cancel_end, Some(0)); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_OPERATION_DEADLINE")) + ); + } + #[test] + fn installer_barrier_requires_every_physical_fact_and_retrieved_result() { + for missing in 0..13 { + let mut core = installer_ready(); + let slot = &mut core.slots[1]; + match missing { + 0 => slot.edge.facts.waits_known = false, + 1 => slot.edge.facts.resource_proof = false, + 2 => slot.edge.facts.group_absent = false, + 3 => slot.edge.facts.terminal_eof = false, + 4 => slot.edge.facts.io.stdin_closed = false, + 5 => slot.edge.facts.io.stdout_eof = false, + 6 => slot.edge.facts.io.stderr_eof = false, + 7 => slot.edge.facts.status = None, + 8 => slot.edge.facts.first_fault = Some("synthetic"), + 9 => slot.edge.facts.io.first_fault = Some("synthetic"), + 10 => slot.accepted_at = None, + 11 => slot.output_taken = false, + _ => slot.accepted_at = Some(slot.hard_end), + } + assert!( + core.seal_installer(true, &mut || Ok(300_000_000)).is_err(), + "missing {missing}" + ); + assert_eq!(core.slots.len(), 2); + assert_eq!(core.io_reserved, 64); + assert!(!core.finish_called); + assert!(core.owner.borrow().first_fault.is_some()); + } + } + #[test] + fn installer_barrier_checks_attached_sent_ledger_even_with_empty_local_map() { + let (wire, _peer) = UnixStream::pair().unwrap(); + let mut endpoint = Endpoint::new(wire, "ab".repeat(16), None).unwrap(); + endpoint.send_live().unwrap(); + let root = std::process::id(); + let child = if root == 42 { 43 } else { 42 }; + endpoint + .metadata(&format!("REGISTER|{root}|{child}|{}|0", "cd".repeat(16))) + .unwrap(); + let mut scope = Scope::with_owner(Rc::default(), now().unwrap() + INSTALL_OPERATION_NS); + scope.upstream = Some(endpoint); + assert!(scope.ledger.is_empty()); + assert!(!scope.ledgers_complete()); + let mut core = installer_ready(); + assert!(core + .seal_installer(scope.ledgers_complete(), &mut || Ok(300_000_000)) + .is_err()); + } + #[test] + fn installer_barrier_is_fresh_nonterminal_and_never_reopens_a_runner() { + let mut late = installer_ready(); + assert!(late + .seal_installer(true, &mut || Ok(1_100_000_000)) + .is_err()); + let mut broken = installer_ready(); + assert!(broken + .seal_installer(true, &mut || Err(error("clock"))) + .is_err()); + assert_eq!(broken.cancel_end, Some(0)); + assert!(broken + .seal_installer(true, &mut || Ok(300_000_000)) + .is_err()); + let mut core = installer_ready(); + core.seal_installer(true, &mut || Ok(300_000_000)).unwrap(); + assert_eq!(core.hard_end, INSTALL_OPERATION_NS); + assert!(!core.finish_called && !core.finished && !core.owner.borrow().admission_closed); + assert_eq!(core.slots.len(), 2); + assert_eq!(core.io_reserved, 64); + core.poll(&mut || Ok(1_500_000_000)); + core.publication_live(true, &mut || Ok(1_500_000_000)) + .unwrap(); + assert!(core + .admit_installer(1_500_000_000, 0, |_, _| panic!("postseal spawn")) + .is_err()); + assert!(core.begin_installer(1_500_000_000, 1).is_err()); + } + #[test] + fn installer_entry_refinement_never_renews_reselects_or_reopens() { + let mut late: Core = Core::new(Rc::default(), 4_100_000_000); + assert!(late.refine_entry(1_100_000_000, 1_100_000_000).is_err()); + assert!(late.refine_entry(4_100_000_000, 1_100_000_000).is_err()); + assert_eq!(late.hard_end, 1_100_000_000); + let mut earlier: Core = Core::new(Rc::default(), 300_000_000); + earlier.refine_entry(4_100_000_000, 100_000_000).unwrap(); + assert_eq!(earlier.hard_end, 300_000_000); + assert!(earlier.refine_entry(4_100_000_000, 100_000_001).is_err()); + assert!(earlier.owner.borrow().admission_closed); + } + #[test] + fn installer_terminal_rechecks_after_an_earlier_clean_finish() { + let mut core = installer_ready(); + core.seal_installer(true, &mut || Ok(300_000_000)).unwrap(); + core.finish_with(&mut || Ok(INSTALL_OPERATION_NS - 60_000_000), &mut || { + panic!("no wait") + }); + assert!(core.finished && core.owner.borrow().first_fault.is_none()); + assert!(!core.terminal_fresh(&mut || Ok(INSTALL_OPERATION_NS))); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_TERMINAL_DEADLINE")) + ); + let mut clock = installer_ready(); + clock.seal_installer(true, &mut || Ok(300_000_000)).unwrap(); + clock.finish_with(&mut || Ok(400_000_000), &mut || panic!("no wait")); + assert!(!clock.terminal_fresh(&mut || Err(error("clock")))); + assert_eq!(clock.cancel_end, Some(0)); + assert!(!clock.terminal_fresh(&mut || Ok(400_000_001))); + } + #[test] + fn normal_completion_retains_a_then_admits_b_in_same_owner() { + let events: Rc>> = Rc::default(); + let owner: SharedOwner = Rc::default(); + let mut core = Core::new(owner.clone(), 500_000_000); + let a = core.admit(1, 1, |_| Ok(fake("a", events.clone()))).unwrap(); + core.request_complete(&a, 2).unwrap(); + core.poll(&mut || Ok(3)); + assert!(core.slots[0].accepted_at.is_some()); + assert!( + !owner.borrow().admission_closed, + "local completion closed containing owner" + ); + let b = core.admit(4, 1, |_| Ok(fake("b", events.clone()))).unwrap(); + assert_eq!(a.index, 0); + assert_eq!(b.index, 1); + assert_eq!(core.slots.len(), 2); + core.request_complete(&b, 5).unwrap(); + core.poll(&mut || Ok(6)); + assert!(core.all_resources()); + assert!(owner.borrow().first_fault.is_none()); + } + #[test] + fn cancellation_broadcasts_every_begin_before_poll_despite_first_begin_error() { + let events: Rc>> = Rc::default(); + let mut core = Core::new(Rc::default(), 500_000_000); + core.admit(1, 1, |_| { + let mut a = fake("a", events.clone()); + a.fail_begin = true; + Ok(a) + }) + .unwrap(); + core.admit(1, 1, |_| Ok(fake("b", events.clone()))).unwrap(); + core.cancel(Some("ORIGINAL"), 2, 500_000_000); + core.poll(&mut || Ok(3)); + assert_eq!( + &events.borrow()[..4], + ["begin:a", "begin:b", "poll:a", "poll:b"] + ); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("ORIGINAL")) + ); + assert!(core.all_resources()); + assert!(core.admit(4, 1, |_| Ok(fake("c", events.clone()))).is_err()); + } + #[test] + fn direct_exit_and_group_proof_do_not_replace_either_output_eof() { + let events: Rc>> = Rc::default(); + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core + .admit(1, 1, |_| { + let mut a = fake("a", events); + a.facts.io_required = true; + Ok(a) + }) + .unwrap(); + core.request_complete(&id, 2).unwrap(); + core.poll(&mut || Ok(3)); + assert!(core.slots[0].edge.facts().waits_known); + assert!(!core.all_resources()); + core.slots[0].edge.facts.io.stdin_closed = true; + core.slots[0].edge.facts.io.stdout_eof = true; + core.poll(&mut || Ok(4)); + assert!(!core.all_resources()); + core.slots[0].edge.facts.io.stderr_eof = true; + core.poll(&mut || Ok(5)); + assert!(core.all_resources()); + } + #[test] + fn proof_equality_never_accepts_and_repeated_cancel_never_extends() { + let events: Rc>> = Rc::default(); + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core.admit(1, 1, |_| Ok(fake("a", events))).unwrap(); + core.request_complete(&id, 2).unwrap(); + let end = core.slots[0].completion_end.unwrap(); + core.poll(&mut || Ok(end)); + assert!(!core.all_resources()); + assert!(core.owner.borrow().first_fault.is_some()); + let bound = core.cancel_end; + core.cancel(None, 100_000_000, 500_000_000); + assert_eq!(core.cancel_end, bound); + } + #[test] + fn slot_identity_and_whole_scope_buffer_budget_are_not_recycled() { + let events: Rc>> = Rc::default(); + let mut a = Core::new(Rc::default(), 500_000_000); + let mut b: Core = Core::new(Rc::default(), 500_000_000); + let id = a + .admit(1, MAX_IO_BYTES, |_| Ok(fake("a", events.clone()))) + .unwrap(); + assert!(b.index(&id).is_err()); + a.request_complete(&id, 2).unwrap(); + a.poll(&mut || Ok(3)); + assert!(a.admit(4, 1, |_| Ok(fake("b", events.clone()))).is_err()); + assert_eq!(a.slots.len(), 1); + assert_eq!(a.io_reserved, MAX_IO_BYTES); + } + #[test] + fn a_valid_zero_clock_is_not_replaced_with_a_clock_failure() { + let events: Rc>> = Rc::default(); + let mut core = Core::new(Rc::default(), 500_000_000); + core.admit(0, 1, |_| { + let mut a = fake("a", events); + a.facts.status = Some(ExitStatus::from_raw(0)); + Ok(a) + }) + .unwrap(); + core.poll(&mut || Ok(0)); + core.poll(&mut || Ok(0)); + assert_eq!(core.slots[0].accepted_at, Some(0)); + assert!(core.owner.borrow().first_fault.is_none()); + } + #[test] + fn final_finish_requires_a_fresh_strictly_before_bound_clock_even_if_empty() { + let mut core: Core = Core::new(Rc::default(), 500_000_000); + core.cancel(None, 2, 500_000_000); + assert!(core.all_resources()); + assert!(core.finish_at(core.cancel_end.unwrap())); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_CLEANUP_DEADLINE")) + ); + } + #[test] + fn result_is_single_use_and_failed_operation_never_returns_output() { + let events: Rc>> = Rc::default(); + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core.admit(1, 1, |_| Ok(fake("a", events))).unwrap(); + core.request_complete(&id, 2).unwrap(); + core.poll(&mut || Ok(3)); + assert!(core.take_result(&id).unwrap().status.success()); + assert!(core.take_result(&id).is_err()); + assert_eq!(core.slots.len(), 1); + assert!(core.slots[0].accepted_at.is_some()); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_RESULT")) + ); + } + #[test] + fn r38_final_finish_clock_error_irreversibly_zeroes_all_pending_ends() { + for (empty, prior_fault) in [(false, false), (false, true), (true, false)] { + let events: Rc>> = Rc::default(); + let mut core: Core = Core::new(Rc::default(), 500_000_000); + if !empty { + let accepted = core + .admit(1, 0, |_| Ok(fake("accepted", events.clone()))) + .unwrap(); + core.request_complete(&accepted, 2).unwrap(); + core.poll(&mut || Ok(3)); + assert!(core.slots[0].accepted_at.is_some()); + core.admit(4, 0, |_| { + let mut pending = fake("pending", events.clone()); + pending.facts.io_required = true; + Ok(pending) + }) + .unwrap(); + } + if prior_fault { + core.poison("ORIGINAL"); + } + events.borrow_mut().clear(); + let mut calls = 0; + core.finish_with( + &mut || { + calls += 1; + match calls { + 1 => Ok(100), + 2 => Ok(101), + 3 => Err(error("SCOPE_CLOCK")), + _ => Ok(200), + } + }, + &mut || panic!("final failed clock must end this envelope"), + ); + assert_eq!(calls, 3); + assert_eq!( + core.cancel_end, + Some(0), + "final clock failure retained a positive end" + ); + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError(if prior_fault { + "ORIGINAL" + } else { + "SCOPE_CLOCK" + })) + ); + assert!(core.finished); + assert!(core.finish_called); + if !empty { + assert!(core.slots[0].accepted_at.is_some()); + assert!(core.slots[1].accepted_at.is_none()); + assert_eq!(core.slots[1].completion_end, Some(0)); + assert_eq!(core.slots[1].edge.begin_ends, [50_000_100, 0]); + assert_eq!( + &*events.borrow(), + &["begin:pending", "poll:pending", "begin:pending"] + ); + } + let before = events.borrow().clone(); + core.cancel(None, 200, 500_000_000); + core.finish_with(&mut || Ok(201), &mut || { + panic!("finished failure cannot restart") + }); + assert_eq!(core.cancel_end, Some(0)); + assert_eq!(*events.borrow(), before); + } + } + #[test] + fn r38_ninth_slot_is_polled_on_next_round_robin_turn() { + let events: Rc>> = Rc::default(); + let mut core = Core::new(Rc::default(), 500_000_000); + for name in ["0", "1", "2", "3", "4", "5", "6", "7", "8"] { + core.admit(1, 0, |_| Ok(fake(name, events.clone()))) + .unwrap(); + } + core.poll(&mut || Ok(2)); + assert_eq!( + &*events.borrow(), + &["poll:0", "poll:1", "poll:2", "poll:3", "poll:4", "poll:5", "poll:6", "poll:7",] + ); + core.poll(&mut || Ok(3)); + assert_eq!(events.borrow()[8], "poll:8"); + assert_eq!(events.borrow().len(), 16); + assert_eq!(core.slots.len(), 9); + } + #[test] + fn r40_leaf_environment_preserves_routing_but_removes_parent_control() { + let mut command = Command::new("inert-never-execute"); + command + .arg("--version") + .env("OPENAI_BASE_URL", "https://proxy.invalid") + .env("CODEX_HOME", "/private/owned-profile") + .env("KEITO_CAPTURE_ACK_FD", "3") + .env("KEITO_PROCESS_OWNER_NONCE", "parent"); + clear_parent_environment(&mut command); + let env: std::collections::BTreeMap<_, _> = command.get_envs().collect(); + assert_eq!( + env[std::ffi::OsStr::new("OPENAI_BASE_URL")], + Some(std::ffi::OsStr::new("https://proxy.invalid")) + ); + assert_eq!( + env[std::ffi::OsStr::new("CODEX_HOME")], + Some(std::ffi::OsStr::new("/private/owned-profile")) + ); + assert_eq!(env[std::ffi::OsStr::new("KEITO_CAPTURE_ACK_FD")], None); + assert_eq!(env[std::ffi::OsStr::new("KEITO_PROCESS_OWNER_NONCE")], None); + assert_eq!( + command.get_args().collect::>(), + [std::ffi::OsStr::new("--version")] + ); + } + #[test] + #[cfg(feature = "capture-profile")] + fn repository_wait_profile_classifies_retained_stages_without_progress_or_proof() { + use crate::capture_profile::Phase; + for (first, second, expected) in [ + ( + Some(Phase::RepoRunningPoll), + Some(Phase::RepoRunningPoll), + Phase::RepoRunningWait, + ), + ( + Some(Phase::RepoCleaningPoll), + Some(Phase::RepoDonePoll), + Phase::RepoCleaningWait, + ), + ( + Some(Phase::RepoRunningPoll), + Some(Phase::RepoCleaningPoll), + Phase::RepoMixedWait, + ), + ( + Some(Phase::RepoParkPoll), + Some(Phase::RepoRunningPoll), + Phase::RepoMixedWait, + ), + (None, None, Phase::RepoUnknownWait), + (None, Some(Phase::RepoRunningPoll), Phase::RepoMixedWait), + ] { + let events = Rc::new(RefCell::new(Vec::new())); + let mut core = Core::new(Rc::default(), 500_000_000); + let a = core.admit(1, 0, |_| Ok(fake("a", events.clone()))).unwrap(); + let b = core.admit(2, 0, |_| Ok(fake("b", events.clone()))).unwrap(); + core.slots[a.index].edge.repository_stage = first; + core.slots[b.index].edge.repository_stage = second; + let cursor = core.cursor; + assert_eq!(core.repository_wait_phase() as usize, expected as usize); + assert_eq!(core.cursor, cursor); + assert_eq!(core.hard_end, 500_000_000); + assert!(core.cancel_end.is_none()); + assert!(events.borrow().is_empty()); + assert!(core.slots.iter().all(|slot| slot.accepted_at.is_none() + && !slot.output_taken + && !slot.edge.facts().resources_complete())); + } + } + #[test] + #[cfg(feature = "capture-profile")] + fn repository_wait_profile_ignores_accepted_slots_without_consuming_them() { + use crate::capture_profile::Phase; + let mut core = Core::new(Rc::default(), 500_000_000); + assert_eq!( + core.repository_wait_phase() as usize, + Phase::RepoUnknownWait as usize + ); + let a = core.admit(1, 0, |_| Ok(fake("a", Rc::default()))).unwrap(); + let b = core.admit(2, 0, |_| Ok(fake("b", Rc::default()))).unwrap(); + core.slots[a.index].edge.repository_stage = Some(Phase::RepoRunningPoll); + core.slots[a.index].accepted_at = Some(3); + core.slots[b.index].edge.repository_stage = Some(Phase::RepoDonePoll); + assert_eq!( + core.repository_wait_phase() as usize, + Phase::RepoCleaningWait as usize + ); + assert_eq!(core.slots[a.index].accepted_at, Some(3)); + assert!(!core.slots[a.index].output_taken); + assert!(core.slots[b.index].accepted_at.is_none()); + } + #[test] + #[cfg(feature = "capture-profile")] + fn repository_wait_profile_keeps_one_original_pause_and_withholds_unproved_output() { + use crate::capture_profile::Phase; + for stage in [ + Phase::RepoRunningPoll, + Phase::RepoCleaningPoll, + Phase::RepoDonePoll, + ] { + let mut core = Core::new(Rc::default(), 500_000_000); + let slot = core + .admit(1, 0, |_| Ok(fake("retained", Rc::default()))) + .unwrap(); + core.slots[slot.index].edge.repository_stage = Some(stage); + let mut pauses = 0; + core.wait_command_progress( + &mut || Ok(10_000_000), + &mut |_, _| panic!("original sleep path became fd poll"), + &mut || pauses += 1, + ) + .unwrap(); + assert_eq!(pauses, 1); + assert!(core.slots[slot.index].accepted_at.is_none()); + assert!(!core.slots[slot.index].output_taken); + assert!(!core.slots[slot.index].edge.facts().resources_complete()); + assert_eq!(core.hard_end, 500_000_000); + assert!(core.cancel_end.is_none()); + } + } + fn running_wait_core(events: Rc>>) -> (Core, SlotId) { + let mut core = Core::new(Rc::default(), 500_000_000); + let id = core.admit(1, 0, |_| Ok(fake("waiting", events))).unwrap(); + core.slots[id.index].edge.progress_sources = vec![(7, libc::POLLIN)]; + core.slots[id.index].edge.progress_end = Some(400_000_000); + (core, id) + } + #[test] + fn running_wait_retained_socket_readiness_schedules_original_turn_before_blind_pause() { + use std::cell::Cell; + // Old blind branch advances1ms, missing the original200us boundary. + let at = Cell::new(100_000_000u64); + let events = Rc::new(RefCell::new(Vec::new())); + let (mut core, id) = running_wait_core(events.clone()); + let pauses = Cell::new(0); + core.wait_command_progress( + &mut || Ok(at.get()), + &mut |fds, timeout| { + assert_eq!(timeout, 1); + assert_eq!(fds[0].fd, 7); + at.set(100_100_000); + fds[0].revents = libc::POLLIN | libc::POLLHUP; + Ok(1) + }, + &mut || { + pauses.set(pauses.get() + 1); + at.set(at.get() + 1_000_000); + }, + ) + .unwrap(); + assert_eq!(pauses.get(), 0); + assert!( + at.get() < 100_200_000, + "blind pause postponed original GONE/EOF parser turn" + ); + assert!(events.borrow().is_empty()); + core.poll(&mut || Ok(at.get())); + assert_eq!(events.borrow().as_slice(), ["poll:waiting"]); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + assert!(!core.slots[id.index].edge.facts().resources_complete()); + } + #[test] + fn running_wait_caps_to_earliest_original_end_and_floors_final_fraction() { + for (slot_end, completion_end, edge_end, at, expected) in [ + (500_000_000, None, 400_000_000, 100_000_000, 1), + (100_900_000, None, 400_000_000, 100_000_000, 0), + (500_000_000, Some(100_700_000), 400_000_000, 100_000_000, 0), + (500_000_000, None, 100_999_999, 100_000_000, 0), + (500_000_000, None, 500_000_000, 449_500_000, 0), + ] { + let (mut core, id) = running_wait_core(Rc::default()); + core.slots[id.index].hard_end = slot_end; + core.slots[id.index].completion_end = completion_end; + core.slots[id.index].edge.progress_end = Some(edge_end); + let mut polls = 0; + core.wait_command_progress( + &mut || Ok(at), + &mut |_, timeout| { + polls += 1; + assert_eq!(timeout, expected); + Ok(0) + }, + &mut || panic!("useful retainedFD became blind pause"), + ) + .unwrap(); + assert_eq!(polls, 1); + assert_eq!(core.slots[id.index].hard_end, slot_end); + assert_eq!(core.slots[id.index].completion_end, completion_end); + assert!(core.slots[id.index].accepted_at.is_none()); + } + } + #[test] + fn running_wait_buffered_frame_schedules_parser_but_partial_without_fd_keeps_pause() { + for (buffered, expected_pauses) in [(true, 0), (false, 1)] { + let (mut core, id) = running_wait_core(Rc::default()); + // No usefulFD after actual EOF, or partial bytes without anFD. + core.slots[id.index].edge.progress_sources.clear(); + core.slots[id.index].edge.progress_buffered = buffered; + let mut pauses = 0; + core.wait_command_progress( + &mut || Ok(100_000_000), + &mut |_, _| panic!("no useful source was polled"), + &mut || pauses += 1, + ) + .unwrap(); + assert_eq!(pauses, expected_pauses); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].edge.facts().waits_known); + } + } + #[test] + fn running_wait_no_fd_final_fraction_does_not_sleep_past_earliest_end() { + let (mut core, id) = running_wait_core(Rc::default()); + core.slots[id.index].edge.progress_sources.clear(); + core.slots[id.index].completion_end = Some(100_999_999); + core.wait_command_progress( + &mut || Ok(100_000_000), + &mut |_, _| panic!("absentFD poll"), + &mut || panic!("final fraction rounded up"), + ) + .unwrap(); + assert!(core.slots[id.index].accepted_at.is_none()); + } + #[test] + fn running_wait_invalid_fd_clock_and_expiry_refuse_before_poll() { + for kind in ["invalid", "clock", "completion", "operation"] { + let (mut core, id) = running_wait_core(Rc::default()); + if kind == "invalid" { + core.slots[id.index].edge.progress_sources[0].0 = -1; + } + if kind == "completion" { + core.slots[id.index].completion_end = Some(100_000_000); + } + let mut polls = 0; + let mut pauses = 0; + let result = core.wait_command_progress( + &mut || { + if kind == "clock" { + Err(error("INJECTED_CLOCK")) + } else if kind == "operation" { + Ok(450_000_000) + } else { + Ok(100_000_000) + } + }, + &mut |_, _| { + polls += 1; + Ok(0) + }, + &mut || pauses += 1, + ); + assert!(result.is_err()); + assert_eq!((polls, pauses), (0, 0)); + assert!(core.owner.borrow().first_fault.is_some()); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + if kind == "clock" { + assert_eq!(core.cancel_end, Some(0)); + assert_eq!(core.slots[id.index].completion_end, Some(0)); + } + } + } + #[test] + fn running_wait_eintr_hup_timeout_are_not_proof_and_poll_faults_stick() { + for kind in ["eintr", "hup", "timeout", "nval", "negative", "error"] { + let (mut core, id) = running_wait_core(Rc::default()); + let result = core.wait_command_progress( + &mut || Ok(100_000_000), + &mut |fds, _| match kind { + "eintr" => Err(io::Error::from(io::ErrorKind::Interrupted)), + "hup" => { + fds[0].revents = libc::POLLHUP; + Ok(1) + } + "nval" => { + fds[0].revents = libc::POLLNVAL; + Ok(1) + } + "negative" => Ok(-1), + "error" => Err(io::Error::from(io::ErrorKind::Other)), + _ => Ok(0), + }, + &mut || panic!("unexpected blind pause"), + ); + assert_eq!( + result.is_err(), + matches!(kind, "nval" | "negative" | "error") + ); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].edge.facts().waits_known); + assert!(!core.slots[id.index].edge.facts().terminal_eof); + assert!(!core.slots[id.index].output_taken); + } + } + #[test] + fn running_wait_rechecks_original_end_and_owner_after_wakeup() { + use std::cell::Cell; + for fault in [false, true] { + let (mut core, id) = running_wait_core(Rc::default()); + core.slots[id.index].completion_end = Some(100_500_000); + let owner = core.owner.clone(); + let at = Cell::new(100_000_000); + let result = core.wait_command_progress( + &mut || Ok(at.get()), + &mut |_, _| { + if fault { + owner.borrow_mut().poison(ProtocolError("ORIGINAL_FAULT")); + } else { + at.set(100_500_000); + } + Ok(1) + }, + &mut || panic!("unexpected blind pause"), + ); + assert!(result.is_err()); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + if fault { + assert_eq!( + core.owner.borrow().first_fault, + Some(ProtocolError("ORIGINAL_FAULT")) + ); + } else { + assert_eq!(core.cancel_end, Some(150_500_000)); + assert_eq!(core.slots[id.index].completion_end, Some(100_500_000)); + } + } + } + #[test] + fn running_wait_local_expiry_preserves_sibling_cleanup_envelope() { + use std::cell::Cell; + for expired_before_wait in [true, false] { + let (mut core, expired) = running_wait_core(Rc::default()); + let sibling = core + .admit(2, 0, |_| Ok(fake("sibling", Rc::default()))) + .unwrap(); + core.request_complete(&expired, 100_000_000).unwrap(); + core.slots[expired.index].edge.progress_end = Some(150_000_000); + let at = Cell::new(if expired_before_wait { + 150_000_000 + } else { + 149_000_000 + }); + let mut polls = 0; + let result = core.wait_command_progress( + &mut || Ok(at.get()), + &mut |_, _| { + polls += 1; + at.set(150_000_000); + Ok(0) + }, + &mut || panic!("retained source became blind pause"), + ); + assert!(result.is_err()); + assert_eq!(polls, usize::from(!expired_before_wait)); + assert_eq!(core.cancel_end, Some(200_000_000)); + assert_eq!(core.slots[expired.index].completion_end, Some(150_000_000)); + assert_eq!(core.slots[sibling.index].completion_end, Some(200_000_000)); + assert_eq!( + core.slots[expired.index].edge.begin_ends, + [150_000_000, 150_000_000] + ); + assert_eq!(core.slots[sibling.index].edge.begin_ends, [200_000_000]); + assert!(core + .slots + .iter() + .all(|slot| slot.accepted_at.is_none() && !slot.output_taken)); + } + } + #[test] + fn running_wait_does_not_reset_cursor_or_release_a_partial_repository_cohort() { + let events = Rc::new(RefCell::new(Vec::new())); + let mut core = Core::new(Rc::default(), 500_000_000); + let mut ids = Vec::new(); + for _ in 0..9 { + ids.push( + core.admit(1, 0, |_| Ok(fake("slot", events.clone()))) + .unwrap(), + ); + } + core.cursor = 8; + core.slots[8].edge.progress_sources = vec![(7, libc::POLLIN)]; + core.wait_command_progress(&mut || Ok(100_000_000), &mut |_, _| Ok(1), &mut || { + panic!("blind pause") + }) + .unwrap(); + assert_eq!(core.cursor, 8); + assert!(events.borrow().is_empty()); + core.poll(&mut || Ok(100_000_000)); + assert_eq!(events.borrow().len(), SLOTS_PER_TURN); + assert_eq!(core.cursor, 7); + assert!(core + .take_repository_results(&[ids[0].clone(), ids[8].clone()]) + .unwrap() + .is_none()); + assert!(core + .slots + .iter() + .all(|slot| slot.accepted_at.is_none() && !slot.output_taken)); + } + #[test] + fn running_wait_upstream_budget_defers_wait_for_original_cancel_pump() { + use super::super::protocol::{PollWork, MAX_PARSE, MAX_READS}; + for (reads, parsed, expected) in [ + (MAX_READS, 0, 0), + (0, MAX_PARSE, 0), + (MAX_READS - 1, MAX_PARSE - 1, 1), + ] { + let work = PollWork { reads, parsed }; + let mut waits = 0; + wait_with_upstream_budget(Some(&work), || { + waits += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(waits, expected); + } + let mut waits = 0; + wait_with_upstream_budget(None, || { + waits += 1; + Err(error("ORIGINAL_WAIT")) + }) + .unwrap_err(); + assert_eq!(waits, 1); + } + + #[test] + fn running_wait_ready_sibling_does_not_release_previously_accepted_cohort_output() { + let (mut core, pending) = running_wait_core(Rc::default()); + let accepted = core + .admit(2, 0, |_| Ok(fake("accepted", Rc::default()))) + .unwrap(); + core.slots[accepted.index].accepted_at = Some(3); + core.slots[accepted.index].edge.facts = EdgeFacts { + status: Some(ExitStatus::from_raw(0)), + waits_known: true, + group_absent: true, + terminal_eof: true, + resource_proof: true, + ..Default::default() + }; + core.wait_command_progress( + &mut || Ok(100_000_000), + &mut |fds, _| { + fds[0].revents = libc::POLLIN; + Ok(1) + }, + &mut || panic!("blind pause"), + ) + .unwrap(); + assert!(core + .take_repository_results(&[accepted.clone(), pending.clone()]) + .unwrap() + .is_none()); + assert_eq!(core.slots[accepted.index].accepted_at, Some(3)); + assert!(!core.slots[accepted.index].output_taken); + assert!(core.slots[pending.index].accepted_at.is_none()); + assert!(!core.slots[pending.index].output_taken); + } + #[test] + fn running_wait_clock_failure_after_wakeup_broadcasts_zero_without_proof() { + use std::cell::Cell; + let (mut core, id) = running_wait_core(Rc::default()); + let reads = Cell::new(0); + assert!(core + .wait_command_progress( + &mut || { + reads.set(reads.get() + 1); + if reads.get() == 1 { + Ok(100_000_000) + } else { + Err(error("INJECTED_CLOCK")) + } + }, + &mut |_, _| Ok(1), + &mut || panic!("blind pause") + ) + .is_err()); + assert_eq!(core.cancel_end, Some(0)); + assert_eq!(core.slots[id.index].completion_end, Some(0)); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + } + #[test] + fn guard_ack_socket_readiness_returns_to_original_poll_without_proof_or_pause() { + use std::cell::Cell; + let events = Rc::new(RefCell::new(Vec::new())); + let (mut core, id) = running_wait_core(events.clone()); + let at = Cell::new(100_000_000u64); + let original_cursor = core.cursor; + core.wait_progress_with_external( + &mut || Ok(at.get()), + &mut |fds, timeout| { + assert_eq!(timeout, 1); + assert_eq!( + fds.iter().map(|fd| (fd.fd, fd.events)).collect::>(), + [(8, libc::POLLIN), (7, libc::POLLIN)] + ); + fds[0].revents = libc::POLLIN | libc::POLLHUP; + at.set(100_100_000); + Ok(1) + }, + &mut || panic!("ready ACK became blind pause"), + Some(8), + &mut || Some(std::time::Duration::from_millis(1)), + ) + .unwrap(); + assert!(events.borrow().is_empty()); + assert_eq!(core.cursor, original_cursor); + assert!(at.get() < 100_200_000); + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].edge.facts().resources_complete()); + assert!(!core.slots[id.index].output_taken); + core.poll(&mut || Ok(at.get())); + assert_eq!(events.borrow().as_slice(), ["poll:waiting"]); + assert!(core.slots[id.index].accepted_at.is_none()); + } + #[test] + fn guard_original_remaining_limit_never_creates_a_new_owner_or_cleanup_end() { + for limit in [ + None, + Some(std::time::Duration::ZERO), + Some(std::time::Duration::from_micros(250)), + Some(std::time::Duration::from_millis(1)), + ] { + let (mut core, id) = running_wait_core(Rc::default()); + let original_end = core.hard_end; + let mut polls = 0; + core.wait_progress_with_external( + &mut || Ok(100_000_000), + &mut |_, timeout| { + polls += 1; + assert_eq!( + timeout, + if limit.unwrap().as_millis() == 0 { + 0 + } else { + 1 + } + ); + Ok(0) + }, + &mut || panic!("ACK fd unexpectedly slept"), + Some(8), + &mut || limit, + ) + .unwrap(); + assert_eq!( + polls, + usize::from(limit.is_some_and(|value| !value.is_zero())) + ); + assert_eq!(core.hard_end, original_end); + assert!(core.cancel_end.is_none()); + assert!(core.slots[id.index].completion_end.is_none()); + assert!(core.slots[id.index].accepted_at.is_none()); + } + } + #[test] + fn guard_local_wait_expiry_keeps_original_sibling_cleanup_allowance() { + use std::cell::Cell; + let mut core = Core::new(Rc::default(), 600_000_000); + let a = core.admit(1, 0, |_| Ok(fake("a", Rc::default()))).unwrap(); + let b = core.admit(2, 0, |_| Ok(fake("b", Rc::default()))).unwrap(); + core.slots[a.index].completion_end = Some(150_000_000); + core.slots[b.index].completion_end = Some(200_000_000); + let at = Cell::new(149_500_000); + assert!(core + .wait_progress_with_external( + &mut || Ok(at.get()), + &mut |_, timeout| { + assert_eq!(timeout, 0); + at.set(150_000_000); + Ok(1) + }, + &mut || panic!("blind pause"), + Some(8), + &mut || Some(std::time::Duration::from_millis(1)) + ) + .is_err()); + assert_eq!(core.slots[a.index].completion_end, Some(150_000_000)); + assert_eq!(core.slots[b.index].completion_end, Some(200_000_000)); + assert_eq!(core.hard_end, 600_000_000); + assert!(core + .slots + .iter() + .all(|slot| slot.accepted_at.is_none() && !slot.output_taken)); + } + #[test] + fn guard_known_ack_and_protocol_eof_leave_only_original_child_wait_cadence() { + for remaining in [ + std::time::Duration::from_millis(1), + std::time::Duration::from_micros(500), + ] { + let (mut core, id) = running_wait_core(Rc::default()); + core.slots[id.index].edge.progress_sources.clear(); + let mut pauses = 0; + core.wait_progress_with_external( + &mut || Ok(100_000_000), + &mut |_, _| panic!("consumed EOF fd was polled"), + &mut || pauses += 1, + None, + &mut || Some(remaining), + ) + .unwrap(); + assert_eq!(pauses, usize::from(remaining.as_millis() != 0)); + assert!(!core.slots[id.index].edge.facts().waits_known); + assert!(core.slots[id.index].accepted_at.is_none()); + } + } + #[test] + fn guard_external_poll_faults_refuse_and_wakeup_states_are_never_acceptance() { + for kind in [ + "invalid", "clock", "nval", "error", "eintr", "hup", "timeout", + ] { + let (mut core, id) = running_wait_core(Rc::default()); + let mut polls = 0; + let result = core.wait_progress_with_external( + &mut || { + if kind == "clock" { + Err(error("INERT_CLOCK")) + } else { + Ok(100_000_000) + } + }, + &mut |fds, _| { + polls += 1; + match kind { + "nval" => { + fds[0].revents = libc::POLLNVAL; + Ok(1) + } + "error" => Err(io::Error::from(io::ErrorKind::Other)), + "eintr" => Err(io::Error::from(io::ErrorKind::Interrupted)), + "hup" => { + fds[0].revents = libc::POLLHUP; + Ok(1) + } + _ => Ok(0), + } + }, + &mut || panic!("unexpected blind pause"), + Some(if kind == "invalid" { -1 } else { 8 }), + &mut || Some(std::time::Duration::from_millis(1)), + ); + assert_eq!( + result.is_err(), + matches!(kind, "invalid" | "clock" | "nval" | "error") + ); + if matches!(kind, "invalid" | "clock") { + assert_eq!(polls, 0); + } + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].edge.facts().resources_complete()); + assert!(!core.slots[id.index].output_taken); + } + } + #[test] + fn guard_buffered_child_metadata_and_upstream_budget_yield_to_original_pump() { + use super::super::protocol::{PollWork, MAX_PARSE, MAX_READS}; + let (mut core, id) = running_wait_core(Rc::default()); + core.slots[id.index].edge.progress_buffered = true; + core.wait_progress_with_external( + &mut || Ok(100_000_000), + &mut |_, _| panic!("buffered metadata waited"), + &mut || panic!("buffered metadata slept"), + Some(8), + &mut || Some(std::time::Duration::from_millis(1)), + ) + .unwrap(); + for work in [ + PollWork { + reads: MAX_READS, + parsed: 0, + }, + PollWork { + reads: 0, + parsed: MAX_PARSE, + }, + ] { + wait_with_upstream_budget(Some(&work), || { + panic!("exhausted upstream budget entered another wait") + }) + .unwrap(); + } + assert!(core.slots[id.index].accepted_at.is_none()); + assert!(!core.slots[id.index].output_taken); + } +} diff --git a/src/process_ownership/signals.rs b/src/process_ownership/signals.rs new file mode 100644 index 0000000..b68098d --- /dev/null +++ b/src/process_ownership/signals.rs @@ -0,0 +1,81 @@ +//! Entry-thread cancellation. Handlers only latch an atomic; they never own a +//! process handle or perform cleanup. No implicit thread-local owner exists. +use std::{ + io, + sync::atomic::{AtomicBool, Ordering}, +}; + +static INTERRUPTED: AtomicBool = AtomicBool::new(false); +extern "C" fn interrupted(_: libc::c_int) { + INTERRUPTED.store(true, Ordering::Relaxed); +} +pub(crate) fn pending() -> bool { + INTERRUPTED.load(Ordering::Relaxed) +} +pub(crate) struct InstalledHandlers { + previous: Vec<(libc::c_int, libc::sigaction)>, +} +impl Drop for InstalledHandlers { + fn drop(&mut self) { + for (signal, previous) in self.previous.iter().rev() { + if unsafe { libc::sigaction(*signal, previous, std::ptr::null_mut()) } != 0 { + INTERRUPTED.store(true, Ordering::Relaxed); + } + } + } +} +pub(crate) fn install() -> io::Result { + let mut guard = InstalledHandlers { + previous: Vec::with_capacity(2), + }; + for signal in [libc::SIGINT, libc::SIGTERM] { + let mut action = unsafe { std::mem::zeroed::() }; + let mut previous = unsafe { std::mem::zeroed::() }; + action.sa_sigaction = interrupted as *const () as libc::sighandler_t; + unsafe { + libc::sigemptyset(&mut action.sa_mask); + if libc::sigaction(signal, &action, &mut previous) != 0 { + return Err(io::Error::last_os_error()); + } + } + guard.previous.push((signal, previous)); + } + Ok(guard) +} +/// The caller retains the returned Child before restoring this mask. The +/// child's pre_exec callback restores the original mask using libc only. +pub(super) struct AdmissionMask { + previous: libc::sigset_t, +} +impl AdmissionMask { + pub(super) fn block(command: &mut std::process::Command) -> io::Result { + use std::os::unix::process::CommandExt; + let mut mask = unsafe { std::mem::zeroed::() }; + let mut previous = unsafe { std::mem::zeroed::() }; + unsafe { + libc::sigemptyset(&mut mask); + libc::sigaddset(&mut mask, libc::SIGINT); + libc::sigaddset(&mut mask, libc::SIGTERM); + if libc::sigprocmask(libc::SIG_BLOCK, &mask, &mut previous) != 0 { + return Err(io::Error::last_os_error()); + } + let child_mask = previous; + command.pre_exec(move || { + if libc::sigprocmask(libc::SIG_SETMASK, &child_mask, std::ptr::null_mut()) != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + Ok(Self { previous }) + } +} +impl Drop for AdmissionMask { + fn drop(&mut self) { + if unsafe { libc::sigprocmask(libc::SIG_SETMASK, &self.previous, std::ptr::null_mut()) } + != 0 + { + INTERRUPTED.store(true, Ordering::Relaxed); + } + } +} diff --git a/src/real_client_qa.rs b/src/real_client_qa.rs new file mode 100644 index 0000000..88f16fd --- /dev/null +++ b/src/real_client_qa.rs @@ -0,0 +1,1742 @@ +//! Closed, developer-only OFFLINE native version/help discovery. +//! +//! No model, login, trust, consent, transcript or arbitrary command entry exists. +//! External OS policy/launch/artifact review is mandatory before execution. +//! An opaque group's known waits do not establish detached-descendant absence. +use crate::process_ownership::{ + image::VerifiedKeeperImage, + io::IoPlan, + protocol::ProtocolError, + scope::{monotonic_now, Scope, ScopeReport}, +}; +use serde::Serialize; +use std::{ + ffi::CString, + fs::{self, File, Metadata, OpenOptions}, + io::{self, Write}, + os::unix::{ + fs::{MetadataExt, OpenOptionsExt}, + process::{CommandExt, ExitStatusExt}, + }, + path::{Path, PathBuf}, + process::Command, +}; + +const TOTAL_NS: u64 = 4_000_000_000; +const OPERATION_NS: u64 = 1_000_000_000; +const CLEANUP_NS: u64 = 50_000_000; +const ROOT_PARENT: &str = "/Users/sionsmith/.t3/userdata/workspaces/keito-agent-capture-recovery-20261109-8bc862f6/evidence"; +const POLICY: &str = "real-client-offline-v1"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +enum Client { + Claude21319, + Codex01670Native, +} +impl Client { + fn path(self) -> &'static str { + match self { + Self::Claude21319 => "/Users/sionsmith/.local/share/claude/versions/2.1.319", + Self::Codex01670Native => "/opt/homebrew/lib/node_modules/@openai/codex/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/codex", + } + } + fn bytes(self) -> u64 { + match self { + Self::Claude21319 => 321_995_200, + Self::Codex01670Native => 270_815_376, + } + } + fn version(self) -> &'static str { + match self { + Self::Claude21319 => "2.1.319", + Self::Codex01670Native => "0.167.0", + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +enum Operation { + Version, + RequiredHelp, +} +const PLAN: [(Client, Operation); 4] = [ + (Client::Claude21319, Operation::Version), + (Client::Claude21319, Operation::RequiredHelp), + (Client::Codex01670Native, Operation::Version), + (Client::Codex01670Native, Operation::RequiredHelp), +]; +fn arguments(client: Client, operation: Operation) -> &'static [&'static str] { + match (client, operation) { + (_, Operation::Version) => &["--version"], + (Client::Claude21319, Operation::RequiredHelp) => &["--help"], + (Client::Codex01670Native, Operation::RequiredHelp) => &["exec", "--help"], + } +} +fn caps(operation: Operation) -> (usize, usize) { + ( + if operation == Operation::Version { + 8192 + } else { + 65536 + }, + 8192, + ) +} + +const STDERR_MARKERS: [(&str, &[u8]); 32] = [ + ("BUN_CRASH", b"oh no: Bun has crashed"), + ("BUN_PANIC", b"panic("), + ("UNREACHABLE", b"reached unreachable code"), + ("ASSERTION_FAILED", b"Assertion failed"), + ("UV_INTERFACE_ADDRESSES", b"uv_interface_addresses"), + ("UV_CPU_INFO", b"uv_cpu_info"), + ("UV_USER_INFO", b"uv_os_get_passwd"), + ("UV_CWD", b"uv_cwd"), + ("GETIFADDRS", b"getifaddrs"), + ("GETPWUID", b"getpwuid"), + ("GETCWD", b"getcwd"), + ("SYSCTL", b"sysctl"), + ("MACH_LOOKUP", b"mach-lookup"), + ("CORE_FOUNDATION", b"CoreFoundation"), + ("JAVA_SCRIPT_CORE", b"JavaScriptCore"), + ("OPERATION_NOT_PERMITTED", b"Operation not permitted"), + ("PERMISSION_DENIED", b"Permission denied"), + ("ERROR_ACCESS_DENIED", b"AccessDenied"), + ("ERROR_PERMISSION_DENIED", b"PermissionDenied"), + ("CODE_EPERM", b"EPERM"), + ("CODE_EACCES", b"EACCES"), + ("MEMORY_ALLOCATION", b"OutOfMemory"), + ("SIGNAL_TRAP", b"Trace/BPT trap"), + ("BUS_ERROR", b"Bus error"), + ("MAP_JIT", b"MAP_JIT"), + ("MMAP", b"mmap"), + ("MPROTECT", b"mprotect"), + ("JIT", b"JIT"), + ("GETRANDOM", b"getrandom"), + ("THREAD_SUSPEND", b"suspend thread"), + ("UV_THREAD_CREATE", b"uv_thread_create"), + ("ERROR_SYSTEM_RESOURCES", b"SystemResources"), +]; +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +enum RuntimePanicKind { + SegmentationFault, + IllegalInstruction, + BusError, + FloatingPointError, + UnalignedMemory, + StackOverflow, + OutOfMemory, + Unreachable, + CppException, + AbortCalled, + Unknown, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +struct BunVersion { + major: u16, + minor: u16, + patch: u16, +} +fn runtime_panic_kind(raw: &[u8]) -> Option { + if raw.len() > 8192 { + return None; + } + // Choose before validating. A malformed first candidate cannot authorize + // attribution from a later fake header in arbitrary diagnostic prose. + let line = raw + .split(|byte| *byte == b'\n') + .find(|line| line.windows(5).any(|part| part == b"panic"))?; + let line = line.strip_suffix(b"\r").unwrap_or(line); + if line.len() > 512 || !line.iter().all(|b| b.is_ascii_graphic() || *b == b' ') { + return Some(RuntimePanicKind::Unknown); + } + let Some(message) = line + .strip_prefix(b"panic(main thread): ") + .or_else(|| line.strip_prefix(b"panic: ")) + else { + return Some(RuntimePanicKind::Unknown); + }; + for (prefix, kind) in [ + ( + b"Segmentation fault at address 0x".as_slice(), + RuntimePanicKind::SegmentationFault, + ), + ( + b"Illegal instruction at address 0x".as_slice(), + RuntimePanicKind::IllegalInstruction, + ), + ( + b"Bus error at address 0x".as_slice(), + RuntimePanicKind::BusError, + ), + ( + b"Floating point error at address 0x".as_slice(), + RuntimePanicKind::FloatingPointError, + ), + ] { + if let Some(address) = message.strip_prefix(prefix) { + return Some( + if !address.is_empty() + && address.len() <= 16 + && address.iter().all(u8::is_ascii_hexdigit) + { + kind + } else { + RuntimePanicKind::Unknown + }, + ); + } + } + // Only a closed category survives; no exception type/message or address. + if message.windows(13).any(|part| part == b"C++ exception") { + return Some(RuntimePanicKind::CppException); + } + Some(match message { + b"Unaligned memory access" => RuntimePanicKind::UnalignedMemory, + b"Stack overflow" => RuntimePanicKind::StackOverflow, + b"Bun ran out of memory" => RuntimePanicKind::OutOfMemory, + b"reached unreachable code" => RuntimePanicKind::Unreachable, + b"abort() called" => RuntimePanicKind::AbortCalled, + _ => RuntimePanicKind::Unknown, + }) +} +fn runtime_bun_version(raw: &[u8]) -> Option { + if raw.len() > 8192 { + return None; + } + let line = raw + .split(|byte| *byte == b'\n') + .find(|line| line.windows(5).any(|part| part == b"Bun v"))?; + let line = line.strip_suffix(b"\r").unwrap_or(line); + if line.len() > 256 || !line.iter().all(|b| b.is_ascii_graphic() || *b == b' ') { + return None; + } + let rest = line.strip_prefix(b"Bun v")?; + let token = rest.split(u8::is_ascii_whitespace).next()?; + let mut parts = token.split(|byte| *byte == b'.'); + let mut component = || { + let value = parts.next()?; + if value.is_empty() + || value.len() > 4 + || (value.len() > 1 && value[0] == b'0') + || !value.iter().all(u8::is_ascii_digit) + { + return None; + } + std::str::from_utf8(value).ok()?.parse::().ok() + }; + let version = BunVersion { + major: component()?, + minor: component()?, + patch: component()?, + }; + if parts.next().is_some() { + return None; + } + Some(version) +} +#[derive(Serialize)] +struct RuntimeDiagnostics { + within_cap: bool, + panic_kind: Option, + bun_version: Option, + markers: std::collections::BTreeMap<&'static str, bool>, +} +fn runtime_diagnostics(raw: &[u8]) -> RuntimeDiagnostics { + let within_cap = raw.len() <= 8192; + RuntimeDiagnostics { + within_cap, + panic_kind: runtime_panic_kind(raw), + bun_version: runtime_bun_version(raw), + // Only literal keys and booleans survive. Oversize input is not scanned + // or partially attributed; neither bytes nor a digest enter evidence. + markers: STDERR_MARKERS + .iter() + .map(|(name, needle)| { + let found = within_cap && raw.windows(needle.len()).any(|part| part == *needle); + (*name, found) + }) + .collect(), + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +enum Failure { + Environment, + PrivateRoot, + NativePin, + Pair, + Clock, + Admission, + Operation, + Version, + Help, + Evidence, + Finality, + Interrupted, +} +type Result = std::result::Result; + +struct PlanState { + end: u64, + last: u64, + next: usize, + failed: bool, +} +impl PlanState { + fn new(entry: u64, parent: u64) -> Result { + let end = entry + .checked_add(TOTAL_NS) + .ok_or(Failure::Clock)? + .min(parent); + if entry == 0 || end <= entry { + return Err(Failure::Clock); + } + Ok(Self { + end, + last: entry, + next: 0, + failed: false, + }) + } + fn admit(&mut self, at: u64, client: Client, operation: Operation) -> Result { + if self.failed + || at < self.last + || at >= self.end + || PLAN.get(self.next) != Some(&(client, operation)) + { + self.failed = true; + return Err(Failure::Admission); + } + let local = at.checked_add(OPERATION_NS).ok_or(Failure::Clock)?; + let end = local.min(self.end); + if at >= end.saturating_sub(CLEANUP_NS) { + self.failed = true; + return Err(Failure::Admission); + } + self.last = at; + self.next += 1; // Charge once, before any image/command/spawn operation. + Ok(end) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Serialize)] +struct Stamp { + device: u64, + inode: u64, + uid: u32, + mode: u32, + links: u64, + bytes: u64, + modified: (i64, i64), + changed: (i64, i64), +} +// libc's stat integer widths differ across the supported Unix ABIs. Keep +// normalization here; the pre-exec callback performs no allocation or logging. +#[allow(clippy::unnecessary_cast)] +fn stat_matches(m: &libc::stat, expected: Stamp) -> bool { + m.st_dev as u64 == expected.device + && m.st_ino as u64 == expected.inode + && m.st_uid == expected.uid + && m.st_mode as u32 == expected.mode + && m.st_nlink as u64 == expected.links + && m.st_size as u64 == expected.bytes +} +impl Stamp { + fn of(m: &Metadata) -> Self { + Self { + device: m.dev(), + inode: m.ino(), + uid: m.uid(), + mode: m.mode(), + links: m.nlink(), + bytes: m.len(), + modified: (m.mtime(), m.mtime_nsec()), + changed: (m.ctime(), m.ctime_nsec()), + } + } +} +struct NativePin { + file: File, + stamp: Stamp, + client: Client, +} +fn native_stamp_allowed(client: Client, stamp: Stamp, uid: u32) -> bool { + // mode_t is u16 on Darwin and u32 on Linux; widen both without platform casts. + u64::from(stamp.mode) & u64::from(libc::S_IFMT) == u64::from(libc::S_IFREG) + && stamp.uid == uid + && stamp.links == 1 + && stamp.mode & 0o777 == 0o755 + && stamp.bytes == client.bytes() +} +impl NativePin { + fn open(client: Client) -> Result { + let path = Path::new(client.path()); + if path.canonicalize().map_err(|_| Failure::NativePin)? != path { + return Err(Failure::NativePin); + } + let file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(path) + .map_err(|_| Failure::NativePin)?; + let m = file.metadata().map_err(|_| Failure::NativePin)?; + if !native_stamp_allowed(client, Stamp::of(&m), unsafe { libc::geteuid() }) { + return Err(Failure::NativePin); + } + let pin = Self { + file, + stamp: Stamp::of(&m), + client, + }; + pin.check()?; + Ok(pin) + } + fn check(&self) -> Result<()> { + let held = self.file.metadata().map_err(|_| Failure::NativePin)?; + let path = fs::symlink_metadata(self.client.path()).map_err(|_| Failure::NativePin)?; + if Stamp::of(&held) != self.stamp || Stamp::of(&path) != self.stamp { + return Err(Failure::NativePin); + } + Ok(()) + } +} + +struct Roots { + root: PathBuf, + held: Vec<(PathBuf, File, u64, u64)>, +} +#[cfg(any(target_os = "macos", test))] +fn normalize_descriptors(mut fds: Vec) -> Result> { + if fds.len() >= 4096 || fds.iter().any(|fd| *fd < 0) { + return Err(Failure::Admission); + } + fds.sort_unstable(); + if fds.windows(2).any(|pair| pair[0] == pair[1]) || [0, 1, 2].iter().any(|fd| !fds.contains(fd)) + { + return Err(Failure::Admission); + } + fds.retain(|fd| *fd >= 3); + Ok(fds) +} +#[cfg(target_os = "macos")] +fn inherited_descriptors() -> Result> { + // Only this process's numeric FD table, never other processes, descriptor + // paths or contents. A lowered soft rlimit cannot conceal inherited FDs. + let mut rows: Vec = Vec::with_capacity(4096); + rows.resize_with(4096, || unsafe { std::mem::zeroed() }); + let capacity = std::mem::size_of_val(rows.as_slice()); + let count = unsafe { + libc::proc_pidinfo( + libc::getpid(), + libc::PROC_PIDLISTFDS, + 0, + rows.as_mut_ptr().cast(), + capacity as i32, + ) + }; + if count <= 0 + || count as usize >= capacity + || !(count as usize).is_multiple_of(std::mem::size_of::()) + { + return Err(Failure::Admission); + } + rows.truncate(count as usize / std::mem::size_of::()); + normalize_descriptors(rows.into_iter().map(|row| row.proc_fd).collect()) +} +#[cfg(not(target_os = "macos"))] +fn inherited_descriptors() -> Result> { + Err(Failure::Admission) +} +impl Roots { + fn open(root: PathBuf) -> Result { + if root.parent() != Some(Path::new(ROOT_PARENT)) + || !root.file_name().is_some_and(|n| { + n.to_string_lossy() + .starts_with("real-client-offline-first-") + }) + || root.canonicalize().map_err(|_| Failure::PrivateRoot)? != root + || std::env::current_dir().map_err(|_| Failure::PrivateRoot)? != root + { + return Err(Failure::PrivateRoot); + } + let mut held = vec![]; + for name in [ + "", + "home", + "home/.claude", + "home/.codex", + "tmp", + "config", + "state", + "cache", + "data", + "repo", + "pair", + ] { + let path = root.join(name); + let file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(&path) + .map_err(|_| Failure::PrivateRoot)?; + let m = file.metadata().map_err(|_| Failure::PrivateRoot)?; + if m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != 0o700 + || path.canonicalize().map_err(|_| Failure::PrivateRoot)? != path + { + return Err(Failure::PrivateRoot); + } + held.push((path, file, m.dev(), m.ino())); + } + let roots = Self { root, held }; + roots.check()?; + Ok(roots) + } + fn check(&self) -> Result<()> { + for (path, file, device, inode) in &self.held { + let a = file.metadata().map_err(|_| Failure::PrivateRoot)?; + let b = fs::symlink_metadata(path).map_err(|_| Failure::PrivateRoot)?; + for m in [a, b] { + if !m.is_dir() + || m.dev() != *device + || m.ino() != *inode + || m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != 0o700 + { + return Err(Failure::PrivateRoot); + } + } + } + Ok(()) + } + fn command(&self, pin: &NativePin, operation: Operation) -> Result { + self.check()?; + pin.check()?; + let mut command = Command::new(pin.client.path()); + command + .args(arguments(pin.client, operation)) + .env_clear() + .current_dir(self.root.join("repo")); + for (key, value) in [ + ("HOME", self.root.join("home")), + ("CODEX_HOME", self.root.join("home/.codex")), + ("CLAUDE_CONFIG_DIR", self.root.join("home/.claude")), + ("TMPDIR", self.root.join("tmp")), + ("TMP", self.root.join("tmp")), + ("TEMP", self.root.join("tmp")), + ("XDG_CONFIG_HOME", self.root.join("config")), + ("XDG_STATE_HOME", self.root.join("state")), + ("XDG_CACHE_HOME", self.root.join("cache")), + ("XDG_DATA_HOME", self.root.join("data")), + ] { + command.env(key, value); + } + command + .env("PATH", "/usr/bin:/bin") + .env("LC_CTYPE", "C.UTF-8") + .env("TERM", "dumb") + .env("NO_COLOR", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null"); + #[cfg(target_os = "macos")] + command.env( + "__CF_USER_TEXT_ENCODING", + format!("0x{:X}:0:0", unsafe { libc::geteuid() }), + ); + let path = CString::new(pin.client.path()).map_err(|_| Failure::NativePin)?; + let expected = pin.stamp; + let descriptors = inherited_descriptors()?; + // These callbacks execute before the existing group join/mask restore. + // Only async-signal-safe syscalls; do not close Rust's exec-error pipe. + unsafe { + command.pre_exec(move || { + let mut m = std::mem::MaybeUninit::::uninit(); + if libc::lstat(path.as_ptr(), m.as_mut_ptr()) != 0 { + return Err(io::Error::from_raw_os_error(libc::ESTALE)); + } + let m = m.assume_init(); + if !stat_matches(&m, expected) { + return Err(io::Error::from_raw_os_error(libc::ESTALE)); + } + // Subsequent Scope/Command-owned pipes and sockets are created + // CLOEXEC. Mark the retained entry-thread snapshot as well; + // this includes inherited descriptors above a lowered rlimit. + for &fd in &descriptors { + let flags = libc::fcntl(fd, libc::F_GETFD); + if flags < 0 { + let error = io::Error::last_os_error(); + if error.raw_os_error() != Some(libc::EBADF) { + return Err(error); + } + } + if flags >= 0 && libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) < 0 { + return Err(io::Error::from_raw_os_error(libc::EBADF)); + } + } + Ok(()) + }); + } + Ok(command) + } +} + +#[derive(Default, Debug, Serialize)] +struct Capabilities { + structured_output: bool, + resume: bool, + model: bool, + turn_limit: bool, + output_token_limit: bool, + retry_limit: bool, + session_id: bool, +} +fn project_help(raw: &[u8]) -> Result { + let body = std::str::from_utf8(raw).map_err(|_| Failure::Help)?; + let options: Vec<&str> = body + .lines() + .filter(|l| l.trim_start().starts_with('-')) + .flat_map(str::split_ascii_whitespace) + .map(|word| word.trim_end_matches(',')) + .collect(); + if options.is_empty() { + return Err(Failure::Help); + } + Ok(Capabilities { + structured_output: options.contains(&"--json") || options.contains(&"--output-format"), + resume: options.contains(&"--resume"), + model: options.contains(&"--model"), + turn_limit: options.contains(&"--max-turns"), + output_token_limit: options.contains(&"--max-output-tokens"), + retry_limit: options.contains(&"--max-retries"), + session_id: options.contains(&"--session-id"), + }) +} +fn project_version(client: Client, raw: &[u8]) -> Result<()> { + let body = std::str::from_utf8(raw) + .map_err(|_| Failure::Version)? + .trim(); + let expected = match client { + Client::Claude21319 => "2.1.319 (Claude Code)", + Client::Codex01670Native => "codex-cli 0.167.0", + }; + if body == expected { + Ok(()) + } else { + Err(Failure::Version) + } +} +#[derive(Serialize)] +struct Observation { + client: Client, + operation: Operation, + entry: &'static str, + expected_version: &'static str, + version_matches: Option, + capabilities: Option, + started_ns: u64, + end_ns: u64, + scope_original_end_ns: u64, + receipt_finished_ns: Option, + exit: Option, + signal: Option, + waits_known: bool, + group_absent: bool, + control_eof: bool, + stdin_closed: bool, + stdout_eof: bool, + stderr_eof: bool, + stdout_bytes: usize, + stderr_bytes: usize, + stderr_diagnostic: RuntimeDiagnostics, + accepted_ns: Option, + native_integrity: &'static str, + native_metadata: Stamp, + unregistered_descendants: &'static str, + product_ack: &'static str, +} +fn write_receipt(root: &Path, name: &str, value: &impl Serialize) -> Result<()> { + let bytes = serde_json::to_vec(value).map_err(|_| Failure::Evidence)?; + if bytes.len() > 262_144 { + return Err(Failure::Evidence); + } + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(root.join(name)) + .map_err(|_| Failure::Evidence)?; + file.write_all(&bytes) + .and_then(|_| file.write_all(b"\n")) + .and_then(|_| file.sync_all()) + .map_err(|_| Failure::Evidence)?; + File::open(root) + .and_then(|f| f.sync_all()) + .map_err(|_| Failure::Evidence) +} +fn entry_environment(root: &Path) -> Result<()> { + let mut expected = std::collections::BTreeMap::from([ + ("HOME".to_owned(), root.join("home").into_os_string()), + ("TMPDIR".to_owned(), root.join("tmp").into_os_string()), + ("PATH".to_owned(), "/usr/bin:/bin".into()), + ("LC_CTYPE".to_owned(), "C.UTF-8".into()), + ("KEITO_REAL_CLIENT_QA_POLICY".to_owned(), POLICY.into()), + ]); + #[cfg(target_os = "macos")] + expected.insert( + "__CF_USER_TEXT_ENCODING".into(), + format!("0x{:X}:0:0", unsafe { libc::geteuid() }).into(), + ); + // Complete attachments are interpreted by Scope, never sent to clients. + for key in [ + "KEITO_PROCESS_OWNER_FD", + "KEITO_PROCESS_OWNER_NONCE", + "KEITO_PROCESS_OWNER_PID", + "KEITO_PROCESS_OWNER_END_NS", + "KEITO_PROCESS_OWNER_CONTRACT", + ] { + if let Some(value) = std::env::var_os(key) { + expected.insert(key.into(), value); + } + } + if std::env::vars_os().collect::>() + != expected.into_iter().map(|(k, v)| (k.into(), v)).collect() + { + return Err(Failure::Environment); + } + Ok(()) +} +fn exercise( + scope: &mut Scope, + roots: &Roots, + entry: u64, + observations: &mut Vec, + claimed: &mut bool, +) -> Result<()> { + let mut state = PlanState::new(entry, scope.hard_end())?; + for name in [ + "FIRST.json", + "FINAL.json", + "operation-1.json", + "operation-2.json", + "operation-3.json", + "operation-4.json", + ] { + match fs::symlink_metadata(roots.root.join(name)) { + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + _ => return Err(Failure::Evidence), + } + } + // One durable, exclusive reservation prevents replay/concurrent launches + // of this root before any pair/native admission or client execution. + write_receipt( + &roots.root, + "START.json", + &serde_json::json!({ + "schema": 1, "entry_ns": entry, "end_ns": state.end, + "offline_only": true, "maximum_native_operations": 4, + }), + )?; + *claimed = true; + let anchor = option_env!("KEITO_RELEASE_GUARD_SHA256").ok_or(Failure::Pair)?; + let pair = crate::capture_runtime_pair::verify( + &roots.root.join("pair/keito"), + anchor, + env!("CARGO_PKG_VERSION"), + env!("KEITO_BUILD_TARGET"), + ) + .map_err(|_| Failure::Pair)?; + let image = VerifiedKeeperImage::open(&pair.guard_path, &pair.guard_sha256) + .map_err(|_| Failure::Pair)?; + for (client, operation) in PLAN { + scope.poll(); + if scope.failed() { + return Err(Failure::Operation); + } + let started = monotonic_now().map_err(|_| Failure::Clock)?; + let end = state.admit(started, client, operation)?; + let native = NativePin::open(client)?; + let command = roots.command(&native, operation)?; + let (out, err) = caps(operation); + let io = IoPlan::new(Vec::new(), out, err).map_err(|_| Failure::Admission)?; + let slot = scope + .start_dev_client_opaque_until(command, io, &image, end) + .map_err(|_| Failure::Admission)?; + while !scope.slot_complete(&slot) { + scope.poll(); + if scope.failed() { + return Err(Failure::Operation); + } + std::thread::yield_now(); + } + let result = scope + .take_dev_client_result(&slot) + .map_err(|_| Failure::Finality)?; + native.check()?; + roots.check()?; + let report = scope.report(); + let facts = report.slots.last().ok_or(Failure::Finality)?; + let mut observation = Observation { + client, + operation, + entry: "DIRECT_NATIVE", + expected_version: client.version(), + version_matches: None, + capabilities: None, + started_ns: started, + end_ns: end, + scope_original_end_ns: state.end, + receipt_finished_ns: None, + exit: result.status.code(), + signal: result.status.signal(), + waits_known: facts.waits_known, + group_absent: facts.group_absent, + control_eof: facts.terminal_eof, + stdin_closed: facts.io.stdin_closed, + stdout_eof: facts.io.stdout_eof, + stderr_eof: facts.io.stderr_eof, + stdout_bytes: facts.io.stdout_bytes, + stderr_bytes: facts.io.stderr_bytes, + stderr_diagnostic: runtime_diagnostics(&result.output.stderr), + accepted_ns: facts.accepted_at, + native_integrity: "METADATA_AND_VERSION_ONLY", + native_metadata: native.stamp, + unregistered_descendants: "UNKNOWN", + product_ack: "NOT_OBSERVED_OFFLINE", + }; + let physical = result.status.success() + && facts.waits_known + && facts.group_absent + && facts.terminal_eof + && facts.io.complete() + && facts.first_fault.is_none() + && facts.accepted_at.is_some_and(|at| at < end); + let projection = if !physical { + Err(Failure::Finality) + } else if operation == Operation::Version { + let checked = project_version(client, &result.output.stdout); + observation.version_matches = Some(checked.is_ok()); + checked + } else { + project_help(&result.output.stdout).map(|value| { + observation.capabilities = Some(value); + }) + }; + drop(result); // No raw output/hash in any receipt, error or Debug path. + observations.push(observation); + projection?; + write_receipt( + &roots.root, + &format!("operation-{}.json", observations.len()), + observations.last().ok_or(Failure::Evidence)?, + )?; + let durable = monotonic_now().map_err(|_| Failure::Clock)?; + if durable >= end { + return Err(Failure::Clock); + } + observations + .last_mut() + .ok_or(Failure::Evidence)? + .receipt_finished_ns = Some(durable); + } + Ok(()) +} + +// Closed developer diagnostics only. Never serialize a supplied error string. +fn fault_code(reason: Option<&'static str>) -> Option<&'static str> { + match reason { + None => None, + Some( + code @ ("GROUP_DEADLINE" + | "GROUP_EOF" + | "GROUP_READY" + | "GROUP_PARK" + | "GROUP_STATE" + | "GROUP_CLOCK" + | "GROUP_ADMISSION" + | "GROUP_START_STATE" + | "GROUP_SPAWN" + | "GROUP_KEEPER_FAILED" + | "GROUP_EARLY_EOF" + | "GROUP_CLEANUP_DEADLINE" + | "GROUP_WORKLOAD_WAIT" + | "GROUP_KEEPER_WAIT" + | "GROUP_FRAME" + | "GROUP_NONCE" + | "GROUP_FRAME_LIMIT" + | "GROUP_WIRE_LIMIT" + | "GROUP_TRUNCATED" + | "GROUP_READ" + | "GROUP_WRITE" + | "GROUP_SHORT_WRITE" + | "GROUP_TERMINAL" + | "GROUP_SHUTDOWN" + | "GROUP_BOUND_SEALED" + | "GROUP_IO" + | "SCOPE_CLOCK" + | "SCOPE_EDGE" + | "SCOPE_BEGIN" + | "SCOPE_OPERATION_DEADLINE" + | "SCOPE_CLEANUP_DEADLINE" + | "SCOPE_RESULT" + | "SCOPE_IO_ATTACH" + | "DEV_CLIENT_OPERATION"), + ) => Some(code), + Some(_) => Some("UNKNOWN"), + } +} +#[derive(Serialize)] +struct SetupTiming { + setup_start_ns: u64, + ready_end_ns: u64, + pre_spawn_ns: u64, + spawn_return_ns: Option, + first_ready_poll_ns: Option, + last_ready_before_ns: Option, + last_ready_after_ns: Option, + ready_frame_observed: bool, + ready_eof_observed: bool, + deadline_observed: Option<(&'static str, u64)>, +} +impl From for SetupTiming { + fn from(trace: crate::process_ownership::group::SetupTrace) -> Self { + Self { + setup_start_ns: trace.setup_start_ns, + ready_end_ns: trace.ready_end_ns, + pre_spawn_ns: trace.pre_spawn_ns, + spawn_return_ns: trace.spawn_return_ns, + first_ready_poll_ns: trace.first_ready_poll_ns, + last_ready_before_ns: trace.last_ready_before_ns, + last_ready_after_ns: trace.last_ready_after_ns, + ready_frame_observed: trace.ready_frame_observed, + ready_eof_observed: trace.ready_eof_observed, + deadline_observed: trace.deadline_observed.map(|(point, at)| { + let point = match point { + "READY_BEFORE_RECEIVE" => "READY_BEFORE_RECEIVE", + "READY_AFTER_RECEIVE" => "READY_AFTER_RECEIVE", + _ => "UNKNOWN", + }; + (point, at) + }), + } + } +} + +#[derive(Serialize)] +struct Physical { + slot: usize, + exit: Option, + signal: Option, + waits_known: bool, + group_absent: bool, + control_eof: bool, + stdin_closed: bool, + stdout_eof: bool, + stderr_eof: bool, + stdout_bytes: usize, + stderr_bytes: usize, + accepted_ns: Option, + completion_end_ns: Option, + fault: bool, + fault_code: Option<&'static str>, + setup: Option, +} +#[derive(Serialize)] +struct Receipt<'a> { + checks_passed_before_persistence: bool, + acceptance_requires_exit_zero: bool, + primary: Option, + scope_fault_code: Option<&'static str>, + scope_clean: bool, + resources_known: bool, + physical_slots: Vec, + observations: &'a [Observation], + detached_descendants: &'static str, + product_qualification: bool, +} +fn receipt<'a>( + primary: Option, + report: &ScopeReport, + observations: &'a [Observation], +) -> Receipt<'a> { + Receipt { + checks_passed_before_persistence: primary.is_none() + && report.clean + && observations.len() == 4, + acceptance_requires_exit_zero: true, + primary, + scope_fault_code: fault_code(report.first_fault.map(|reason| reason.0)), + scope_clean: report.clean, + resources_known: report.all_resources, + observations, + physical_slots: report + .slots + .iter() + .map(|slot| Physical { + slot: slot.slot, + exit: slot.status.and_then(|s| s.code()), + signal: slot.status.and_then(|s| s.signal()), + waits_known: slot.waits_known, + group_absent: slot.group_absent, + control_eof: slot.terminal_eof, + stdin_closed: slot.io.stdin_closed, + stdout_eof: slot.io.stdout_eof, + stderr_eof: slot.io.stderr_eof, + stdout_bytes: slot.io.stdout_bytes, + stderr_bytes: slot.io.stderr_bytes, + accepted_ns: slot.accepted_at, + completion_end_ns: slot.completion_end, + fault: slot.first_fault.is_some() || slot.io.first_fault.is_some(), + fault_code: fault_code(slot.first_fault.or(slot.io.first_fault)), + setup: slot.setup_trace.map(SetupTiming::from), + }) + .collect(), + detached_descendants: "UNKNOWN", + product_qualification: false, + } +} + +/// This candidate is written after the outcome receipts, but is deliberately +/// not an acceptance assertion: its own persistence and terminal publication +/// must still pass the final clock/cancellation gate, witnessed by exit zero. +#[derive(Serialize)] +struct AcceptanceCandidate { + kind: &'static str, + entry_ns: u64, + end_ns: u64, + after_outcome_persistence_ns: Option, + primary: Option, + acceptance_requires_exit_zero: bool, + product_qualification: bool, +} +trait TerminalIo { + fn observe(&mut self) -> Result; + fn outcomes(&mut self, primary: Option) -> Result<()>; + fn candidate(&mut self, candidate: &AcceptanceCandidate) -> Result<()>; + fn publish(&mut self, clean: bool) -> bool; +} +struct EntryTerminal<'a, F> { + scope: &'a mut Scope, + root: &'a Path, + persist_outcomes: F, +} +impl) -> Result<()>> TerminalIo for EntryTerminal<'_, F> { + fn observe(&mut self) -> Result { + self.scope.poll(); + if crate::process_ownership::signals::pending() { + return Err(Failure::Interrupted); + } + if self.scope.failed() { + return Err(Failure::Finality); + } + monotonic_now().map_err(|_| Failure::Clock) + } + fn outcomes(&mut self, primary: Option) -> Result<()> { + (self.persist_outcomes)(self.scope, primary) + } + fn candidate(&mut self, candidate: &AcceptanceCandidate) -> Result<()> { + write_receipt(self.root, "ACCEPTANCE-CANDIDATE.json", candidate) + } + fn publish(&mut self, clean: bool) -> bool { + self.scope.publish_terminal(clean) + } +} +fn terminal_checkpoint( + io: &mut impl TerminalIo, + entry: u64, + end: u64, + last: &mut u64, + primary: &mut Option, +) -> Option { + match io.observe().and_then(|at| { + if at < entry || at < *last || at >= end { + Err(Failure::Clock) + } else { + *last = at; + Ok(at) + } + }) { + Ok(at) => Some(at), + Err(error) => { + primary.get_or_insert(error); + None + } + } +} +fn finalize_terminal( + io: &mut impl TerminalIo, + entry: u64, + end: u64, + mut primary: Option, +) -> bool { + let mut last = entry; + terminal_checkpoint(io, entry, end, &mut last, &mut primary); + if let Err(error) = io.outcomes(primary) { + primary.get_or_insert(error); + } + let after_outcomes = terminal_checkpoint(io, entry, end, &mut last, &mut primary); + let candidate = AcceptanceCandidate { + kind: "PROVISIONAL_OFFLINE_ACCEPTANCE", + entry_ns: entry, + end_ns: end, + after_outcome_persistence_ns: after_outcomes, + primary, + acceptance_requires_exit_zero: true, + product_qualification: false, + }; + if let Err(error) = io.candidate(&candidate) { + primary.get_or_insert(error); + } + // Every durable write is now behind us. A candidate is never accepted + // solely because it exists: late fsync/cancellation refuses terminal + // success and exit zero. Preserve the original fault on all later errors. + terminal_checkpoint(io, entry, end, &mut last, &mut primary); + if !io.publish(primary.is_none()) { + primary.get_or_insert(Failure::Finality); + } + // Publication can itself observe cancellation or consume the remaining + // budget. This last observation is the acceptance linearization point; + // there is no receipt persistence after it. + terminal_checkpoint(io, entry, end, &mut last, &mut primary); + primary.is_none() +} +/// Fixed CLI shape: exactly one fresh private case root. No program/argv/budget input. +pub fn run_offline() -> bool { + let Ok(entry) = monotonic_now() else { + return false; + }; + let Some(end) = entry.checked_add(TOTAL_NS) else { + return false; + }; + if !cfg!(target_os = "macos") { + return false; + } + let args: Vec<_> = std::env::args_os().take(4).collect(); + let controls = args.len() == 3 && args[1] == "--check-policy"; + if args.len() != 2 && !controls { + return false; + } + let root = PathBuf::from(&args[if controls { 2 } else { 1 }]); + if entry_environment(&root).is_err() { + return false; + } + let Ok(mut scope) = Scope::attach_at(entry, end).and_then(|attached| match attached { + Some(scope) => Ok(scope), + None => Scope::local_entry(end), + }) else { + return false; + }; + if controls { + return policy_controls(&mut scope, root, entry, end); + } + let mut observations = Vec::with_capacity(4); + let mut claimed = false; + let setup = Roots::open(root.clone()); + let mut primary = match setup.as_ref() { + Ok(roots) => exercise(&mut scope, roots, entry, &mut observations, &mut claimed).err(), + Err(error) => Some(*error), + }; + let mut first_attempted = false; + if primary.is_some() { + scope.begin_cancel(ProtocolError("DEV_CLIENT_OPERATION"), end); + if claimed { + first_attempted = true; + let _ = write_receipt( + &root, + "FIRST.json", + &receipt(primary, &scope.report(), &observations), + ); + } + } + let report = scope.finish(); + if !report.clean { + primary.get_or_insert(Failure::Finality); + } + if !claimed { + scope.publish_terminal(false); + return false; + } + if observations.len() != 4 { + primary.get_or_insert(Failure::Finality); + } + let end = end.min(scope.hard_end()); + finalize_terminal( + &mut EntryTerminal { + scope: &mut scope, + root: &root, + persist_outcomes: |scope: &Scope, primary| { + let report = scope.report(); + let mut failure = None; + if !first_attempted { + failure = write_receipt( + &root, + "FIRST.json", + &receipt(primary, &report, &observations), + ) + .err(); + } + let final_primary = primary.or(failure); + if let Err(error) = write_receipt( + &root, + "FINAL.json", + &receipt(final_primary, &report, &observations), + ) { + failure.get_or_insert(error); + } + failure.map_or(Ok(()), Err) + }, + }, + entry, + end, + primary, + ) +} + +fn permission_denied(error: &io::Error) -> bool { + matches!(error.raw_os_error(), Some(libc::EPERM) | Some(libc::EACCES)) +} +fn policy_controls(scope: &mut Scope, root: PathBuf, entry: u64, end: u64) -> bool { + let end = end.min(scope.hard_end()); + let Ok(roots) = Roots::open(root) else { + scope.begin_cancel(ProtocolError("DEV_CLIENT_POLICY_ROOT"), end); + scope.finish(); + scope.publish_terminal(false); + return false; + }; + let canary = Path::new(ROOT_PARENT).join(format!( + "{}-denied-canary", + roots.root.file_name().unwrap().to_string_lossy() + )); + // The preparer must attest this new run-owned canary exists. Never read its + // body, even on a policy failure; no original profile/service is probed. + let file_denied = match File::open(canary) { + Ok(file) => { + drop(file); + false + } + Err(error) => permission_denied(&error), + }; + #[cfg(target_os = "macos")] + let udp_denied = { + use std::os::fd::FromRawFd; + let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0) }; + if fd < 0 { + permission_denied(&io::Error::last_os_error()) + } else { + // Own the returned socket before any fallible operation. UDP + // connect does not send a datagram; there is no send/listen call. + let socket = unsafe { std::net::UdpSocket::from_raw_fd(fd) }; + let denied = socket + .connect((std::net::Ipv4Addr::LOCALHOST, 9)) + .err() + .is_some_and(|error| permission_denied(&error)); + drop(socket); + denied + } + }; + #[cfg(not(target_os = "macos"))] + let udp_denied = false; + let within_end = monotonic_now().is_ok_and(|at| entry <= at && at < end); + let operation_clean = file_denied && udp_denied && within_end && roots.check().is_ok(); + if !operation_clean { + scope.begin_cancel(ProtocolError("DEV_CLIENT_POLICY_DENIAL"), end); + } + let report = scope.finish(); + let primary = if operation_clean && report.clean { + None + } else { + Some(Failure::Finality) + }; + finalize_terminal( + &mut EntryTerminal { + scope, + root: &roots.root, + persist_outcomes: |scope: &Scope, primary| { + let report = scope.report(); + let receipt = serde_json::json!({ + "kind": "OFFLINE_POLICY_CONTROLS", "file_open_permission_denied": file_denied, + "udp_endpoint_permission_denied": udp_denied, + "scope_clean": report.clean, "primary": primary, + "acceptance_requires_exit_zero": true, + "entry_ns": entry, "end_ns": end, "client_invocations": 0, + "no_datagram_send_or_listener_API": true, + "original_profile_or_service_probe": false, + "effective_policy_for_actual_clients": "NOT_YET_QUALIFIED", + }); + write_receipt(&roots.root, "POLICY-CONTROLS.json", &receipt) + }, + }, + entry, + end, + primary, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + #[derive(Clone, Copy, PartialEq, Eq)] + enum During { + Outcomes, + Candidate, + Publication, + } + struct FakeTerminal { + now: u64, + during: Option, + advance: u64, + interrupted: bool, + interrupt: bool, + write_failed: bool, + observations: Vec<&'static str>, + published: Option, + candidate_time: Option, + candidate_primary: Option, + } + impl FakeTerminal { + fn new(during: Option, advance: u64, interrupt: bool) -> Self { + Self { + now: 101, + during, + advance, + interrupted: false, + interrupt, + write_failed: false, + observations: vec![], + published: None, + candidate_time: None, + candidate_primary: None, + } + } + fn step(&mut self, during: During) { + if self.during == Some(during) { + self.now = self.advance; + self.interrupted |= self.interrupt; + } + } + } + impl TerminalIo for FakeTerminal { + fn observe(&mut self) -> Result { + self.observations.push("observe"); + if self.interrupted { + Err(Failure::Interrupted) + } else { + Ok(self.now) + } + } + fn outcomes(&mut self, _: Option) -> Result<()> { + self.observations.push("outcomes"); + self.step(During::Outcomes); + if self.write_failed { + Err(Failure::Evidence) + } else { + Ok(()) + } + } + fn candidate(&mut self, candidate: &AcceptanceCandidate) -> Result<()> { + self.observations.push("candidate"); + self.candidate_time = candidate.after_outcome_persistence_ns; + self.candidate_primary = candidate.primary; + assert!(candidate.acceptance_requires_exit_zero && !candidate.product_qualification); + self.step(During::Candidate); + Ok(()) + } + fn publish(&mut self, clean: bool) -> bool { + self.observations.push("publish"); + self.published = Some(clean); + self.step(During::Publication); + clean + } + } + #[test] + fn offline_client_terminal_rejects_deadline_during_outcome_candidate_or_publication() { + for stage in [During::Outcomes, During::Candidate, During::Publication] { + for late in [200, 201] { + let mut io = FakeTerminal::new(Some(stage), late, false); + assert!(!finalize_terminal(&mut io, 100, 200, None)); + } + } + } + #[test] + fn offline_client_terminal_rejects_interruption_during_each_persistence_or_publication() { + for stage in [During::Outcomes, During::Candidate, During::Publication] { + let mut io = FakeTerminal::new(Some(stage), 102, true); + assert!(!finalize_terminal(&mut io, 100, 200, None)); + } + } + #[test] + fn offline_client_terminal_witness_and_publication_follow_durable_outcomes() { + let mut io = FakeTerminal::new(None, 0, false); + assert!(finalize_terminal(&mut io, 100, 200, None)); + assert_eq!(io.candidate_time, Some(101)); + assert_eq!( + io.observations, + [ + "observe", + "outcomes", + "observe", + "candidate", + "observe", + "publish", + "observe" + ] + ); + assert_eq!(io.published, Some(true)); + } + #[test] + fn offline_client_terminal_rejects_backwards_or_already_expired_inherited_end() { + let mut io = FakeTerminal::new(Some(During::Outcomes), 100, false); + assert!(!finalize_terminal(&mut io, 100, 200, None)); + let mut io = FakeTerminal::new(None, 0, false); + assert!(!finalize_terminal(&mut io, 100, 101, None)); + } + #[test] + fn offline_client_terminal_failure_preserves_first_error_and_never_publishes_success() { + let mut io = FakeTerminal::new(Some(During::Outcomes), 201, true); + io.write_failed = true; + assert!(!finalize_terminal( + &mut io, + 100, + 200, + Some(Failure::Version) + )); + assert_eq!(io.candidate_primary, Some(Failure::Version)); + assert_eq!(io.published, Some(false)); + let mut io = FakeTerminal::new(None, 0, false); + io.write_failed = true; + assert!(!finalize_terminal(&mut io, 100, 200, None)); + assert_eq!(io.published, Some(false)); + } + #[test] + fn offline_client_descriptor_projection_covers_high_fds_and_rejects_ambiguous_tables() { + assert_eq!(normalize_descriptors(vec![2000, 0, 2, 1]).unwrap(), [2000]); + assert!(normalize_descriptors(vec![0, 1, 2, 4, 4]).is_err()); + assert!(normalize_descriptors(vec![0, 1, 2, -1]).is_err()); + assert!(normalize_descriptors(vec![1, 2, 4]).is_err()); + assert!(normalize_descriptors(vec![0; 4096]).is_err()); + } + #[test] + fn offline_client_offline_plan_has_only_four_fixed_non_model_operations() { + assert_eq!(PLAN.len(), 4); + assert_eq!( + arguments(Client::Claude21319, Operation::Version), + ["--version"] + ); + assert_eq!( + arguments(Client::Claude21319, Operation::RequiredHelp), + ["--help"] + ); + assert_eq!( + arguments(Client::Codex01670Native, Operation::RequiredHelp), + ["exec", "--help"] + ); + assert_eq!( + PLAN.iter() + .map(|(_, op)| { + let (a, b) = caps(*op); + a + b + }) + .sum::(), + 180_224 + ); + } + #[test] + fn offline_client_deadlines_are_not_renewed_and_inherited_parent_wins() { + let mut state = PlanState::new(100, 2_000_000_100).unwrap(); + assert_eq!( + state.admit(100, PLAN[0].0, PLAN[0].1).unwrap(), + 1_000_000_100 + ); + assert_eq!( + state.admit(1_500_000_100, PLAN[1].0, PLAN[1].1).unwrap(), + 2_000_000_100 + ); + assert_eq!(state.end, 2_000_000_100); + assert!(state.admit(2_000_000_100, PLAN[2].0, PLAN[2].1).is_err()); + assert!(PlanState::new(u64::MAX, u64::MAX).is_err()); + } + #[test] + fn offline_client_duplicate_out_of_order_backwards_and_fifth_admission_fail_closed() { + let mut state = PlanState::new(100, u64::MAX).unwrap(); + assert!(state.admit(100, PLAN[1].0, PLAN[1].1).is_err()); + assert!(state.admit(100, PLAN[0].0, PLAN[0].1).is_err()); + let mut state = PlanState::new(100, u64::MAX).unwrap(); + state.admit(200, PLAN[0].0, PLAN[0].1).unwrap(); + assert!(state.admit(199, PLAN[1].0, PLAN[1].1).is_err()); + let mut state = PlanState::new(100, u64::MAX).unwrap(); + for (client, op) in PLAN { + state.admit(200, client, op).unwrap(); + } + assert!(state.admit(200, PLAN[0].0, PLAN[0].1).is_err()); + } + #[test] + fn offline_client_version_projection_refuses_near_versions_private_output_and_invalid_utf8() { + assert!(project_version(Client::Claude21319, b"2.1.319 (Claude Code)\n").is_ok()); + assert!(project_version(Client::Codex01670Native, b"codex-cli 0.167.0\n").is_ok()); + for raw in [ + &b"2.1.322 (Claude Code)"[..], + &b"PRIVATE_token 0.167.0"[..], + &[255][..], + ] { + assert!(project_version(Client::Codex01670Native, raw).is_err()); + } + } + #[test] + fn offline_client_native_pin_rejects_symlink_mode_owner_link_or_size_substitutes() { + let valid = Stamp { + device: 1, + inode: 2, + uid: 501, + mode: 0o100755, // POSIX regular file with 0755 permissions. + links: 1, + bytes: Client::Claude21319.bytes(), + modified: (1, 2), + changed: (3, 4), + }; + assert!(native_stamp_allowed(Client::Claude21319, valid, 501)); + let mut invalid = valid; + invalid.links = 2; + assert!(!native_stamp_allowed(Client::Claude21319, invalid, 501)); + let mut invalid = valid; + invalid.uid = 502; + assert!(!native_stamp_allowed(Client::Claude21319, invalid, 501)); + let mut invalid = valid; + invalid.mode |= 0o020; + assert!(!native_stamp_allowed(Client::Claude21319, invalid, 501)); + let mut invalid = valid; + invalid.mode = 0o120755; // POSIX symlink with the same permission bits. + assert!(!native_stamp_allowed(Client::Claude21319, invalid, 501)); + let mut invalid = valid; + invalid.bytes += 1; + assert!(!native_stamp_allowed(Client::Claude21319, invalid, 501)); + } + #[test] + fn offline_client_help_projection_does_not_treat_prose_as_a_capability_or_serialize_it() { + let value = + project_help(b"PRIVATE_PROMPT --resume\n --json JSON\n -m, --model \n") + .unwrap(); + assert!(value.structured_output && value.model && !value.resume); + let text = serde_json::to_string(&value).unwrap(); + assert!(!text.contains("PRIVATE") && !text.contains("MODEL")); + assert!(project_help(b"PRIVATE_prose only").is_err()); + } + fn diagnostic_report( + scope_fault: Option<&'static str>, + slot_fault: Option<&'static str>, + ) -> ScopeReport { + ScopeReport { + first_fault: scope_fault.map(ProtocolError), + admission_closed: true, + finish_called: true, + all_resources: false, + clean: false, + slots: vec![crate::process_ownership::scope::SlotReport { + slot: 0, + status: None, + waits_known: false, + group_absent: false, + terminal_eof: false, + io_required: false, + io: Default::default(), + accepted_at: None, + completion_end: Some(80), + first_fault: slot_fault, + setup_trace: Some(crate::process_ownership::group::SetupTrace { + setup_start_ns: 10, + ready_end_ns: 30, + pre_spawn_ns: 11, + spawn_return_ns: Some(12), + first_ready_poll_ns: Some(14), + last_ready_before_ns: Some(29), + last_ready_after_ns: None, + ready_frame_observed: false, + ready_eof_observed: true, + deadline_observed: Some(("READY_BEFORE_RECEIVE", 31)), + fault_origin: None, + ..Default::default() + }), + }], + } + } + #[test] + fn offline_client_failure_receipt_preserves_first_fault_and_setup_without_output() { + let report = diagnostic_report(Some("GROUP_DEADLINE"), Some("GROUP_EOF")); + let value = serde_json::to_value(receipt(Some(Failure::Operation), &report, &[])).unwrap(); + assert_eq!(value["scope_fault_code"], "GROUP_DEADLINE"); + assert_eq!(value["physical_slots"][0]["fault_code"], "GROUP_EOF"); + assert_eq!(value["physical_slots"][0]["setup"]["ready_end_ns"], 30); + assert_eq!( + value["physical_slots"][0]["setup"]["ready_eof_observed"], + true + ); + assert_eq!( + value["physical_slots"][0]["setup"]["deadline_observed"][0], + "READY_BEFORE_RECEIVE" + ); + assert_eq!(value["primary"], "OPERATION"); + assert_eq!(value["resources_known"], false); + assert_eq!(value["observations"], serde_json::json!([])); + } + #[test] + fn offline_client_failure_receipt_refuses_unknown_reason_and_phase_text() { + let mut report = + diagnostic_report(Some("PRIVATE_SCOPE_CANARY"), Some("PRIVATE_SLOT_CANARY")); + report.slots[0] + .setup_trace + .as_mut() + .unwrap() + .deadline_observed = Some(("PRIVATE_PHASE_CANARY", 31)); + let value = serde_json::to_value(receipt(Some(Failure::Operation), &report, &[])).unwrap(); + assert_eq!(value["scope_fault_code"], "UNKNOWN"); + assert_eq!(value["physical_slots"][0]["fault_code"], "UNKNOWN"); + assert_eq!( + value["physical_slots"][0]["setup"]["deadline_observed"][0], + "UNKNOWN" + ); + assert!(!value.to_string().contains("PRIVATE")); + } + #[test] + fn offline_client_failure_receipt_keeps_absent_fault_and_setup_null() { + let mut report = diagnostic_report(None, None); + report.slots[0].setup_trace = None; + let value = serde_json::to_value(receipt(Some(Failure::Finality), &report, &[])).unwrap(); + assert!(value.as_object().unwrap().contains_key("scope_fault_code")); + assert_eq!(value["scope_fault_code"], serde_json::Value::Null); + assert!(value["physical_slots"][0] + .as_object() + .unwrap() + .contains_key("fault_code")); + assert!(value["physical_slots"][0] + .as_object() + .unwrap() + .contains_key("setup")); + assert_eq!(value["physical_slots"][0]["setup"], serde_json::Value::Null); + } + #[test] + fn offline_client_runtime_diagnostics_classify_only_fixed_public_markers() { + let value = runtime_diagnostics( + b"PRIVATE_CANARY uv_cpu_info: EPERM; MAP_JIT mmap; oh no: Bun has crashed", + ); + assert!(value.within_cap); + assert!( + value.markers["UV_CPU_INFO"] + && value.markers["CODE_EPERM"] + && value.markers["BUN_CRASH"] + ); + assert!(!value.markers["UV_INTERFACE_ADDRESSES"]); + assert!(value.markers["MAP_JIT"] && value.markers["MMAP"] && value.markers["JIT"]); + let text = serde_json::to_string(&value).unwrap(); + assert!(!text.contains("PRIVATE_CANARY") && !text.contains("uv_cpu_info:")); + } + #[test] + fn offline_client_runtime_diagnostics_unknown_text_has_no_dynamic_keys_or_content() { + let value = runtime_diagnostics(b"PRIVATE_PROMPT_CANARY /private/PRIVATE_PATH_CANARY 1234"); + assert!(value.within_cap && value.markers.values().all(|x| !x)); + let expected: std::collections::BTreeSet<_> = + STDERR_MARKERS.iter().map(|(key, _)| *key).collect(); + assert_eq!( + value + .markers + .keys() + .copied() + .collect::>(), + expected + ); + assert_eq!(expected.len(), 32); + let text = serde_json::to_string(&value).unwrap(); + assert!(!text.contains("PRIVATE") && !text.contains("1234")); + } + #[test] + fn offline_client_runtime_diagnostics_refuse_oversize_without_matching_prefix() { + let mut raw = b"oh no: Bun has crashed".to_vec(); + raw.resize(8193, b'x'); + let value = runtime_diagnostics(&raw); + assert!(!value.within_cap); + assert!(value.markers.values().all(|x| !x)); + } + #[test] + fn offline_client_runtime_diagnostics_empty_is_bounded_without_a_cause() { + let value = runtime_diagnostics(b""); + assert!(value.within_cap && value.markers.values().all(|x| !x)); + } + #[test] + fn offline_client_panic_kind_projects_public_family_without_address_or_message() { + assert_eq!( + runtime_panic_kind(b"panic(main thread): Segmentation fault at address 0xDEADBEEF\n"), + Some(RuntimePanicKind::SegmentationFault) + ); + assert_eq!( + runtime_panic_kind(b"panic(main thread): A C++ exception occurred\n"), + Some(RuntimePanicKind::CppException) + ); + } + #[test] + fn offline_client_panic_kind_first_malformed_candidate_blocks_later_fake() { + assert_eq!( + runtime_panic_kind( + b"panic(main thread):\npanic(main thread): A C++ exception occurred\n" + ), + Some(RuntimePanicKind::Unknown) + ); + assert_eq!( + runtime_panic_kind(b"PRIVATE panic hidden\npanic(main thread): Stack overflow\n"), + Some(RuntimePanicKind::Unknown) + ); + } + #[test] + fn offline_client_panic_kind_private_suffix_or_oversize_is_unknown() { + assert_eq!( + runtime_panic_kind( + b"panic(main thread): Segmentation fault at address 0x1 PRIVATE_PATH\n" + ), + Some(RuntimePanicKind::Unknown) + ); + let mut raw = b"panic(main thread): A C++ exception occurred\n".to_vec(); + raw.resize(8193, b'x'); + assert_eq!(runtime_panic_kind(&raw), None); + } + #[test] + fn offline_client_bun_version_projects_numeric_components_only() { + assert_eq!( + runtime_bun_version(b"Bun v1.3.0 (PRIVATE_HASH) macOS Silicon\n"), + Some(BunVersion { + major: 1, + minor: 3, + patch: 0 + }) + ); + let text = + serde_json::to_string(&runtime_bun_version(b"Bun v1.3.0 (PRIVATE_HASH)\n")).unwrap(); + assert!(!text.contains("PRIVATE") && !text.contains("macOS")); + } + #[test] + fn offline_client_bun_version_first_invalid_candidate_cannot_fall_through() { + assert_eq!( + runtime_bun_version(b"Bun vPRIVATE\nBun v1.3.0 (fake)\n"), + None + ); + assert_eq!( + runtime_bun_version(b"PRIVATE Bun v1.3.0\nBun v1.3.0 (fake)\n"), + None + ); + assert_eq!(runtime_bun_version(b"Bun v1.3.0PRIVATE\n"), None); + } + #[test] + fn offline_client_bun_version_rejects_overflow_non_ascii_empty_and_oversize() { + for raw in [ + b"Bun v65536.3.0".as_slice(), + b"Bun v1.03.0", + b"Bun v1.3.0\xff", + b"", + ] { + assert_eq!(runtime_bun_version(raw), None); + } + let mut raw = b"Bun v1.3.0\n".to_vec(); + raw.resize(8193, b'x'); + assert_eq!(runtime_bun_version(&raw), None); + } +} diff --git a/src/skill_adapter.rs b/src/skill_adapter.rs new file mode 100644 index 0000000..2fd794f --- /dev/null +++ b/src/skill_adapter.rs @@ -0,0 +1,59 @@ +//! Platform boundary for native adapter management; manual CLI stays portable. +use crate::capture_runtime_pair::CaptureRuntimeIdentity; +use crate::cli::skill::SkillAgent; +use serde::Serialize; +use std::path::Path; + +pub struct InstallOptions<'a> { + pub source_root: &'a Path, + pub profile_home: &'a Path, + pub agent: SkillAgent, + pub runtime: &'a CaptureRuntimeIdentity, + pub confirm_migration: bool, + pub harness_version: Option<&'a str>, +} +#[derive(Debug, Serialize)] +pub struct InstallOutcome { + pub generation: String, + pub hooks_registered: usize, + pub migrated: bool, +} +#[derive(Debug, Serialize)] +pub struct UninstallOutcome { + pub hooks_removed: usize, + pub payload_removed: bool, + pub retained_generations: usize, +} +#[cfg(unix)] +#[path = "skill_adapter_unix.rs"] +mod implementation; +#[cfg(not(unix))] +mod implementation { + use super::*; + use crate::error::AppError; + fn unsupported() -> AppError { + AppError::Config("Native coding-agent capture installation is not supported on this platform. Manual CLI time workflows remain available.".into()) + } + pub fn install(_: InstallOptions<'_>) -> Result { + Err(unsupported()) + } + pub fn uninstall(_: &Path, _: SkillAgent) -> Result { + Err(unsupported()) + } + pub fn inspect( + _: &Path, + _: SkillAgent, + _: Option<&CaptureRuntimeIdentity>, + ) -> Result { + Ok(false) + } +} +#[cfg(all(unix, test))] +pub(crate) use implementation::tests; +#[cfg(unix)] +pub(crate) use implementation::{detect_version, install_prepared}; +pub use implementation::{inspect, install, uninstall}; +#[cfg(unix)] +pub(crate) fn registration_words(command: &str) -> Option> { + implementation::words(command) +} diff --git a/src/skill_adapter_unix.rs b/src/skill_adapter_unix.rs new file mode 100644 index 0000000..7ddc5f2 --- /dev/null +++ b/src/skill_adapter_unix.rs @@ -0,0 +1,2599 @@ +//! Native, recoverable management of only integration-owned adapter registrations. +use super::{InstallOptions, InstallOutcome, UninstallOutcome}; +use crate::adapter_files::{checkpoint, digest, failure, hex, identifier, nonce, Dir}; +use crate::capture_runtime_pair::CaptureRuntimeIdentity; +use crate::cli::skill::SkillAgent; +use crate::error::AppError; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +const RECEIPT: &str = "capture-install.json"; +const JOURNAL: &str = ".keito-capture-publication.json"; +const PLUGIN: &str = "keito-time-track@keito"; +type Payload = BTreeMap>; +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Receipt { + adapter_contract: u32, + agent: String, + harness_version: String, + trusted: String, + delivery_verified: bool, + generation: String, + files: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + guard_interpreter: Option, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Publication { + schema_version: u8, + stage: Option, + backup: String, +} +fn agent_name(agent: SkillAgent) -> &'static str { + match agent { + SkillAgent::Codex => "codex", + SkillAgent::ClaudeCode => "claude-code", + } +} +fn host_name(agent: SkillAgent) -> &'static str { + match agent { + SkillAgent::Codex => ".codex", + SkillAgent::ClaudeCode => ".claude", + } +} +fn config_name(agent: SkillAgent) -> &'static str { + match agent { + SkillAgent::Codex => "hooks.json", + SkillAgent::ClaudeCode => "settings.json", + } +} +fn payload_tree(dir: &Dir, prefix: &str, out: &mut Payload, depth: usize) -> Result<(), AppError> { + if depth > 16 { + return Err(failure()); + } + for entry in dir.entries()? { + if entry == RECEIPT && prefix.is_empty() { + continue; + } + let relative = if prefix.is_empty() { + entry.clone() + } else { + format!("{prefix}/{entry}") + }; + if let Ok(child) = dir.child(&entry, false) { + payload_tree(&child, &relative, out, depth + 1)?; + } else { + let bytes = dir.read(&entry, 8 * 1024 * 1024)?.ok_or_else(failure)?; + if out.len() >= 4096 + || out.values().map(Vec::len).sum::() + bytes.len() > 32 * 1024 * 1024 + { + return Err(failure()); + } + out.insert(relative, bytes); + } + } + Ok(()) +} +fn tree(dir: &Dir) -> Result { + let mut out = BTreeMap::new(); + payload_tree(dir, "", &mut out, 0)?; + Ok(out) +} +fn hashes(payload: &Payload) -> BTreeMap { + payload + .iter() + .map(|(k, v)| (k.clone(), digest(v))) + .collect() +} +fn generation_key( + agent: &str, + version: &str, + files: &BTreeMap, + runtime: &Value, +) -> Result { + Ok(digest( + serde_json::to_vec(&serde_json::json!([agent, version, files, runtime])) + .map_err(|_| failure())?, + )) +} +fn valid_runtime(value: &Value) -> bool { + let Some(v) = value.as_object() else { + return false; + }; + if v.len() != 7 { + return false; + } + ["core_path", "guard_path"].iter().all(|k| { + v.get(*k).and_then(Value::as_str).is_some_and(|s| { + Path::new(s).is_absolute() + && !Path::new(s).components().any(|c| { + matches!( + c, + std::path::Component::ParentDir | std::path::Component::CurDir + ) + }) + }) + }) && ["core_sha256", "guard_sha256"].iter().all(|k| { + v.get(*k) + .and_then(Value::as_str) + .is_some_and(|s| hex(s, 64)) + }) && ["version", "target"].iter().all(|k| { + v.get(*k) + .and_then(Value::as_str) + .is_some_and(|s| identifier(s, 128)) + }) && v.get("guard_contract").and_then(Value::as_u64) + == Some(crate::capture_runtime_pair::GUARD_CONTRACT as u64) +} +fn validate_receipt(dir: &Dir) -> Result { + let receipt: Receipt = + serde_json::from_slice(&dir.read(RECEIPT, 512 * 1024)?.ok_or_else(failure)?) + .map_err(|_| failure())?; + if !matches!(receipt.adapter_contract, 1 | 2) + || !matches!(receipt.agent.as_str(), "codex" | "claude-code") + || !identifier(&receipt.harness_version, 64) + || !hex(&receipt.generation, 64) + || receipt.files.is_empty() + { + return Err(failure()); + } + for (path, hash) in &receipt.files { + if Path::new(path).is_absolute() + || path + .split('/') + .any(|c| c.is_empty() || c == "." || c == "..") + || !hex(hash, 64) + { + return Err(failure()); + } + } + if receipt.adapter_contract == 2 { + let runtime = receipt + .runtime + .as_ref() + .filter(|v| valid_runtime(v)) + .ok_or_else(failure)?; + if receipt.guard_interpreter.is_some() + || generation_key( + &receipt.agent, + &receipt.harness_version, + &receipt.files, + runtime, + )? != receipt.generation + { + return Err(failure()); + } + } else if let Some(pin) = &receipt.guard_interpreter { + let p = pin + .as_object() + .filter(|p| p.len() == 2) + .ok_or_else(failure)?; + if !p + .get("path") + .and_then(Value::as_str) + .is_some_and(|s| Path::new(s).is_absolute()) + || !p + .get("sha256") + .and_then(Value::as_str) + .is_some_and(|s| hex(s, 64)) + || generation_key( + &receipt.agent, + &receipt.harness_version, + &receipt.files, + pin, + )? != receipt.generation + { + return Err(failure()); + } + } + let payload = tree(dir)?; + if hashes(&payload) != receipt.files { + return Err(failure()); + } + validate_modes(dir, "")?; + Ok(receipt) +} +fn validate_expected_receipt(dir: &Dir, expected: &[u8]) -> Result<(), AppError> { + validate_receipt(dir)?; + if dir.read(RECEIPT, 512 * 1024)?.as_deref() != Some(expected) { + return Err(failure()); + } + Ok(()) +} +fn validate_modes(dir: &Dir, prefix: &str) -> Result<(), AppError> { + use std::os::unix::fs::PermissionsExt; + if dir.metadata()?.permissions().mode() & 0o500 != 0o500 { + return Err(failure()); + } + for entry in dir.entries()? { + if let Ok(child) = dir.child(&entry, false) { + validate_modes(&child, &format!("{prefix}{entry}/"))?; + } else { + let mode = dir + .open(&entry)? + .metadata() + .map_err(|_| failure())? + .permissions() + .mode(); + if mode & 0o400 == 0 || (entry.ends_with(".sh") && mode & 0o100 == 0) { + return Err(failure()); + } + } + } + Ok(()) +} +fn write_payload( + dir: &Dir, + payload: &Payload, + check: &mut impl FnMut() -> Result<(), AppError>, +) -> Result<(), AppError> { + // Do not let a payload batch hide a cancellation/deadline between files. + // Individual filesystem syscalls remain synchronous and unpreemptable. + check()?; + // Payload is sorted. Retain only the common parent chain, never a growing + // path cache. Source traversal permits at most sixteen directory levels. + let mut directories = Vec::with_capacity(17); + directories.push(dir.clone()); + let mut previous: Vec<&str> = Vec::new(); + for (relative, bytes) in payload { + check()?; + let parts: Vec<_> = relative.split('/').collect(); + let (file, parents) = parts.split_last().ok_or_else(failure)?; + if parents.len() > 16 { + return Err(failure()); + } + let retained = previous + .iter() + .zip(parents) + .take_while(|(old, new)| old == new) + .count(); + directories.truncate(retained + 1); + for component in parents.iter().skip(retained) { + check()?; + let child = directories + .last() + .ok_or_else(failure)? + .child(component, true)?; + check()?; + directories.push(child); + } + previous = parents.to_vec(); + // atomic revalidates the entire anchored parent chain before opening + // and again after the file flush. Reuse never bypasses replacement checks. + check()?; + directories.last().ok_or_else(failure)?.atomic_checked( + file, + bytes, + if file.ends_with(".sh") { 0o700 } else { 0o600 }, + Some(None), + "install-payload-file-fsynced", + check, + )?; + check()?; + } + check()?; + dir.sync()?; + check() +} +fn parse_config(bytes: Option<&[u8]>) -> Result { + let value = match bytes { + Some(b) => serde_json::from_slice::(b).map_err(|_| failure())?, + None => serde_json::json!({}), + }; + let obj = value.as_object().ok_or_else(failure)?; + if let Some(hooks) = obj.get("hooks") { + for groups in hooks.as_object().ok_or_else(failure)?.values() { + for group in groups.as_array().ok_or_else(failure)? { + if group.as_object().is_none() + || group + .get("hooks") + .and_then(Value::as_array) + .ok_or_else(failure)? + .iter() + .any(|h| !h.is_object()) + { + return Err(failure()); + } + } + } + } + if obj.get("enabledPlugins").is_some_and(|v| !v.is_object()) { + return Err(failure()); + } + Ok(value) +} +/// Literal POSIX words only. Expansion, executable combinations and uncertainty +/// preserve the original command. Double-quoted backslash semantics are POSIX. +pub(super) fn words(command: &str) -> Option> { + let mut words = Vec::new(); + let mut word = String::new(); + let mut quote = None; + let mut active = false; + let mut chars = command.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\n' || c == '\r' { + return None; + } + match quote { + Some('\'') => { + if c == '\'' { + quote = None; + } else { + word.push(c); + } + } + _ => { + if c == '\\' { + let next = chars.next()?; + if next == '\n' || next == '\r' { + return None; + } + if quote == Some('"') && !"$`\"\\".contains(next) { + word.push('\\'); + } + word.push(next); + active = true; + continue; + } + if c == '\'' && quote.is_none() { + quote = Some('\''); + active = true; + continue; + } + if c == '"' { + quote = if quote == Some('"') { None } else { Some('"') }; + active = true; + continue; + } + if "$`".contains(c) || (quote.is_none() && ";&|<>(){}*?[]~#".contains(c)) { + return None; + } + if c.is_whitespace() && quote.is_none() { + if active { + words.push(std::mem::take(&mut word)); + active = false; + } + continue; + } + word.push(c); + } + } + active = true; + } + if quote.is_some() { + return None; + } + if active { + words.push(word); + } + Some(words) +} +fn resolve_existing_prefix(path: &Path) -> Option { + let mut prefix = path.to_path_buf(); + let mut tail = Vec::new(); + loop { + if let Ok(mut canonical) = prefix.canonicalize() { + for part in tail.iter().rev() { + canonical.push(part); + } + return Some(canonical); + } + tail.push(prefix.file_name()?.to_os_string()); + if !prefix.pop() { + return None; + } + } +} +fn owned(hook: &Value, dest: &Path, agent: &str) -> Option { + if hook.get("type")?.as_str()? != "command" { + return None; + } + let mut argv = words(hook.get("command")?.as_str()?)?; + let modern = argv.first().is_some_and(|s| s == "exec"); + if modern { + argv.remove(0); + if argv.first().map(String::as_str) != Some("/usr/bin/env") { + return None; + } + } + if argv + .first() + .is_some_and(|s| matches!(s.as_str(), "env" | "/usr/bin/env")) + { + argv.remove(0); + } + let mut environment = BTreeMap::new(); + while let Some((key, value)) = argv.first().and_then(|s| s.split_once('=')) { + if !matches!( + key, + "KEITO_CLI_BIN" + | "KEITO_CAPTURE_GUARD_BIN" + | "KEITO_CAPTURE_CORE_SHA256" + | "KEITO_AGENT_TYPE" + | "KEITO_HARNESS_VERSION" + | "KEITO_CAPTURE_PYTHON" + ) || environment + .insert(key.to_owned(), value.to_owned()) + .is_some() + { + return None; + } + argv.remove(0); + } + if modern + && (environment.len() != 3 + || !["KEITO_CLI_BIN", "KEITO_CAPTURE_GUARD_BIN"] + .iter() + .all(|k| { + environment + .get(*k) + .is_some_and(|s| Path::new(s).is_absolute()) + }) + || !environment + .get("KEITO_CAPTURE_CORE_SHA256") + .is_some_and(|s| hex(s, 64))) + { + return None; + } + if argv + .first() + .is_some_and(|s| matches!(s.as_str(), "bash" | "/bin/bash" | "/usr/bin/bash")) + { + argv.remove(0); + } + let supplied = Path::new(argv.first()?); + if !supplied.is_absolute() + || supplied.components().any(|c| { + matches!( + c, + std::path::Component::ParentDir | std::path::Component::CurDir + ) + }) + { + return None; + } + let resolved = resolve_existing_prefix(supplied)?; + let executable = resolved.as_path(); + if !executable.is_absolute() + || executable.components().any(|c| { + matches!( + c, + std::path::Component::ParentDir | std::path::Component::CurDir + ) + }) + { + return None; + } + let script = executable.file_name()?.to_str()?; + let scripts = [ + "dispatch.sh", + "session-start.sh", + "session-end.sh", + "session-finalize.sh", + "prompt.sh", + "stop.sh", + "interrupt.sh", + ]; + let legacy = + executable.parent() == Some(dest.join("hooks").as_path()) && scripts.contains(&script); + let generation = executable.parent()?.parent()?; + let host = dest.parent()?.parent()?; + let generated = script == "dispatch.sh" + && executable.parent()?.file_name()?.to_str()? == "hooks" + && generation.parent() == Some(host.join(".keito-capture-generations").as_path()) + && hex(generation.file_name()?.to_str()?, 64); + if !legacy && !generated { + return None; + } + let args = &argv[1..]; + if script != "dispatch.sh" { + return (args.is_empty() + && environment.get("KEITO_AGENT_TYPE").map(String::as_str) == Some(agent)) + .then_some(true); + } + if args.len() != 6 { + return None; + } + let mut flags = BTreeMap::new(); + for pair in args.as_chunks::<2>().0 { + if !matches!( + pair[0].as_str(), + "--agent" | "--event" | "--harness-version" + ) || flags.insert(pair[0].as_str(), pair[1].as_str()).is_some() + { + return None; + } + } + (flags.get("--agent") == Some(&agent) + && flags.get("--event").is_some_and(|e| { + matches!( + *e, + "session-start" | "prompt" | "stop" | "session-end" | "interrupt" + ) + }) + && flags + .get("--harness-version") + .is_some_and(|v| identifier(v, 64))) + .then_some(false) +} +fn strip(value: &mut Value, dest: &Path, agent: &str) -> (usize, bool) { + let mut removed = 0; + let mut legacy = false; + if let Some(events) = value.get_mut("hooks").and_then(Value::as_object_mut) { + events.retain(|_, groups| { + groups.as_array_mut().unwrap().retain_mut(|group| { + let hooks = group["hooks"].as_array_mut().unwrap(); + let empty = hooks.is_empty(); + hooks.retain(|h| { + if let Some(old) = owned(h, dest, agent) { + removed += 1; + legacy |= old; + false + } else { + true + } + }); + empty || !hooks.is_empty() + }); + !groups.as_array().unwrap().is_empty() + }); + } + (removed, legacy) +} +fn recovery_name(value: &str, prefix: &str, length: Option) -> bool { + value.strip_prefix(prefix).is_some_and(|s| { + !s.is_empty() + && s.bytes() + .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c)) + && length.is_none_or(|n| hex(s, n)) + }) +} +fn recover(host: &Dir, skills: &Dir) -> Result<(), AppError> { + recover_checked(host, skills, &mut || Ok(())) +} +fn recover_checked( + host: &Dir, + skills: &Dir, + check: &mut impl FnMut() -> Result<(), AppError>, +) -> Result<(), AppError> { + check()?; + let Some(bytes) = host.read(JOURNAL, 512 * 1024)? else { + return Ok(()); + }; + check()?; + let journal: Publication = serde_json::from_slice(&bytes).map_err(|_| failure())?; + if journal.schema_version != 1 + || !recovery_name(&journal.backup, ".keito-time-track-backup-", Some(32)) + || journal + .stage + .as_ref() + .is_some_and(|s| !recovery_name(s, ".keito-time-track-stage-", None)) + { + return Err(failure()); + } + check()?; + if skills.exists(&journal.backup)? { + skills.child(&journal.backup, false)?; + if !skills.exists("keito-time-track")? { + check()?; + skills.rename(&journal.backup, skills, "keito-time-track")?; + check()?; + } + } + check()?; + if let Some(stage) = journal.stage { + if skills.exists(&stage)? { + let staged = skills.child(&stage, false)?; + check()?; + validate_receipt(&staged)?; + skills.remove_tree_checked(&stage, check)?; + } + } + check()?; + host.unlink(JOURNAL, false)?; + check() +} +fn runtime_unchanged(runtime: &CaptureRuntimeIdentity) -> Result<(), AppError> { + use sha2::{Digest, Sha256}; + use std::io::Read; + use std::os::unix::fs::PermissionsExt; + let value = serde_json::to_value(runtime).map_err(|_| failure())?; + if !valid_runtime(&value) { + return Err(failure()); + } + for (path, expected) in [ + (&runtime.core_path, &runtime.core_sha256), + (&runtime.guard_path, &runtime.guard_sha256), + ] { + let parent = Dir::anchor(path.parent().ok_or_else(failure)?)?; + let file = parent.open( + path.file_name() + .and_then(|s| s.to_str()) + .ok_or_else(failure)?, + )?; + let info = file.metadata().map_err(|_| failure())?; + if info.len() > 512 * 1024 * 1024 || info.permissions().mode() & 0o100 == 0 { + return Err(failure()); + } + let mut hasher = Sha256::new(); + let mut file = file.take(512 * 1024 * 1024 + 1); + let mut block = [0u8; 64 * 1024]; + loop { + let n = file.read(&mut block).map_err(|_| failure())?; + if n == 0 { + break; + } + hasher.update(&block[..n]); + } + let hash: String = hasher + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + if &hash != expected { + return Err(failure()); + } + } + Ok(()) +} +pub(crate) fn detect_version( + agent: SkillAgent, + runner: &mut impl crate::process_ownership::probes::LeafRunner, +) -> Result { + use std::process::{Command, Stdio}; + let binary = if agent == SkillAgent::Codex { + "codex" + } else { + "claude" + }; + let mut command = Command::new(binary); + command + .arg("--version") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + let result = runner + .output(command, 8192, 8192) + .map_err(crate::capture_command_owner::version_probe_error)?; + if !result.status.success() { + return Ok("unknown".into()); + } + let bytes = String::from_utf8(result.output.stdout).map_err(|_| failure())?; + Ok(bytes + .split_whitespace() + .find(|s| { + identifier(s, 64) + && s.split('.').take(3).count() == 3 + && s.as_bytes()[0].is_ascii_digit() + }) + .unwrap_or("unknown") + .to_owned()) +} +pub fn install(options: InstallOptions<'_>) -> Result { + let version = match options.harness_version { + Some(version) => version.to_owned(), + None => { + let mut owner = crate::capture_command_owner::CommandOwner::standalone()?; + let result = detect_version(options.agent, &mut owner); + owner.finish(result)? + } + }; + install_versioned(options, version) +} +pub(crate) fn install_prepared( + options: InstallOptions<'_>, + version: String, + check: &mut impl FnMut() -> Result<(), AppError>, +) -> Result { + install_versioned_checked(options, version, check) +} +fn install_versioned( + options: InstallOptions<'_>, + version: String, +) -> Result { + install_versioned_checked(options, version, &mut || Ok(())) +} +fn install_versioned_checked( + options: InstallOptions<'_>, + version: String, + check: &mut impl FnMut() -> Result<(), AppError>, +) -> Result { + check()?; + if !identifier(&version, 64) { + return Err(AppError::InvalidInput("Harness version is incompatible with the capture identifier contract; review and qualify the exact version without truncating it.".into())); + } + runtime_unchanged(options.runtime)?; + let payload = tree(&Dir::anchor(options.source_root)?)?; + check()?; + if payload.is_empty() + || !payload.contains_key("SKILL.md") + || !payload.contains_key("hooks/dispatch.sh") + || payload.keys().any(|p| { + p.ends_with(".py") + || p.starts_with("tests/") + || p.split('/').any(|c| c == "__pycache__") + }) + { + return Err(failure()); + } + let home = Dir::anchor(options.profile_home)?; + let host = home.child(host_name(options.agent), true)?; + let _lock = host.lock(&format!("{}.keito.lock", config_name(options.agent)))?; + // Check each parent before publishing a generation or a configuration. + let skills = host.child("skills", true)?; + recover_checked(&host, &skills, check)?; + let config = config_name(options.agent); + let original = host.read(config, 1024 * 1024)?; + let mut data = parse_config(original.as_deref())?; + let dest = skills.path.join("keito-time-track"); + let (_, legacy) = strip(&mut data, &dest, agent_name(options.agent)); + let plugin = options.agent == SkillAgent::ClaudeCode + && data + .get("enabledPlugins") + .and_then(|p| p.get(PLUGIN)) + .and_then(Value::as_bool) + == Some(true); + if (legacy || plugin) && !options.confirm_migration { + return Err(AppError::Conflict("Legacy Keito hooks/plugin require review; retry with --confirm-migration only after reviewing the migration.".into())); + } + let exists = skills.exists("keito-time-track")?; + let known = exists + && skills + .child("keito-time-track", false) + .and_then(|d| validate_receipt(&d)) + .is_ok(); + let original_receipt = if known { + skills + .child("keito-time-track", false)? + .read(RECEIPT, 512 * 1024)? + } else { + None + }; + if exists && !known && !options.confirm_migration { + return Err(failure()); + } + // Even confirmed legacy migration must never move a symlink or non-directory. + if exists { + skills.child("keito-time-track", false)?; + } + if plugin { + data["enabledPlugins"][PLUGIN] = Value::Bool(false); + } + let runtime = serde_json::to_value(options.runtime).map_err(|_| failure())?; + let files = hashes(&payload); + let key = generation_key(agent_name(options.agent), &version, &files, &runtime)?; + let generations = host.child(".keito-capture-generations", true)?; + let stage_name = format!(".keito-time-track-stage-{}", &nonce()?[..32]); + let staged = generations.child(&stage_name, true)?; + let mut complete = payload.clone(); + let receipt = Receipt { + adapter_contract: 2, + agent: agent_name(options.agent).into(), + harness_version: version.clone(), + trusted: "unknown".into(), + delivery_verified: false, + generation: key.clone(), + files, + runtime: Some(runtime), + guard_interpreter: None, + }; + complete.insert( + RECEIPT.into(), + serde_json::to_vec_pretty(&receipt).map_err(|_| failure())?, + ); + write_payload(&staged, &complete, check)?; + check()?; + if generations.exists(&key)? { + let existing = generations.child(&key, false)?; + let old = validate_receipt(&existing)?; + if old.adapter_contract != 2 + || old.generation != key + || old.runtime != receipt.runtime + || tree(&existing)? != payload + { + return Err(failure()); + } + generations.remove_tree_checked(&stage_name, check)?; + } else { + generations.rename(&stage_name, &generations, &key)?; + checkpoint("install-generation-published"); + } + let generation = generations.child(&key, false)?; + validate_receipt(&generation)?; + check()?; + let discovery_stage = format!(".keito-time-track-stage-{}", &nonce()?[..32]); + let staged = skills.child(&discovery_stage, true)?; + write_payload(&staged, &complete, check)?; + check()?; + let hooks = data + .as_object_mut() + .unwrap() + .entry("hooks") + .or_insert_with(|| Value::Object(Map::new())) + .as_object_mut() + .unwrap(); + let events = [ + ("SessionStart", "session-start"), + ("UserPromptSubmit", "prompt"), + ("Stop", "stop"), + ("SessionEnd", "session-end"), + ( + if options.agent == SkillAgent::ClaudeCode { + "StopFailure" + } else { + "Interrupt" + }, + "interrupt", + ), + ]; + for (event, lifecycle) in events { + let command=format!("exec /usr/bin/env KEITO_CLI_BIN={} KEITO_CAPTURE_GUARD_BIN={} KEITO_CAPTURE_CORE_SHA256={} {} --agent {} --event {} --harness-version {}",quote(options.runtime.core_path.to_str().ok_or_else(failure)?),quote(options.runtime.guard_path.to_str().ok_or_else(failure)?),options.runtime.core_sha256,quote(generation.path.join("hooks/dispatch.sh").to_str().ok_or_else(failure)?),agent_name(options.agent),lifecycle,quote(&version)); + hooks + .entry(event) + .or_insert_with(|| Value::Array(vec![])) + .as_array_mut() + .unwrap() + .push(serde_json::json!({"hooks":[{"type":"command","command":command,"timeout":1}]})); + } + let backup = format!(".keito-time-track-backup-{}", &nonce()?[..32]); + let publication = Publication { + schema_version: 1, + stage: Some(discovery_stage.clone()), + backup: backup.clone(), + }; + let result = (|| { + host.atomic( + JOURNAL, + &serde_json::to_vec(&publication).map_err(|_| failure())?, + 0o600, + Some(None), + "install-journal-fsynced", + )?; + check()?; + runtime_unchanged(options.runtime)?; + if let Some(receipt) = &original_receipt { + validate_expected_receipt(&skills.child("keito-time-track", false)?, receipt)?; + } + host.atomic_checked( + config, + &serde_json::to_vec_pretty(&data).map_err(|_| failure())?, + 0o600, + Some(original.as_deref()), + "install-config-fsynced", + check, + )?; + checkpoint("install-config-published"); + if exists { + if let Some(receipt) = &original_receipt { + validate_expected_receipt(&skills.child("keito-time-track", false)?, receipt)?; + } + check()?; + skills.rename("keito-time-track", &skills, &backup)?; + checkpoint("install-payload-backup"); + if let Some(receipt) = &original_receipt { + validate_expected_receipt(&skills.child(&backup, false)?, receipt)?; + } + } + check()?; + skills.rename(&discovery_stage, &skills, "keito-time-track")?; + checkpoint("install-discovery-published"); + host.unlink(JOURNAL, false) + })(); + // Refusal retains the journal/stage for a later operation rather than + // starting recursive recovery outside the original publication owner. + let cleanup: Result<(), AppError> = (|| { + check()?; + if host.exists(JOURNAL)? { + recover_checked(&host, &skills, check)?; + } else if skills.exists(&discovery_stage)? { + skills.remove_tree_checked(&discovery_stage, check)?; + } + Ok(()) + })(); + // A secondary cleanup refusal must not replace the original failure. + result?; + cleanup?; + if let Some(receipt) = &original_receipt { + if skills.exists(&backup)? { + validate_expected_receipt(&skills.child(&backup, false)?, receipt)?; + skills.remove_tree_checked(&backup, check)?; + } + } + check()?; + Ok(InstallOutcome { + generation: key, + hooks_registered: 5, + migrated: legacy || plugin || (exists && !known), + }) +} +pub fn uninstall(profile_home: &Path, agent: SkillAgent) -> Result { + let home = Dir::anchor(profile_home)?; + if !home.exists(host_name(agent))? { + return Ok(UninstallOutcome { + hooks_removed: 0, + payload_removed: false, + retained_generations: 0, + }); + } + let host = home.child(host_name(agent), false)?; + let _lock = host.lock(&format!("{}.keito.lock", config_name(agent)))?; + let skills = host.child("skills", true)?; + recover(&host, &skills)?; + let config = config_name(agent); + let original = host.read(config, 1024 * 1024)?; + let mut data = parse_config(original.as_deref())?; + let exists = skills.exists("keito-time-track")?; + if exists { + validate_receipt(&skills.child("keito-time-track", false)?)?; + } + let original_receipt = if exists { + skills + .child("keito-time-track", false)? + .read(RECEIPT, 512 * 1024)? + } else { + None + }; + let (removed, _) = strip( + &mut data, + &skills.path.join("keito-time-track"), + agent_name(agent), + ); + let backup = format!(".keito-time-track-backup-{}", &nonce()?[..32]); + let publication = Publication { + schema_version: 1, + stage: None, + backup: backup.clone(), + }; + let result = (|| { + host.atomic( + JOURNAL, + &serde_json::to_vec(&publication).map_err(|_| failure())?, + 0o600, + Some(None), + "uninstall-journal-fsynced", + )?; + if let Some(receipt) = &original_receipt { + validate_expected_receipt(&skills.child("keito-time-track", false)?, receipt)?; + } + host.atomic( + config, + &serde_json::to_vec_pretty(&data).map_err(|_| failure())?, + 0o600, + Some(original.as_deref()), + "uninstall-config-fsynced", + )?; + if exists { + if let Some(receipt) = &original_receipt { + validate_expected_receipt(&skills.child("keito-time-track", false)?, receipt)?; + } + skills.rename("keito-time-track", &skills, &backup)?; + checkpoint("uninstall-payload-backup"); + if let Some(receipt) = &original_receipt { + validate_expected_receipt(&skills.child(&backup, false)?, receipt)?; + } + } + host.unlink(JOURNAL, false) + })(); + if host.exists(JOURNAL)? { + recover(&host, &skills)?; + } + result?; + if let Some(receipt) = &original_receipt { + if skills.exists(&backup)? { + validate_expected_receipt(&skills.child(&backup, false)?, receipt)?; + skills.remove_tree(&backup)?; + } + } + let retained = if host.exists(".keito-capture-generations")? { + host.child(".keito-capture-generations", false)? + .entries()? + .iter() + .filter(|s| hex(s, 64)) + .count() + } else { + 0 + }; + Ok(UninstallOutcome { + hooks_removed: removed, + payload_removed: exists, + retained_generations: retained, + }) +} + +/// Read-only configuration inspection. Runtime identity must come from the +/// caller's release-anchor verifier; no binaries, network or version probes run. +/// Invalid, legacy, pending or incomplete local state is conservatively false. +pub fn inspect( + profile_home: &Path, + agent: SkillAgent, + runtime: Option<&CaptureRuntimeIdentity>, +) -> Result { + let Some(runtime) = runtime else { + return Ok(false); + }; + let checked = (|| -> Result { + runtime_unchanged(runtime)?; + let home = Dir::anchor(profile_home)?; + if !home.exists(host_name(agent))? { + return Ok(false); + } + let host = home.child(host_name(agent), false)?; + if host.exists(JOURNAL)? { + return Ok(false); + } + let skills = host.child("skills", false)?; + let dest = skills.child("keito-time-track", false)?; + let receipt = validate_receipt(&dest)?; + let serialized_runtime = serde_json::to_value(runtime).map_err(|_| failure())?; + if receipt.adapter_contract != 2 + || receipt.agent != agent_name(agent) + || receipt.harness_version == "unknown" + || receipt.files.keys().any(|p| { + p.ends_with(".py") + || p.ends_with(".pyc") + || p.starts_with("tests/") + || p.split('/').any(|c| c == "__pycache__") + }) + || receipt.runtime.as_ref() != Some(&serialized_runtime) + || receipt.trusted != "unknown" + || receipt.delivery_verified + { + return Ok(false); + } + let generation = host + .child(".keito-capture-generations", false)? + .child(&receipt.generation, false)?; + let generation_receipt = validate_receipt(&generation)?; + if serde_json::to_value(&generation_receipt).map_err(|_| failure())? + != serde_json::to_value(&receipt).map_err(|_| failure())? + { + return Ok(false); + } + let original = host.read(config_name(agent), 1024 * 1024)?; + let data = parse_config(original.as_deref())?; + if agent == SkillAgent::ClaudeCode + && data + .get("enabledPlugins") + .and_then(|p| p.get(PLUGIN)) + .and_then(Value::as_bool) + == Some(true) + { + return Ok(false); + } + let Some(events) = data.get("hooks").and_then(Value::as_object) else { + return Ok(false); + }; + let expected_events = [ + ("SessionStart", "session-start"), + ("UserPromptSubmit", "prompt"), + ("Stop", "stop"), + ("SessionEnd", "session-end"), + ( + if agent == SkillAgent::ClaudeCode { + "StopFailure" + } else { + "Interrupt" + }, + "interrupt", + ), + ]; + let mut seen = BTreeMap::new(); + for (event, groups) in events { + for group in groups.as_array().ok_or_else(failure)? { + for hook in group["hooks"].as_array().ok_or_else(failure)? { + let command = hook.get("command").and_then(Value::as_str).unwrap_or(""); + let actual = words(command); + let expected = expected_events.iter().find(|(name, _)| name == event).map( + |(_, lifecycle)| { + vec![ + "exec".into(), + "/usr/bin/env".into(), + format!("KEITO_CLI_BIN={}", runtime.core_path.display()), + format!("KEITO_CAPTURE_GUARD_BIN={}", runtime.guard_path.display()), + format!("KEITO_CAPTURE_CORE_SHA256={}", runtime.core_sha256), + generation + .path + .join("hooks/dispatch.sh") + .display() + .to_string(), + "--agent".into(), + agent_name(agent).into(), + "--event".into(), + (*lifecycle).into(), + "--harness-version".into(), + receipt.harness_version.clone(), + ] + }, + ); + if actual + .as_ref() + .is_some_and(|v| Some(v) == expected.as_ref()) + { + if hook.as_object().is_none_or(|h| h.len() != 3) + || hook.get("type").and_then(Value::as_str) != Some("command") + || hook.get("timeout").and_then(Value::as_u64) != Some(1) + || group.as_object().is_none_or(|g| g.len() != 1) + || group["hooks"].as_array().is_none_or(|h| h.len() != 1) + { + return Ok(false); + } + *seen.entry(event.as_str()).or_insert(0usize) += 1; + } else if owned(hook, &dest.path, agent_name(agent)).is_some() + || actual + .as_ref() + .is_some_and(|v| invokes_adapter(v, &dest.path, &host.path)) + || (actual.is_none() + && (command.contains(".keito-capture-generations/") + || command.contains("/skills/keito-time-track/hooks/"))) + { + return Ok(false); + } + } + } + } + Ok(expected_events + .iter() + .all(|(name, _)| seen.get(name) == Some(&1)) + && seen.len() == 5) + })(); + Ok(checked.unwrap_or(false)) +} +fn invokes_adapter(words: &[String], dest: &Path, host: &Path) -> bool { + let mut argv = words; + if argv.first().is_some_and(|s| s == "exec") { + if argv.get(1).map(String::as_str) != Some("/usr/bin/env") { + return false; + } + argv = &argv[1..]; + } + if argv + .first() + .is_some_and(|s| matches!(s.as_str(), "env" | "/usr/bin/env")) + { + argv = &argv[1..]; + } + while argv.first().is_some_and(|s| { + s.split_once('=').is_some_and(|(key, _)| { + !key.is_empty() && key.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') + }) + }) { + argv = &argv[1..]; + } + if argv + .first() + .is_some_and(|s| matches!(s.as_str(), "bash" | "/bin/bash" | "/usr/bin/bash")) + { + argv = &argv[1..]; + } + let Some(path) = argv + .first() + .and_then(|s| resolve_existing_prefix(Path::new(s))) + else { + return false; + }; + path.starts_with(dest.join("hooks")) + || path.starts_with(host.join(".keito-capture-generations")) +} + +fn quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\"'\"'")) +} +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::adapter_files::set_hook; + use std::fs; + use std::os::unix::fs::{symlink, PermissionsExt}; + struct RefusedVersion(std::io::Error); + impl crate::process_ownership::probes::LeafRunner for RefusedVersion { + fn output( + &mut self, + _: std::process::Command, + _: usize, + _: usize, + ) -> std::io::Result { + Err(std::mem::replace( + &mut self.0, + std::io::Error::other("used"), + )) + } + } + #[test] + fn version_probe_failure_has_closed_category_and_no_file_or_login_diagnosis() { + let canary = "PRIVATE_PROBE_SECRET_/original/profile"; + let error = detect_version( + SkillAgent::Codex, + &mut RefusedVersion(std::io::Error::other(canary)), + ) + .err() + .unwrap(); + let serialized = error.to_json(); + let value: Value = serde_json::from_str(&serialized).unwrap(); + assert_eq!(value["details"]["kind"], "capture_version_probe"); + assert_eq!(value["details"]["reason"], "unavailable"); + assert!(!serialized.contains(canary)); + assert!(!serialized.contains("adapter files")); + assert!(!serialized.contains("auth login")); + assert_eq!(error.exit_code(), 8); + } + #[test] + fn version_probe_failure_retains_closed_owner_admission_reason() { + let error = detect_version( + SkillAgent::ClaudeCode, + &mut RefusedVersion(std::io::Error::other( + crate::process_ownership::protocol::ProtocolError("SCOPE_ADMISSION"), + )), + ) + .err() + .unwrap(); + let value: Value = serde_json::from_str(&error.to_json()).unwrap(); + assert_eq!(value["details"]["kind"], "capture_version_probe"); + assert_eq!(value["details"]["reason"], "admission_refused"); + assert_eq!(value["details"]["cleanup_unverified"], false); + } + struct Fixture { + root: tempfile::TempDir, + home: PathBuf, + source: PathBuf, + runtime: CaptureRuntimeIdentity, + } + impl Fixture { + fn new() -> Self { + let root = tempfile::tempdir().unwrap(); + let home = root.path().join("home with ' literal $"); + let source = root.path().join("source"); + fs::create_dir(&home).unwrap(); + fs::create_dir(home.join("capture")).unwrap(); + fs::create_dir_all(source.join("hooks")).unwrap(); + fs::write(source.join("SKILL.md"), "synthetic native skill").unwrap(); + fs::write(source.join("hooks/dispatch.sh"), "#!/bin/sh\nexit 0\n").unwrap(); + let core = root.path().join("core"); + let guard = root.path().join("guard"); + fs::write(&core, b"synthetic core").unwrap(); + fs::write(&guard, b"synthetic guard").unwrap(); + for p in [&core, &guard] { + fs::set_permissions(p, fs::Permissions::from_mode(0o700)).unwrap(); + } + let runtime = CaptureRuntimeIdentity { + core_path: core, + guard_path: guard, + core_sha256: digest(b"synthetic core"), + guard_sha256: digest(b"synthetic guard"), + version: "0.2.0".into(), + target: "aarch64-apple-darwin".into(), + guard_contract: 2, + }; + Self { + root, + home, + source, + runtime, + } + } + fn install( + &self, + agent: SkillAgent, + version: &str, + migrate: bool, + ) -> Result { + install(InstallOptions { + source_root: &self.source, + profile_home: &self.home, + agent, + runtime: &self.runtime, + confirm_migration: migrate, + harness_version: Some(version), + }) + } + fn config(&self) -> PathBuf { + self.home.join(".codex/hooks.json") + } + fn json(&self) -> Value { + serde_json::from_slice(&fs::read(self.config()).unwrap()).unwrap() + } + fn seed(&self, value: Value) { + fs::create_dir_all(self.home.join(".codex")).unwrap(); + fs::write(self.config(), serde_json::to_vec(&value).unwrap()).unwrap(); + } + } + #[test] + fn payload_directory_reuse_keeps_each_mutation_durable_without_noop_parent_flushes() { + use std::{cell::Cell, rc::Rc}; + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + set_hook(None); + } + } + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let payload: Payload = [ + "SKILL.md", + "hooks/nested/a.sh", + "hooks/nested/b.sh", + "hooks/one.sh", + "hooks/two.sh", + ] + .into_iter() + .map(|path| (path.to_owned(), path.as_bytes().to_vec())) + .collect(); + let syncs = Rc::new(Cell::new(0)); + let count = Rc::clone(&syncs); + let _reset = Reset; + set_hook(Some(Box::new(move |phase| { + if phase == "adapter-directory-fsynced" { + count.set(count.get() + 1); + } + }))); + write_payload(&dir, &payload, &mut || Ok(())).unwrap(); + assert_eq!( + syncs.get(), + 8, + "five file renames, two directory creations, final root flush" + ); + assert_eq!(tree(&dir).unwrap(), payload); + for path in payload.keys() { + let expected = if path.ends_with(".sh") { 0o700 } else { 0o600 }; + assert_eq!( + fs::metadata(root.path().join(path)) + .unwrap() + .permissions() + .mode() + & 0o777, + expected + ); + } + for path in ["hooks", "hooks/nested"] { + assert_eq!( + fs::metadata(root.path().join(path)) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o700 + ); + } + } + #[test] + fn payload_directory_reuse_refuses_a_replaced_parent_before_the_next_file() { + use std::{cell::Cell, rc::Rc}; + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + set_hook(None); + } + } + let root = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let payload: Payload = ["hooks/a.sh", "hooks/b.sh"] + .into_iter() + .map(|path| (path.to_owned(), path.as_bytes().to_vec())) + .collect(); + let replaced = Rc::new(Cell::new(false)); + let observed = Rc::clone(&replaced); + let base = root.path().to_owned(); + let foreign = outside.path().to_owned(); + let _reset = Reset; + set_hook(Some(Box::new(move |phase| { + if phase == "adapter-entry-renamed" && !observed.replace(true) { + fs::rename(base.join("hooks"), base.join("retained")).unwrap(); + std::os::unix::fs::symlink(&foreign, base.join("hooks")).unwrap(); + } + }))); + assert!(write_payload(&dir, &payload, &mut || Ok(())).is_err()); + assert!(replaced.get()); + assert!(fs::read_dir(outside.path()).unwrap().next().is_none()); + assert!(root.path().join("retained/a.sh").is_file()); + assert!(!root.path().join("retained/b.sh").exists()); + assert!(fs::symlink_metadata(root.path().join("hooks")) + .unwrap() + .file_type() + .is_symlink()); + } + struct PayloadOwnerHookReset; + impl Drop for PayloadOwnerHookReset { + fn drop(&mut self) { + set_hook(None); + } + } + fn payload_owner_refusal() -> AppError { + AppError::Conflict("Original payload owner refusal".into()) + } + #[test] + fn payload_owner_already_refused_creates_no_file_or_directory() { + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let payload: Payload = [("hooks/a.sh".into(), b"a".to_vec())].into_iter().collect(); + let result = write_payload(&dir, &payload, &mut || Err(payload_owner_refusal())); + assert!( + matches!(result, Err(AppError::Conflict(message)) if message == "Original payload owner refusal") + ); + assert!(dir.entries().unwrap().is_empty()); + } + #[test] + fn payload_owner_file_flush_refusal_prevents_rename_and_next_file() { + use std::{cell::Cell, rc::Rc}; + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let payload: Payload = [("a".into(), b"a".to_vec()), ("b".into(), b"b".to_vec())] + .into_iter() + .collect(); + let refused = Rc::new(Cell::new(false)); + let observed = Rc::clone(&refused); + let _reset = PayloadOwnerHookReset; + set_hook(Some(Box::new(move |phase| { + if phase == "install-payload-file-fsynced" { + observed.set(true); + } + }))); + let result = write_payload(&dir, &payload, &mut || { + if refused.get() { + Err(payload_owner_refusal()) + } else { + Ok(()) + } + }); + assert!(refused.get(), "actual payload file flush must be reached"); + assert!( + matches!(result, Err(AppError::Conflict(message)) if message == "Original payload owner refusal") + ); + assert!( + dir.entries().unwrap().is_empty(), + "refused temporary payload must not publish or leak" + ); + } + #[test] + fn payload_owner_after_rename_preserves_first_file_and_refuses_second() { + use std::{cell::Cell, rc::Rc}; + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let payload: Payload = [("a".into(), b"a".to_vec()), ("b".into(), b"b".to_vec())] + .into_iter() + .collect(); + let refused = Rc::new(Cell::new(false)); + let observed = Rc::clone(&refused); + let _reset = PayloadOwnerHookReset; + set_hook(Some(Box::new(move |phase| { + if phase == "adapter-entry-renamed" { + observed.set(true); + } + }))); + let result = write_payload(&dir, &payload, &mut || { + if refused.get() { + Err(payload_owner_refusal()) + } else { + Ok(()) + } + }); + assert!(refused.get(), "actual rename must be reached"); + assert!( + matches!(result, Err(AppError::Conflict(message)) if message == "Original payload owner refusal") + ); + assert_eq!(fs::read(root.path().join("a")).unwrap(), b"a"); + assert_eq!(dir.entries().unwrap(), vec!["a".to_owned()]); + } + #[test] + fn payload_owner_directory_flush_refusal_prevents_descending_or_writing() { + use std::{cell::Cell, rc::Rc}; + let root = tempfile::tempdir().unwrap(); + let dir = Dir::anchor(root.path()).unwrap(); + let payload: Payload = [("hooks/nested/a.sh".into(), b"a".to_vec())] + .into_iter() + .collect(); + let refused = Rc::new(Cell::new(false)); + let observed = Rc::clone(&refused); + let _reset = PayloadOwnerHookReset; + set_hook(Some(Box::new(move |phase| { + if phase == "adapter-directory-fsynced" { + observed.set(true); + } + }))); + let result = write_payload(&dir, &payload, &mut || { + if refused.get() { + Err(payload_owner_refusal()) + } else { + Ok(()) + } + }); + assert!(refused.get(), "actual directory flush must be reached"); + assert!( + matches!(result, Err(AppError::Conflict(message)) if message == "Original payload owner refusal") + ); + assert!(dir + .child("hooks", false) + .unwrap() + .entries() + .unwrap() + .is_empty()); + assert!(!root.path().join("hooks/nested").exists()); + } + #[test] + fn installer_preflight_errors_reach_no_real_adapter_publication() { + use crate::commands::skill::{selected_install, InstallSteps}; + struct Steps<'a> { + fixture: &'a Fixture, + fail_barrier: bool, + published: usize, + } + impl InstallSteps for Steps<'_> { + fn probe(&mut self, agent: SkillAgent) -> Result { + if !self.fail_barrier && agent == SkillAgent::ClaudeCode { + return Err(failure()); + } + Ok("0.167.0".into()) + } + fn barrier(&mut self) -> Result<(), AppError> { + Err(failure()) + } + fn publish(&mut self, agent: SkillAgent, version: String) -> Result<(), AppError> { + self.published += 1; + self.fixture.install(agent, &version, false)?; + Ok(()) + } + } + for fail_barrier in [false, true] { + let fixture = Fixture::new(); + let mut steps = Steps { + fixture: &fixture, + fail_barrier, + published: 0, + }; + assert!( + selected_install(&[SkillAgent::Codex, SkillAgent::ClaudeCode], &mut steps).is_err() + ); + assert_eq!(steps.published, 0); + assert!(!fixture.home.join(".codex").exists()); + assert!(!fixture.home.join(".claude").exists()); + } + } + #[test] + fn recovery_owner_config_refusal_retains_journal_for_a_fresh_operation() { + use std::{cell::Cell, rc::Rc}; + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + set_hook(None); + } + } + let fixture = Fixture::new(); + fixture.seed(serde_json::json!({"foreign": true})); + let before = fs::read(fixture.config()).unwrap(); + let reached = Rc::new(Cell::new(false)); + let observe = Rc::clone(&reached); + let _reset = Reset; + set_hook(Some(Box::new(move |phase| { + if phase == "install-config-fsynced" { + observe.set(true); + } + }))); + let result = install_prepared( + InstallOptions { + source_root: &fixture.source, + profile_home: &fixture.home, + agent: SkillAgent::Codex, + runtime: &fixture.runtime, + confirm_migration: false, + harness_version: None, + }, + "0.167.0".into(), + &mut || { + if reached.get() { + Err(failure()) + } else { + Ok(()) + } + }, + ); + assert!(result.is_err()); + assert!(reached.get()); + assert_eq!(fs::read(fixture.config()).unwrap(), before); + assert!(fixture.home.join(".codex").join(JOURNAL).exists()); + assert!(!fixture.home.join(".codex/skills/keito-time-track").exists()); + set_hook(None); + let host = Dir::anchor(&fixture.home.join(".codex")).unwrap(); + let skills = host.child("skills", false).unwrap(); + let journal: Publication = + serde_json::from_slice(&host.read(JOURNAL, 4096).unwrap().unwrap()).unwrap(); + validate_receipt( + &skills + .child(journal.stage.as_deref().unwrap(), false) + .unwrap(), + ) + .unwrap(); + recover(&host, &skills).unwrap(); + assert!(!fixture.home.join(".codex").join(JOURNAL).exists()); + assert_eq!(fs::read(fixture.config()).unwrap(), before); + } + #[test] + fn recovery_owner_second_target_refusal_preserves_first_and_retains_journal() { + use crate::commands::skill::{selected_install, InstallSteps}; + use std::{cell::Cell, rc::Rc}; + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + set_hook(None); + } + } + struct Steps<'a> { + fixture: &'a Fixture, + barrier: bool, + first: Option>, + } + impl InstallSteps for Steps<'_> { + fn probe(&mut self, agent: SkillAgent) -> Result { + Ok(match agent { + SkillAgent::Codex => "0.167.0", + SkillAgent::ClaudeCode => "2.1.319", + } + .into()) + } + fn barrier(&mut self) -> Result<(), AppError> { + self.barrier = true; + Ok(()) + } + fn publish(&mut self, agent: SkillAgent, version: String) -> Result<(), AppError> { + assert!(self.barrier); + if agent == SkillAgent::Codex { + self.fixture.install(agent, &version, false)?; + self.first = Some(fs::read(self.fixture.config()).unwrap()); + return Ok(()); + } + let reached = Rc::new(Cell::new(false)); + let observe = Rc::clone(&reached); + let _reset = Reset; + set_hook(Some(Box::new(move |phase| { + if phase == "install-config-fsynced" { + observe.set(true); + } + }))); + install_prepared( + InstallOptions { + source_root: &self.fixture.source, + profile_home: &self.fixture.home, + agent, + runtime: &self.fixture.runtime, + confirm_migration: false, + harness_version: None, + }, + version, + &mut || { + if reached.get() { + Err(failure()) + } else { + Ok(()) + } + }, + )?; + Ok(()) + } + } + let fixture = Fixture::new(); + let mut steps = Steps { + fixture: &fixture, + barrier: false, + first: None, + }; + assert!( + selected_install(&[SkillAgent::Codex, SkillAgent::ClaudeCode], &mut steps).is_err() + ); + assert_eq!( + &fs::read(fixture.config()).unwrap(), + steps.first.as_ref().unwrap() + ); + assert!(fixture.home.join(".codex/skills/keito-time-track").is_dir()); + assert!(!fixture.home.join(".claude/settings.json").exists()); + assert!(fixture.home.join(".claude").join(JOURNAL).exists()); + assert!(!fixture + .home + .join(".claude/skills/keito-time-track") + .exists()); + let host = Dir::anchor(&fixture.home.join(".claude")).unwrap(); + let skills = host.child("skills", false).unwrap(); + recover(&host, &skills).unwrap(); + assert!(!fixture.home.join(".claude").join(JOURNAL).exists()); + assert_eq!( + &fs::read(fixture.config()).unwrap(), + steps.first.as_ref().unwrap() + ); + } + #[test] + fn recovery_owner_reinstall_preserves_remaining_redundant_stage_after_refusal() { + use std::{ + cell::{Cell, RefCell}, + rc::Rc, + }; + let fixture = Fixture::new(); + let installed = fixture + .install(SkillAgent::Codex, "0.167.0", false) + .unwrap(); + let before = fs::read(fixture.config()).unwrap(); + let generations = fixture.home.join(".codex/.keito-capture-generations"); + let original = generations.join(&installed.generation); + let original_receipt = fs::read(original.join(RECEIPT)).unwrap(); + let refused = Rc::new(Cell::new(false)); + let stage = Rc::new(RefCell::new(None::)); + let observed_refusal = Rc::clone(&refused); + let observed_stage = Rc::clone(&stage); + let scan = generations.clone(); + let _reset = PayloadOwnerHookReset; + set_hook(Some(Box::new(move |phase| { + if phase != "adapter-directory-fsynced" { + return; + } + for entry in fs::read_dir(&scan).unwrap() { + let path = entry.unwrap().path(); + if path + .file_name() + .unwrap() + .to_str() + .unwrap() + .starts_with(".keito-time-track-stage-") + && path.join(RECEIPT).is_file() + && path.join("hooks/dispatch.sh").is_file() + && !path.join("SKILL.md").exists() + { + observed_refusal.set(true); + *observed_stage.borrow_mut() = Some(path); + } + } + }))); + let result = install_prepared( + InstallOptions { + source_root: &fixture.source, + profile_home: &fixture.home, + agent: SkillAgent::Codex, + runtime: &fixture.runtime, + confirm_migration: false, + harness_version: None, + }, + "0.167.0".into(), + &mut || { + if refused.get() { + Err(AppError::Conflict( + "Original reinstall owner refusal".into(), + )) + } else { + Ok(()) + } + }, + ); + assert!( + refused.get(), + "actual redundant-stage deletion must be reached" + ); + assert!(matches!(result, Err(AppError::Conflict(message)) + if message == "Original reinstall owner refusal")); + let stage = stage.borrow().clone().unwrap(); + assert!(!stage.join("SKILL.md").exists()); + assert!( + stage.join(RECEIPT).is_file(), + "refusal must stop later deletions" + ); + assert!(stage.join("hooks/dispatch.sh").is_file()); + assert_eq!(fs::read(fixture.config()).unwrap(), before); + assert_eq!(fs::read(original.join(RECEIPT)).unwrap(), original_receipt); + validate_receipt(&Dir::anchor(&original).unwrap()).unwrap(); + } + #[test] + fn native_install_is_immutable_idempotent_and_records_runtime_pair() { + let f = Fixture::new(); + let first = f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + assert_eq!(first.hooks_registered, 5); + let config = f.json(); + let second = f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + assert_eq!(first.generation, second.generation); + assert_eq!(config, f.json()); + let receipt: Value = serde_json::from_slice( + &fs::read( + f.home + .join(".codex/skills/keito-time-track/capture-install.json"), + ) + .unwrap(), + ) + .unwrap(); + assert_eq!(receipt["adapter_contract"], 2); + assert_eq!(receipt["runtime"]["guard_sha256"], f.runtime.guard_sha256); + assert_eq!(receipt["trusted"], "unknown"); + assert_eq!(receipt["delivery_verified"], false); + for groups in config["hooks"].as_object().unwrap().values() { + let c = groups[0]["hooks"][0]["command"].as_str().unwrap(); + assert!(c.contains("KEITO_CAPTURE_GUARD_BIN=")); + assert!(c.contains(&format!( + "KEITO_CAPTURE_CORE_SHA256={}", + f.runtime.core_sha256 + ))); + assert!(!c.contains("PYTHON")); + assert_eq!(groups[0]["hooks"][0]["timeout"], 1); + } + } + #[test] + fn grouped_foreign_commands_plugin_fields_and_empty_groups_survive() { + let f = Fixture::new(); + let foreign = serde_json::json!({"type":"command","command":"audit --safe"}); + f.seed(serde_json::json!({"hooks":{"Stop":[{"matcher":"anything","timeout":9,"hooks":[foreign.clone()]},{"hooks":[]}]},"enabledPlugins":{"other@vendor":true},"description":"preserve"})); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let out = uninstall(&f.home, SkillAgent::Codex).unwrap(); + assert_eq!(out.hooks_removed, 5); + assert!(out.payload_removed); + assert!(out.retained_generations >= 1); + assert_eq!(f.json()["hooks"]["Stop"][0]["hooks"][0], foreign); + assert_eq!(f.json()["hooks"]["Stop"][0]["timeout"], 9); + assert_eq!(f.json()["hooks"]["Stop"][1]["hooks"], serde_json::json!([])); + assert_eq!(f.json()["enabledPlugins"]["other@vendor"], true); + } + #[test] + fn ambiguous_shell_substitutions_and_path_mentions_are_never_deleted() { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let mut data = f.json(); + let command = data["hooks"]["Stop"][0]["hooks"][0]["command"] + .as_str() + .unwrap() + .to_string(); + let foreign = vec![ + format!( + "printf '%s' {}", + quote( + &f.home + .join(".codex/skills/keito-time-track/hooks/dispatch.sh") + .display() + .to_string() + ) + ), + format!("{command} && audit"), + command.replacen("KEITO_CLI_BIN=", "KEITO_CLI_BIN=$(audit) ", 1), + format!("bash -c {}", quote(&command)), + ]; + for c in &foreign { + data["hooks"]["Stop"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({"hooks":[{"type":"command","command":c}]})); + } + f.seed(data); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + uninstall(&f.home, SkillAgent::Codex).unwrap(); + let got: Vec<_> = f.json()["hooks"]["Stop"] + .as_array() + .unwrap() + .iter() + .map(|g| g["hooks"][0]["command"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(got, foreign); + } + #[test] + fn edited_discovery_or_generation_never_changes_configuration() { + for edit_generation in [false, true] { + let f = Fixture::new(); + let first = f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let target = if edit_generation { + f.home + .join(".codex/.keito-capture-generations") + .join(first.generation) + } else { + f.home.join(".codex/skills/keito-time-track") + }; + fs::write(target.join("SKILL.md"), "local edit").unwrap(); + let before = fs::read(f.config()).unwrap(); + assert!(f.install(SkillAgent::Codex, "0.167.0", false).is_err()); + assert_eq!(fs::read(f.config()).unwrap(), before); + if !edit_generation { + assert!(uninstall(&f.home, SkillAgent::Codex).is_err()); + assert_eq!(fs::read(f.config()).unwrap(), before); + } + } + } + #[test] + fn damaged_executable_generation_is_not_reused_or_repaired() { + let f = Fixture::new(); + let first = f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let target = f + .home + .join(".codex/.keito-capture-generations") + .join(first.generation) + .join("hooks/dispatch.sh"); + fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).unwrap(); + let before = fs::read(f.config()).unwrap(); + assert!(f.install(SkillAgent::Codex, "0.167.0", false).is_err()); + assert_eq!(fs::read(f.config()).unwrap(), before); + assert_eq!( + fs::metadata(target).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + #[test] + fn uninstall_does_not_require_the_old_runtime_to_exist() { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + fs::remove_file(&f.runtime.core_path).unwrap(); + fs::remove_file(&f.runtime.guard_path).unwrap(); + assert!( + uninstall(&f.home, SkillAgent::Codex) + .unwrap() + .payload_removed + ); + } + #[test] + fn symlink_harness_settings_and_sources_are_refused() { + for which in ["host", "skills", "config", "source"] { + let f = Fixture::new(); + let outside = f.root.path().join("outside"); + fs::create_dir(&outside).unwrap(); + fs::write(outside.join("keep"), "unchanged").unwrap(); + match which { + "host" => symlink(&outside, f.home.join(".codex")).unwrap(), + "skills" => { + fs::create_dir(f.home.join(".codex")).unwrap(); + symlink(&outside, f.home.join(".codex/skills")).unwrap(); + } + "config" => { + fs::create_dir(f.home.join(".codex")).unwrap(); + symlink(outside.join("keep"), f.config()).unwrap(); + } + _ => symlink(outside.join("keep"), f.source.join("unexpected")).unwrap(), + }; + assert!(f.install(SkillAgent::Codex, "0.167.0", false).is_err()); + assert_eq!(fs::read(outside.join("keep")).unwrap(), b"unchanged"); + } + } + #[test] + fn malformed_settings_receipts_and_journals_are_sanitized() { + let f = Fixture::new(); + f.seed(serde_json::json!({"hooks":{"Stop":"PRIVATE_SECRET"}})); + let before = fs::read(f.config()).unwrap(); + let e = f + .install(SkillAgent::Codex, "0.167.0", false) + .unwrap_err() + .to_string(); + assert!(!e.contains("PRIVATE_SECRET")); + assert!(!e.contains(&f.home.display().to_string())); + assert_eq!(fs::read(f.config()).unwrap(), before); + f.seed(serde_json::json!({})); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let receipt = f + .home + .join(".codex/skills/keito-time-track/capture-install.json"); + for bad in [b"[]".as_slice(), b"null", b"{\"files\":[]}"] { + fs::write(&receipt, bad).unwrap(); + let before = fs::read(f.config()).unwrap(); + assert!(uninstall(&f.home, SkillAgent::Codex).is_err()); + assert_eq!(fs::read(f.config()).unwrap(), before); + } + } + #[test] + fn legacy_plugin_migration_requires_confirmation_and_preserves_foreign_plugin() { + let f = Fixture::new(); + let host = f.home.join(".claude"); + fs::create_dir(&host).unwrap(); + let config = host.join("settings.json"); + fs::write( + &config, + br#"{"enabledPlugins":{"keito-time-track@keito":true,"other@vendor":true}}"#, + ) + .unwrap(); + let before = fs::read(&config).unwrap(); + assert!(f.install(SkillAgent::ClaudeCode, "2.1.319", false).is_err()); + assert_eq!(fs::read(&config).unwrap(), before); + assert!( + f.install(SkillAgent::ClaudeCode, "2.1.319", true) + .unwrap() + .migrated + ); + let data: Value = serde_json::from_slice(&fs::read(config).unwrap()).unwrap(); + assert_eq!(data["enabledPlugins"]["keito-time-track@keito"], false); + assert_eq!(data["enabledPlugins"]["other@vendor"], true); + } + #[test] + fn late_settings_edit_after_journal_fsync_is_preserved() { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let target = f.config(); + set_hook(Some(Box::new(move |p| { + if p == "install-journal-fsynced" { + fs::write(&target, b"{\"external\":true}").unwrap(); + } + }))); + let result = f.install(SkillAgent::Codex, "0.167.1", false); + set_hook(None); + assert!(result.is_err()); + assert_eq!(fs::read(f.config()).unwrap(), b"{\"external\":true}"); + assert!(f + .home + .join(".codex/skills/keito-time-track/SKILL.md") + .exists()); + } + #[test] + fn generation_changes_with_runtime_and_rejects_python_payload() { + let mut f = Fixture::new(); + let first = f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + fs::write(&f.runtime.guard_path, b"replacement guard").unwrap(); + f.runtime.guard_sha256 = digest(b"replacement guard"); + assert_ne!( + first.generation, + f.install(SkillAgent::Codex, "0.167.0", false) + .unwrap() + .generation + ); + fs::write(f.source.join("runtime.py"), b"not allowed").unwrap(); + assert!(f.install(SkillAgent::Codex, "0.167.0", false).is_err()); + } + #[test] + fn invalid_version_is_not_silently_truncated() { + let f = Fixture::new(); + assert!(f + .install(SkillAgent::Codex, "0.167.0+build", false) + .is_err()); + assert!(!f.config().exists()); + } + #[test] + fn literal_parser_observes_posix_double_quote_backslashes() { + assert_eq!( + words(r#"KEITO_CLI_BIN="/safe/a\q" '/safe/dispatch.sh' --agent codex"#).unwrap()[0], + r"KEITO_CLI_BIN=/safe/a\q" + ); + assert_eq!( + words(r#"'/safe/a'"'"'b$literal'"#).unwrap(), + vec!["/safe/a'b$literal"] + ); + for command in [ + "echo $(audit)", + "echo `audit`", + "x ; y", + "x\ny", + r#"echo "$(audit)""#, + "echo ~root", + "echo *", + ] { + assert!(words(command).is_none(), "{command}"); + } + } + #[test] + fn legacy_grouped_hook_requires_explicit_migration_and_retains_backup() { + let f = Fixture::new(); + let dest = f.home.join(".codex/skills/keito-time-track"); + fs::create_dir_all(dest.join("hooks")).unwrap(); + fs::write(dest.join("private-note"), b"legacy content").unwrap(); + let old = format!( + "KEITO_AGENT_TYPE=codex {}", + quote(dest.join("hooks/session-end.sh").to_str().unwrap()) + ); + let foreign = serde_json::json!({"type":"command","command":"audit"}); + f.seed(serde_json::json!({"hooks":{"Stop":[{"matcher":"keep","hooks":[{"type":"command","command":old},foreign.clone()]}]}})); + let original = fs::read(f.config()).unwrap(); + assert!(f.install(SkillAgent::Codex, "0.167.0", false).is_err()); + assert_eq!(fs::read(f.config()).unwrap(), original); + assert!( + f.install(SkillAgent::Codex, "0.167.0", true) + .unwrap() + .migrated + ); + assert_eq!( + f.json()["hooks"]["Stop"][0]["hooks"], + serde_json::json!([foreign]) + ); + let backups: Vec<_> = fs::read_dir(dest.parent().unwrap()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| { + p.file_name() + .unwrap() + .to_str() + .unwrap() + .starts_with(".keito-time-track-backup-") + }) + .collect(); + assert_eq!(backups.len(), 1); + assert_eq!( + fs::read(backups[0].join("private-note")).unwrap(), + b"legacy content" + ); + } + #[test] + fn legacy_receipt_can_uninstall_but_cannot_be_reused_as_native_generation() { + let f = Fixture::new(); + let installed = f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let receipt = f + .home + .join(".codex/skills/keito-time-track/capture-install.json"); + let mut v: Value = serde_json::from_slice(&fs::read(&receipt).unwrap()).unwrap(); + v["adapter_contract"] = 1.into(); + v.as_object_mut().unwrap().remove("runtime"); + fs::write(&receipt, serde_json::to_vec(&v).unwrap()).unwrap(); + assert!(uninstall(&f.home, SkillAgent::Codex).is_ok()); + let generation = f + .home + .join(".codex/.keito-capture-generations") + .join(installed.generation) + .join(RECEIPT); + fs::write(generation, serde_json::to_vec(&v).unwrap()).unwrap(); + assert!(f.install(SkillAgent::Codex, "0.167.0", false).is_err()); + } + #[test] + fn malformed_or_symlinked_recovery_never_changes_settings() { + for bad in [ + serde_json::json!([]), + serde_json::json!({"schema_version":1,"stage":"../../outside","backup":"bad"}), + ] { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let config = fs::read(f.config()).unwrap(); + let journal = f.home.join(".codex").join(JOURNAL); + fs::write(&journal, serde_json::to_vec(&bad).unwrap()).unwrap(); + assert!(uninstall(&f.home, SkillAgent::Codex).is_err()); + assert_eq!(fs::read(f.config()).unwrap(), config); + assert!(journal.exists()); + } + } + #[test] + fn final_config_temporary_fsync_edit_is_preserved() { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let target = f.config(); + set_hook(Some(Box::new(move |phase| { + if phase == "install-config-fsynced" { + fs::write(&target, b"{\"late\":true}").unwrap(); + } + }))); + let result = f.install(SkillAgent::Codex, "0.167.1", false); + set_hook(None); + assert!(result.is_err()); + assert_eq!(fs::read(f.config()).unwrap(), b"{\"late\":true}"); + } + #[test] + fn concurrent_installer_refuses_before_configuration_mutation() { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let host = Dir::anchor(&f.home) + .unwrap() + .child(".codex", false) + .unwrap(); + let _lock = host.lock("hooks.json.keito.lock").unwrap(); + let before = fs::read(f.config()).unwrap(); + assert!(f.install(SkillAgent::Codex, "0.167.1", false).is_err()); + assert!(uninstall(&f.home, SkillAgent::Codex).is_err()); + assert_eq!(fs::read(f.config()).unwrap(), before); + } + pub(crate) fn isolated_fixture_process( + root: &Path, + home: Option<&Path>, + capture: Option<&Path>, + ) -> Result { + let root = root + .canonicalize() + .map_err(|_| "fixture root unavailable")?; + let home = home + .ok_or("missing isolated home")? + .canonicalize() + .map_err(|_| "isolated home unavailable")?; + let capture = capture + .ok_or("missing isolated capture root")? + .canonicalize() + .map_err(|_| "isolated capture root unavailable")?; + if home != root.join("home with ' literal $") || capture != home.join("capture") { + return Err("foreign profile refused before spawn"); + } + let executable = std::env::current_exe() + .map_err(|_| "test executable unavailable")? + .canonicalize() + .map_err(|_| "test executable unavailable")?; + let mut command = std::process::Command::new(executable); + command + .env("HOME", &home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("KEITO_CAPTURE_HOME", capture) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null"); + Ok(command) + } + #[test] + fn missing_or_foreign_home_refuses_before_constructing_mutation_process() { + let f = Fixture::new(); + let capture = f.home.join("capture"); + assert!(isolated_fixture_process(f.root.path(), None, Some(&capture)).is_err()); + assert!(isolated_fixture_process(f.root.path(), Some(&f.home), None).is_err()); + let foreign = tempfile::tempdir().unwrap(); + assert!( + isolated_fixture_process(f.root.path(), Some(foreign.path()), Some(&capture)).is_err() + ); + assert!( + isolated_fixture_process(f.root.path(), Some(&f.home), Some(foreign.path())).is_err() + ); + assert!(isolated_fixture_process(f.root.path(), Some(&f.home), Some(&capture)).is_ok()); + assert!(!f.config().exists()); + } + #[test] + fn signal_fixture_child() { + let Ok(root) = std::env::var("KEITO_TEST_NATIVE_ADAPTER_ROOT") else { + return; + }; + let root = PathBuf::from(root).canonicalize().unwrap(); + let isolated_home = root.join("home with ' literal $").canonicalize().unwrap(); + assert_eq!( + std::env::var_os("HOME").map(PathBuf::from), + Some(isolated_home.clone()) + ); + assert_eq!( + std::env::var_os("KEITO_CAPTURE_HOME").map(PathBuf::from), + Some(isolated_home.join("capture")) + ); + let runtime = CaptureRuntimeIdentity { + core_path: root.join("core"), + guard_path: root.join("guard"), + core_sha256: digest(b"synthetic core"), + guard_sha256: digest(b"synthetic guard"), + version: "0.2.0".into(), + target: "aarch64-apple-darwin".into(), + guard_contract: 2, + }; + let boundary = std::env::var("KEITO_TEST_NATIVE_BOUNDARY").unwrap(); + let signal = std::env::var("KEITO_TEST_NATIVE_SIGNAL") + .unwrap() + .parse::() + .unwrap(); + set_hook(Some(Box::new(move |p| { + if p == boundary { + unsafe { + libc::kill(libc::getpid(), signal); + } + } + }))); + install(InstallOptions { + source_root: &root.join("source"), + profile_home: &root.join("home with ' literal $"), + agent: SkillAgent::Codex, + runtime: &runtime, + confirm_migration: false, + harness_version: Some("0.167.1"), + }) + .unwrap(); + panic!("fault boundary was not reached"); + } + #[test] + fn real_process_death_preserves_registered_generations_and_recovers_discovery() { + use std::os::unix::process::ExitStatusExt; + for boundary in [ + "install-generation-published", + "install-config-fsynced", + "install-config-published", + "install-payload-backup", + "install-discovery-published", + ] { + for signal in [libc::SIGTERM, libc::SIGKILL] { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let output = isolated_fixture_process( + f.root.path(), + Some(&f.home), + Some(&f.home.join("capture")), + ) + .unwrap() + .args([ + "--exact", + "skill_adapter::implementation::tests::signal_fixture_child", + "--nocapture", + ]) + .env( + "KEITO_TEST_NATIVE_ADAPTER_ROOT", + f.root.path().canonicalize().unwrap(), + ) + .env("KEITO_TEST_NATIVE_BOUNDARY", boundary) + .env("KEITO_TEST_NATIVE_SIGNAL", signal.to_string()) + .output() + .unwrap(); + assert_eq!(output.status.signal(), Some(signal), "boundary {boundary}"); + for groups in f.json()["hooks"].as_object().unwrap().values() { + for group in groups.as_array().unwrap() { + for hook in group["hooks"].as_array().unwrap() { + let argv = words(hook["command"].as_str().unwrap()).unwrap(); + let executable = argv + .iter() + .find(|s| s.ends_with("/hooks/dispatch.sh")) + .unwrap(); + assert!( + Path::new(executable).is_file(), + "registered immutable payload lost at {boundary}" + ); + } + } + } + f.install(SkillAgent::Codex, "0.167.1", false).unwrap(); + assert!(f + .home + .join(".codex/skills/keito-time-track/SKILL.md") + .is_file()); + } + } + } + #[test] + fn edited_discovery_after_journal_fsync_is_preserved_before_settings_switch() { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let before = fs::read(f.config()).unwrap(); + let target = f.home.join(".codex/skills/keito-time-track/SKILL.md"); + let edited = target.clone(); + set_hook(Some(Box::new(move |p| { + if p == "install-journal-fsynced" { + fs::write(&edited, b"late user edit").unwrap(); + } + }))); + let result = f.install(SkillAgent::Codex, "0.167.1", false); + set_hook(None); + assert!(result.is_err()); + assert_eq!(fs::read(f.config()).unwrap(), before); + assert_eq!(fs::read(target).unwrap(), b"late user edit"); + } + #[test] + fn backup_modified_after_move_is_never_deleted_by_install_or_uninstall() { + for uninstalling in [false, true] { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let skills = f.home.join(".codex/skills"); + let scan = skills.clone(); + set_hook(Some(Box::new(move |p| { + if p == if uninstalling { + "uninstall-payload-backup" + } else { + "install-payload-backup" + } { + let backup = fs::read_dir(&scan) + .unwrap() + .map(|e| e.unwrap().path()) + .find(|p| { + p.file_name() + .unwrap() + .to_str() + .unwrap() + .starts_with(".keito-time-track-backup-") + }) + .unwrap(); + fs::write(backup.join("SKILL.md"), b"edited after move").unwrap(); + } + }))); + let failed = if uninstalling { + uninstall(&f.home, SkillAgent::Codex).is_err() + } else { + f.install(SkillAgent::Codex, "0.167.1", false).is_err() + }; + set_hook(None); + assert!(failed); + assert!(fs::read_dir(skills) + .unwrap() + .map(|e| e.unwrap().path()) + .any(|p| fs::read(p.join("SKILL.md")).ok().as_deref() + == Some(b"edited after move".as_slice()))); + } + } + #[test] + fn ordinary_config_io_failure_preserves_prior_discovery_and_settings() { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let before = fs::read(f.config()).unwrap(); + let payload = f.home.join(".codex/skills/keito-time-track/SKILL.md"); + let original = fs::read(&payload).unwrap(); + crate::adapter_files::set_publication_fault(Some("install-config-fsynced")); + let result = f.install(SkillAgent::Codex, "0.167.1", false); + crate::adapter_files::set_publication_fault(None); + assert!(result.is_err()); + assert_eq!(fs::read(f.config()).unwrap(), before); + assert_eq!(fs::read(payload).unwrap(), original); + assert!(!f.home.join(".codex").join(JOURNAL).exists()); + } + #[test] + fn selected_target_preserves_other_harness_and_codex_feature_trust_bytes() { + let f = Fixture::new(); + fs::create_dir_all(f.home.join(".codex")).unwrap(); + fs::create_dir_all(f.home.join(".claude")).unwrap(); + let config = f.home.join(".codex/config.toml"); + let other = f.home.join(".claude/settings.json"); + let trust = + b"[features]\nhooks=false\n[hooks.state.synthetic]\ntrusted_hash='sha256:synthetic'\n"; + let foreign = b"{\"preserve\":\"other harness\"}"; + fs::write(&config, trust).unwrap(); + fs::write(&other, foreign).unwrap(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + uninstall(&f.home, SkillAgent::Codex).unwrap(); + assert_eq!(fs::read(config).unwrap(), trust); + assert_eq!(fs::read(other).unwrap(), foreign); + assert!(!f.home.join(".claude/skills").exists()); + } + #[test] + fn deep_recovery_metadata_is_sanitized_and_keeps_original_configuration() { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let before = fs::read(f.config()).unwrap(); + let nested = format!("{}0{}", "[".repeat(1200), "]".repeat(1200)); + let journal = f.home.join(".codex").join(JOURNAL); + fs::write(&journal, &nested).unwrap(); + let error = uninstall(&f.home, SkillAgent::Codex) + .unwrap_err() + .to_string(); + assert!(!error.contains(&f.home.display().to_string())); + assert_eq!(fs::read(f.config()).unwrap(), before); + assert_eq!(fs::read_to_string(journal).unwrap(), nested); + } + #[test] + fn real_bundled_native_payload_installs_without_python_or_developer_tests() { + let f = Fixture::new(); + let this = Path::new(file!()); + let root = if this.is_absolute() { + this.parent().unwrap().parent().unwrap().to_path_buf() + } else { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + }; + let source = root.join("skills/keito-time-track"); + assert!(source.is_dir(), "the actual CLI runtime payload must exist"); + let out = install(InstallOptions { + source_root: &source, + profile_home: &f.home, + agent: SkillAgent::Codex, + runtime: &f.runtime, + confirm_migration: false, + harness_version: Some("0.167.0"), + }) + .unwrap(); + let installed = Dir::anchor(&f.home) + .unwrap() + .child(".codex", false) + .unwrap() + .child(".keito-capture-generations", false) + .unwrap() + .child(&out.generation, false) + .unwrap(); + let receipt = validate_receipt(&installed).unwrap(); + assert_eq!(receipt.files.len(), 21); + assert!(receipt + .files + .keys() + .all(|p| !p.ends_with(".py") && !p.starts_with("tests/"))); + assert_eq!( + installed.metadata().unwrap().permissions().mode() & 0o777, + 0o700 + ); + } + #[test] + fn inspect_requires_exact_current_native_pair_without_executing_it() { + let f = Fixture::new(); + assert!(!inspect(&f.home, SkillAgent::Codex, None).unwrap()); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let config = fs::read(f.config()).unwrap(); + assert!(inspect(&f.home, SkillAgent::Codex, Some(&f.runtime)).unwrap()); + assert!(!inspect(&f.home, SkillAgent::Codex, None).unwrap()); + fs::write(&f.runtime.guard_path, b"changed image").unwrap(); + assert!(!inspect(&f.home, SkillAgent::Codex, Some(&f.runtime)).unwrap()); + assert_eq!(fs::read(f.config()).unwrap(), config); + } + #[test] + fn inspect_refuses_missing_duplicate_or_changed_native_registration() { + for case in [ + "missing", + "extra", + "timeout", + "wrong-image", + "matcher", + "missing-core-hash", + "wrong-core-hash", + ] { + let f = Fixture::new(); + f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let mut data = f.json(); + match case { + "missing" => { + data["hooks"].as_object_mut().unwrap().remove("Stop"); + } + "extra" => { + let duplicate = data["hooks"]["Stop"][0].clone(); + data["hooks"]["Stop"] + .as_array_mut() + .unwrap() + .push(duplicate); + } + "timeout" => data["hooks"]["Stop"][0]["hooks"][0]["timeout"] = 2.into(), + "missing-core-hash" => { + let old = data["hooks"]["Stop"][0]["hooks"][0]["command"] + .as_str() + .unwrap(); + data["hooks"]["Stop"][0]["hooks"][0]["command"] = old + .replace( + &format!("KEITO_CAPTURE_CORE_SHA256={} ", f.runtime.core_sha256), + "", + ) + .into(); + } + "wrong-core-hash" => { + let old = data["hooks"]["Stop"][0]["hooks"][0]["command"] + .as_str() + .unwrap(); + data["hooks"]["Stop"][0]["hooks"][0]["command"] = old + .replace( + &format!("KEITO_CAPTURE_CORE_SHA256={}", f.runtime.core_sha256), + &format!("KEITO_CAPTURE_CORE_SHA256={}", "0".repeat(64)), + ) + .into(); + } + "wrong-image" => { + let old = data["hooks"]["Stop"][0]["hooks"][0]["command"] + .as_str() + .unwrap(); + data["hooks"]["Stop"][0]["hooks"][0]["command"] = old + .replace("KEITO_CAPTURE_GUARD_BIN=", "UNRECOGNIZED_GUARD=") + .into(); + } + _ => data["hooks"]["Stop"][0]["matcher"] = "never".into(), + } + f.seed(data); + assert!( + !inspect(&f.home, SkillAgent::Codex, Some(&f.runtime)).unwrap(), + "{case}" + ); + } + } + #[test] + fn inspect_refuses_changed_payload_generation_and_legacy_receipts() { + for case in ["payload", "generation", "legacy"] { + let f = Fixture::new(); + let installed = f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let dest = f.home.join(".codex/skills/keito-time-track"); + match case { + "payload" => fs::write(dest.join("SKILL.md"), b"edit").unwrap(), + "generation" => fs::set_permissions( + f.home + .join(".codex/.keito-capture-generations") + .join(installed.generation) + .join("hooks/dispatch.sh"), + fs::Permissions::from_mode(0o600), + ) + .unwrap(), + _ => { + let receipt = dest.join(RECEIPT); + let mut data: Value = + serde_json::from_slice(&fs::read(&receipt).unwrap()).unwrap(); + data["adapter_contract"] = 1.into(); + data.as_object_mut().unwrap().remove("runtime"); + fs::write(receipt, serde_json::to_vec(&data).unwrap()).unwrap(); + } + } + assert!( + !inspect(&f.home, SkillAgent::Codex, Some(&f.runtime)).unwrap(), + "{case}" + ); + } + } + #[test] + fn inspect_does_not_accept_a_rehashed_python_payload_as_native_contract_two() { + let f = Fixture::new(); + let installed = f.install(SkillAgent::Codex, "0.167.0", false).unwrap(); + let dest = f.home.join(".codex/skills/keito-time-track"); + let generations = f.home.join(".codex/.keito-capture-generations"); + let generation = generations.join(&installed.generation); + let mut receipt: Value = + serde_json::from_slice(&fs::read(dest.join(RECEIPT)).unwrap()).unwrap(); + receipt["files"]["forged-runtime.py"] = digest(b"never executed").into(); + let files: BTreeMap = + serde_json::from_value(receipt["files"].clone()).unwrap(); + let new_key = generation_key( + "codex", + "0.167.0", + &files, + &serde_json::to_value(&f.runtime).unwrap(), + ) + .unwrap(); + receipt["generation"] = new_key.clone().into(); + for folder in [&dest, &generation] { + fs::write(folder.join("forged-runtime.py"), b"never executed").unwrap(); + fs::write(folder.join(RECEIPT), serde_json::to_vec(&receipt).unwrap()).unwrap(); + } + fs::rename(&generation, generations.join(&new_key)).unwrap(); + let config = fs::read_to_string(f.config()) + .unwrap() + .replace(&installed.generation, &new_key); + fs::write(f.config(), config).unwrap(); + assert!(!inspect(&f.home, SkillAgent::Codex, Some(&f.runtime)).unwrap()); + } +} diff --git a/src/source_qa_group.rs b/src/source_qa_group.rs new file mode 100644 index 0000000..7d03ae2 --- /dev/null +++ b/src/source_qa_group.rs @@ -0,0 +1,3 @@ +//! Developer compatibility API for the shared product group implementation. +//! No capture/profile/auth proof or runtime qualification is granted here. +pub use crate::process_ownership::group::*; diff --git a/src/source_qa_protocol.rs b/src/source_qa_protocol.rs new file mode 100644 index 0000000..9c9e499 --- /dev/null +++ b/src/source_qa_protocol.rs @@ -0,0 +1,2 @@ +//! Developer compatibility API for the shared cancellation metadata protocol. +pub use crate::process_ownership::protocol::*; diff --git a/src/source_qa_scope.rs b/src/source_qa_scope.rs new file mode 100644 index 0000000..c4026a8 --- /dev/null +++ b/src/source_qa_scope.rs @@ -0,0 +1,738 @@ +//! Developer Scope integration: locally retained opaque-group slots. +//! +//! This layer does not yet own cooperative core edges or output-pipe EOF and +//! cannot issue upstream SETTLED or any capture/profile approval. +use crate::{ + source_qa_group::{GroupLease, GroupReport}, + source_qa_protocol::{ProtocolError, SharedOwner, MAX_REGISTRATIONS}, +}; +use std::{io, path::Path, process::Command, rc::Rc}; + +const CLEANUP_NS: u64 = 1_800_000_000; + +/// Developer fixture gateway to the SAME product opaque runner. The caller +/// cannot supply a hash/manifest as authority: the final guard anchor must be +/// compiled into this Cargo-linked fixture. This grants no capture consent. +pub fn run_fixture_opaque( + scope: &mut crate::process_ownership::scope::Scope, + command: Command, + plan: crate::process_ownership::io::IoPlan, + core: &Path, +) -> io::Result { + prepare_fixture_scope(scope, crate::process_ownership::scope::monotonic_now)?; + let anchor = option_env!("KEITO_RELEASE_GUARD_SHA256") + .ok_or_else(|| io::Error::other("FIXTURE_PAIR_ANCHOR"))?; + let runtime = crate::capture_runtime_pair::verify( + core, + anchor, + env!("CARGO_PKG_VERSION"), + env!("KEITO_BUILD_TARGET"), + ) + .map_err(|_| io::Error::other("FIXTURE_PAIR_ANCHOR"))?; + let image = crate::process_ownership::image::VerifiedKeeperImage::open( + &runtime.guard_path, + &runtime.guard_sha256, + )?; + scope.run_verified_with_policy( + command, + plan, + &image, + crate::process_ownership::group::CleanupPolicy::CommandProbe, + ) +} + +fn prepare_fixture_scope( + scope: &mut crate::process_ownership::scope::Scope, + mut clock: impl FnMut() -> io::Result, +) -> io::Result<()> { + match clock() { + Ok(at) => scope.tighten_end(scope.hard_end().min(at.saturating_add(1_000_000_000))), + Err(error) => { + scope.tighten_end(0); + scope.begin_cancel(ProtocolError("SCOPE_CLOCK"), 0); + return Err(error); + } + } + Ok(()) +} + +fn probe_observation( + scope: &mut crate::process_ownership::scope::Scope, + result: io::Result, + publish: impl FnOnce(&crate::process_ownership::scope::ScopeReport) -> io::Result<()>, +) -> io::Result { + if let Err(receipt) = publish(&scope.report()) { + scope.begin_cancel(ProtocolError("QA_PROBE_RECEIPT"), scope.hard_end()); + return match result { + Err(primary) => Err(primary), + Ok(_) => Err(receipt), + }; + } + result +} + +fn hook_probe_clock(scope: &mut crate::process_ownership::scope::Scope) -> io::Result { + match crate::process_ownership::scope::monotonic_now() { + Ok(at) => Ok(at), + Err(error) => { + scope.tighten_end(0); + scope.begin_cancel(ProtocolError("SCOPE_CLOCK"), 0); + Err(error) + } + } +} + +// Developer-only adapter: cohort diagnostics must never silently exercise the +// resolver's sequential fallback instead of the product repository cohort. +struct RepositoryCohortDiagnostic { + run: F, +} +impl crate::process_ownership::probes::LeafRunner for RepositoryCohortDiagnostic +where + F: FnMut([Command; 2]) -> io::Result<[crate::process_ownership::scope::CommandResult; 2]>, +{ + fn repository_outputs( + &mut self, + commands: [Command; 2], + ) -> Option> { + Some((self.run)(commands)) + } + fn output( + &mut self, + _: Command, + _: usize, + _: usize, + ) -> io::Result { + Err(io::Error::other("QA_COHORT_SEQUENTIAL_REFUSED")) + } +} + +/// Observe the SAME staged repository cohort as the product hook. This is a +/// separate developer diagnostic, never a default-artifact benchmark or ACK. +pub fn diagnose_fixture_repository_cohort( + scope: &mut crate::process_ownership::scope::Scope, + core: &Path, + repository: &Path, + mut observe: impl FnMut( + u64, + Option, + bool, + &crate::process_ownership::scope::ScopeReport, + ) -> io::Result<()>, +) -> Result<(), crate::error::AppError> { + let refused = || crate::error::AppError::Config("Source cohort diagnosis refused".into()); + let at = hook_probe_clock(scope).map_err(|_| refused())?; + scope.tighten_end(scope.hard_end().min(at.saturating_add(500_000_000))); + let anchor = option_env!("KEITO_RELEASE_GUARD_SHA256").ok_or_else(refused)?; + let runtime = crate::capture_runtime_pair::verify( + core, + anchor, + env!("CARGO_PKG_VERSION"), + env!("KEITO_BUILD_TARGET"), + ) + .map_err(|_| refused())?; + let image = crate::process_ownership::image::VerifiedKeeperImage::open( + &runtime.guard_path, + &runtime.guard_sha256, + ) + .map_err(|_| refused())?; + let mut runner = RepositoryCohortDiagnostic { + run: |commands| { + let before = hook_probe_clock(scope)?; + let result = scope.run_verified_repository(commands, &image); + let after = hook_probe_clock(scope); + let finished = after.as_ref().ok().copied(); + let result = match (result, after) { + (Err(primary), _) => Err(primary), + (Ok(_), Err(clock)) => Err(clock), + (Ok(value), Ok(_)) => Ok(value), + }; + let ok = result.is_ok(); + probe_observation(scope, result, |report| { + observe(before, finished, ok, report) + }) + }, + }; + crate::capture::Repository::resolve_with(repository, &mut runner)?; + Ok(()) +} + +/// Developer diagnosis of the actual repository/clock callers. Only metadata +/// reaches the observer: never Command, arguments, environment or tool output. +/// This is not default-artifact latency or capture/usage authority. +pub fn diagnose_fixture_hook_probes( + scope: &mut crate::process_ownership::scope::Scope, + core: &Path, + repository: &Path, + mut observe: impl FnMut( + u8, + u64, + Option, + bool, + &crate::process_ownership::scope::ScopeReport, + ) -> io::Result<()>, +) -> Result<(), crate::error::AppError> { + use crate::process_ownership::{ + image::VerifiedKeeperImage, + probes::LeafRunner, + scope::{CommandResult, Scope, ScopeReport}, + }; + let refused = || crate::error::AppError::Config("Source hook probe diagnosis refused".into()); + let at = hook_probe_clock(scope).map_err(|_| refused())?; + scope.tighten_end(scope.hard_end().min(at.saturating_add(500_000_000))); + let anchor = option_env!("KEITO_RELEASE_GUARD_SHA256").ok_or_else(refused)?; + let runtime = crate::capture_runtime_pair::verify( + core, + anchor, + env!("CARGO_PKG_VERSION"), + env!("KEITO_BUILD_TARGET"), + ) + .map_err(|_| refused())?; + let image = VerifiedKeeperImage::open(&runtime.guard_path, &runtime.guard_sha256) + .map_err(|_| refused())?; + struct Runner<'a, F> { + scope: &'a mut Scope, + image: VerifiedKeeperImage, + ordinal: u8, + observe: &'a mut F, + } + impl, bool, &ScopeReport) -> io::Result<()>> LeafRunner + for Runner<'_, F> + { + fn output( + &mut self, + command: Command, + stdout_cap: usize, + stderr_cap: usize, + ) -> io::Result { + if self.ordinal >= 4 { + self.scope + .begin_cancel(ProtocolError("QA_PROBE_COUNT"), self.scope.hard_end()); + return Err(io::Error::other("QA_PROBE_COUNT")); + } + self.ordinal += 1; + let before = hook_probe_clock(self.scope)?; + let plan = + crate::process_ownership::io::IoPlan::new(Vec::new(), stdout_cap, stderr_cap)?; + // SAME HookShort policy as CommandOwner::for_hook, not the + // ordinary-command diagnostic gateway's longer setup interval. + let result = self.scope.run_verified(command, plan, &self.image); + let after = hook_probe_clock(self.scope); + let finished = after.as_ref().ok().copied(); + let result = match (result, after) { + (Err(primary), _) => Err(primary), + (Ok(_), Err(clock)) => Err(clock), + (Ok(value), Ok(_)) => Ok(value), + }; + let ok = result.is_ok(); + let ordinal = self.ordinal; + let observer = &mut self.observe; + probe_observation(self.scope, result, |report| { + observer(ordinal, before, finished, ok, report) + }) + } + } + let mut runner = Runner { + scope, + image, + ordinal: 0, + observe: &mut observe, + }; + // Do not duplicate/substitute the original fixed Git/sysctl commands or + // their text interpretation. The own repository is validated by native. + crate::capture::Repository::resolve_with(repository, &mut runner)?; + crate::capture::Clock::now_with(&mut runner)?; + // Boot metadata no longer starts a leaf on macOS; only three Git probes. + let expected = 3; + if runner.ordinal != expected { + runner + .scope + .begin_cancel(ProtocolError("QA_PROBE_COUNT"), runner.scope.hard_end()); + return Err(refused()); + } + Ok(()) +} + +fn now() -> io::Result { + let mut value = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, value.as_mut_ptr()) } != 0 { + return Err(io::Error::other("SCOPE_CLOCK")); + } + let value = unsafe { value.assume_init() }; + u64::try_from(value.tv_sec) + .ok() + .and_then(|s| s.checked_mul(1_000_000_000)) + .and_then(|s| s.checked_add(value.tv_nsec as u64)) + .ok_or_else(|| io::Error::other("SCOPE_CLOCK")) +} + +#[derive(Clone, Debug)] +pub struct SlotId { + index: usize, + registry: Rc<()>, +} +impl SlotId { + pub fn index(&self) -> usize { + self.index + } +} + +trait Edge { + fn begin(&mut self, end: u64) -> io::Result<()>; + fn poll(&mut self) -> io::Result<()>; + fn proof(&self) -> bool; + fn waits_known(&self) -> bool; +} + +struct GroupSlot { + lease: GroupLease, + proof: bool, +} +impl Edge for GroupSlot { + fn begin(&mut self, end: u64) -> io::Result<()> { + self.lease.begin_cleanup(end) + } + fn poll(&mut self) -> io::Result<()> { + if self.lease.poll_cleanup()?.is_some() { + self.proof = true; + } + Ok(()) + } + fn proof(&self) -> bool { + self.proof + } + fn waits_known(&self) -> bool { + let facts = self.lease.report(); + facts.keeper_status.is_some() + && (!facts.workload_spawned || facts.workload_status.is_some()) + } +} + +struct Registry { + owner: SharedOwner, + identity: Rc<()>, + slots: Vec, + hard_end: u64, + cleanup_end: Option, + finished: bool, + secondary_faults: Vec, +} +impl Registry { + fn new(owner: SharedOwner, hard_end: u64) -> Self { + Self { + owner, + identity: Rc::new(()), + slots: Vec::new(), + hard_end, + cleanup_end: None, + finished: false, + secondary_faults: Vec::new(), + } + } + fn poison(&mut self, reason: &'static str) { + self.owner.borrow_mut().poison(ProtocolError(reason)); + if self.owner.borrow().first_fault != Some(ProtocolError(reason)) + && self.secondary_faults.len() < 8 + && !self.secondary_faults.contains(&ProtocolError(reason)) + { + self.secondary_faults.push(ProtocolError(reason)); + } + } + fn admit( + &mut self, + at: u64, + create: impl FnOnce(SharedOwner) -> io::Result, + publish: impl FnOnce(&SlotId, &[E]) -> io::Result<()>, + ) -> io::Result { + let admission = self.owner.borrow().check_admission(); + if let Err(error) = admission { + self.begin(at, self.hard_end); + return Err(io::Error::other(error.0)); + } + if self.finished || self.cleanup_end.is_some() || at >= self.hard_end { + self.poison("SCOPE_ADMISSION"); + self.begin(at, self.hard_end); + return Err(io::Error::other("SCOPE_ADMISSION")); + } + if self.slots.len() >= MAX_REGISTRATIONS || self.slots.try_reserve(1).is_err() { + self.poison("SCOPE_SLOT_LIMIT"); + self.begin(at, self.hard_end); + return Err(io::Error::other("SCOPE_SLOT_LIMIT")); + } + let edge = match create(self.owner.clone()) { + Ok(edge) => edge, + Err(error) => { + self.poison("SCOPE_SPAWN"); + self.begin(at, self.hard_end); + return Err(error); + } + }; + let id = SlotId { + index: self.slots.len(), + registry: self.identity.clone(), + }; + // Capacity was reserved BEFORE creating the handle. No fallible I/O or + // publication occurs between factory return and local slot ownership. + self.slots.push(edge); + if let Err(error) = publish(&id, &self.slots) { + self.poison("SCOPE_PUBLICATION"); + self.begin(at, self.hard_end); + return Err(error); + } + Ok(id) + } + fn slot(&mut self, id: &SlotId) -> io::Result<&mut E> { + if !Rc::ptr_eq(&id.registry, &self.identity) || id.index >= self.slots.len() { + self.poison("SCOPE_SLOT_ID"); + return Err(io::Error::other("SCOPE_SLOT_ID")); + } + Ok(&mut self.slots[id.index]) + } + fn begin(&mut self, at: u64, requested: u64) { + self.owner.borrow_mut().admission_closed = true; + if self.finished { + if requested < self.cleanup_end.unwrap_or(self.hard_end) { + self.poison("SCOPE_BOUND_SEALED"); + } + return; + } + let end = requested + .min(self.hard_end) + .min(at.saturating_add(CLEANUP_NS)) + .min(self.cleanup_end.unwrap_or(u64::MAX)); + if self.cleanup_end == Some(end) { + return; + } + self.cleanup_end = Some(end); + let mut fault = false; + for edge in &mut self.slots { + if edge.begin(end).is_err() { + fault = true; + } + } + // Broadcast EVERY known slot before any poll/wait, including when one + // begin fails. Individual edges may already have set a specific cause. + if fault { + self.poison("SCOPE_BEGIN"); + } + } + fn poll(&mut self) { + let mut fault = false; + for edge in &mut self.slots { + if edge.poll().is_err() { + fault = true; + } + } + if fault { + self.poison("SCOPE_POLL"); + } + // Keep successful and failed slots alike. A wait is a fact, never a + // substitute for group proof or permission to erase a failed handle. + } + fn finish_at(&mut self, at: u64) -> bool { + if self.finished { + return true; + } + if at >= self.cleanup_end.unwrap_or(0) { + self.poison("SCOPE_CLEANUP_DEADLINE"); + self.finished = true; + } else if self.slots.iter().all(Edge::waits_known) + && (self.slots.iter().all(Edge::proof) || self.owner.borrow().first_fault.is_some()) + { + self.finished = true; + } + self.finished + } +} + +/// Group-only observations. This is deliberately not a whole-Scope proof. +#[derive(Clone, Debug)] +pub struct RegisteredGroupReport { + pub slot: usize, + pub facts: GroupReport, + pub group_proof: bool, +} + +#[derive(Clone, Debug)] +pub struct RegistryReport { + pub first_fault: Option, + pub secondary_faults: Vec, + pub admission_closed: bool, + pub retained_slots: usize, + pub groups: Vec, + pub cleanup_end: Option, + pub all_group_proofs: bool, + pub all_direct_waits_known: bool, + pub finish_called: bool, + pub output_eof_proven: bool, +} + +pub struct GroupRegistry { + inner: Registry, +} +impl GroupRegistry { + pub fn new(owner: SharedOwner, hard_end: u64) -> Self { + Self { + inner: Registry::new(owner, hard_end), + } + } + pub fn spawn_group( + &mut self, + root: &Path, + keeper: &Path, + publish: impl FnOnce(&SlotId, &GroupReport) -> io::Result<()>, + ) -> io::Result { + let at = match now() { + Ok(at) => at, + Err(error) => { + self.inner.poison("SCOPE_CLOCK"); + self.inner.begin(0, 0); + return Err(error); + } + }; + let hard_end = self.inner.hard_end; + self.inner.admit( + at, + |owner| { + GroupLease::spawn_keeper(owner, root, keeper, hard_end).map(|lease| GroupSlot { + lease, + proof: false, + }) + }, + |id, edges| { + // Publication sees only an actually retained lease's report. + let edge = edges + .get(id.index) + .ok_or_else(|| io::Error::other("SCOPE_NOT_REGISTERED"))?; + publish(id, &edge.lease.report()) + }, + ) + } + pub fn await_ready(&mut self, id: &SlotId) -> io::Result<()> { + self.with_slot(id, |slot| slot.lease.await_ready()) + } + pub fn start(&mut self, id: &SlotId, command: Command) -> io::Result<()> { + self.with_slot(id, |slot| slot.lease.start(command)) + } + fn with_slot( + &mut self, + id: &SlotId, + action: impl FnOnce(&mut GroupSlot) -> io::Result, + ) -> io::Result { + let admission = self.inner.owner.borrow().check_admission(); + let result = admission + .map_err(|e| io::Error::other(e.0)) + .and_then(|()| self.inner.slot(id).and_then(action)); + if result.is_err() { + self.inner.poison("SCOPE_EDGE_OPERATION"); + self.begin_cleanup(self.inner.hard_end); + } + result + } + pub fn group_report(&self, id: &SlotId) -> io::Result { + if !Rc::ptr_eq(&id.registry, &self.inner.identity) || id.index >= self.inner.slots.len() { + return Err(io::Error::other("SCOPE_SLOT_ID")); + } + Ok(self.inner.slots[id.index].lease.report()) + } + pub fn begin_cleanup(&mut self, deadline: u64) { + match now() { + Ok(at) => self.inner.begin(at, deadline), + Err(_) => { + self.inner.poison("SCOPE_CLOCK"); + self.inner.begin(0, 0); + } + } + } + pub fn poll_cleanup(&mut self) -> RegistryReport { + if self.inner.cleanup_end.is_none() { + self.begin_cleanup(self.inner.hard_end); + } + self.inner.poll(); + self.report() + } + pub fn report(&self) -> RegistryReport { + let owner = self.inner.owner.borrow(); + let groups: Vec<_> = self + .inner + .slots + .iter() + .enumerate() + .map(|(slot, edge)| RegisteredGroupReport { + slot, + facts: edge.lease.report(), + group_proof: edge.proof, + }) + .collect(); + let all_group_proofs = groups.iter().all(|g| g.group_proof); + let all_direct_waits_known = groups.iter().all(|g| { + g.facts.keeper_status.is_some() + && (!g.facts.workload_spawned || g.facts.workload_status.is_some()) + }); + RegistryReport { + first_fault: owner.first_fault, + admission_closed: owner.admission_closed, + secondary_faults: self.inner.secondary_faults.clone(), + retained_slots: self.inner.slots.len(), + cleanup_end: self.inner.cleanup_end, + groups, + all_group_proofs, + all_direct_waits_known, + finish_called: self.inner.finished, + output_eof_proven: false, + } + } + pub fn finish(&mut self) -> RegistryReport { + if self.inner.finished { + return self.report(); + } + self.begin_cleanup(self.inner.hard_end); + loop { + // Always collect one round even if the proof bound already expired + // or the clock failed. Retain those late facts without upgrading it. + self.poll_cleanup(); + match now() { + Ok(at) => { + if self.inner.finish_at(at) { + break; + } + } + Err(_) => { + self.inner.poison("SCOPE_CLOCK"); + self.inner.finished = true; + break; + } + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + self.report() + } +} +impl Drop for GroupRegistry { + fn drop(&mut self) { + if !self.inner.finished { + self.inner.poison("SCOPE_DROPPED_WITHOUT_FINISH"); + let _ = self.finish(); + } + } +} + +#[cfg(test)] +#[path = "../tests/unit/source_qa_scope.rs"] +mod tests; + +#[cfg(test)] +mod hook_probe_diagnostic_tests { + use super::*; + use crate::process_ownership::scope::{monotonic_now, Scope}; + + fn cohort_reply(code: i32, stdout: Vec) -> crate::process_ownership::scope::CommandResult { + use std::os::unix::process::ExitStatusExt; + crate::process_ownership::scope::CommandResult { + status: std::process::ExitStatus::from_raw(code << 8), + output: crate::process_ownership::io::CommandOutput { + stdout, + stderr: Vec::new(), + }, + } + } + + #[test] + fn repository_cohort_diagnostic_routes_two_commands_and_three_facts_once() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().canonicalize().unwrap(); + let bytes = format!("{}\n{}\n", root.display(), root.display()).into_bytes(); + let mut calls = 0; + let mut runner = RepositoryCohortDiagnostic { + run: |commands: [Command; 2]| { + calls += 1; + assert_eq!(calls, 1); + let expected = [ + vec![ + "rev-parse", + "--path-format=absolute", + "--show-toplevel", + "--git-common-dir", + ], + vec!["config", "--get-regexp", "^remote\\..*\\.url$"], + ]; + for (command, arguments) in commands.iter().zip(expected) { + assert_eq!(command.get_program(), "git"); + let actual = command.get_args().collect::>(); + assert_eq!(actual[0], "-C"); + assert_eq!(actual[1], root.as_os_str()); + assert_eq!(actual[2..], arguments); + } + Ok([cohort_reply(0, bytes.clone()), cohort_reply(1, Vec::new())]) + }, + }; + let repository = crate::capture::Repository::resolve_with(&root, &mut runner).unwrap(); + assert_eq!(repository.remote_hash, crate::capture::hash("")); + assert_eq!(calls, 1); + } + + #[test] + fn repository_cohort_diagnostic_failure_is_observed_without_fallback() { + let temporary = tempfile::tempdir().unwrap(); + let end = monotonic_now().unwrap() + 1_000_000_000; + let mut scope = Scope::with_owner(Default::default(), end); + let mut called = false; + let mut runner = RepositoryCohortDiagnostic { + run: |_: [Command; 2]| { + called = true; + scope.begin_cancel(ProtocolError("GROUP_DEADLINE"), end); + let original: io::Result<[crate::process_ownership::scope::CommandResult; 2]> = + Err(io::Error::new(io::ErrorKind::TimedOut, "GROUP_DEADLINE")); + let result = probe_observation(&mut scope, original, |report| { + assert_eq!(report.first_fault, Some(ProtocolError("GROUP_DEADLINE"))); + Ok(()) + }); + assert!(matches!(&result, Err(error) if error.kind() == io::ErrorKind::TimedOut)); + result + }, + }; + assert!(crate::capture::Repository::resolve_with(temporary.path(), &mut runner).is_err()); + assert!(called); + } + + #[test] + fn hook_probe_diagnostic_receipt_failure_poison_same_scope() { + let end = monotonic_now().unwrap() + 1_000_000_000; + let mut scope = Scope::with_owner(Default::default(), end); + let result = probe_observation(&mut scope, Ok(()), |_| { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "QA_RECEIPT", + )) + }); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::PermissionDenied); + assert_eq!( + scope.report().first_fault, + Some(ProtocolError("QA_PROBE_RECEIPT")) + ); + assert!(scope.failed()); + } + + #[test] + fn hook_probe_diagnostic_primary_error_survives_failed_receipt() { + let end = monotonic_now().unwrap() + 1_000_000_000; + let mut scope = Scope::with_owner(Default::default(), end); + scope.begin_cancel(ProtocolError("SCOPE_OPERATION_DEADLINE"), end); + let original: io::Result<()> = Err(io::Error::new( + io::ErrorKind::TimedOut, + ProtocolError("SCOPE_OPERATION_DEADLINE"), + )); + let result = probe_observation(&mut scope, original, |report| { + assert_eq!( + report.first_fault, + Some(ProtocolError("SCOPE_OPERATION_DEADLINE")) + ); + Err(io::Error::other("QA_RECEIPT")) + }); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::TimedOut); + assert_eq!( + scope.report().first_fault, + Some(ProtocolError("SCOPE_OPERATION_DEADLINE")) + ); + } +} diff --git a/tests/api_mock.rs b/tests/api_mock.rs index 04775ef..7ce6b87 100644 --- a/tests/api_mock.rs +++ b/tests/api_mock.rs @@ -396,7 +396,10 @@ async fn create_time_entry_success() { .and(header("Keito-Account-Id", "co_test")) .and(header("X-Keito-Client", "cli")) .and(header("X-Keito-Client-Version", env!("CARGO_PKG_VERSION"))) - .and(header_regex("User-Agent", r"^keito-cli/\d+\.\d+\.\d+$")) + .and(header( + "User-Agent", + concat!("keito-cli/", env!("CARGO_PKG_VERSION")), + )) .and(header_regex("Idempotency-Key", r"^keito-cli-\d+-\d+-\d+$")) .and(body_json(serde_json::json!({ "project_id": "p1", diff --git a/tests/capture.rs b/tests/capture.rs new file mode 100644 index 0000000..24b52ca --- /dev/null +++ b/tests/capture.rs @@ -0,0 +1,179 @@ +#[path = "support/service_boundary.rs"] +mod service_boundary; +use predicates::prelude::*; + +fn private_process( + program: impl AsRef, + home: &std::path::Path, +) -> assert_cmd::Command { + let home = home.canonicalize().unwrap(); + let mut cmd = service_boundary::command(program); + cmd.env_clear() + .env("HOME", &home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("KEITO_CAPTURE_HOME", home.join("capture")) + .env("XDG_CONFIG_HOME", home.join("config")) + .env("APPDATA", home.join("AppData/Roaming")) + .env( + "PATH", + if cfg!(windows) { + std::env::var_os("PATH").unwrap_or_default() + } else { + "/usr/bin:/bin".into() + }, + ) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null"); + cmd +} + +// Acceptance evidence for CAP/MAP/SEC: a missing command is the intentional red +// baseline, not an authentication or fixture failure. +#[cfg(unix)] +#[test] +fn capture_status_is_a_local_metadata_only_command() { + let home = tempfile::tempdir().unwrap(); + private_process(assert_cmd::cargo::cargo_bin!("keito"), home.path()) + .env("KEITO_CAPTURE_HOME", home.path().join("capture")) + .args(["capture", "status", "--json"]) + .assert() + .success() + .stdout(predicate::str::contains("\"pending\": 0")) + .stdout(predicate::str::contains("\"delivery_verified\": false")); +} + +#[cfg(unix)] +#[test] +fn capture_setup_requires_explicit_local_consent_and_targets() { + let home = tempfile::tempdir().unwrap(); + private_process(assert_cmd::cargo::cargo_bin!("keito"), home.path()) + .args(["capture", "setup", "--project", "p1", "--task", "t1"]) + .assert() + .failure() + .stderr(predicate::str::contains("--agent")); +} + +#[cfg(unix)] +#[test] +fn capture_hook_discards_sensitive_input_without_a_mapping() { + let home = tempfile::tempdir().unwrap(); + private_process(assert_cmd::cargo::cargo_bin!("keito"),home.path()) + .env("KEITO_CAPTURE_HOME", home.path().join("capture")) + .args(["capture", "hook", "--agent", "codex", "--event", "stop", "--harness-version", "fixture-v1"]) + .write_stdin(r#"{"session_id":"synthetic-session","cwd":"/does-not-exist/PRIVATE_PATH_CANARY","prompt":"PRIVATE_PROMPT_CANARY","last_assistant_message":"PRIVATE_ASSISTANT_CANARY"}"#) + .assert().success().stdout("") + .stderr(predicate::str::contains("PRIVATE").not()); + for entry in std::fs::read_dir(home.path()).unwrap() { + let entry = entry.unwrap(); + if entry.path().is_file() { + assert!( + !String::from_utf8_lossy(&std::fs::read(entry.path()).unwrap()).contains("PRIVATE") + ); + } + } +} + +#[test] +fn scripted_skill_install_without_targets_has_no_side_effects() { + let home = tempfile::tempdir().unwrap(); + private_process(assert_cmd::cargo::cargo_bin!("keito"), home.path()) + .env("HOME", home.path()) + .env("KEITO_CAPTURE_HOME", home.path().join("capture")) + .args(["skill", "install", "--json"]) + .assert() + .failure() + .stderr(predicate::str::contains("--agent")); + assert!(!home.path().join(".codex").exists()); + assert!(!home.path().join(".claude").exists()); +} + +#[cfg(unix)] +#[test] +fn scripted_source_setup_without_targets_stops_before_installation() { + let home = tempfile::tempdir().unwrap(); + private_process("bash", home.path()) + .arg("setup") + .env("HOME", home.path()) + .env("KEITO_CAPTURE_HOME", home.path().join("capture")) + .assert() + .failure() + .stderr(predicate::str::contains("--host")); + assert_eq!(std::fs::read_dir(home.path()).unwrap().count(), 0); +} + +#[cfg(unix)] +#[test] +fn replaced_worker_runtime_is_refused_before_loading_credentials_or_network() { + let home = tempfile::tempdir().unwrap(); + private_process(assert_cmd::cargo::cargo_bin!("keito"), home.path()) + .args([ + "capture", + "worker", + "--expected-runtime-hash", + "0000000000000000000000000000000000000000000000000000000000000000", + "--json", + ]) + .assert() + .failure() + .stderr(predicate::str::contains("runtime changed")); +} + +#[test] +fn live_doctor_malformed_config_never_echoes_credential_source_lines() { + let home = tempfile::tempdir().unwrap(); + for directory in [ + home.path().join("Library/Application Support/keito"), + home.path().join("config/keito"), + home.path().join("AppData/Roaming/keito"), + ] { + std::fs::create_dir_all(&directory).unwrap(); + std::fs::write( + directory.join("config.toml"), + "api_key = \"kto_PRIVATE_CONFIG_CANARY\" invalid\n", + ) + .unwrap(); + } + private_process(assert_cmd::cargo::cargo_bin!("keito"), home.path()) + .env("HOME", home.path()) + .env("KEITO_CAPTURE_HOME", home.path().join("capture")) + .env("XDG_CONFIG_HOME", home.path().join("config")) + .env("APPDATA", home.path().join("AppData/Roaming")) + .args(["skill", "doctor", "--live", "--json"]) + .assert() + .failure() + .stderr(predicate::str::contains("PRIVATE_CONFIG_CANARY").not()); +} + +#[test] +fn local_doctor_distinguishes_repository_worker_and_delivery_from_credential_presence() { + let home = tempfile::tempdir().unwrap(); + let output = private_process(assert_cmd::cargo::cargo_bin!("keito"), home.path()) + .env("HOME", home.path()) + .env("KEITO_CAPTURE_HOME", home.path().join("capture")) + .env("KEITO_CAPTURE_HOME", home.path().join("capture")) + .args(["skill", "doctor", "--json"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let status: serde_json::Value = serde_json::from_slice(&output).unwrap(); + assert!(status["capture"]["current_repository"].is_object()); + assert!(status["worker"].is_object()); + assert_eq!(status["ready"], false); + assert_eq!(status["delivery_verified"], false); + assert_eq!(status["hook_trust"], "UNKNOWN_REVIEW_IN_HARNESS"); + #[cfg(not(unix))] + { + assert_eq!(status["capture"]["reason"], "UNSUPPORTED_PLATFORM"); + assert_eq!(status["capture"]["current_repository"]["approved"], false); + assert_eq!(status["worker"]["state"], "UNSUPPORTED_PLATFORM"); + assert_eq!(status["worker"]["installed"], false); + assert_eq!(status["worker"]["running"], false); + assert!( + !home.path().join("capture").exists(), + "unsupported doctor created native storage" + ); + } +} diff --git a/tests/capture_busy_wiring.rs b/tests/capture_busy_wiring.rs new file mode 100644 index 0000000..8bdf559 --- /dev/null +++ b/tests/capture_busy_wiring.rs @@ -0,0 +1,329 @@ +//! Actual SQLite connection/callback wiring; no harness, service or CLI process. +#![cfg(unix)] +#[path = "support/mutation_environment.rs"] +mod isolation; +use keito_cli::{ + capture::{self, Binding, Clock, Repository, Signal, Store}, + cli::capture::CaptureEvent, +}; +use std::{ + fs, + os::unix::fs::{MetadataExt, PermissionsExt}, + path::PathBuf, + time::{Duration, Instant}, +}; + +struct Fixture { + _temp: tempfile::TempDir, + root: PathBuf, + capture: PathBuf, + repository: Repository, +} +impl Fixture { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let home = root.join("home"); + let capture = home.join("capture"); + for path in [ + &home, + &capture, + &home.join(".codex"), + &home.join(".claude"), + &home.join("config"), + &home.join("state"), + &root.join("empty-bin"), + &root.join("tmp"), + ] { + fs::create_dir_all(path).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + let metadata = fs::symlink_metadata(path).unwrap(); + assert_eq!(metadata.uid(), unsafe { libc::geteuid() }); + assert!(!metadata.file_type().is_symlink()); + assert_eq!(path.canonicalize().unwrap(), *path); + } + let core = root.join("inert-never-executed-core"); + fs::write(&core, b"inert test boundary only; never executable").unwrap(); + let marker = root.join("invalid-mutation"); + for missing in [0, 1, 2] { + let result = isolation::checked( + &root, + &root, + (missing != 0).then_some(home.as_path()), + (missing != 1).then_some(capture.as_path()), + (missing != 2).then_some(core.as_path()), + ); + if result.is_ok() { + fs::write(&marker, b"unsafe").unwrap(); + } + assert!(!marker.exists()); + } + let checked = + isolation::checked(&root, &root, Some(&home), Some(&capture), Some(&core)).unwrap(); + assert_eq!(checked.home, home); + assert_eq!(checked.capture, capture); + assert_eq!(checked.core, core); + let repository = Repository { + key: capture::hash("wiring-repo"), + remote_hash: capture::hash("wiring-remote"), + hint_hash: capture::hash("wiring-hint"), + linked_without_hint: false, + disabled: false, + }; + Self { + _temp: temp, + root, + capture, + repository, + } + } + fn database(&self) -> rusqlite::Connection { + rusqlite::Connection::open(self.capture.join("capture.sqlite3")).unwrap() + } + fn store(&self) -> Store { + Store::open(&self.capture).unwrap() + } + fn approve(&self, store: &mut Store) { + store + .approve(Binding { + repository_key: self.repository.key.clone(), + remote_hash: self.repository.remote_hash.clone(), + hint_hash: self.repository.hint_hash.clone(), + id: String::new(), + version: 0, + workspace_id: "workspace_wiring".into(), + owner_id: "owner_wiring".into(), + origin_hash: capture::hash("https://example.invalid"), + project_id: "project_wiring".into(), + task_id: "task_wiring".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }) + .unwrap(); + } + fn event( + &self, + store: &mut Store, + session: &str, + turn: &str, + event: CaptureEvent, + n: i64, + ) -> Result<(), keito_cli::error::AppError> { + store.event( + &self.repository, + Signal { + source: "codex", + resumed: false, + source_id: session, + turn_id: Some(turn), + version: "0.167.0", + event, + clock: &Clock { + wall: 1_794_067_200 + n, + monotonic: 1000 + n, + boot: "owned-wiring-fixture".into(), + }, + }, + ) + } + fn refused_event(&self, store: &mut Store, session: &str, turn: &str, n: i64) { + let started = Instant::now(); + assert!(self + .event(store, session, turn, CaptureEvent::Prompt, n) + .is_err()); + let elapsed = started.elapsed(); + println!("actual SQLite rejected locking operation: {elapsed:?}"); + // This lower-bound control distinguishes a fresh real callback budget + // from incorrectly retained exhausted state. The existing dedicated + // contention case retains the unchanged 700ms upper acceptance gate. + assert!( + elapsed >= Duration::from_millis(450), + "new locking event inherited an exhausted/immediate refusal" + ); + } +} + +#[test] +fn same_store_failed_lock_then_success_then_second_contention_gets_a_fresh_budget() { + let fixture = Fixture::new(); + let mut store = fixture.store(); + fixture.approve(&mut store); + let blocker = fixture.database(); + blocker.execute_batch("BEGIN IMMEDIATE").unwrap(); + fixture.refused_event(&mut store, "session_same", "first", 0); + blocker.execute_batch("ROLLBACK").unwrap(); + fixture + .event( + &mut store, + "session_same", + "first", + CaptureEvent::Prompt, + 10, + ) + .unwrap(); + fixture + .event(&mut store, "session_same", "first", CaptureEvent::Stop, 40) + .unwrap(); + blocker.execute_batch("BEGIN IMMEDIATE").unwrap(); + fixture.refused_event(&mut store, "session_same", "second", 50); + blocker.execute_batch("ROLLBACK").unwrap(); + fixture + .event( + &mut store, + "session_same", + "second", + CaptureEvent::Prompt, + 60, + ) + .unwrap(); + fixture + .event(&mut store, "session_same", "second", CaptureEvent::Stop, 90) + .unwrap(); + let sessions = store.preview("session_same").unwrap(); + assert_eq!( + sessions[0] + .segments + .iter() + .map(|s| s.duration_seconds) + .collect::>(), + [30, 30] + ); + assert!(!store.status().unwrap().storage_paused); +} + +#[test] +fn independent_stores_keep_their_own_failed_and_recovered_locking_state() { + let fixture = Fixture::new(); + let mut first = fixture.store(); + fixture.approve(&mut first); + let mut second = fixture.store(); + let blocker = fixture.database(); + blocker.execute_batch("BEGIN IMMEDIATE").unwrap(); + fixture.refused_event(&mut first, "session_one", "turn", 0); + fixture.refused_event(&mut second, "session_two", "turn", 0); + blocker.execute_batch("ROLLBACK").unwrap(); + for (store, session) in [(&mut first, "session_one"), (&mut second, "session_two")] { + fixture + .event(store, session, "turn", CaptureEvent::Prompt, 10) + .unwrap(); + fixture + .event(store, session, "turn", CaptureEvent::Stop, 40) + .unwrap(); + assert_eq!( + store.preview(session).unwrap()[0].segments[0].duration_seconds, + 30 + ); + } +} + +#[test] +fn schema_open_installs_the_busy_budget_before_locked_schema_work() { + let fixture = Fixture::new(); + drop(fixture.store()); + let blocker = fixture.database(); + blocker.execute_batch("BEGIN EXCLUSIVE").unwrap(); + let started = Instant::now(); + assert!(Store::open(&fixture.capture).is_err()); + let elapsed = started.elapsed(); + println!("locked schema/open: {elapsed:?}"); + assert!(elapsed >= Duration::from_millis(450)); + blocker.execute_batch("ROLLBACK").unwrap(); + let mut recovered = fixture.store(); + fixture.approve(&mut recovered); + fixture + .event( + &mut recovered, + "session_schema", + "turn", + CaptureEvent::Prompt, + 0, + ) + .unwrap(); + fixture + .event( + &mut recovered, + "session_schema", + "turn", + CaptureEvent::Stop, + 30, + ) + .unwrap(); + assert_eq!( + recovered.preview("session_schema").unwrap()[0].segments[0].duration_seconds, + 30 + ); +} + +#[test] +fn reader_blocked_commit_rolls_back_and_the_same_store_can_later_commit() { + let fixture = Fixture::new(); + let mut store = fixture.store(); + fixture.approve(&mut store); + let reader = fixture.database(); + reader + .execute_batch("BEGIN; SELECT COUNT(*) FROM bindings") + .unwrap(); + fixture.refused_event(&mut store, "session_commit", "turn", 0); + #[cfg(feature = "dev-tools")] + { + let timing = store.last_admission_timing().unwrap(); + assert_eq!( + timing.sqlite_error, None, + "BEGIN must succeed before this commit-only contention" + ); + assert!(timing.authority.is_some()); + } + let count: i64 = reader + .query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0)) + .unwrap(); + assert_eq!(count, 0, "failed commit must not leave a partial session"); + reader.execute_batch("ROLLBACK").unwrap(); + fixture + .event( + &mut store, + "session_commit", + "turn", + CaptureEvent::Prompt, + 10, + ) + .unwrap(); + fixture + .event(&mut store, "session_commit", "turn", CaptureEvent::Stop, 40) + .unwrap(); + assert_eq!( + store.preview("session_commit").unwrap()[0].segments[0].duration_seconds, + 30 + ); +} + +#[test] +fn uncontended_store_preserves_normal_schema_event_and_commit_behavior() { + let fixture = Fixture::new(); + let mut store = fixture.store(); + fixture.approve(&mut store); + fixture + .event( + &mut store, + "session_control", + "turn", + CaptureEvent::Prompt, + 0, + ) + .unwrap(); + fixture + .event( + &mut store, + "session_control", + "turn", + CaptureEvent::Stop, + 30, + ) + .unwrap(); + let sessions = store.preview("session_control").unwrap(); + assert_eq!(sessions[0].segments[0].duration_seconds, 30); + assert_eq!(sessions[0].segments[0].completeness, "COMPLETE"); + assert!(!store.status().unwrap().storage_paused); + assert!(!fixture.root.join("invalid-mutation").exists()); +} diff --git a/tests/capture_dispatch_refusal.rs b/tests/capture_dispatch_refusal.rs new file mode 100644 index 0000000..1586859 --- /dev/null +++ b/tests/capture_dispatch_refusal.rs @@ -0,0 +1,320 @@ +//! Broken cores must reach the guardian before any accounting continuation. +//! Owned faults are injected after private preflight and command construction. +#![cfg(unix)] +#[path = "support/mutation_environment.rs"] +mod isolation; +use keito_cli::{ + capture::{self, Binding, Clock, Repository, Signal, Store}, + cli::capture::CaptureEvent, +}; +use std::{ + fs, + io::Write, + os::unix::{ + fs::{symlink, PermissionsExt}, + process::ExitStatusExt, + }, + path::{Path, PathBuf}, + process::{Command, Stdio}, + time::{Duration, Instant}, +}; +struct Case { + _temp: tempfile::TempDir, + root: PathBuf, + home: PathBuf, + capture: PathBuf, + core: PathBuf, + guard: PathBuf, + repo: Repository, + store: Store, +} +impl Case { + fn new(name: &str) -> Self { + let temp = tempfile::tempdir().unwrap(); + let owner = temp.path().canonicalize().unwrap(); + let root = owner.join("case"); + fs::create_dir(&root).unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let home = root.join("home"); + let capture = home.join("capture"); + fs::create_dir_all(&capture).unwrap(); + fs::set_permissions(&capture, fs::Permissions::from_mode(0o700)).unwrap(); + let core = root.join("core"); + let guard = root.join("guard"); + fs::write( + &core, + "#!/bin/sh\n: > \"$KEITO_DISPATCH_TEST_ENTERED\"\nexit 89\n", + ) + .unwrap(); + fs::set_permissions(&core, fs::Permissions::from_mode(0o700)).unwrap(); + fs::copy(assert_cmd::cargo::cargo_bin!("keito-capture-guard"), &guard).unwrap(); + let bin = root.join("bin"); + fs::create_dir(&bin).unwrap(); + fs::write(bin.join("sleep"), "#!/bin/sh\nexec /bin/sleep \"$@\"\n").unwrap(); + fs::set_permissions(bin.join("sleep"), fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(bin.join("bash"), "#!/bin/sh\nexec /bin/bash \"$@\"\n").unwrap(); + fs::set_permissions(bin.join("bash"), fs::Permissions::from_mode(0o700)).unwrap(); + let repo = Repository { + key: capture::hash(name), + remote_hash: capture::hash("remote"), + hint_hash: capture::hash("hint"), + disabled: false, + linked_without_hint: false, + }; + let mut store = Store::open(&capture).unwrap(); + store + .approve(Binding { + repository_key: repo.key.clone(), + remote_hash: repo.remote_hash.clone(), + hint_hash: repo.hint_hash.clone(), + id: String::new(), + version: 0, + workspace_id: "co_fixture".into(), + owner_id: "owner".into(), + origin_hash: capture::hash("synthetic"), + project_id: "project".into(), + task_id: "task".into(), + agents: vec!["codex".into(), "claude-code".into()], + paused: false, + revoked: false, + }) + .unwrap(); + Self { + _temp: temp, + root, + home, + capture, + core, + guard, + repo, + store, + } + } + fn event(&mut self, source: &str, event: CaptureEvent, second: i64) { + self.store + .event( + &self.repo, + Signal { + source, + resumed: false, + source_id: "session", + turn_id: Some("turn"), + version: if source == "codex" { + "0.167.0" + } else { + "2.1.319" + }, + event, + clock: &Clock { + wall: 1_794_067_200 + second, + monotonic: 100_000 + second, + boot: "fixture-boot".into(), + }, + }, + ) + .unwrap(); + } + fn command(&self, program: &Path) -> Command { + let checked = isolation::checked( + self.root.parent().unwrap(), + &self.root, + Some(&self.home), + Some(&self.capture), + Some(&self.core), + ) + .unwrap(); + let mut cmd = Command::new(program); + cmd.env_clear() + .current_dir(&self.root) + .env("HOME", &checked.home) + .env("KEITO_CAPTURE_HOME", &checked.capture) + .env("CODEX_HOME", checked.home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", checked.home.join(".claude")) + .env("XDG_CONFIG_HOME", checked.home.join("config")) + .env("APPDATA", checked.home.join("AppData")) + .env("PATH", self.root.join("bin")) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("KEITO_CLI_BIN", &checked.core) + .env("KEITO_CAPTURE_GUARD_BIN", &self.guard) + .env( + "KEITO_CAPTURE_CORE_SHA256", + capture::hash(fs::read(&checked.core).unwrap()), + ) + .env( + "KEITO_DISPATCH_TEST_ENTERED", + self.root.join("MUST_NOT_ENTER_CORE"), + ) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + cmd + } + fn flags(&self) -> usize { + fs::read_dir(self.capture.join("capture-invocations")) + .map(|v| v.count()) + .unwrap_or(0) + } + fn scan(&self) { + fn visit(path: &Path) { + for entry in fs::read_dir(path).unwrap() { + let path = entry.unwrap().path(); + let m = fs::symlink_metadata(&path).unwrap(); + assert!(!m.file_type().is_symlink()); + if m.is_dir() { + visit(&path); + } else { + let bytes = fs::read(path).unwrap(); + assert!(!bytes + .windows(b"PRIVATE_DISPATCH_CANARY".len()) + .any(|v| v == b"PRIVATE_DISPATCH_CANARY")); + } + } + } + visit(&self.capture); + } +} +fn refused_core(route: &str, mode: &str) { + let mut case = Case::new(&format!("{route}-{mode}")); + let source = if route == "plugin" { + "claude-code" + } else { + "codex" + }; + case.event(source, CaptureEvent::Prompt, 0); + let mut cmd = case.command(if route == "direct" { + &case.guard + } else { + Path::new("/bin/bash") + }); + match route { + "direct" => { + cmd.arg("--core").arg(&case.core).args([ + "--agent", + "codex", + "--event", + "stop", + "--harness-version", + "0.167.0", + ]); + } + "plugin" => { + let plugin: serde_json::Value = serde_json::from_str(include_str!( + "../skills/keito-time-track/hooks/claude-plugin.json" + )) + .unwrap(); + let literal = plugin["hooks"]["Stop"][0]["hooks"][0]["command"] + .as_str() + .unwrap(); + cmd.env( + "CLAUDE_PLUGIN_ROOT", + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("skills"), + ) + .env("KEITO_HARNESS_VERSION", "2.1.319") + .args(["-c", literal]); + } + "bundled" => { + cmd.arg(concat!( + env!("CARGO_MANIFEST_DIR"), + "/skills/keito-time-track/hooks/dispatch.sh" + )) + .args([ + "--agent", + "codex", + "--event", + "stop", + "--harness-version", + "0.167.0", + ]); + } + _ => unreachable!(), + } + let saved = case.root.join("saved-core"); + match mode { + "missing" => fs::rename(&case.core, &saved).unwrap(), + "mode" => fs::set_permissions(&case.core, fs::Permissions::from_mode(0o600)).unwrap(), + "symlink" => { + fs::rename(&case.core, &saved).unwrap(); + symlink(&saved, &case.core).unwrap(); + } + _ => unreachable!(), + } + // A deliberate owned fault after checked() must exercise refusal, never a + // foreign path or an inherited operator environment. + let start = Instant::now(); + let mut child = cmd.spawn().unwrap(); + let _ = child + .stdin + .take() + .unwrap() + .write_all(b"{\"prompt\":\"PRIVATE_DISPATCH_CANARY\"}"); + let out = child.wait_with_output().unwrap(); + assert!( + out.status.success() && out.stdout.is_empty() && out.stderr.is_empty(), + "route={route} mode={mode}: exit={:?} signal={:?} stdout_bytes={} stderr_bytes={} elapsed_ms={:.3} shell_termination_notice={} shell_kill_notice={}", + out.status.code(), out.status.signal(), out.stdout.len(), out.stderr.len(), + start.elapsed().as_secs_f64() * 1000.0, + out.stderr.windows(b"Terminated".len()).any(|bytes| bytes == b"Terminated"), + out.stderr.windows(b"Killed".len()).any(|bytes| bytes == b"Killed") + ); + assert!(start.elapsed() < Duration::from_secs(1)); + let flags = case.flags(); + assert!(!case.root.join("MUST_NOT_ENTER_CORE").exists()); + match mode { + "missing" => fs::rename(&saved, &case.core).unwrap(), + "mode" => fs::set_permissions(&case.core, fs::Permissions::from_mode(0o700)).unwrap(), + "symlink" => { + fs::remove_file(&case.core).unwrap(); + fs::rename(&saved, &case.core).unwrap(); + } + _ => unreachable!(), + } + case.event(source, CaptureEvent::Stop, 150); + let session = case.store.preview("session").unwrap().remove(0); + let seconds: i64 = session + .segments + .iter() + .filter(|v| v.completeness == "COMPLETE") + .map(|v| v.duration_seconds) + .sum(); + case.scan(); + assert_eq!(flags, 1, "route={route} mode={mode}: no durable refusal"); + assert_eq!(seconds, 0, "missed Stop became COMPLETE time"); + assert!(session.needs_attention); +} +#[test] +fn bundled_missing_core() { + refused_core("bundled", "missing"); +} +#[test] +fn bundled_nonexecutable_core() { + refused_core("bundled", "mode"); +} +#[test] +fn bundled_symlink_core() { + refused_core("bundled", "symlink"); +} +#[test] +fn plugin_missing_core() { + refused_core("plugin", "missing"); +} +#[test] +fn plugin_nonexecutable_core() { + refused_core("plugin", "mode"); +} +#[test] +fn plugin_symlink_core() { + refused_core("plugin", "symlink"); +} +#[test] +fn direct_guard_missing_core() { + refused_core("direct", "missing"); +} +#[test] +fn direct_guard_nonexecutable_core() { + refused_core("direct", "mode"); +} +#[test] +fn direct_guard_symlink_core() { + refused_core("direct", "symlink"); +} diff --git a/tests/capture_invocations.rs b/tests/capture_invocations.rs new file mode 100644 index 0000000..aadb477 --- /dev/null +++ b/tests/capture_invocations.rs @@ -0,0 +1,307 @@ +#![cfg(unix)] +#[path = "support/mutation_environment.rs"] +mod isolation; +use keito_cli::capture::{self, Binding, Clock, Repository, Signal, Store}; +use keito_cli::cli::capture::CaptureEvent::*; +use std::{fs, io::Write, os::fd::AsRawFd, os::unix::fs::OpenOptionsExt, path::Path}; +const PENDING: &[u8] = b"KEITO_CAPTURE_PENDING_V1\n"; +fn clock(n: i64) -> Clock { + Clock { + wall: 1794067200 + n, + monotonic: 1000 + n, + boot: "fixture".into(), + } +} +fn repo() -> Repository { + Repository { + key: capture::hash("r"), + remote_hash: capture::hash("remote"), + hint_hash: capture::hash("hint"), + linked_without_hint: false, + disabled: false, + } +} +fn fixture() -> (tempfile::TempDir, Store, Binding) { + let t = tempfile::tempdir().unwrap(); + let mut s = Store::open(&t.path().canonicalize().unwrap()).unwrap(); + let b = s + .approve(Binding { + repository_key: repo().key, + remote_hash: repo().remote_hash, + hint_hash: repo().hint_hash, + id: String::new(), + version: 0, + workspace_id: "co_test".into(), + owner_id: "owner".into(), + origin_hash: capture::hash("origin"), + project_id: "p".into(), + task_id: "t".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }) + .unwrap(); + (t, s, b) +} +fn marker(root: &Path, nonce: &str, live: bool) -> fs::File { + use std::os::unix::fs::PermissionsExt; + let root = root.join("capture-invocations"); + fs::create_dir_all(&root).unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let mut file = fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .mode(0o600) + .open(root.join(format!("{nonce}.pending"))) + .unwrap(); + file.write_all(PENDING).unwrap(); + file.sync_all().unwrap(); + if live { + assert_eq!( + unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + } + file +} +fn event(s: &mut Store, e: keito_cli::cli::capture::CaptureEvent, n: i64) { + s.event( + &repo(), + Signal { + source: "codex", + resumed: false, + source_id: "session", + turn_id: Some("turn"), + version: "0.167.0", + event: e, + clock: &clock(n), + }, + ) + .unwrap(); +} +#[test] +fn core_never_entered_marker_prevents_a_later_stop_from_inventing_complete_seconds() { + let (t, mut s, b) = fixture(); + event(&mut s, Prompt, 0); + let nonce = capture::hash("never-entered"); + drop(marker(&t.path().canonicalize().unwrap(), &nonce, false)); + event(&mut s, Stop, 150); + let v = s.preview("session").unwrap(); + assert_eq!(v[0].segments[0].duration_seconds, 0); + assert!(v[0].needs_attention); + assert!(s.claim(&b, clock(160).wall).unwrap().is_none()); + assert!(s.status().unwrap().storage_paused); +} +#[test] +fn live_guard_blocks_delivery_and_only_own_live_nonce_allows_hook_accounting() { + let (t, mut s, b) = fixture(); + let root = t.path().canonicalize().unwrap(); + let nonce = capture::hash("live"); + let _guard = marker(&root, &nonce, true); + s.hook_invocation(&nonce).unwrap(); + event(&mut s, Prompt, 0); + event(&mut s, Stop, 30); + assert!(!s.has_ready(&b, clock(31).wall).unwrap()); + assert!(s.claim(&b, clock(31).wall).unwrap().is_none()); + assert!(s.recover(&clock(32)).is_err()); + assert_eq!( + s.preview("session").unwrap()[0].segments[0].duration_seconds, + 30 + ); +} +#[test] +fn dead_guard_cannot_be_impersonated_or_acknowledged_by_a_late_core() { + let (t, mut s, _) = fixture(); + let nonce = capture::hash("dead"); + drop(marker(&t.path().canonicalize().unwrap(), &nonce, false)); + assert!(s.hook_invocation(&nonce).is_err()); +} +#[test] +fn dead_invocation_quarantines_existing_frozen_complete_bodies_through_recovery() { + let (t, mut s, b) = fixture(); + event(&mut s, Prompt, 0); + event(&mut s, Stop, 30); + let row = s.claim(&b, clock(31).wall).unwrap().unwrap(); + let nonce = capture::hash("missing-ack"); + drop(marker(&t.path().canonicalize().unwrap(), &nonce, false)); + s.maintain(clock(32).wall).unwrap(); + s.recover(&clock(40)).unwrap(); + assert!(s.claim(&b, clock(50).wall).unwrap().is_none()); + let db = rusqlite::Connection::open(t.path().join("capture.sqlite3")).unwrap(); + let frozen: String = db + .query_row("SELECT body FROM outbox", [], |r| r.get(0)) + .unwrap(); + assert_eq!(frozen, row.body); + assert!(!s.status().unwrap().storage_paused); + assert_eq!(s.status().unwrap().held, 1); +} + +#[test] +fn abandoned_preparing_prefix_is_reconciled_and_recoverable() { + let (t, mut s, b) = fixture(); + event(&mut s, Prompt, 0); + let directory = t.path().join("capture-invocations"); + fs::create_dir(&directory).unwrap(); + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap(); + let nonce = capture::hash("preparing-kill"); + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(directory.join(format!("{nonce}.preparing"))) + .unwrap(); + file.write_all(&PENDING[..8]).unwrap(); + file.sync_all().unwrap(); + drop(file); + event(&mut s, Stop, 150); + assert_eq!( + s.preview("session").unwrap()[0].segments[0].duration_seconds, + 0 + ); + assert!(s.claim(&b, clock(155).wall).unwrap().is_none()); + s.recover(&clock(160)).unwrap(); + assert!(!s.status().unwrap().storage_paused); + assert_eq!(fs::read_dir(&directory).unwrap().count(), 0); +} +#[test] +fn replaced_nonce_inode_cannot_authorize_a_late_hook() { + let (t, mut s, _) = fixture(); + let root = t.path().canonicalize().unwrap(); + let nonce = capture::hash("replaced"); + let guard = marker(&root, &nonce, true); + s.hook_invocation(&nonce).unwrap(); + drop(guard); + fs::remove_file(root.join(format!("capture-invocations/{nonce}.pending"))).unwrap(); + let _replacement = marker(&root, &nonce, true); + assert!(s + .event( + &repo(), + Signal { + source: "codex", + resumed: false, + source_id: "session", + turn_id: Some("turn"), + version: "0.167.0", + event: Prompt, + clock: &clock(0) + } + ) + .is_err()); + assert!(s.preview("session").unwrap().is_empty()); +} +#[test] +fn malformed_marker_and_symlink_are_never_healthy_or_read_as_an_invocation() { + let (t, s, _) = fixture(); + let root = t.path().canonicalize().unwrap(); + let nonce = capture::hash("invalid"); + drop(marker(&root, &nonce, false)); + let path = root.join(format!("capture-invocations/{nonce}.pending")); + fs::write(&path, b"PRIVATE_MALFORMED_CANARY").unwrap(); + assert!(s.status().is_err()); + fs::remove_file(&path).unwrap(); + std::os::unix::fs::symlink(root.join("capture.sqlite3"), &path).unwrap(); + assert!(s.status().is_err()); +} + +#[test] +fn unqualified_actual_hook_never_acknowledges_or_accepts_a_guarded_boundary() { + use std::{ + os::unix::fs::PermissionsExt, + process::{Command, Stdio}, + }; + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().canonicalize().unwrap(); + let home = base.join("home"); + fs::create_dir(&home).unwrap(); + let directory = home.join("capture"); + fs::create_dir(&directory).unwrap(); + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap(); + let core = base.join("keito"); + fs::copy(assert_cmd::cargo::cargo_bin!("keito"), &core).unwrap(); + let checked = + isolation::checked(&base, &base, Some(&home), Some(&directory), Some(&core)).unwrap(); + let mut store = Store::open(&directory).unwrap(); + let binding = Binding { + repository_key: repo().key, + remote_hash: repo().remote_hash, + hint_hash: repo().hint_hash, + id: String::new(), + version: 0, + workspace_id: "co_test".into(), + owner_id: "owner".into(), + origin_hash: capture::hash("origin"), + project_id: "p".into(), + task_id: "t".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }; + store.approve(binding).unwrap(); + for malformed in [false, true] { + let nonce = capture::hash(if malformed { + "bad-input" + } else { + "valid-input" + }); + let guard = marker(&directory, &nonce, true); + let mut pipe = [0; 2]; + assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0); + let mut child = Command::new(&checked.core) + .env_clear() + .current_dir(&home) + .env("HOME", &checked.home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("KEITO_CAPTURE_HOME", &checked.capture) + .env("XDG_CONFIG_HOME", home.join("config")) + .env("APPDATA", home.join("AppData")) + .env("PATH", base.join("empty-bin")) + .env("KEITO_CAPTURE_INVOCATION_NONCE", &nonce) + .env("KEITO_CAPTURE_ACK_FD", pipe[1].to_string()) + .args([ + "capture", + "hook", + "--agent", + "codex", + "--event", + "prompt", + "--harness-version", + "0.167.0", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let input = if malformed { + b"{PRIVATE_RAW_CANARY".as_slice() + } else { + b"{\"session_id\":\"native\",\"turn_id\":\"turn\",\"prompt\":\"PRIVATE_RAW_CANARY\"}" + .as_slice() + }; + let _ = child.stdin.take().unwrap().write_all(input); + let output = child.wait_with_output().unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + assert!(!String::from_utf8_lossy(&output.stderr).contains("PRIVATE_RAW_CANARY")); + unsafe { + libc::close(pipe[1]); + let flags = libc::fcntl(pipe[0], libc::F_GETFL); + libc::fcntl(pipe[0], libc::F_SETFL, flags | libc::O_NONBLOCK); + } + let mut bytes = [0; 128]; + assert!(unsafe { libc::read(pipe[0], bytes.as_mut_ptr().cast(), bytes.len()) } <= 0); + unsafe { + libc::close(pipe[0]); + } + assert_eq!(store.status().unwrap().unfinished, 0); + assert!(directory + .join(format!("capture-invocations/{nonce}.pending")) + .exists()); + drop(guard); + } + store.maintain(clock(100).wall).unwrap(); + assert!(store.status().unwrap().storage_paused); +} diff --git a/tests/capture_processes.rs b/tests/capture_processes.rs new file mode 100644 index 0000000..3c2edb8 --- /dev/null +++ b/tests/capture_processes.rs @@ -0,0 +1,621 @@ +#![cfg(unix)] +#[path = "support/runtime_pair.rs"] +mod runtime_pair; +#[path = "support/service_boundary.rs"] +mod service_boundary; +use keito_cli::capture::{self, Binding, Clock, Repository, Signal, Store}; +use keito_cli::cli::capture::CaptureEvent::Prompt; +use std::io::Write; +use std::process::{Command, Stdio}; + +#[cfg(feature = "dev-tools")] +#[test] +fn repository_cohort_with_cooperative_parent() { + use keito_cli::process_ownership::scope::Scope; + if let Some(root) = std::env::var_os("KEITO_TEST_COHORT_CHILD") { + let mut scope = Scope::entry_from_environment(500_000_000).unwrap().unwrap(); + let result = keito_cli::source_qa_scope::diagnose_fixture_repository_cohort( + &mut scope, + &runtime_pair::pair().core_path, + std::path::Path::new(&root), + |_, _, _, _| Ok(()), + ); + let report = scope.finish(); + scope.publish_terminal(result.is_ok() && report.clean); + assert!(result.is_ok() && report.clean, "{result:?} {report:?}"); + return; + } + let temp = tempfile::tempdir().unwrap(); + assert!(Command::new("git") + .arg("-C") + .arg(temp.path()) + .arg("init") + .output() + .unwrap() + .status + .success()); + let mut now: libc::timespec = unsafe { std::mem::zeroed() }; + assert_eq!( + unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now) }, + 0 + ); + let end = now.tv_sec as u64 * 1_000_000_000 + now.tv_nsec as u64 + 600_000_000; + let mut scope = Scope::local_entry(end).unwrap(); + let mut child = Command::new(std::env::current_exe().unwrap()); + child + .env_clear() + .env("HOME", temp.path()) + .env("PATH", runtime_pair::process_path()) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("KEITO_TEST_PAIR_CORE", runtime_pair::pair().core_path) + .args([ + "--exact", + "repository_cohort_with_cooperative_parent", + "--nocapture", + ]) + .env("KEITO_TEST_COHORT_CHILD", temp.path()); + let slot = scope.start_cooperative(child).unwrap(); + while !scope.slot_complete(&slot) && !scope.failed() { + scope.poll(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let report = scope.finish(); + assert!(report.clean, "{report:?}"); +} + +#[cfg(feature = "dev-tools")] +#[test] +fn verified_pair_repository_cohort_fits_the_hook_scope() { + let temp = tempfile::tempdir().unwrap(); + assert!(Command::new("git") + .arg("-C") + .arg(temp.path()) + .arg("init") + .output() + .unwrap() + .status + .success()); + let pair = runtime_pair::pair(); + let mut now: libc::timespec = unsafe { std::mem::zeroed() }; + assert_eq!( + unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now) }, + 0 + ); + let end = now.tv_sec as u64 * 1_000_000_000 + now.tv_nsec as u64 + 500_000_000; + let mut scope = keito_cli::process_ownership::scope::Scope::local_entry(end).unwrap(); + let result = keito_cli::source_qa_scope::diagnose_fixture_repository_cohort( + &mut scope, + &pair.core_path, + temp.path(), + |_, _, _, _| Ok(()), + ); + let report = scope.finish(); + assert!(result.is_ok(), "cohort error={result:?} report={report:?}"); + assert!(report.clean); +} + +// Exercise the installed ownership entry rather than the now-refused bare hook. +fn hook(root: &std::path::Path, capture: &std::path::Path, event: &str) -> Command { + let pair = runtime_pair::pair(); + drop(service_boundary::command(&pair.guard_path)); + let home = capture.parent().unwrap(); + let mut command = Command::new(&pair.guard_path); + command + .env_clear() + .current_dir(root) + .env("HOME", home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("XDG_CONFIG_HOME", home.join("config")) + .env("APPDATA", home.join("AppData")) + .env("PATH", runtime_pair::process_path()) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("KEITO_CAPTURE_HOME", capture) + .env("KEITO_CAPTURE_CORE_SHA256", &pair.core_sha256) + .arg("--core") + .arg(pair.core_path) + .args([ + "--agent", + "codex", + "--event", + event, + "--harness-version", + "0.167.0", + ]); + command +} + +#[test] +fn concurrent_real_hook_processes_persist_once_and_discard_raw_content() { + assert_concurrent_hooks(20, 90); +} + +#[test] +fn one_verified_guard_hook_accepts_the_seeded_boundary() { + assert_concurrent_hooks(1, 90); +} + +#[test] +fn guarded_hook_preserves_an_older_seeded_interval_without_a_startup_speed_assumption() { + assert_concurrent_hooks(1, 93); +} + +#[test] +fn guarded_hook_preserves_newline_quoted_unicode_repository_paths() { + assert_concurrent_hooks_in(1, 93, "PRIVATE_PATH_CANARY ' ü\nline"); +} + +fn assert_concurrent_hooks(count: usize, seed_age_seconds: i64) { + assert_concurrent_hooks_in(count, seed_age_seconds, "PRIVATE_PATH_CANARY"); +} + +fn assert_concurrent_hooks_in(count: usize, seed_age_seconds: i64, repository_name: &str) { + let temp = tempfile::tempdir().unwrap(); + let repo_root = temp.path().join(repository_name); + std::fs::create_dir(&repo_root).unwrap(); + assert!(Command::new("git") + .arg("-C") + .arg(&repo_root) + .arg("init") + .output() + .unwrap() + .status + .success()); + let repo = Repository::resolve(&repo_root).unwrap(); + let capture_dir = temp.path().join("capture"); + let mut store = Store::open(&capture_dir).unwrap(); + store + .approve(Binding { + repository_key: repo.key.clone(), + remote_hash: repo.remote_hash.clone(), + hint_hash: repo.hint_hash.clone(), + id: String::new(), + version: 0, + workspace_id: "co_fixture".into(), + owner_id: "user_fixture".into(), + origin_hash: capture::hash("https://example.invalid"), + project_id: "p_fixture".into(), + task_id: "t_fixture".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }) + .unwrap(); + let mut start = Clock::now().unwrap(); + start.wall -= seed_age_seconds; + start.monotonic -= seed_age_seconds; + store + .event( + &repo, + Signal { + source: "codex", + resumed: false, + source_id: "session-fixture", + turn_id: Some("turn-fixture"), + version: "0.167.0", + event: Prompt, + clock: &start, + }, + ) + .unwrap(); + let body=serde_json::json!({"session_id":"session-fixture","turn_id":"turn-fixture","cwd":repo_root,"prompt":"PRIVATE_PROMPT_CANARY","last_assistant_message":"PRIVATE_ASSISTANT_CANARY","transcript_path":"/PRIVATE_TRANSCRIPT_CANARY","tool_input":{"secret":"PRIVATE_TOOL_CANARY"}}).to_string(); + // Bound the real stop clock independently of machine startup speed. + let earliest_stop_wall = chrono::Utc::now().timestamp(); + let children: Vec<_> = (0..count) + .map(|_| { + let mut child = hook(&repo_root, &capture_dir, "stop") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(body.as_bytes()) + .unwrap(); + child + }) + .collect(); + for child in children { + let out = child.wait_with_output().unwrap(); + assert!(out.status.success()); + assert!(out.stdout.is_empty()); + assert!(!String::from_utf8_lossy(&out.stderr).contains("PRIVATE")); + } + let latest_stop_wall = chrono::Utc::now().timestamp(); + let sessions = store.preview("session-fixture").unwrap(); + assert_eq!(sessions.len(), 1); + assert_eq!( + sessions[0].segments.len(), + 1, + "synthetic session={} status={}", + serde_json::to_string(&sessions).unwrap(), + serde_json::to_string(&store.status().unwrap()).unwrap() + ); + let segment = &sessions[0].segments[0]; + let segment_start = chrono::DateTime::parse_from_rfc3339(&segment.started_at) + .unwrap() + .timestamp(); + let segment_end = chrono::DateTime::parse_from_rfc3339(&segment.ended_at) + .unwrap() + .timestamp(); + assert_eq!( + segment.completeness, + "COMPLETE", + "seconds={} attention={} stop_clock=[{},{}] remaining={}", + segment.duration_seconds, + sessions[0].needs_attention, + earliest_stop_wall, + latest_stop_wall, + capture_failure_diagnostics(&store) + ); + assert!( + !sessions[0].needs_attention, + "completed stop requires review: {}", + capture_failure_diagnostics(&store) + ); + assert_eq!(segment_start, start.wall); + assert!((earliest_stop_wall..=latest_stop_wall).contains(&segment_end)); + assert_eq!(segment.duration_seconds, segment_end - start.wall); + assert!( + (earliest_stop_wall - start.wall..=latest_stop_wall - start.wall) + .contains(&segment.duration_seconds) + ); + assert_eq!(sessions[0].revision, 1); + assert_no_private_content(&capture_dir); +} + +// Read only bounded metadata from this test's synthetic capture directory, +// after an assertion has already failed. A silent guard exit is not proof +// that its core acknowledged or that every owned descendant terminated. +fn capture_failure_diagnostics(store: &Store) -> serde_json::Value { + let status = match store.status() { + Ok(status) => serde_json::json!({ + "storage_paused": status.storage_paused, + "storage_reason": status.storage_reason, + "pending_invocations": status.pending_invocations, + "pending": status.pending, + "held": status.held, + "needs_attention": status.needs_attention, + "unfinished": status.unfinished, + "capture_failure": status.capture_failure, + }), + Err(_) => serde_json::json!({ "state": "unavailable" }), + }; + #[cfg(feature = "dev-tools")] + let failures = match store.developer_failure_summary() { + Ok(summary) => serde_json::json!({ "state": "observed", "summary": summary }), + Err(_) => serde_json::json!({ "state": "unavailable" }), + }; + #[cfg(not(feature = "dev-tools"))] + let failures = serde_json::json!({ "state": "not_enabled" }); + serde_json::json!({ "status": status, "developer_failures": failures, "descendant_finality": "UNPROVED" }) +} + +fn assert_no_private_content(directory: &std::path::Path) { + for entry in std::fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + let metadata = std::fs::symlink_metadata(&path).unwrap(); + assert!(!metadata.file_type().is_symlink(), "fixture tree escaped"); + if metadata.is_dir() { + assert_no_private_content(&path); + } else { + assert!(metadata.is_file()); + let bytes = std::fs::read(path).unwrap(); + assert!(!String::from_utf8_lossy(&bytes).contains("PRIVATE")); + } + } +} + +#[test] +fn sqlite_contention_exposes_lost_boundary_as_storage_pause_in_status() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("repo"); + std::fs::create_dir(&root).unwrap(); + assert!(Command::new("git") + .arg("-C") + .arg(&root) + .arg("init") + .output() + .unwrap() + .status + .success()); + let capture = temp.path().join("capture"); + let _store = Store::open(&capture).unwrap(); + // Hold the independent authority lock as well as real SQLite contention: + // refusal publication must use its nonblocking immutable-marker fallback. + let mut authority=Command::new("python3").args(["-c","import fcntl,sys; f=open(sys.argv[1],'a+'); fcntl.flock(f,fcntl.LOCK_EX); print('locked',flush=True); sys.stdin.read()"]) + .arg(capture.join("capture-authority.lock")).stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + use std::io::BufRead; + let mut ready = String::new(); + std::io::BufReader::new(authority.stdout.take().unwrap()) + .read_line(&mut ready) + .unwrap(); + assert_eq!(ready.trim(), "locked"); + let database = rusqlite::Connection::open(capture.join("capture.sqlite3")).unwrap(); + database.execute_batch("BEGIN IMMEDIATE").unwrap(); + // The core admission+durable marker bound is independent of OS first-launch + // admission before main. The actual CLI path below remains a separate safety + // check; its first-launch timing is retained as qualification evidence. + let mut probe = Store::open(&capture).unwrap(); + let diagnostic_repo = Repository::resolve(&root).unwrap(); + let diagnostic_clock = Clock::now().unwrap(); + let core_start = std::time::Instant::now(); + assert!(probe + .event( + &diagnostic_repo, + Signal { + source: "codex", + resumed: false, + source_id: "core-contention", + turn_id: Some("turn"), + version: "0.167.0", + event: Prompt, + clock: &diagnostic_clock + } + ) + .is_err()); + let event_elapsed = core_start.elapsed(); + #[cfg(feature = "dev-tools")] + let admission = probe.last_admission_timing().unwrap().clone(); + let refusal_start = std::time::Instant::now(); + capture::record_failure( + &capture, + &capture::hash("core-contention"), + "STORAGE_UNAVAILABLE", + ) + .unwrap(); + let refusal_elapsed = refusal_start.elapsed(); + let core_elapsed = core_start.elapsed(); + println!( + "contention timings: event={:.3}ms refusal={:.3}ms total={:.3}ms", + event_elapsed.as_secs_f64() * 1000.0, + refusal_elapsed.as_secs_f64() * 1000.0, + core_elapsed.as_secs_f64() * 1000.0 + ); + #[cfg(feature = "dev-tools")] + { + println!( + "admission phases: permit={:?} sqlite_begin={:?} sqlite_error={:?} authority={:?}", + admission.permit_validation, + admission.sqlite_begin, + admission.sqlite_error, + admission.authority + ); + assert!(admission.permit_validation.is_some()); + assert!(admission.sqlite_begin.is_some()); + assert_eq!( + admission.sqlite_error, + Some(rusqlite::ErrorCode::DatabaseBusy) + ); + assert_eq!( + admission.authority, None, + "authority must not start after failed SQLite admission" + ); + } + assert!( + core_elapsed < std::time::Duration::from_millis(700), + "core admission and marker exceeded watchdog budget: event={event_elapsed:?} refusal={refusal_elapsed:?} total={core_elapsed:?}" + ); + drop(probe); + let start = std::time::Instant::now(); + let mut child = hook(&root, &capture, "prompt") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(serde_json::json!({"cwd":root,"session_id":"session-contention","turn_id":"turn-contention","prompt":"PRIVATE_CANARY"}).to_string().as_bytes()).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success()); + let elapsed = start.elapsed(); + println!( + "combined SQLite/authority refusal completed in {}ms", + elapsed.as_millis() + ); + authority.kill().unwrap(); + authority.wait().unwrap(); + database.execute_batch("ROLLBACK").unwrap(); + let result = Command::new(runtime_pair::pair().core_path) + .current_dir(&root) + .env("KEITO_CAPTURE_HOME", &capture) + .args(["capture", "status", "--json"]) + .output() + .unwrap(); + assert!(result.status.success()); + let status: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); + assert_eq!(status["storage_paused"], true); + assert!(status["capture_failure"]["boundary_id"].as_str().is_some()); + assert!(!String::from_utf8_lossy(&result.stdout).contains("PRIVATE_CANARY")); + assert!(!String::from_utf8_lossy(&output.stderr).contains("held this event")); +} + +#[test] +fn refused_stop_under_real_lock_cannot_be_completed_by_another_hook_process() { + assert_refused_stop(false); +} + +#[test] +fn refused_stop_survives_a_duplicate_that_is_also_refused_before_sqlite_admission() { + assert_refused_stop(true); +} + +fn assert_refused_stop(duplicate_contended: bool) { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("repo"); + std::fs::create_dir(&root).unwrap(); + assert!(Command::new("git") + .arg("-C") + .arg(&root) + .arg("init") + .output() + .unwrap() + .status + .success()); + let repository = Repository::resolve(&root).unwrap(); + let capture = temp.path().join("capture"); + let mut store = Store::open(&capture).unwrap(); + let binding = store + .approve(Binding { + repository_key: repository.key.clone(), + remote_hash: repository.remote_hash.clone(), + hint_hash: repository.hint_hash.clone(), + id: String::new(), + version: 0, + workspace_id: "co_fixture".into(), + owner_id: "usr_fixture".into(), + origin_hash: capture::hash("https://example.invalid"), + project_id: "p_fixture".into(), + task_id: "t_fixture".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }) + .unwrap(); + let mut start = Clock::now().unwrap(); + start.wall -= 90; + start.monotonic -= 90; + store + .event( + &repository, + Signal { + source: "codex", + resumed: false, + source_id: "refused-native", + turn_id: Some("refused-turn"), + version: "0.167.0", + event: Prompt, + clock: &start, + }, + ) + .unwrap(); + let payload=serde_json::json!({"cwd":root,"session_id":"refused-native","turn_id":"refused-turn","prompt":"PRIVATE_CANARY"}).to_string(); + let database = rusqlite::Connection::open(capture.join("capture.sqlite3")).unwrap(); + let invoke_hook = || { + let mut child = hook(&root, &capture, "stop") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(payload.as_bytes()) + .unwrap(); + child.wait_with_output().unwrap() + }; + database.execute_batch("BEGIN IMMEDIATE").unwrap(); + let refused = invoke_hook(); + assert!(refused.status.success()); + assert!(refused.stderr.is_empty(), "installed guard stays silent"); + assert!( + store.status().unwrap().storage_paused, + "refusal must be durable" + ); + if !duplicate_contended { + database.execute_batch("ROLLBACK").unwrap(); + } + let duplicate = invoke_hook(); + assert!(duplicate.status.success()); + if duplicate_contended { + database.execute_batch("ROLLBACK").unwrap(); + } + // Guard success is silent/fail-open, so the duplicate may itself have + // refused before reaching SQLite. Never allow it to manufacture time, + // even temporarily, before the normal transmission gate reconciles it. + let before_claim = store.preview("refused-native").unwrap(); + assert!(before_claim[0] + .segments + .iter() + .all(|segment| segment.completeness != "COMPLETE" || segment.duration_seconds == 0)); + assert!(store.status().unwrap().storage_paused); + assert!( + store + .claim(&binding, chrono::Utc::now().timestamp()) + .unwrap() + .is_none(), + "a retained failed invocation must block transmission" + ); + let session = &store.preview("refused-native").unwrap()[0]; + assert!(session.needs_attention); + assert_eq!(session.segments.len(), 1); + assert_eq!(session.segments[0].duration_seconds, 0); + assert_eq!(session.segments[0].completeness, "INCOMPLETE"); + assert!(store.status().unwrap().storage_paused); + store.recover(&Clock::now().unwrap()).unwrap_or_else(|error| { + panic!( + "explicit recovery refused after directly waiting both guards: error={error}; duplicate_contended={duplicate_contended}; remaining={}", + capture_failure_diagnostics(&store) + ) + }); + let queued = store + .claim(&binding, chrono::Utc::now().timestamp()) + .unwrap() + .unwrap(); + let body: serde_json::Value = serde_json::from_str(&queued.body).unwrap(); + assert_eq!(body["segments"][0]["duration_seconds"], 0); + assert_eq!(body["segments"][0]["completeness"], "INCOMPLETE"); + assert!(!queued.body.contains("PRIVATE_CANARY")); +} + +#[test] +fn authority_lock_contention_never_blocks_refusal_publication_and_kill_releases_lock() { + use std::io::BufRead; + let temp = tempfile::tempdir().unwrap(); + let directory = temp.path().join("capture"); + let mut store = Store::open(&directory).unwrap(); + let mut child=Command::new("python3").args(["-c","import fcntl,sys; f=open(sys.argv[1],'a+'); fcntl.flock(f,fcntl.LOCK_EX); print('locked',flush=True); sys.stdin.read()"]) + .arg(directory.join("capture-authority.lock")).stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + let mut ready = String::new(); + std::io::BufReader::new(child.stdout.take().unwrap()) + .read_line(&mut ready) + .unwrap(); + assert_eq!(ready.trim(), "locked"); + let start = std::time::Instant::now(); + capture::record_failure( + &directory, + &capture::hash("refused-with-authority-held"), + "STORAGE_UNAVAILABLE", + ) + .unwrap(); + assert!( + start.elapsed() < std::time::Duration::from_millis(100), + "refusal publication added an authority wait" + ); + let clock = Clock::now().unwrap(); + assert!(store.recover(&clock).is_err()); + assert!(store.status().unwrap().storage_paused); + child.kill().unwrap(); + child.wait().unwrap(); + store.recover(&clock).unwrap(); + assert!(!store.status().unwrap().storage_paused); +} + +#[test] +fn distinct_refusals_are_immutable_and_recovery_cannot_confuse_replayed_boundary_ids() { + let temp = tempfile::tempdir().unwrap(); + let mut store = Store::open(temp.path()).unwrap(); + let boundary = capture::hash("same-boundary"); + for _ in 0..4 { + capture::record_failure(temp.path(), &boundary, "BOUNDARY_REFUSED").unwrap(); + } + let count = std::fs::read_dir(temp.path()) + .unwrap() + .filter_map(Result::ok) + .filter(|entry| { + entry + .file_name() + .to_string_lossy() + .starts_with("capture-refusal-") + }) + .count(); + assert_eq!(count, 4); + store.recover(&Clock::now().unwrap()).unwrap(); + assert!(!store.status().unwrap().storage_paused); +} diff --git a/tests/capture_store.rs b/tests/capture_store.rs new file mode 100644 index 0000000..d408c6a --- /dev/null +++ b/tests/capture_store.rs @@ -0,0 +1,1388 @@ +use keito_cli::capture::{self, Repository}; +#[cfg(unix)] +use keito_cli::capture::{Binding, Clock, Store}; +#[cfg(unix)] +use keito_cli::cli::capture::CaptureEvent::*; +#[cfg(unix)] +use std::path::Path; + +#[cfg(unix)] +fn clock(s: i64) -> Clock { + Clock { + wall: 1_794_067_200 + s, + monotonic: 100_000 + s, + boot: "fixture-boot".into(), + } +} +#[cfg(unix)] +fn repo() -> Repository { + Repository { + key: capture::hash("fixture-repo"), + remote_hash: capture::hash("fixture-remote"), + linked_without_hint: false, + hint_hash: capture::hash("fixture-config"), + disabled: false, + } +} +#[cfg(unix)] +fn binding() -> Binding { + Binding { + repository_key: repo().key, + remote_hash: repo().remote_hash, + hint_hash: repo().hint_hash, + id: String::new(), + version: 0, + workspace_id: "co_fixture".into(), + owner_id: "user_fixture".into(), + origin_hash: capture::hash("http://fixture"), + project_id: "project_fixture".into(), + task_id: "task_fixture".into(), + agents: vec!["codex".into(), "claude-code".into()], + paused: false, + revoked: false, + } +} +#[cfg(unix)] +fn setup() -> (tempfile::TempDir, Store, Binding) { + let dir = tempfile::tempdir().unwrap(); + let mut store = Store::open(&dir.path().join("capture")).unwrap(); + let b = store.approve(binding()).unwrap(); + (dir, store, b) +} +#[cfg(unix)] +fn event( + store: &mut Store, + session: &str, + turn: Option<&str>, + event: keito_cli::cli::capture::CaptureEvent, + s: i64, +) { + let result = store.event( + &repo(), + capture::Signal { + source: "codex", + resumed: false, + source_id: session, + turn_id: turn, + version: "fixture-v1", + event, + clock: &clock(s), + }, + ); + if let Err(error) = result { + #[cfg(feature = "dev-tools")] + panic!( + "capture fixture event failed: {error:?}; admission={:?}", + store.last_admission_timing() + ); + #[cfg(not(feature = "dev-tools"))] + panic!("capture fixture event failed: {error:?}"); + } +} +#[cfg(unix)] +fn body(store: &mut Store, b: &Binding, s: i64) -> (capture::Queued, serde_json::Value) { + let queued = store.claim(b, clock(s).wall).unwrap().unwrap(); + let body = serde_json::from_str(&queued.body).unwrap(); + (queued, body) +} + +#[cfg(unix)] +#[test] +fn three_turns_short_first_idle_and_resume_preserve_exact_seconds() { + let (_dir, mut store, b) = setup(); + event(&mut store, "session", None, SessionStart, 0); + event(&mut store, "session", Some("turn-1"), Prompt, 0); + event(&mut store, "session", Some("turn-1"), Stop, 1); + event(&mut store, "session", None, SessionStart, 100); + event(&mut store, "session", Some("turn-2"), Prompt, 100); + event(&mut store, "session", Some("turn-2"), Stop, 159); + event(&mut store, "session", Some("turn-3"), Prompt, 500); + event(&mut store, "session", Some("turn-3"), Stop, 590); + let session = store.preview("session").unwrap().remove(0); + assert_eq!( + session + .segments + .iter() + .map(|s| s.duration_seconds) + .collect::>(), + vec![1, 59, 90] + ); + assert_eq!(session.revision, 3); + let (q, payload) = body(&mut store, &b, 600); + assert_eq!(payload["segments"][0]["duration_seconds"], 1); + assert_eq!(payload["expected_revision"], 0); + assert!(!q.body.contains("PRIVATE")); + assert!(payload.get("owner_id").is_none()); + assert!(payload.get("billable").is_none()); +} + +#[cfg(unix)] +#[test] +fn frozen_failure_retries_do_not_count_upload_wait_and_preserve_identity() { + let (_dir, mut store, b) = setup(); + event(&mut store, "session", Some("turn"), Prompt, 0); + event(&mut store, "session", Some("turn"), Stop, 90); + let (q, first) = body(&mut store, &b, 91); + store + .finish(&q, "pending", "NETWORK_UNAVAILABLE", clock(91).wall, None) + .unwrap(); + let (retry, second) = body(&mut store, &b, 391); + assert_eq!(q.body, retry.body); + assert_eq!(q.hash, retry.hash); + assert_eq!(first, second); + assert_eq!(second["segments"][0]["duration_seconds"], 90); +} + +#[cfg(unix)] +#[test] +fn missing_or_wrong_session_never_uses_latest_directory_state() { + let (_dir, mut store, _) = setup(); + event(&mut store, "session-b", Some("turn-b"), Prompt, 0); + event(&mut store, "session-a", Some("turn-a"), Stop, 100); + assert!(store.preview("session-a").unwrap().is_empty()); + event(&mut store, "session-b", Some("turn-b"), Stop, 59); + assert_eq!( + store.preview("session-b").unwrap()[0].segments[0].duration_seconds, + 59 + ); +} + +#[cfg(unix)] +#[test] +fn duplicate_boundaries_are_idempotent_and_out_of_order_stop_cannot_close_new_turn() { + let (_dir, mut store, _) = setup(); + for _ in 0..3 { + event(&mut store, "session", Some("turn-1"), Prompt, 0); + } + event(&mut store, "session", Some("turn-1"), Stop, 60); + event(&mut store, "session", Some("turn-1"), Prompt, 61); + event(&mut store, "session", Some("turn-2"), Prompt, 100); + event(&mut store, "session", Some("turn-1"), Stop, 110); + event(&mut store, "session", Some("turn-2"), Stop, 190); + for _ in 0..3 { + event(&mut store, "session", Some("turn-2"), Stop, 191); + } + let s = &store.preview("session").unwrap()[0]; + assert_eq!(s.segments.len(), 2); + assert_eq!( + s.segments.iter().map(|s| s.duration_seconds).sum::(), + 150 + ); + assert_eq!(s.revision, 2); +} + +#[cfg(unix)] +#[test] +fn pause_excludes_interval_and_does_not_reset_earned_time() { + let (_dir, mut store, _) = setup(); + event(&mut store, "session", Some("turn"), Prompt, 0); + store.control(&repo(), "pause", &clock(30)).unwrap(); + store.control(&repo(), "resume", &clock(130)).unwrap(); + event(&mut store, "session", Some("turn"), Stop, 175); + let s = &store.preview("session").unwrap()[0]; + assert_eq!( + s.segments.iter().map(|s| s.duration_seconds).sum::(), + 75 + ); + assert_eq!(s.segments.len(), 2); +} + +#[cfg(unix)] +#[test] +fn interrupt_missing_stop_and_reboot_never_invent_complete_time() { + let (_dir, mut store, _) = setup(); + event(&mut store, "session", Some("turn-1"), Prompt, 0); + event(&mut store, "session", Some("turn-2"), Prompt, 300); + event(&mut store, "session", Some("turn-2"), Interrupt, 400); + event(&mut store, "session", Some("turn-3"), Prompt, 500); + let mut reboot = clock(590); + reboot.boot = "other-boot".into(); + store + .event( + &repo(), + capture::Signal { + source: "codex", + resumed: false, + source_id: "session", + turn_id: Some("turn-3"), + version: "fixture-v1", + event: Stop, + clock: &reboot, + }, + ) + .unwrap(); + event(&mut store, "session", None, SessionEnd, 600); + let s = &store.preview("session").unwrap()[0]; + assert!(s.needs_attention); + assert_eq!( + s.segments.iter().map(|s| s.duration_seconds).sum::(), + 0 + ); + assert!(s.segments.iter().all(|s| s.completeness == "INCOMPLETE")); +} + +#[cfg(unix)] +#[test] +fn backward_clock_and_implausible_intervals_are_incomplete() { + for end in [-1, 100_000] { + let (_dir, mut store, _) = setup(); + event(&mut store, "session", Some("turn"), Prompt, 0); + event(&mut store, "session", Some("turn"), Stop, end); + let s = &store.preview("session").unwrap()[0]; + assert!(s.needs_attention); + assert_eq!(s.segments[0].duration_seconds, 0); + } +} + +#[cfg(unix)] +#[test] +fn no_native_turn_identity_is_a_refusal_not_fabricated_elapsed_time() { + let (_dir, mut store, _) = setup(); + assert!(store + .event( + &repo(), + capture::Signal { + source: "claude-code", + resumed: false, + source_id: "session", + turn_id: None, + version: "fixture-v1", + event: Prompt, + clock: &clock(0) + } + ) + .is_err()); + assert!(store.preview("session").unwrap().is_empty()); +} + +#[cfg(unix)] +#[test] +fn changed_mapping_or_revoked_consent_holds_new_collection_and_pending_delivery() { + let (_dir, mut store, b) = setup(); + event(&mut store, "session", Some("turn"), Prompt, 0); + event(&mut store, "session", Some("turn"), Stop, 60); + let mut changed = repo(); + changed.hint_hash = capture::hash("other-config"); + store + .event( + &changed, + capture::Signal { + source: "codex", + resumed: false, + source_id: "new-session", + turn_id: Some("turn"), + version: "fixture-v1", + event: Prompt, + clock: &clock(70), + }, + ) + .unwrap(); + assert!(store.preview("new-session").unwrap().is_empty()); + store.control(&repo(), "disable", &clock(70)).unwrap(); + assert!(store.claim(&b, clock(71).wall).unwrap().is_none()); + assert!(store.control(&repo(), "resume", &clock(72)).is_err()); + assert_eq!(store.status().unwrap().pending, 0); + assert_eq!(store.status().unwrap().held, 1); +} + +#[cfg(unix)] +#[test] +fn next_revision_is_not_claimed_until_previous_acknowledgement() { + let (_dir, mut store, b) = setup(); + for n in 0..2 { + let turn = format!("turn-{n}"); + event(&mut store, "session", Some(&turn), Prompt, n * 100); + event(&mut store, "session", Some(&turn), Stop, n * 100 + 90); + } + let (q, p) = body(&mut store, &b, 300); + assert_eq!(p["revision"], 1); + assert!(store.claim(&b, clock(301).wall).unwrap().is_none()); + store + .finish(&q, "acknowledged", "ACCEPTED", clock(301).wall, None) + .unwrap(); + let (_, p) = body(&mut store, &b, 302); + assert_eq!(p["revision"], 2); + assert_eq!(p["expected_revision"], 1); +} + +#[cfg(unix)] +fn join_all_before_asserting( + handles: Vec>, +) -> Vec> { + handles.into_iter().map(|handle| handle.join()).collect() +} + +#[cfg(unix)] +#[test] +fn worker_join_collection_retains_later_outcomes_after_a_failure() { + let handles = vec![ + std::thread::spawn(|| -> u8 { panic!("controlled join failure") }), + std::thread::spawn(|| 17_u8), + ]; + let outcomes = join_all_before_asserting(handles); + assert_eq!(outcomes.len(), 2); + assert!(outcomes[0].is_err()); + assert_eq!(outcomes[1].as_ref().unwrap(), &17_u8); +} + +#[cfg(unix)] +#[test] +fn sqlite_connections_serialize_duplicate_hooks_into_one_revision() { + let (dir, mut store, b) = setup(); + event(&mut store, "session", Some("turn"), Prompt, 0); + let dir = dir.path().join("capture"); + let origin = std::time::Instant::now(); + let handles: Vec<_> = (0..20) + .map(|_| { + let path = dir.clone(); + std::thread::spawn(move || { + let open_started = std::time::Instant::now(); + let open_at = open_started.duration_since(origin); + let opened = Store::open(&path); + let open_elapsed = open_started.elapsed(); + let mut store = match opened { + Ok(store) => store, + Err(error) => { + return Err(format!("open_at={open_at:?}; open={open_elapsed:?}; open_error={error:?}")); + } + }; + let event_started = std::time::Instant::now(); + let event_at = event_started.duration_since(origin); + let result = store.event( + &repo(), + capture::Signal { + source: "codex", + resumed: false, + source_id: "session", + turn_id: Some("turn"), + version: "fixture-v1", + event: Stop, + clock: &clock(90), + }, + ); + let event_elapsed = event_started.elapsed(); + #[cfg(feature = "dev-tools")] + let receipt = format!( + "open_at={open_at:?}; open={open_elapsed:?}; event_at={event_at:?}; event={event_elapsed:?}; admission={:?}", + store.last_admission_timing() + ); + #[cfg(not(feature = "dev-tools"))] + let receipt = format!("open_at={open_at:?}; open={open_elapsed:?}; event_at={event_at:?}; event={event_elapsed:?}"); + match result { + Ok(()) => Ok(receipt), + Err(error) => Err(format!("{receipt}; event_error={error:?}")), + } + }) + }) + .collect(); + // Retain the TempDir until every original worker has settled, even if + // an earlier worker panicked. Keep the original all-success assertion. + let outcomes = join_all_before_asserting(handles); + // Emit every successful and failed holder receipt before any assertion. + // No worker failure can hide later outcomes or drop the original TempDir. + for (worker, outcome) in outcomes.iter().enumerate() { + println!("sqlite_duplicate_worker={worker}; outcome={outcome:?}"); + } + for outcome in outcomes { + outcome.unwrap().unwrap(); + } + let s = &store.preview("session").unwrap()[0]; + assert_eq!(s.segments.len(), 1); + assert_eq!(s.revision, 1); + let (_, p) = body(&mut store, &b, 200); + assert_eq!(p["segments"][0]["duration_seconds"], 90); +} + +#[cfg(unix)] +#[cfg(unix)] +#[test] +fn queue_has_private_modes_and_rejects_symlinks() { + use std::os::unix::fs::{symlink, PermissionsExt}; + let (dir, _store, _) = setup(); + let path = dir.path().join("capture"); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o700 + ); + assert_eq!( + std::fs::metadata(path.join("capture.sqlite3")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + let link = dir.path().join("link"); + symlink(&path, &link).unwrap(); + assert!(Store::open(&link).is_err()); +} + +#[test] +fn credential_and_path_identifiers_reject_without_echo() { + for value in [ + "/Users/private", + "../secrets", + "kto_SECRET_CANARY", + "sk-secret", + "ghp_SECRET_CANARY", + "AKIASECRETCANARY", + ] { + let error = capture::identifier(value).unwrap_err().to_string(); + assert!(!error.contains(value)); + } +} + +#[cfg(unix)] +fn git(path: &Path, args: &[&str]) { + assert!(std::process::Command::new("git") + .arg("-C") + .arg(path) + .args(args) + .output() + .unwrap() + .status + .success()) +} +#[cfg(unix)] +#[test] +fn linked_worktrees_share_identity_but_nested_repositories_and_changed_remotes_do_not() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("repo"); + std::fs::create_dir(&root).unwrap(); + git(&root, &["init"]); + git( + &root, + &[ + "-c", + "user.email=fixture@example.invalid", + "-c", + "user.name=Fixture", + "commit", + "--allow-empty", + "-m", + "fixture", + ], + ); + let linked = temp.path().join("linked"); + git( + &root, + &["worktree", "add", "--detach", linked.to_str().unwrap()], + ); + let original = Repository::resolve(&root).unwrap(); + assert_eq!(original.key, Repository::resolve(&linked).unwrap().key); + let sub = root.join("sub"); + std::fs::create_dir(&sub).unwrap(); + assert_eq!(original.key, Repository::resolve(&sub).unwrap().key); + git(&sub, &["init"]); + assert_ne!(original.key, Repository::resolve(&sub).unwrap().key); + git( + &root, + &[ + "remote", + "add", + "origin", + "https://credential:SECRET_CANARY@example.invalid/repo", + ], + ); + let changed = Repository::resolve(&root).unwrap(); + assert_eq!(original.key, changed.key); + assert_ne!(original.remote_hash, changed.remote_hash); + assert!(!changed.key.contains("SECRET")); +} + +#[cfg(unix)] +#[test] +fn repeated_resume_does_not_reset_an_active_interval() { + let (_dir, mut store, _) = setup(); + event(&mut store, "session", Some("turn"), Prompt, 0); + store.control(&repo(), "resume", &clock(30)).unwrap(); + store.control(&repo(), "resume", &clock(45)).unwrap(); + event(&mut store, "session", Some("turn"), Stop, 90); + assert_eq!( + store.preview("session").unwrap()[0].segments[0].duration_seconds, + 90 + ); +} +#[cfg(unix)] +#[test] +fn repeated_setup_preserves_approval_identity_and_pause() { + let (_dir, mut store, b) = setup(); + store.control(&repo(), "pause", &clock(0)).unwrap(); + let same = store.approve(binding()).unwrap(); + assert_eq!(same.id, b.id); + assert_eq!(same.version, b.version); + assert!(same.paused); +} +#[cfg(unix)] +#[test] +fn old_completed_prompt_replay_cannot_close_or_duplicate_a_newer_turn() { + let (_dir, mut store, _) = setup(); + for n in 1..=2 { + let id = format!("turn-{n}"); + event(&mut store, "session", Some(&id), Prompt, n * 100); + event(&mut store, "session", Some(&id), Stop, n * 100 + 90); + } + event(&mut store, "session", Some("turn-3"), Prompt, 300); + event(&mut store, "session", Some("turn-1"), Prompt, 310); + event(&mut store, "session", Some("turn-3"), Stop, 390); + assert_eq!( + store.preview("session").unwrap()[0] + .segments + .iter() + .map(|s| s.duration_seconds) + .sum::(), + 270 + ); +} + +#[cfg(unix)] +#[test] +fn resumed_harness_keeps_completed_turns_and_marks_the_abandoned_interval_incomplete() { + let (_dir, mut store, _) = setup(); + event(&mut store, "session", Some("first"), Prompt, 0); + event(&mut store, "session", Some("first"), Stop, 90); + event(&mut store, "session", Some("abandoned"), Prompt, 100); + store + .event( + &repo(), + capture::Signal { + source: "codex", + resumed: true, + source_id: "session", + turn_id: None, + version: "0.167.0", + event: SessionStart, + clock: &clock(1000), + }, + ) + .unwrap(); + let s = &store.preview("session").unwrap()[0]; + assert_eq!(s.segments.len(), 2); + assert_eq!(s.segments[0].duration_seconds, 90); + assert_eq!(s.segments[1].duration_seconds, 0); + assert_eq!(s.segments[1].completeness, "INCOMPLETE"); + assert!(s.needs_attention); +} + +#[cfg(unix)] +#[test] +fn stopped_while_paused_never_reopens_or_counts_idle_after_resume() { + let (_dir, mut store, _) = setup(); + event(&mut store, "paused-end", Some("turn"), Prompt, 0); + store.control(&repo(), "pause", &clock(30)).unwrap(); + event(&mut store, "paused-end", Some("turn"), Stop, 60); + store.control(&repo(), "resume", &clock(100)).unwrap(); + event(&mut store, "paused-end", Some("turn"), Stop, 150); + assert_eq!( + store.preview("paused-end").unwrap()[0] + .segments + .iter() + .map(|s| s.duration_seconds) + .sum::(), + 30 + ); + assert_eq!(store.status().unwrap().unfinished, 0); + assert_eq!(store.status().unwrap().pending, 1); +} +#[cfg(unix)] +#[test] +fn adding_harness_preserves_native_session_revision_and_identical_reenable_keeps_identity() { + let temp = tempfile::tempdir().unwrap(); + let mut store = Store::open(&temp.path().join("capture")).unwrap(); + let mut b = binding(); + b.agents = vec!["codex".into()]; + let first = store.approve(b).unwrap(); + event(&mut store, "native", Some("first"), Prompt, 0); + event(&mut store, "native", Some("first"), Stop, 60); + let (q, _) = body(&mut store, &first, 61); + store + .finish(&q, "acknowledged", "ACCEPTED", clock(61).wall, None) + .unwrap(); + let second = store.approve(binding()).unwrap(); + event(&mut store, "native", Some("second"), Prompt, 100); + event(&mut store, "native", Some("second"), Stop, 160); + let (_, p) = body(&mut store, &second, 161); + assert_eq!(p["revision"], 2); + store.control(&repo(), "disable", &clock(170)).unwrap(); + let renewed = store.approve(binding()).unwrap(); + assert_eq!(renewed.id, second.id); +} +#[cfg(unix)] +#[test] +fn absent_linked_hint_inherits_approval_but_explicit_conflict_is_held() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("main"); + std::fs::create_dir(&root).unwrap(); + git(&root, &["init"]); + git( + &root, + &[ + "-c", + "user.email=fixture@example.invalid", + "-c", + "user.name=Fixture", + "commit", + "--allow-empty", + "-m", + "fixture", + ], + ); + std::fs::create_dir(root.join(".keito")).unwrap(); + std::fs::write( + root.join(".keito/config.yml"), + "project_id: p_fixture\ntask_id: t_fixture\nagent_tracking:\n enabled: true\n", + ) + .unwrap(); + let linked = temp.path().join("linked"); + git( + &root, + &["worktree", "add", "--detach", linked.to_str().unwrap()], + ); + let main = Repository::resolve(&root).unwrap(); + let worktree = Repository::resolve(&linked).unwrap(); + let mut b = binding(); + b.repository_key = main.key.clone(); + b.remote_hash = main.remote_hash.clone(); + b.hint_hash = main.hint_hash.clone(); + let mut store = Store::open(&temp.path().join("capture")).unwrap(); + store.approve(b).unwrap(); + for (kind, s) in [(Prompt, 0), (Stop, 90)] { + store + .event( + &worktree, + capture::Signal { + source: "codex", + resumed: false, + source_id: "linked-session", + turn_id: Some("turn"), + version: "0.167.0", + event: kind, + clock: &clock(s), + }, + ) + .unwrap(); + } + assert_eq!( + store.preview("linked-session").unwrap()[0].segments[0].duration_seconds, + 90 + ); + std::fs::create_dir(linked.join(".keito")).unwrap(); + std::fs::write(linked.join(".keito/config.yml"), "project_id: other\n").unwrap(); + let conflict = Repository::resolve(&linked).unwrap(); + store + .event( + &conflict, + capture::Signal { + source: "codex", + resumed: false, + source_id: "wrong-session", + turn_id: Some("turn"), + version: "0.167.0", + event: Prompt, + clock: &clock(100), + }, + ) + .unwrap(); + assert!(store.preview("wrong-session").unwrap().is_empty()); +} +#[cfg(unix)] +#[test] +fn remote_changes_do_not_change_operational_repository_family_identity() { + let temp = tempfile::tempdir().unwrap(); + git(temp.path(), &["init"]); + let before = Repository::resolve(temp.path()).unwrap(); + git( + temp.path(), + &["remote", "add", "origin", "https://example.invalid/other"], + ); + let after = Repository::resolve(temp.path()).unwrap(); + assert_eq!(before.key, after.key); +} + +#[cfg(unix)] +#[test] +fn remapping_a_native_session_is_held_instead_of_starting_revision_one_again() { + let (_dir, mut store, first) = setup(); + event(&mut store, "native-remap", Some("first"), Prompt, 0); + event(&mut store, "native-remap", Some("first"), Stop, 60); + let mut changed = binding(); + changed.project_id = "other_project".into(); + let next = store.approve(changed).unwrap(); + assert_ne!(first.id, next.id); + assert!(store + .event( + &repo(), + capture::Signal { + source: "codex", + resumed: false, + source_id: "native-remap", + turn_id: Some("second"), + version: "fixture-v1", + event: Prompt, + clock: &clock(100) + } + ) + .is_err()); + let sessions = store.preview("native-remap").unwrap(); + assert_eq!(sessions.len(), 1); + assert_eq!(sessions[0].revision, 1); + assert!(sessions[0].needs_attention); + assert_eq!(store.status().unwrap().held, 1); + assert_eq!( + store.status().unwrap().queue[0].reason.as_deref(), + Some("MAPPING_CHANGED_REVIEW_REQUIRED") + ); +} +#[cfg(unix)] +#[test] +fn all_terminal_events_during_pause_reconcile_without_reopening_the_turn() { + for terminal in [Interrupt, SessionEnd] { + let (_dir, mut store, _) = setup(); + event(&mut store, "pause-final", Some("turn"), Prompt, 0); + store.control(&repo(), "pause", &clock(30)).unwrap(); + event(&mut store, "pause-final", Some("turn"), terminal, 60); + store.control(&repo(), "resume", &clock(100)).unwrap(); + event(&mut store, "pause-final", Some("turn"), Stop, 150); + let s = &store.preview("pause-final").unwrap()[0]; + assert_eq!( + s.segments.iter().map(|s| s.duration_seconds).sum::(), + 30 + ); + assert!(s.needs_attention); + assert_eq!(store.status().unwrap().unfinished, 0); + } +} + +#[cfg(unix)] +#[test] +fn storage_failure_requires_explicit_recovery_and_never_reconstructs_missing_seconds() { + let (dir, mut store, _) = setup(); + event(&mut store, "unfinished", Some("turn"), Prompt, 0); + capture::record_failure( + &dir.path().join("capture"), + &capture::hash("refused-boundary"), + "STORAGE_UNAVAILABLE", + ) + .unwrap(); + let status = store.status().unwrap(); + assert!(status.storage_paused); + assert_eq!( + status.capture_failure.unwrap().reason, + "STORAGE_UNAVAILABLE" + ); + assert!(store + .event( + &repo(), + capture::Signal { + source: "codex", + resumed: false, + source_id: "new", + turn_id: Some("new"), + version: "fixture-v1", + event: Prompt, + clock: &clock(10) + } + ) + .is_err()); + store.recover(&clock(1000)).unwrap(); + assert!(!store.status().unwrap().storage_paused); + let s = &store.preview("unfinished").unwrap()[0]; + assert_eq!(s.segments[0].duration_seconds, 0); + assert_eq!(s.segments[0].completeness, "INCOMPLETE"); + assert!(s.needs_attention); +} +#[cfg(unix)] +#[test] +fn queue_ceiling_reports_paused_reason_without_evicting_existing_evidence() { + let (dir, mut store, b) = setup(); + event(&mut store, "existing", Some("turn"), Prompt, 0); + event(&mut store, "existing", Some("turn"), Stop, 90); + let (q, _) = body(&mut store, &b, 91); + let database = rusqlite::Connection::open(dir.path().join("capture/capture.sqlite3")).unwrap(); + database + .execute("CREATE TABLE synthetic_full_queue (bytes BLOB)", []) + .unwrap(); + database + .execute( + "INSERT INTO synthetic_full_queue VALUES(zeroblob(104780000))", + [], + ) + .unwrap(); + let status = store.status().unwrap(); + assert!(status.storage_paused); + assert_eq!( + status.storage_reason.as_deref(), + Some("QUEUE_LIMIT_REACHED") + ); + assert_eq!(status.pending, 1); + assert!(store + .event( + &repo(), + capture::Signal { + source: "codex", + resumed: false, + source_id: "blocked", + turn_id: Some("turn"), + version: "fixture-v1", + event: Prompt, + clock: &clock(100) + } + ) + .is_err()); + let body: String = database + .query_row("SELECT body FROM outbox WHERE id=?1", [q.id], |r| r.get(0)) + .unwrap(); + assert_eq!(body, q.body); +} + +#[cfg(unix)] +#[test] +fn typed_acknowledgement_retires_only_expired_acknowledged_payloads() { + let (_dir, mut store, b) = setup(); + for n in 0..2 { + let id = format!("turn-{n}"); + event(&mut store, "retention", Some(&id), Prompt, n * 100); + event(&mut store, "retention", Some(&id), Stop, n * 100 + 90); + } + let (q, _) = body(&mut store, &b, 300); + store + .acknowledge(&q, "canonical-retention", clock(300).wall - 8 * 24 * 3600) + .unwrap(); + let (next, _) = body(&mut store, &b, 301); + store + .acknowledge(&next, "canonical-retention", clock(301).wall) + .unwrap(); + // Domain revision/session state remains, but an old local transport receipt is disposable. + let state = store.preview("retention").unwrap(); + assert_eq!(state[0].revision, 2); + assert_eq!( + state[0].canonical_server_id.as_deref(), + Some("canonical-retention") + ); + let dbpath = _dir.path().join("capture/capture.sqlite3"); + let db = rusqlite::Connection::open(dbpath).unwrap(); + let old: i64 = db + .query_row("SELECT COUNT(*) FROM outbox WHERE id=?1", [q.id], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(old, 0); +} + +#[cfg(unix)] +#[test] +fn legacy_yaml_and_json_mapping_hints_have_the_same_minimized_identity() { + let temp = tempfile::tempdir().unwrap(); + git(temp.path(), &["init"]); + std::fs::create_dir(temp.path().join(".keito")).unwrap(); + let file = temp.path().join(".keito/config.yml"); + std::fs::write(&file,"workspace_id: co_fixture\nproject_id: p_fixture\ntask_id: t_fixture\nagent_tracking:\n enabled: true\n privacy: metadata-only\nmetadata:\n ignored: PRIVATE_CANARY\n").unwrap(); + let yaml = Repository::resolve(temp.path()).unwrap(); + std::fs::write(&file,r#"{"workspace_id":"co_fixture","project_id":"p_fixture","task_id":"t_fixture","agent_tracking":{"enabled":true,"privacy":"metadata-only"},"metadata":{"ignored":"OTHER_IGNORED_CANARY"}}"#).unwrap(); + let json = Repository::resolve(temp.path()).unwrap(); + assert_eq!(yaml.hint_hash, json.hint_hash); +} +#[cfg(unix)] +#[test] +fn mapping_parser_refuses_deep_resource_amplification_without_echo() { + let temp = tempfile::tempdir().unwrap(); + git(temp.path(), &["init"]); + std::fs::create_dir(temp.path().join(".keito")).unwrap(); + let file = temp.path().join(".keito/config.yml"); + let body = format!( + "project_id: p_fixture\nmetadata:\n deep: {}PRIVATE_CANARY{}\n", + "[".repeat(32), + "]".repeat(32) + ); + std::fs::write(&file, body).unwrap(); + let error = Repository::resolve(temp.path()).unwrap_err().to_string(); + assert!(!error.contains("PRIVATE_CANARY")); +} +#[cfg(unix)] +#[test] +fn malformed_and_duplicate_mapping_keys_are_refused_without_source_excerpt() { + let temp = tempfile::tempdir().unwrap(); + git(temp.path(), &["init"]); + std::fs::create_dir(temp.path().join(".keito")).unwrap(); + let file = temp.path().join(".keito/config.yml"); + for body in [ + "project_id: p_fixture\nproject_id: another_project\n", + "project_id: [PRIVATE_CANARY\n", + ] { + std::fs::write(&file, body).unwrap(); + let error = Repository::resolve(temp.path()).unwrap_err().to_string(); + assert!(!error.contains("PRIVATE_CANARY")); + } +} + +#[cfg(unix)] +#[test] +fn global_revoke_and_reenable_cannot_resurrect_an_active_turn() { + let (_dir, mut store, _) = setup(); + event(&mut store, "revoked-live", Some("turn"), Prompt, 0); + store.disable_all().unwrap(); + event(&mut store, "revoked-live", Some("turn"), Stop, 60); + store.approve(binding()).unwrap(); + event(&mut store, "revoked-live", Some("turn"), Stop, 150); + let s = &store.preview("revoked-live").unwrap()[0]; + assert_eq!( + s.segments.iter().map(|s| s.duration_seconds).sum::(), + 0 + ); + assert!(s.needs_attention); + assert_eq!(store.status().unwrap().unfinished, 0); +} +#[cfg(unix)] +#[test] +fn removed_harness_and_reapproval_cannot_count_the_unapproved_interval() { + let (_dir, mut store, _) = setup(); + event(&mut store, "removed-live", Some("turn"), Prompt, 0); + let mut remaining = binding(); + remaining.agents = vec!["claude-code".into()]; + store.approve(remaining).unwrap(); + event(&mut store, "removed-live", Some("turn"), Stop, 60); + store.approve(binding()).unwrap(); + event(&mut store, "removed-live", Some("turn"), Stop, 150); + let s = &store.preview("removed-live").unwrap()[0]; + assert_eq!( + s.segments.iter().map(|s| s.duration_seconds).sum::(), + 0 + ); + assert!(s.needs_attention); +} +#[cfg(unix)] +#[test] +fn abandoned_preparation_refusal_holds_completed_stop_and_survives_marker_removal() { + use std::os::{ + fd::AsRawFd, + unix::fs::{OpenOptionsExt, PermissionsExt}, + }; + let (dir, mut store, binding) = setup(); + event( + &mut store, + "completed-before-preparation", + Some("turn"), + Prompt, + 0, + ); + event( + &mut store, + "completed-before-preparation", + Some("turn"), + Stop, + 30, + ); + let (frozen, _) = body(&mut store, &binding, 31); + let root = dir.path().join("capture"); + let flags = root.join("capture-invocations"); + std::fs::create_dir_all(&flags).unwrap(); + std::fs::set_permissions(&flags, std::fs::Permissions::from_mode(0o700)).unwrap(); + let nonce = capture::hash("visible-abandoned-preparation"); + let path = flags.join(format!("{nonce}.preparing")); + let mut marker = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&path) + .unwrap(); + // No live owner: this must be a genuine immutable refusal even though an + // identical Stop has already committed COMPLETE evidence. + store.maintain(clock(32).wall).unwrap(); + let failure = store.status().unwrap().capture_failure.unwrap(); + assert_eq!(failure.reason, "BOUNDARY_REFUSED"); + assert_eq!( + failure.boundary_id, + capture::hash(format!("INVOCATION\0{nonce}")) + ); + // A later lock or disappearance cannot rehabilitate a classified refusal. + assert_eq!( + unsafe { libc::flock(marker.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + use std::io::Write; + marker.write_all(b"KEITO_CAPTURE_PENDING_V1\n").unwrap(); + marker.sync_all().unwrap(); + std::fs::remove_file(&path).unwrap(); + drop(marker); + let status = store.status().unwrap(); + assert_eq!(status.pending_invocations, 0); + assert!(status.storage_paused); + assert_eq!(status.held, 1); + let session = store + .preview("completed-before-preparation") + .unwrap() + .remove(0); + assert_eq!(session.revision, 1); + assert_eq!(session.segments.len(), 1); + assert_eq!(session.segments[0].completeness, "COMPLETE"); + assert!(session.needs_attention); + let db = rusqlite::Connection::open(root.join("capture.sqlite3")).unwrap(); + let retained: String = db + .query_row("SELECT body FROM outbox WHERE id=?1", [frozen.id], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(retained, frozen.body); + assert!(store.claim(&binding, clock(34).wall).unwrap().is_none()); +} + +#[cfg(unix)] +#[test] +fn refused_stop_cannot_be_replaced_by_the_time_of_a_later_duplicate_stop() { + let (dir, mut store, _) = setup(); + event(&mut store, "refused-stop", Some("turn"), Prompt, 0); + capture::record_failure( + &dir.path().join("capture"), + &capture::hash("refused-stop"), + "STORAGE_UNAVAILABLE", + ) + .unwrap(); + event(&mut store, "refused-stop", Some("turn"), Stop, 150); + let s = &store.preview("refused-stop").unwrap()[0]; + assert_eq!( + s.segments.iter().map(|s| s.duration_seconds).sum::(), + 0 + ); + assert!(s.needs_attention); + assert!(s.segments.iter().all(|s| s.completeness == "INCOMPLETE")); + assert!(store.status().unwrap().storage_paused); +} + +#[cfg(unix)] +#[test] +fn refusal_is_reconciled_before_pause_and_resume_clock_transitions() { + let (dir, mut store, _) = setup(); + event(&mut store, "refused-control", Some("turn"), Prompt, 0); + capture::record_failure( + &dir.path().join("capture"), + &capture::hash("boundary"), + "STORAGE_UNAVAILABLE", + ) + .unwrap(); + store.control(&repo(), "pause", &clock(150)).unwrap(); + let _ = store.control(&repo(), "resume", &clock(170)); + event(&mut store, "refused-control", Some("turn"), Stop, 180); + let session = &store.preview("refused-control").unwrap()[0]; + assert_eq!( + session + .segments + .iter() + .map(|s| s.duration_seconds) + .sum::(), + 0 + ); + assert!(session + .segments + .iter() + .all(|s| s.completeness == "INCOMPLETE")); + let database = rusqlite::Connection::open(dir.path().join("capture/capture.sqlite3")).unwrap(); + let clocks: i64 = database + .query_row( + "SELECT COUNT(*) FROM sessions WHERE json_type(data,'$.active.clock')='object'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(clocks, 0); +} +#[cfg(unix)] +#[test] +fn refusal_published_while_terminal_waits_for_sqlite_is_not_a_stale_authorization() { + let (dir, mut store, _) = setup(); + event(&mut store, "racing-terminal", Some("turn"), Prompt, 0); + let database = rusqlite::Connection::open(dir.path().join("capture/capture.sqlite3")).unwrap(); + database.execute_batch("BEGIN IMMEDIATE").unwrap(); + let worker = std::thread::spawn(move || { + event(&mut store, "racing-terminal", Some("turn"), Stop, 150); + store + }); + std::thread::sleep(std::time::Duration::from_millis(100)); + capture::record_failure( + &dir.path().join("capture"), + &capture::hash("boundary"), + "STORAGE_UNAVAILABLE", + ) + .unwrap(); + database.execute_batch("ROLLBACK").unwrap(); + let store = worker.join().unwrap(); + let session = &store.preview("racing-terminal").unwrap()[0]; + assert_eq!( + session + .segments + .iter() + .map(|s| s.duration_seconds) + .sum::(), + 0 + ); + assert!(session.needs_attention); +} +#[cfg(unix)] +#[test] +fn observed_mapping_invalidation_is_durable_until_explicit_reapproval() { + for remote in [false, true] { + let (_dir, mut store, binding) = setup(); + event(&mut store, "invalidated", Some("turn"), Prompt, 0); + let mut changed = repo(); + if remote { + changed.remote_hash = capture::hash("changed"); + } else { + changed.disabled = true; + } + store + .event( + &changed, + capture::Signal { + source: "codex", + resumed: false, + source_id: "invalidated", + turn_id: Some("turn"), + version: "fixture-v1", + event: Stop, + clock: &clock(60), + }, + ) + .unwrap(); + event(&mut store, "invalidated", Some("turn"), Stop, 150); + let session = &store.preview("invalidated").unwrap()[0]; + assert_eq!( + session + .segments + .iter() + .map(|s| s.duration_seconds) + .sum::(), + 0 + ); + assert!(session.needs_attention); + assert!(store.binding(&repo().key).unwrap().unwrap().revoked); + assert!(store.claim(&binding, clock(160).wall).unwrap().is_none()); + store.approve(binding.clone()).unwrap(); + assert!(store.claim(&binding, clock(170).wall).unwrap().is_some()); + } +} +#[cfg(unix)] +#[test] +fn repo_disable_checkpoints_previously_earned_fragments_without_another_native_hook() { + let (_dir, mut store, binding) = setup(); + event(&mut store, "earned", Some("turn"), Prompt, 0); + store.control(&repo(), "pause", &clock(30)).unwrap(); + store.control(&repo(), "disable", &clock(60)).unwrap(); + assert!(store.claim(&binding, clock(65).wall).unwrap().is_none()); + store.approve(binding.clone()).unwrap(); + let (_, body) = body(&mut store, &binding, 100); + assert_eq!(body["segments"][0]["duration_seconds"], 30); +} +#[cfg(unix)] +#[test] +fn idle_maintenance_expires_only_acknowledged_bodies_with_an_injected_clock() { + let (dir, mut store, binding) = setup(); + event(&mut store, "expired", Some("turn"), Prompt, 0); + event(&mut store, "expired", Some("turn"), Stop, 30); + let (row, _) = body(&mut store, &binding, 31); + store.acknowledge(&row, "server", clock(31).wall).unwrap(); + event(&mut store, "unsent", Some("turn"), Prompt, 40); + event(&mut store, "unsent", Some("turn"), Stop, 70); + store.maintain(clock(31).wall + 8 * 24 * 3600).unwrap(); + let database = rusqlite::Connection::open(dir.path().join("capture/capture.sqlite3")).unwrap(); + let acknowledged: i64 = database + .query_row( + "SELECT COUNT(*) FROM outbox WHERE state='acknowledged'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(acknowledged, 0); + assert_eq!(store.status().unwrap().pending, 1); + assert_eq!(store.preview("expired").unwrap().len(), 1); +} + +#[cfg(unix)] +#[test] +fn refusal_quarantine_survives_recover_reapproval_and_an_inflight_retry_finish() { + let (dir, mut store, binding) = setup(); + event(&mut store, "uncertain-frozen", Some("turn"), Prompt, 0); + event(&mut store, "uncertain-frozen", Some("turn"), Stop, 30); + let (row, _) = body(&mut store, &binding, 31); + let original = row.body.clone(); + capture::record_failure( + &dir.path().join("capture"), + &capture::hash("late-refusal"), + "STORAGE_UNAVAILABLE", + ) + .unwrap(); + store.maintain(clock(32).wall).unwrap(); + store + .finish(&row, "pending", "NETWORK_UNAVAILABLE", clock(33).wall, None) + .unwrap(); + store.recover(&clock(40)).unwrap(); + store.approve(binding.clone()).unwrap(); + assert!(store.claim(&binding, clock(100).wall).unwrap().is_none()); + let status = store.status().unwrap(); + assert_eq!(status.held, 1); + assert_eq!( + status.queue[0].reason.as_deref(), + Some("REFUSED_BOUNDARY_REVIEW_REQUIRED") + ); + let database = rusqlite::Connection::open(dir.path().join("capture/capture.sqlite3")).unwrap(); + let frozen: String = database + .query_row("SELECT body FROM outbox", [], |r| r.get(0)) + .unwrap(); + assert_eq!(frozen, original); +} +#[cfg(unix)] +#[test] +fn observing_repository_in_sync_abandons_clocks_before_identity_can_be_restored() { + let (_dir, mut store, binding) = setup(); + event(&mut store, "sync-observed", Some("turn"), Prompt, 0); + let mut changed = repo(); + changed.disabled = true; + store.observe_repository(&changed).unwrap(); + store.observe_repository(&repo()).unwrap(); + event(&mut store, "sync-observed", Some("turn"), Stop, 90); + assert_eq!( + store.preview("sync-observed").unwrap()[0].segments[0].duration_seconds, + 0 + ); + assert!(store.claim(&binding, clock(100).wall).unwrap().is_none()); +} + +#[cfg(unix)] +#[test] +fn a_stop_from_an_unapproved_repository_cannot_leave_the_same_native_clock_alive() { + let (_dir, mut store, _) = setup(); + event(&mut store, "native-gap", Some("turn"), Prompt, 0); + let mut unapproved = repo(); + unapproved.key = capture::hash("different-unapproved-repo"); + store + .event( + &unapproved, + capture::Signal { + source: "codex", + resumed: false, + source_id: "native-gap", + turn_id: Some("turn"), + version: "fixture-v1", + event: Stop, + clock: &clock(60), + }, + ) + .unwrap(); + event(&mut store, "native-gap", Some("turn"), Stop, 150); + let session = &store.preview("native-gap").unwrap()[0]; + assert_eq!(session.segments[0].duration_seconds, 0); + assert!(session.needs_attention); +} + +#[cfg(unix)] +#[test] +fn native_resume_during_capture_pause_abandons_old_turn_for_both_harnesses() { + for source in ["codex", "claude-code"] { + let (_dir, mut store, binding) = setup(); + for (event, resumed, n) in [(Prompt, false, 0), (SessionStart, true, 100)] { + if event == SessionStart { + store.control(&repo(), "pause", &clock(30)).unwrap(); + } + store + .event( + &repo(), + capture::Signal { + source, + resumed, + source_id: "paused-native-resume", + turn_id: Some("native-turn"), + version: "fixture-v1", + event, + clock: &clock(n), + }, + ) + .unwrap(); + } + let paused = store.status().unwrap(); + assert!(paused.bindings[0].paused); + assert_eq!( + paused.unfinished, 0, + "native resume must remove the old continuation for {source}" + ); + assert_eq!( + paused.pending, 1, + "earned fragments must be checkpointed for {source}" + ); + store.control(&repo(), "resume", &clock(150)).unwrap(); + store + .event( + &repo(), + capture::Signal { + source, + resumed: false, + source_id: "paused-native-resume", + turn_id: Some("native-turn"), + version: "fixture-v1", + event: Stop, + clock: &clock(200), + }, + ) + .unwrap(); + let session = &store.preview("paused-native-resume").unwrap()[0]; + assert_eq!( + session + .segments + .iter() + .map(|v| v.duration_seconds) + .sum::(), + 30, + "{source}" + ); + assert!(session.needs_attention); + let (_, payload) = body(&mut store, &binding, 210); + assert!( + payload["segments"] + .as_array() + .unwrap() + .iter() + .any(|segment| segment["completeness"] == "INCOMPLETE" + && segment["duration_seconds"] == 0), + "incomplete continuation must reach canonical review for {source}" + ); + assert_eq!( + payload["segments"] + .as_array() + .unwrap() + .iter() + .map(|s| s["duration_seconds"].as_i64().unwrap()) + .sum::(), + 30 + ); + } +} + +// Repository discovery requires the owned Unix process boundary. Other +// platforms refuse before reading mapping bodies or launching Git. +#[cfg(not(unix))] +#[test] +fn unsupported_repository_capture_refuses_before_reading_mapping_or_creating_state() { + let temp = tempfile::tempdir().unwrap(); + let mapping = temp.path().join(".keito"); + std::fs::create_dir(&mapping).unwrap(); + let file = mapping.join("config.yml"); + for body in [ + "project_id: synthetic-project\n", + "project_id: [PRIVATE_CANARY\n", + "project_id: one\nproject_id: PRIVATE_CANARY\n", + ] { + std::fs::write(&file, body).unwrap(); + let error = Repository::resolve(temp.path()).unwrap_err(); + assert!( + matches!(error, keito_cli::error::AppError::Config(ref message) + if message == "Automatic capture is unsupported on this platform; manual time commands remain available") + ); + assert!(!error.to_string().contains("PRIVATE_CANARY")); + assert_eq!(std::fs::read_to_string(&file).unwrap(), body); + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1); + assert_eq!(std::fs::read_dir(&mapping).unwrap().count(), 1); + } + let absent = temp.path().join("must-not-be-created"); + assert!( + matches!(Repository::resolve(&absent), Err(keito_cli::error::AppError::Config(ref message)) + if message == "Automatic capture is unsupported on this platform; manual time commands remain available") + ); + assert!(!absent.exists()); +} diff --git a/tests/capture_supervisor.rs b/tests/capture_supervisor.rs new file mode 100644 index 0000000..727ae80 --- /dev/null +++ b/tests/capture_supervisor.rs @@ -0,0 +1,223 @@ +#[path = "support/service_boundary.rs"] +mod service_boundary; +use predicates::prelude::*; + +#[cfg(unix)] +#[test] +fn capture_worker_status_never_claims_an_uninstalled_service_running() { + let home = tempfile::tempdir().unwrap(); + service_boundary::command(assert_cmd::cargo::cargo_bin!("keito")) + .env_clear() + .env("HOME", home.path()) + .env("CODEX_HOME", home.path().join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.path().join(".claude")) + .env("XDG_CONFIG_HOME", home.path().join("config")) + .env("APPDATA", home.path().join("AppData/Roaming")) + .env( + "PATH", + if cfg!(windows) { + std::env::var_os("PATH").unwrap_or_default() + } else { + "/usr/bin:/bin".into() + }, + ) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("KEITO_CAPTURE_HOME", home.path().join("capture")) + .args(["capture", "worker-status", "--json"]) + .assert() + .success() + .stdout(predicate::str::contains("\"running\": false")); +} + +#[test] +fn setup_explains_explicit_supervisor_install() { + service_boundary::command(assert_cmd::cargo::cargo_bin!("keito")) + .args(["capture", "setup", "--help"]) + .assert() + .success() + .stdout(predicate::str::contains("--install-worker")); +} + +#[cfg(unix)] +mod launchd { + use keito_cli::capture_supervisor::{Supervisor, WorkerConfig}; + use std::os::unix::fs::{symlink, PermissionsExt}; + use std::path::PathBuf; + fn fixture() -> (tempfile::TempDir, Supervisor, PathBuf, PathBuf, PathBuf) { + let temp = tempfile::tempdir().unwrap(); + let launchctl = temp.path().join("launchctl"); + std::fs::write( + &launchctl, + r#"#!/bin/sh +state="$(dirname "$0")/running" +fail="$(dirname "$0")/fail" +case "$1" in + print) if [ -f "$state" ]; then printf 'state = running\npid = 123\n'; exit 0; else printf 'Could not find service "%s"\n' "${2##*/}" >&2; exit 113; fi;; + bootout) rm -f "$state"; exit 0;; + bootstrap) if [ -f "$fail" ]; then exit 1; fi; touch "$state"; exit 0;; +esac +exit 1 +"#, + ) + .unwrap(); + std::fs::set_permissions(&launchctl, std::fs::Permissions::from_mode(0o700)).unwrap(); + let exe = temp.path().join("keito runtime with spaces"); + std::fs::write(&exe, b"fixture binary").unwrap(); + let root = temp.path().join("project with & spaces"); + std::fs::create_dir(&root).unwrap(); + let capture = temp.path().join("capture"); + let supervisor = Supervisor { + home: temp.path().join("home"), + launchctl, + uid: 123, + }; + (temp, supervisor, exe, root, capture) + } + fn config<'a>( + exe: &'a std::path::Path, + root: &'a std::path::Path, + capture: &'a std::path::Path, + ) -> WorkerConfig<'a> { + WorkerConfig { + repository_key: "repository-fixture", + repository_root: root, + executable: exe, + capture_home: capture, + workspace_id: "workspace_fixture", + api_origin: "https://example.invalid", + } + } + #[test] + fn supervisor_installs_only_owned_service_and_preserves_unrelated_agents() { + let (temp, s, exe, root, capture) = fixture(); + let conf = config(&exe, &root, &capture); + let agents = s.home.join("Library/LaunchAgents"); + std::fs::create_dir_all(&agents).unwrap(); + std::fs::write(agents.join("unrelated.plist"), b"unrelated settings").unwrap(); + let status = s.install(&conf).unwrap(); + assert!(status.installed); + assert!(status.running); + assert!(!status.stale); + assert!(s.install(&conf).unwrap().running); + let mut files: Vec<_> = std::fs::read_dir(&agents) + .unwrap() + .map(|x| x.unwrap().path()) + .filter(|x| x.file_name().unwrap() != "unrelated.plist") + .collect(); + assert_eq!(files.len(), 1); + let owned = files.remove(0); + let text = std::fs::read_to_string(&owned).unwrap(); + assert!(text.contains("project with & spaces")); + assert!(!text.contains("KEITO_API_KEY")); + assert!(text.contains("KeepAlive")); + assert_eq!( + std::fs::metadata(&owned).unwrap().permissions().mode() & 0o777, + 0o600 + ); + std::fs::write(&exe, b"changed runtime").unwrap(); + assert!(s.status(conf.repository_key, Some(&conf)).unwrap().stale); + assert!(!s.uninstall(conf.repository_key).unwrap().installed); + assert_eq!( + std::fs::read(agents.join("unrelated.plist")).unwrap(), + b"unrelated settings" + ); + assert!(!temp.path().join("running").exists()); + } + #[test] + fn failed_bootstrap_restores_original_owned_bytes_and_never_claims_running() { + let (temp, s, exe, root, capture) = fixture(); + let conf = config(&exe, &root, &capture); + s.install(&conf).unwrap(); + let file = std::fs::read_dir(s.home.join("Library/LaunchAgents")) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let prior = std::fs::read(&file).unwrap(); + std::fs::write(&exe, b"updated runtime").unwrap(); + std::fs::write(temp.path().join("fail"), b"fail").unwrap(); + assert!(s.install(&conf).is_err()); + assert_eq!(std::fs::read(&file).unwrap(), prior); + assert!(!s.status(conf.repository_key, None).unwrap().running); + } + #[test] + fn malicious_origin_and_symlinked_agent_directory_are_refused() { + let (temp, s, exe, root, capture) = fixture(); + let mut conf = config(&exe, &root, &capture); + conf.api_origin = "https://secret:password@example.invalid?token=PRIVATE_CANARY"; + let error = s.render(&conf).unwrap_err().to_string(); + assert!(!error.contains("PRIVATE_CANARY")); + conf.api_origin = "https://example.invalid"; + std::fs::create_dir_all(s.home.join("Library")).unwrap(); + let other = temp.path().join("other"); + std::fs::create_dir(&other).unwrap(); + symlink(&other, s.home.join("Library/LaunchAgents")).unwrap(); + assert!(s.install(&conf).is_err()); + assert_eq!(std::fs::read_dir(&other).unwrap().count(), 0); + } + #[test] + fn symlinked_parent_of_launch_agents_cannot_escape_the_owned_home() { + let (temp, s, exe, root, capture) = fixture(); + let conf = config(&exe, &root, &capture); + std::fs::create_dir_all(&s.home).unwrap(); + let outside = temp.path().join("outside-library"); + std::fs::create_dir_all(&outside).unwrap(); + symlink(&outside, s.home.join("Library")).unwrap(); + assert!(s.install(&conf).is_err()); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + } + #[test] + fn failed_bootout_of_loaded_waiting_job_keeps_its_owned_settings() { + let (_temp, s, exe, root, capture) = fixture(); + let conf = config(&exe, &root, &capture); + s.install(&conf).unwrap(); + let agents = s.home.join("Library/LaunchAgents"); + let owned = std::fs::read_dir(&agents) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let original = std::fs::read(&owned).unwrap(); + std::fs::write(&s.launchctl,"#!/bin/sh\ncase \"$1\" in\nprint) printf 'state = waiting\\n'; exit 0;;\nbootout) exit 1;;\n*) exit 0;;\nesac\n".replace("\\\"","\"")).unwrap(); + assert!(s.uninstall(conf.repository_key).is_err()); + assert_eq!(std::fs::read(&owned).unwrap(), original); + } + #[test] + fn owned_worker_registry_survives_repository_removal_and_allows_exact_removal() { + let (_temp, s, exe, root, capture) = fixture(); + let key = keito_cli::capture::hash("stable-family"); + let mut conf = config(&exe, &root, &capture); + conf.repository_key = &key; + s.install(&conf).unwrap(); + std::fs::remove_dir(&root).unwrap(); + let workers = s.list().unwrap(); + assert_eq!(workers.len(), 1); + assert_eq!(workers[0].worker_id, key); + assert!(workers[0].status.loaded); + s.uninstall(&workers[0].worker_id).unwrap(); + assert!(s.list().unwrap().is_empty()); + } + #[test] + fn failed_permission_observation_cannot_prove_worker_absence_or_remove_settings() { + let (_temp, s, exe, root, capture) = fixture(); + let conf = config(&exe, &root, &capture); + s.install(&conf).unwrap(); + let owned = std::fs::read_dir(s.home.join("Library/LaunchAgents")) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let prior = std::fs::read(&owned).unwrap(); + std::fs::write( + &s.launchctl, + "#!/bin/sh\nprintf 'Operation not permitted\\n' >&2\nexit 1\n", + ) + .unwrap(); + assert!(s.uninstall(conf.repository_key).is_err()); + assert_eq!(std::fs::read(&owned).unwrap(), prior); + } +} diff --git a/tests/capture_transport.rs b/tests/capture_transport.rs new file mode 100644 index 0000000..158c074 --- /dev/null +++ b/tests/capture_transport.rs @@ -0,0 +1,484 @@ +#![cfg(unix)] +// Native consent/store/reader assertions require the supported POSIX authority. +#![allow(deprecated)] +#[path = "support/runtime_pair.rs"] +mod runtime_pair; +#[path = "support/service_boundary.rs"] +mod service_boundary; +use assert_cmd::Command; +use keito_cli::capture::{self, Binding, Clock, Repository, Signal, Store}; +use keito_cli::cli::capture::CaptureEvent::{Prompt, Stop}; +use serde_json::{json, Value}; +use std::path::Path; +use wiremock::matchers::{header, method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; +fn init(root: &Path) { + std::fs::create_dir_all(root).unwrap(); + assert!(std::process::Command::new("git") + .arg("-C") + .arg(root) + .arg("init") + .output() + .unwrap() + .status + .success()); +} +fn command(home: &Path, root: &Path, origin: &str) -> Command { + let mut cmd = service_boundary::command(runtime_pair::pair().core_path); + cmd.env_clear() + .current_dir(root) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("PATH", runtime_pair::process_path()) + .env("HOME", home) + .env("XDG_CONFIG_HOME", home.join("config")) + .env("APPDATA", home.join("AppData/Roaming")) + .env("KEITO_CAPTURE_HOME", home.join("capture")) + .env("KEITO_API_URL", origin) + .env("KEITO_API_KEY", "kto_test_key") + .env("KEITO_ACCOUNT_ID", "co_test"); + cmd +} +async fn me(server: &MockServer, owner: &str) { + let mut value: Value = + serde_json::from_str(include_str!("fixtures/api_v2/users_me.json")).unwrap(); + value["id"] = json!(owner); + Mock::given(method("GET")) + .and(path("/api/v2/users/me")) + .respond_with(ResponseTemplate::new(200).set_body_json(value)) + .mount(server) + .await; +} +fn seed(home: &Path, root: &Path, origin: &str) -> (Store, Binding) { + let repo = Repository::resolve(root).unwrap(); + let mut store = Store::open(&home.join("capture")).unwrap(); + let b = store + .approve(Binding { + repository_key: repo.key.clone(), + remote_hash: repo.remote_hash.clone(), + hint_hash: repo.hint_hash.clone(), + id: String::new(), + version: 0, + workspace_id: "co_test".into(), + owner_id: "usr_1".into(), + origin_hash: capture::hash(origin), + project_id: "p1".into(), + task_id: "t1".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }) + .unwrap(); + let clock = Clock { + wall: 1_794_067_200, + monotonic: 10, + boot: "fixture".into(), + }; + let end = Clock { + wall: clock.wall + 90, + monotonic: 100, + boot: "fixture".into(), + }; + for (event, time) in [(Prompt, &clock), (Stop, &end)] { + store + .event( + &repo, + Signal { + source: "codex", + resumed: false, + source_id: "synthetic-session", + turn_id: Some("synthetic-turn"), + version: "0.167.0", + event, + clock: time, + }, + ) + .unwrap(); + } + (store, b) +} +#[tokio::test] +async fn sync_sends_only_canonical_exact_metadata_and_acknowledges_once() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + let (store, _) = seed(home.path(), &root, &server.uri()); + Mock::given(method("POST")).and(path("/api/v2/agent-sessions")).and(header("Authorization","Bearer kto_test_key")).and(header("Keito-Account-Id","co_test")) + .respond_with(ResponseTemplate::new(201).set_body_json(json!({"agent_session":{"id":"canonical-session","revision":1,"projection_state":"PROJECTED","review_state":"PENDING"}}))).expect(1).mount(&server).await; + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success(); + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success(); + assert_eq!(store.status().unwrap().pending, 0); + assert!(store.status().unwrap().delivery_verified); + let requests = server.received_requests().await.unwrap(); + let request = requests.iter().find(|r| r.method == "POST").unwrap(); + let payload: Value = serde_json::from_slice(&request.body).unwrap(); + assert_eq!(payload["segments"][0]["duration_seconds"], 90); + assert_eq!(payload["usage"]["status"], "UNAVAILABLE"); + assert!(payload.get("metadata").is_none()); + assert!(!String::from_utf8_lossy(&request.body).contains(home.path().to_str().unwrap())); + assert_eq!( + request.headers["idempotency-key"].to_str().unwrap(), + capture::hash(&request.body) + ); +} +#[tokio::test] +async fn revoked_owner_or_changed_mapping_never_uploads_pending_evidence() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "different_owner").await; + let (store, _) = seed(home.path(), &root, &server.uri()); + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success(); + assert_eq!(store.status().unwrap().pending, 1); + assert!(!server + .received_requests() + .await + .unwrap() + .iter() + .any(|r| r.method == "POST")); +} +#[tokio::test] +async fn transient_response_is_held_with_frozen_body_and_retry_after() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + let (mut store, b) = seed(home.path(), &root, &server.uri()); + Mock::given(method("POST")) + .and(path("/api/v2/agent-sessions")) + .respond_with( + ResponseTemplate::new(429) + .insert_header("Retry-After", "60") + .set_body_string("PRIVATE_SERVER_CANARY"), + ) + .expect(1) + .mount(&server) + .await; + let out = command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success() + .get_output() + .clone(); + assert!(!String::from_utf8_lossy(&out.stdout).contains("PRIVATE")); + assert!(!String::from_utf8_lossy(&out.stderr).contains("PRIVATE")); + assert!(store + .claim(&b, chrono::Utc::now().timestamp() + 30) + .unwrap() + .is_none()); + let queued = store + .claim(&b, chrono::Utc::now().timestamp() + 65) + .unwrap() + .unwrap(); + let payload: Value = serde_json::from_str(&queued.body).unwrap(); + assert_eq!(payload["segments"][0]["duration_seconds"], 90); +} +#[tokio::test] +async fn setup_validates_auth_project_and_task_before_persisting_approval() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + for (route, fixture) in [ + ( + "/api/v2/projects", + include_str!("fixtures/api_v2/projects_list.json"), + ), + ( + "/api/v2/tasks", + include_str!("fixtures/api_v2/tasks_list.json"), + ), + ] { + Mock::given(method("GET")) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_raw(fixture, "application/json")) + .mount(&server) + .await; + } + command(home.path(), &root, &server.uri()) + .args([ + "capture", + "setup", + "--agent", + "codex", + "--project", + "p1", + "--task", + "wrong_task", + "--confirm", + "--json", + ]) + .assert() + .failure(); + assert!(!home.path().join("capture/capture.sqlite3").exists()); + command(home.path(), &root, &server.uri()) + .args([ + "capture", + "setup", + "--agent", + "codex", + "--project", + "p1", + "--task", + "t1", + "--confirm", + "--json", + ]) + .assert() + .success(); + let store = Store::open(&home.path().join("capture")).unwrap(); + assert_eq!(store.status().unwrap().bindings.len(), 1); +} + +#[tokio::test] +async fn paused_or_revoked_local_consent_performs_no_network_even_preflight() { + for action in ["pause", "disable"] { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + let (mut store, _) = seed(home.path(), &root, &server.uri()); + let repo = Repository::resolve(&root).unwrap(); + store + .control( + &repo, + action, + &Clock { + wall: 1_794_067_300, + monotonic: 110, + boot: "fixture".into(), + }, + ) + .unwrap(); + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success(); + assert!( + server.received_requests().await.unwrap().is_empty(), + "Local disable must not cause authentication or capture requests" + ); + } +} + +#[tokio::test] +async fn mapping_change_between_queued_revisions_stops_before_next_upload() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + let (mut store, _) = seed(home.path(), &root, &server.uri()); + let repo = Repository::resolve(&root).unwrap(); + for (event, offset) in [(Prompt, 100), (Stop, 190)] { + store + .event( + &repo, + Signal { + source: "codex", + resumed: false, + source_id: "synthetic-session", + turn_id: Some("second-turn"), + version: "0.167.0", + event, + clock: &Clock { + wall: 1_794_067_200 + offset, + monotonic: 10 + offset, + boot: "fixture".into(), + }, + }, + ) + .unwrap(); + } + let changed_root = root.clone(); + Mock::given(method("POST")) + .and(path("/api/v2/agent-sessions")) + .respond_with(move |request: &wiremock::Request| { + std::fs::create_dir_all(changed_root.join(".keito")).unwrap(); + std::fs::write( + changed_root.join(".keito/config.yml"), + "agent_tracking:\n enabled: false\n", + ) + .unwrap(); + let payload: Value = serde_json::from_slice(&request.body).unwrap(); + ResponseTemplate::new(201).set_body_json( + json!({"agent_session":{"id":"canonical-session","revision":payload["revision"],"projection_state":"PROJECTED","review_state":"PENDING"}}), + ) + }) + .mount(&server) + .await; + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success(); + assert_eq!( + server + .received_requests() + .await + .unwrap() + .iter() + .filter(|r| r.method == "POST") + .count(), + 1 + ); + assert_eq!(store.status().unwrap().pending, 0); + assert_eq!(store.status().unwrap().held, 1); + assert!(store.status().unwrap().bindings[0].revoked); +} + +#[tokio::test] +async fn malformed_success_acknowledgement_is_not_delivery_evidence() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + let (store, _) = seed(home.path(), &root, &server.uri()); + Mock::given(method("POST")).and(path("/api/v2/agent-sessions")).respond_with(ResponseTemplate::new(201).set_body_json(json!({"agent_session":{"id":"","revision":1,"projection_state":"PROJECTED","review_state":"PENDING"}}))).mount(&server).await; + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success(); + let status = store.status().unwrap(); + assert_eq!(status.pending, 1); + assert!(!status.delivery_verified); + assert_eq!( + status.queue[0].reason.as_deref(), + Some("INVALID_ACKNOWLEDGEMENT") + ); +} +#[tokio::test] +async fn in_progress_409_remains_retryable_and_server_prose_never_persists() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + let (store, _) = seed(home.path(), &root, &server.uri()); + Mock::given(method("POST")) + .and(path("/api/v2/agent-sessions")) + .respond_with( + ResponseTemplate::new(409) + .insert_header("Retry-After", "1") + .set_body_json( + json!({"error":{"code":"in_progress","message":"PRIVATE_SERVER_CANARY"}}), + ), + ) + .mount(&server) + .await; + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success(); + let status = store.status().unwrap(); + assert_eq!(status.pending, 1); + assert_eq!(status.held, 0); + assert_eq!(status.queue[0].reason.as_deref(), Some("IN_PROGRESS")); + assert!(!serde_json::to_string(&status).unwrap().contains("PRIVATE")); +} +#[tokio::test] +async fn damaged_frozen_body_is_quarantined_before_any_post() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + let (store, _) = seed(home.path(), &root, &server.uri()); + let db = rusqlite::Connection::open(home.path().join("capture/capture.sqlite3")).unwrap(); + db.execute( + "UPDATE outbox SET body=json_set(body,'$.project_id','another_project')", + [], + ) + .unwrap(); + Mock::given(method("POST")).and(path("/api/v2/agent-sessions")).respond_with(ResponseTemplate::new(201).set_body_json(json!({"agent_session":{"id":"canonical-session","revision":1,"projection_state":"PROJECTED","review_state":"PENDING"}}))).mount(&server).await; + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .failure(); + assert!(!server + .received_requests() + .await + .unwrap() + .iter() + .any(|r| r.method == "POST")); + assert_eq!( + store.status().unwrap().queue[0].reason.as_deref(), + Some("FROZEN_PAYLOAD_INVALID") + ); +} +#[tokio::test] +async fn http_date_retry_after_is_not_replaced_by_short_backoff() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + let (_store, _) = seed(home.path(), &root, &server.uri()); + let future = chrono::Utc::now() + chrono::Duration::seconds(120); + let header = future.format("%a, %d %b %Y %H:%M:%S GMT").to_string(); + Mock::given(method("POST")) + .and(path("/api/v2/agent-sessions")) + .respond_with(ResponseTemplate::new(429).insert_header("Retry-After", header)) + .mount(&server) + .await; + command(home.path(), &root, &server.uri()) + .args(["capture", "sync", "--json"]) + .assert() + .success(); + let db = rusqlite::Connection::open(home.path().join("capture/capture.sqlite3")).unwrap(); + let retry_at: i64 = db + .query_row("SELECT retry_at FROM outbox", [], |r| r.get(0)) + .unwrap(); + assert!(retry_at >= future.timestamp()); +} + +#[tokio::test] +async fn doctor_never_reuses_another_workspace_delivery_as_current_binding_proof() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let root = home.path().join("repo"); + init(&root); + me(&server, "usr_1").await; + let (mut store, b) = seed(home.path(), &root, &server.uri()); + let queued = store + .claim(&b, chrono::Utc::now().timestamp()) + .unwrap() + .unwrap(); + store + .acknowledge(&queued, "canonical-doctor", chrono::Utc::now().timestamp()) + .unwrap(); + let output = command(home.path(), &root, &server.uri()) + .env("KEITO_ACCOUNT_ID", "other_workspace") + .args(["skill", "doctor", "--live", "--json"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let status: Value = serde_json::from_slice(&output).unwrap(); + assert_eq!(status["authentication_state"], "VERIFIED"); + assert_eq!( + status["capture"]["current_repository"]["authentication_binding"], + "MISMATCH" + ); + assert_eq!(status["delivery_verified"], false); + assert_eq!(status["capture"]["delivery_verified"], false); + assert_eq!(status["ready"], false); + assert_eq!(status["capture_runtime"], "VERIFIED_RELEASE_PAIR"); +} diff --git a/tests/capture_unsupported.rs b/tests/capture_unsupported.rs new file mode 100644 index 0000000..c8ff73d --- /dev/null +++ b/tests/capture_unsupported.rs @@ -0,0 +1,172 @@ +//! Windows has manual commands, not qualified automatic capture. Detect accidental +//! entry into auth/network/store/profile work before the unsupported boundary. +#![cfg(not(unix))] +use assert_cmd::Command; +use std::{ + collections::BTreeMap, + fs, + path::{Path, PathBuf}, +}; +use wiremock::MockServer; + +fn files(root: &Path) -> BTreeMap> { + fn visit(root: &Path, directory: &Path, result: &mut BTreeMap>) { + for entry in fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + assert!(!fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink()); + if path.is_dir() { + visit(root, &path, result); + } else { + result.insert( + path.strip_prefix(root).unwrap().to_owned(), + fs::read(path).unwrap(), + ); + } + } + } + let mut result = BTreeMap::new(); + visit(root, root, &mut result); + result +} + +#[tokio::test] +async fn unsupported_native_commands_never_read_auth_upload_acknowledge_or_change_state() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let home = root.join("home"); + let executable = root.join("keito.exe"); + fs::copy(assert_cmd::cargo::cargo_bin!("keito"), &executable).unwrap(); + assert_eq!(executable.canonicalize().unwrap(), executable); + for relative in [ + ".codex", + ".claude", + "capture", + "config/keito", + "AppData/Roaming/keito", + "empty-bin", + "tmp", + ] { + fs::create_dir_all(home.join(relative)).unwrap(); + } + // Loading this private malformed credential config would fail with a different + // diagnostic. Existing unrelated profile bytes must survive every refusal. + for relative in [ + "config/keito/config.toml", + "AppData/Roaming/keito/config.toml", + ] { + fs::write( + home.join(relative), + "api_key = \"PRIVATE_AUTH_CANARY\" malformed\n", + ) + .unwrap(); + } + fs::write(home.join(".codex/hooks.json"), "{\"unrelated\":true}\n").unwrap(); + fs::write(home.join(".claude/settings.json"), "{\"unrelated\":true}\n").unwrap(); + let before = files(&home); + let server = MockServer::start().await; + let commands: Vec> = vec![ + vec!["status"], + vec![ + "setup", + "--agent", + "codex", + "--project", + "p1", + "--task", + "t1", + "--confirm", + ], + vec!["sync"], + vec!["worker", "--interval-seconds", "1"], + vec!["worker-status", "--all"], + vec!["worker-uninstall", "--repo"], + vec!["recover", "--confirm"], + vec!["preview", "--session", "s1"], + vec!["pause", "--repo"], + vec!["resume", "--repo"], + vec!["disable", "--repo"], + vec!["disable-all"], + vec![ + "hook", + "--agent", + "codex", + "--event", + "prompt", + "--harness-version", + "0.167.0", + ], + vec![ + "hook", + "--agent", + "claude-code", + "--event", + "prompt", + "--harness-version", + "2.1.319", + ], + vec!["usage", "status", "--repo", "--agent", "codex"], + vec!["usage", "disable", "--repo", "--agent", "claude-code"], + vec![ + "usage", + "enable", + "--repo", + "--agent", + "codex", + "--profile-home", + "C:\\owned-inert-fixture\\home", + "--harness-executable", + "C:\\owned-inert-fixture\\codex.exe", + "--confirm", + ], + ]; + for args in commands { + let mut command = Command::new(&executable); + command + .env_clear() + .current_dir(&root) + .env("HOME", &home) + .env("USERPROFILE", &home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("XDG_CONFIG_HOME", home.join("config")) + .env("APPDATA", home.join("AppData/Roaming")) + .env("LOCALAPPDATA", home.join("AppData/Local")) + .env("KEITO_CAPTURE_HOME", home.join("capture")) + .env("PATH", home.join("empty-bin")) + .env("TEMP", home.join("tmp")) + .env("TMP", home.join("tmp")) + .env("KEITO_API_URL", server.uri()) + .env("KEITO_API_KEY", "PRIVATE_AUTH_CANARY") + .env("KEITO_ACCOUNT_ID", "workspace_fixture") + .env("KEITO_CAPTURE_ACK_FD", "3"); + for key in ["SystemRoot", "WINDIR"] { + if let Some(value) = std::env::var_os(key) { + command.env(key, value); + } + } + command.args(["--json", "capture"]).args(&args); + if args[0] == "hook" { + command.write_stdin(serde_json::json!({"cwd":root,"session_id":"session_fixture","turn_id":"turn_fixture","prompt_id":"prompt_fixture","prompt":"PRIVATE_INPUT_CANARY"}).to_string()); + } + let output = command.output().unwrap(); + assert!(!output.status.success(), "{args:?}"); + assert!( + output.stdout.is_empty(), + "unexpected readiness or ACK: {args:?}" + ); + let error = String::from_utf8(output.stderr).unwrap(); + assert!( + error.contains("Automatic capture is unsupported on this platform"), + "{args:?}: {error}" + ); + assert!(!error.contains("PRIVATE_") && !error.contains("KEITO_CAPTURE_DURABLE")); + assert_eq!(files(&home), before, "state/profile side effect: {args:?}"); + assert!( + server.received_requests().await.unwrap().is_empty(), + "network before refusal: {args:?}" + ); + } +} diff --git a/tests/capture_usage_commands.rs b/tests/capture_usage_commands.rs new file mode 100644 index 0000000..5b9ba54 --- /dev/null +++ b/tests/capture_usage_commands.rs @@ -0,0 +1,877 @@ +//! Normal command acceptance, not a synthetic UsageSource approval path. +//! The first selected status case is intentionally RED on 3ac: `usage` is absent. +//! Source-fixture paired numeric positives are a separate subsequent gate. +#![cfg(unix)] +#[path = "support/mutation_environment.rs"] +mod isolation; +#[path = "support/runtime_pair.rs"] +mod runtime_pair; +#[path = "support/service_boundary.rs"] +mod service_boundary; + +use keito_cli::capture::{self, Binding, Store}; +use serde_json::{json, Value}; +use std::{ + collections::BTreeMap, + fs, + os::unix::fs::{symlink, MetadataExt, PermissionsExt}, + path::{Path, PathBuf}, + process::Output, +}; + +const SESSION: &str = "12345678-1234-4234-8234-123456789abc"; +const NAMESPACES: [(&str, &str); 2] = [("claude-code", "2.1.319"), ("codex", "0.167.0")]; + +struct Fixture { + _temp: tempfile::TempDir, + root: PathBuf, + home: PathBuf, + capture: PathBuf, + repo: PathBuf, + core: PathBuf, +} + +impl Fixture { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let home = root.join("home"); + let capture = home.join("capture"); + let repo = root.join("repo"); + for path in [ + home.clone(), + capture.clone(), + home.join(".claude"), + home.join(".codex"), + home.join("config"), + home.join("AppData"), + home.join("state"), + root.join("bin"), + root.join("tmp"), + root.join("escape"), + repo.clone(), + ] { + fs::create_dir_all(&path).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + } + let core = root.join("keito-source-cli"); + let pair = runtime_pair::pair(); + fs::copy(&pair.core_path, &core).unwrap(); + fs::set_permissions(&core, fs::Permissions::from_mode(0o700)).unwrap(); + fs::copy(&pair.guard_path, root.join("keito-capture-guard")).unwrap(); + fs::set_permissions( + root.join("keito-capture-guard"), + fs::Permissions::from_mode(0o700), + ) + .unwrap(); + fs::copy( + pair.core_path + .parent() + .unwrap() + .join("capture-runtime-manifest.json"), + root.join("capture-runtime-manifest.json"), + ) + .unwrap(); + let fixture = Self { + _temp: temp, + root, + home, + capture, + repo, + core, + }; + fixture.boundary_negatives_before_any_command(); + + // Only Git exists on this explicit PATH. No real harness, service or + // credential helper can accidentally be selected from the operator PATH. + let git = std::env::split_paths(&runtime_pair::process_path()) + .next() + .unwrap() + .join("git"); + symlink(&git, fixture.root.join("bin/git")).unwrap(); + let git = fixture + .command(&git) + .args(["init", "--quiet"]) + .output() + .unwrap(); + assert!(git.status.success(), "private Git setup failed"); + let mut store = Store::open(&fixture.capture).unwrap(); + store + .approve(Binding { + repository_key: capture::hash( + fixture.repo.join(".git").to_string_lossy().as_bytes(), + ), + remote_hash: capture::hash(""), + hint_hash: capture::hash("no-mapping-hint"), + id: String::new(), + version: 0, + workspace_id: "co_synthetic".into(), + owner_id: "user_synthetic".into(), + origin_hash: capture::hash("https://example.invalid"), + project_id: "project_synthetic".into(), + task_id: "task_synthetic".into(), + agents: NAMESPACES.iter().map(|(n, _)| (*n).into()).collect(), + paused: false, + revoked: false, + }) + .unwrap(); + drop(store); + fixture + } + + fn unpaired() -> Self { + let fixture = Self::new(); + fs::remove_file(fixture.root.join("keito-capture-guard")).unwrap(); + fs::remove_file(fixture.root.join("capture-runtime-manifest.json")).unwrap(); + fixture + } + + fn checked(&self) -> isolation::CheckedEnvironment { + for path in [ + &self.root, + &self.home, + &self.capture, + &self.repo, + &self.root.join("tmp"), + ] { + let metadata = fs::symlink_metadata(path).unwrap(); + assert!(metadata.is_dir() && !metadata.file_type().is_symlink()); + assert_eq!(metadata.uid(), unsafe { libc::geteuid() }); + assert_eq!(metadata.mode() & 0o777, 0o700); + assert_eq!(path.canonicalize().unwrap(), *path); + } + isolation::checked( + &self.root, + &self.root, + Some(&self.home), + Some(&self.capture), + Some(&self.core), + ) + .expect("explicit private source-command environment") + } + + fn boundary_negatives_before_any_command(&self) { + let marker = self.root.join("command-must-not-be-constructed"); + for (home, capture, core) in [ + ( + None, + Some(self.capture.as_path()), + Some(self.core.as_path()), + ), + (Some(self.home.as_path()), None, Some(self.core.as_path())), + ( + Some(self.home.as_path()), + Some(self.capture.as_path()), + None, + ), + ( + Some(self.root.as_path()), + Some(self.capture.as_path()), + Some(self.core.as_path()), + ), + ( + Some(self.home.as_path()), + Some(self.capture.as_path()), + Some(Path::new("/inert-foreign-cli")), + ), + ] { + if isolation::checked(&self.root, &self.root, home, capture, core).is_ok() { + fs::write(&marker, b"unsafe").unwrap(); + } + assert!( + !marker.exists(), + "negative boundary reached a mutation marker" + ); + } + for name in [".claude", ".codex"] { + let profile = self.home.join(name); + fs::remove_dir(&profile).unwrap(); + symlink(self.root.join("escape"), &profile).unwrap(); + assert!(isolation::checked( + &self.root, + &self.root, + Some(&self.home), + Some(&self.capture), + Some(&self.core) + ) + .is_err()); + assert_eq!(fs::read_dir(self.root.join("escape")).unwrap().count(), 0); + fs::remove_file(&profile).unwrap(); + fs::create_dir(&profile).unwrap(); + fs::set_permissions(profile, fs::Permissions::from_mode(0o700)).unwrap(); + } + self.checked(); + } + + fn command(&self, program: &Path) -> assert_cmd::Command { + let checked = self.checked(); // Always before even constructing Command. + assert_eq!(checked.core, self.core); + let mut command = service_boundary::command(program); + command + .env_clear() + .current_dir(&self.repo) + .env("HOME", checked.home) + .env("CODEX_HOME", self.home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", self.home.join(".claude")) + .env("KEITO_CAPTURE_HOME", checked.capture) + .env("XDG_CONFIG_HOME", self.home.join("config")) + .env("XDG_STATE_HOME", self.home.join("state")) + .env("APPDATA", self.home.join("AppData")) + .env("TMPDIR", self.root.join("tmp")) + .env("PATH", self.root.join("bin")) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null"); + command + } + + fn cli(&self) -> assert_cmd::Command { + self.command(&self.core) + } + + fn source(&self, namespace: &str) -> PathBuf { + if namespace == "claude-code" { + self.home + .join(format!(".claude/projects/synthetic/{SESSION}.jsonl")) + } else { + self.home.join(format!( + ".codex/sessions/2026/11/08/rollout-synthetic-{SESSION}.jsonl" + )) + } + } + + fn source_canaries(&self) -> BTreeMap> { + let mut before = BTreeMap::new(); + for (namespace, _) in NAMESPACES { + let source = self.source(namespace); + fs::create_dir_all(source.parent().unwrap()).unwrap(); + fs::write(&source, b"PRIVATE_SOURCE_CONTENT_MUST_NOT_BE_RETAINED\n").unwrap(); + before.insert( + source, + b"PRIVATE_SOURCE_CONTENT_MUST_NOT_BE_RETAINED\n".to_vec(), + ); + } + before + } + + fn assert_no_raw_leak(&self, output: &Output) { + for bytes in [&output.stdout, &output.stderr] { + let text = String::from_utf8_lossy(bytes); + assert!(!text.contains("PRIVATE_")); + assert!(!text.contains(self.root.to_str().unwrap())); + } + for table in ["sessions", "outbox"] { + let database = + rusqlite::Connection::open(self.capture.join("capture.sqlite3")).unwrap(); + let column = if table == "sessions" { "data" } else { "body" }; + let mut statement = database + .prepare(&format!("SELECT {column} FROM {table}")) + .unwrap(); + for row in statement + .query_map([], |row| row.get::<_, String>(0)) + .unwrap() + { + let text = row.unwrap(); + assert!(!text.contains("PRIVATE_") && !text.contains(self.root.to_str().unwrap())); + } + } + } +} + +#[test] +fn normal_usage_status_defaults_disabled_independently_for_both_namespaces() { + let fixture = Fixture::new(); + let before = fixture.source_canaries(); + fixture + .cli() + .args(["capture", "status", "--json"]) + .assert() + .success(); + for (namespace, _) in NAMESPACES { + let output = fixture + .cli() + .args([ + "capture", "usage", "status", "--repo", "--agent", namespace, "--json", + ]) + .output() + .unwrap(); + assert!( + output.status.success(), + "missing normal numeric-consent status for {namespace}: {}", + String::from_utf8_lossy(&output.stderr) + ); + let status: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(status["enabled"], false); + assert_eq!(status["status"], "UNAVAILABLE"); + assert_eq!(status["reason"], "NUMERIC_CAPTURE_DISABLED"); + assert_eq!(status["source_namespace"], namespace); + fixture.assert_no_raw_leak(&output); + } + for (path, bytes) in before { + assert_eq!(fs::read(path).unwrap(), bytes); + } + assert!( + !fixture.capture.join("profiles").exists(), + "disabled status must not create a functional profile record" + ); +} + +#[test] +fn numeric_enable_requires_separate_explicit_confirmation_before_any_profile_work() { + let fixture = Fixture::new(); + for (namespace, _) in NAMESPACES { + let output = fixture + .cli() + .args(["capture", "usage", "enable", "--repo", "--agent", namespace]) + .arg("--profile-home") + .arg(&fixture.home) + .arg("--harness-executable") + .arg(fixture.root.join("inert-never-execute")) + .output() + .unwrap(); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("--confirm"), + "the missing independent consent must be visible" + ); + assert!(!fixture.capture.join("profiles").exists()); + fixture.assert_no_raw_leak(&output); + } +} + +#[test] +fn normal_numeric_disable_revokes_only_selected_namespace_without_opening_a_profile() { + let fixture = Fixture::new(); + let database = rusqlite::Connection::open(fixture.capture.join("capture.sqlite3")).unwrap(); + let binding: String = database + .query_row("SELECT data FROM bindings", [], |row| row.get(0)) + .unwrap(); + let binding: Value = serde_json::from_str(&binding).unwrap(); + // These are path-free, deliberately unqualified policy rows. They cannot + // provide the private profile, guard or origin proof needed for source reads. + for (namespace, _) in NAMESPACES { + let policy = json!({"policy_version":1,"binding_id":binding["id"],"binding_version":binding["version"], + "source_namespace":namespace,"profile_id":capture::hash(format!("unqualified-{namespace}")), + "profile_digest":capture::hash("no-functional-profile"),"epoch":10,"enabled":true}); + database + .execute( + "INSERT INTO usage_consents(binding_id,namespace,data) VALUES(?1,?2,?3)", + rusqlite::params![ + binding["id"].as_str().unwrap(), + namespace, + policy.to_string() + ], + ) + .unwrap(); + } + for (namespace, _) in NAMESPACES { + let other = if namespace == "claude-code" { + "codex" + } else { + "claude-code" + }; + let prior_other: String = database + .query_row( + "SELECT data FROM usage_consents WHERE namespace=?1", + [other], + |row| row.get(0), + ) + .unwrap(); + let output = fixture + .cli() + .args([ + "capture", "usage", "disable", "--repo", "--agent", namespace, "--json", + ]) + .output() + .unwrap(); + assert!( + output.status.success(), + "explicit local numeric withdrawal must work without a qualified numeric profile" + ); + let status: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(status["enabled"], false); + assert_eq!(status["status"], "UNAVAILABLE"); + let chosen: String = database + .query_row( + "SELECT data FROM usage_consents WHERE namespace=?1", + [namespace], + |row| row.get(0), + ) + .unwrap(); + let chosen: Value = serde_json::from_str(&chosen).unwrap(); + assert_eq!(chosen["enabled"], false); + assert_eq!(chosen["epoch"], 11); + let after_other: String = database + .query_row( + "SELECT data FROM usage_consents WHERE namespace=?1", + [other], + |row| row.get(0), + ) + .unwrap(); + assert_eq!( + after_other, prior_other, + "withdrawing one namespace rewrote the other consent" + ); + fixture.assert_no_raw_leak(&output); + } + assert!(!fixture.capture.join("profiles").exists()); +} + +#[test] +fn normal_numeric_enable_requires_an_embedded_pair_before_profile_or_version_work() { + let fixture = Fixture::unpaired(); + for (namespace, _) in NAMESPACES { + let output = fixture + .cli() + .args([ + "capture", + "usage", + "enable", + "--repo", + "--agent", + namespace, + "--confirm", + ]) + .arg("--profile-home") + .arg(&fixture.home) + .arg("--harness-executable") + .arg(fixture.root.join("never-executed-version-probe")) + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr) + .contains("intact official keito / keito-capture-guard release pair")); + assert!(!fixture.capture.join("profiles").exists()); + let database = rusqlite::Connection::open(fixture.capture.join("capture.sqlite3")).unwrap(); + let rows: i64 = database + .query_row("SELECT COUNT(*) FROM usage_consents", [], |row| row.get(0)) + .unwrap(); + assert_eq!(rows, 0); + fixture.assert_no_raw_leak(&output); + } +} + +#[test] +fn default_normal_hooks_remain_metadata_only_even_with_supported_version_and_active_path() { + let fixture = Fixture::new(); + let before = fixture.source_canaries(); + for (namespace, version) in NAMESPACES { + for event in ["prompt", "stop"] { + let input = json!({"session_id":SESSION,"turn_id":"turn_synthetic","prompt_id":"turn_synthetic","cwd":fixture.repo,"transcript_path":fixture.source(namespace),"prompt":"PRIVATE_PROMPT_CANARY","tool_input":{"secret":"PRIVATE_TOOL_CANARY"}}); + let output = fixture + .command(&fixture.root.join("keito-capture-guard")) + .env( + "KEITO_CAPTURE_CORE_SHA256", + capture::hash(fs::read(&fixture.core).unwrap()), + ) + .arg("--core") + .arg(&fixture.core) + .args([ + "--agent", + namespace, + "--event", + event, + "--harness-version", + version, + ]) + .write_stdin(input.to_string()) + .output() + .unwrap(); + assert!(output.status.success()); + assert!(output.stdout.is_empty()); + fixture.assert_no_raw_leak(&output); + } + } + let database = rusqlite::Connection::open(fixture.capture.join("capture.sqlite3")).unwrap(); + let mut statement = database + .prepare("SELECT body FROM outbox ORDER BY id") + .unwrap(); + let bodies: Vec = statement + .query_map([], |row| row.get::<_, String>(0)) + .unwrap() + .map(|row| serde_json::from_str(&row.unwrap()).unwrap()) + .collect(); + assert_eq!( + bodies.len(), + 2, + "normal hooks must preserve both namespaces' timing path" + ); + for body in bodies { + assert_eq!(body["usage"]["status"], "UNAVAILABLE"); + assert!(body["usage"] + .get("records") + .and_then(Value::as_array) + .is_none_or(Vec::is_empty)); + } + for (path, bytes) in before { + assert_eq!(fs::read(path).unwrap(), bytes); + } + assert!(!fixture.capture.join("profiles").exists()); +} + +// R12 regression: policies below are deliberately unqualified local fixtures. +// They permit status inspection, never construct a normal numeric capability. +fn r12_signal( + store: &mut Store, + repo: &capture::Repository, + scope: (&str, &str, &str), + boundary: (keito_cli::cli::capture::CaptureEvent, &str, i64), +) { + let (source, version, session) = scope; + let (event, turn, seconds) = boundary; + store + .event( + repo, + capture::Signal { + source, + resumed: false, + source_id: session, + turn_id: Some(turn), + version, + event, + clock: &capture::Clock { + wall: 1_794_067_200 + seconds, + monotonic: 1000 + seconds, + boot: "r12-private-clock".into(), + }, + }, + ) + .unwrap(); +} + +fn r12_policy(database: &rusqlite::Connection, binding: &Binding, namespace: &str) { + let policy = json!({"policy_version":1,"binding_id":binding.id,"binding_version":binding.version, + "source_namespace":namespace,"profile_id":capture::hash(format!("r12-unqualified-{namespace}")), + "profile_digest":capture::hash("r12-no-functional-profile"),"epoch":10,"enabled":true}); + database + .execute( + "INSERT INTO usage_consents(binding_id,namespace,data) VALUES(?1,?2,?3)", + rusqlite::params![binding.id, namespace, policy.to_string()], + ) + .unwrap(); +} + +fn r12_other_snapshot(database: &rusqlite::Connection, binding: &Binding) -> Vec { + let mut output = vec![database + .query_row( + "SELECT data FROM bindings WHERE repo_key=?1", + [&binding.repository_key], + |row| row.get::<_, String>(0), + ) + .unwrap()]; + for sql in [ + "SELECT namespace || data FROM usage_consents WHERE binding_id=?1 ORDER BY namespace", + "SELECT id || data FROM sessions WHERE binding_id=?1 ORDER BY id", + "SELECT json_object('id',id,'body',body,'hash',payload_hash,'state',state,'reason',reason,'claim',claimed_until) FROM outbox WHERE session_id IN(SELECT id FROM sessions WHERE binding_id=?1) ORDER BY id", + ] { + let mut statement = database.prepare(sql).unwrap(); + output.extend(statement.query_map([&binding.id], |row| row.get::<_, String>(0)).unwrap().map(Result::unwrap)); + } + output +} + +fn r12_freeze_numeric_fixture( + database: &rusqlite::Connection, + binding: &Binding, + source: &str, + source_id: &str, +) -> (String, String, String) { + let session_id: String = database.query_row("SELECT id FROM sessions WHERE binding_id=?1 AND source_id=?2 AND json_extract(data,'$.source_namespace')=?3", + rusqlite::params![binding.id, source_id, source], |row| row.get(0)).unwrap(); + let body: String = database + .query_row( + "SELECT body FROM outbox WHERE session_id=?1", + [&session_id], + |row| row.get(0), + ) + .unwrap(); + let mut body: Value = serde_json::from_str(&body).unwrap(); + let record = json!({"source_adapter":if source=="codex" {"CODEX_ROLLOUT_0_167_0_V1"} else {"CLAUDE_JSONL_2_1_319_V1"}, + "source_record_id":"r12_frozen_request","source_turn_id":if source=="codex" {Some("frozen_turn")} else {None}, + "model":null,"model_provenance":"UNKNOWN","counter_semantics":"REQUEST_DELTA", + "input_basis":if source=="codex" {"CODEX_TOTAL_INPUT"} else {"CLAUDE_UNCACHED_INPUT"}, + "input_tokens":7,"cached_input_tokens":null,"cache_write_input_tokens":null,"output_tokens":3,"reasoning_output_tokens":null}); + body["usage"] = json!({"schema_version":1,"status":"PARTIAL","reason":"OBSERVED_REQUEST_RECORDS","records":[record.clone()]}); + let body = body.to_string(); + let digest = capture::hash(&body); + database + .execute( + "UPDATE outbox SET body=?2,payload_hash=?3 WHERE session_id=?1", + rusqlite::params![session_id, body, digest], + ) + .unwrap(); + let ledger = json!({"records":[record],"record_revisions":[1],"queued":1,"incomplete":false,"held":false, + "consent_epoch":0,"baseline_epoch":0,"excluded_request_ids":[]}); + database + .execute( + "UPDATE sessions SET data=json_set(data,'$.usage_ledger',json(?2)) WHERE id=?1", + rusqlite::params![session_id, ledger.to_string()], + ) + .unwrap(); + (session_id, body, digest) +} + +#[test] +fn normal_usage_status_persists_changed_repository_revocation_after_exact_restoration() { + use keito_cli::cli::capture::CaptureEvent::{Prompt, Stop}; + let mut failures = Vec::new(); + let mut observations = Vec::new(); + for (selected, selected_version) in NAMESPACES { + for mutation in ["hint", "remote", "disabled"] { + let fixture = Fixture::new(); + // Every case uses TempDir cleanup; aggregate failure facts stay in the test log. + let canaries = fixture.source_canaries(); + let database = + rusqlite::Connection::open(fixture.capture.join("capture.sqlite3")).unwrap(); + let key = capture::hash(fixture.repo.join(".git").to_string_lossy().as_bytes()); + let mut store = Store::open(&fixture.capture).unwrap(); + let binding = store.binding(&key).unwrap().unwrap(); + let repo = capture::Repository { + key: binding.repository_key.clone(), + remote_hash: binding.remote_hash.clone(), + hint_hash: binding.hint_hash.clone(), + linked_without_hint: false, + disabled: false, + }; + let mut other = binding.clone(); + other.repository_key = capture::hash("r12-unrelated-repository"); + other.id = String::new(); + other.version = 0; + let other = store.approve(other).unwrap(); + let other_repo = capture::Repository { + key: other.repository_key.clone(), + remote_hash: other.remote_hash.clone(), + hint_hash: other.hint_hash.clone(), + linked_without_hint: false, + disabled: false, + }; + let mut frozen = Vec::new(); + for (namespace, version) in NAMESPACES { + r12_signal( + &mut store, + &repo, + (namespace, version, "11111111-1111-4111-8111-111111111111"), + (Prompt, "frozen_turn", 0), + ); + r12_signal( + &mut store, + &repo, + (namespace, version, "11111111-1111-4111-8111-111111111111"), + (Stop, "frozen_turn", 10), + ); + frozen.push(r12_freeze_numeric_fixture( + &database, + &binding, + namespace, + "11111111-1111-4111-8111-111111111111", + )); + r12_signal( + &mut store, + &repo, + (namespace, version, SESSION), + (Prompt, "active_turn", 20), + ); + r12_signal( + &mut store, + &other_repo, + (namespace, version, "33333333-3333-4333-8333-333333333333"), + (Prompt, "other_turn", 0), + ); + r12_signal( + &mut store, + &other_repo, + (namespace, version, "33333333-3333-4333-8333-333333333333"), + (Stop, "other_turn", 5), + ); + r12_signal( + &mut store, + &other_repo, + (namespace, version, "44444444-4444-4444-8444-444444444444"), + (Prompt, "other_active", 10), + ); + r12_policy(&database, &binding, namespace); + r12_policy(&database, &other, namespace); + } + drop(store); + let unrelated_before = r12_other_snapshot(&database, &other); + let original = fixture + .cli() + .args([ + "capture", "usage", "status", "--repo", "--agent", selected, "--json", + ]) + .output() + .unwrap(); + assert!(original.status.success()); + assert_eq!( + serde_json::from_slice::(&original.stdout).unwrap()["enabled"], + true + ); + if mutation == "remote" { + let result = fixture + .command(Path::new("/usr/bin/git")) + .args([ + "remote", + "add", + "origin", + "https://example.invalid/r12-changed", + ]) + .output() + .unwrap(); + assert!(result.status.success()); + } else { + fs::create_dir_all(fixture.repo.join(".keito")).unwrap(); + fs::write( + fixture.repo.join(".keito/config.yml"), + if mutation == "disabled" { + "agent_tracking:\n enabled: false\n" + } else { + "project_id: project_r12_changed\n" + }, + ) + .unwrap(); + } + let changed = fixture + .cli() + .args([ + "capture", "usage", "status", "--repo", "--agent", selected, "--json", + ]) + .output() + .unwrap(); + assert!(changed.status.success()); + let changed: Value = serde_json::from_slice(&changed.stdout).unwrap(); + let observed_raw: String = database + .query_row( + "SELECT data FROM bindings WHERE repo_key=?1", + [&binding.repository_key], + |row| row.get(0), + ) + .unwrap(); + let observed: Value = serde_json::from_str(&observed_raw).unwrap(); + let active_after_observe: i64=database.query_row("SELECT COUNT(*) FROM sessions WHERE binding_id=?1 AND json_type(data,'$.active')='object'",[&binding.id],|row|row.get(0)).unwrap(); + if mutation == "remote" { + let result = fixture + .command(Path::new("/usr/bin/git")) + .args(["remote", "remove", "origin"]) + .output() + .unwrap(); + assert!(result.status.success()); + } else { + fs::remove_file(fixture.repo.join(".keito/config.yml")).unwrap(); + } + let restored = fixture + .cli() + .args([ + "capture", "usage", "status", "--repo", "--agent", selected, "--json", + ]) + .output() + .unwrap(); + assert!(restored.status.success()); + fixture.assert_no_raw_leak(&restored); + let restored: Value = serde_json::from_slice(&restored.stdout).unwrap(); + let mut case_failures = Vec::new(); + for (okay, label) in [ + (changed["enabled"] == false, "changed-disabled"), + ( + observed["revoked"] == true && observed["paused"] == true, + "durable-binding", + ), + (active_after_observe == 0, "clock-abandoned"), + (restored["enabled"] == false, "restored-stays-disabled"), + ] { + if !okay { + case_failures.push(label); + } + } + for (namespace, _) in NAMESPACES { + let raw: String = database + .query_row( + "SELECT data FROM usage_consents WHERE binding_id=?1 AND namespace=?2", + rusqlite::params![binding.id, namespace], + |row| row.get(0), + ) + .unwrap(); + let policy: Value = serde_json::from_str(&raw).unwrap(); + if policy["enabled"] != false || policy["epoch"] != 11 { + case_failures.push("both-binding-policies-revoked"); + } + let raw:String=database.query_row("SELECT data FROM sessions WHERE binding_id=?1 AND source_id=?2 AND json_extract(data,'$.source_namespace')=?3",rusqlite::params![binding.id,SESSION,namespace],|row|row.get(0)).unwrap(); + let session: Value = serde_json::from_str(&raw).unwrap(); + if !session["active"].is_null() + || !session["segments"] + .as_array() + .unwrap() + .iter() + .any(|segment| { + segment["duration_seconds"] == 0 + && segment["completeness"] == "INCOMPLETE" + }) + { + case_failures.push("observed-clock-zero-incomplete"); + } + if !session["usage_ledger"]["baseline_epoch"].is_null() + || session["usage_ledger"]["consent_epoch"] + .as_u64() + .unwrap_or(0) + == 0 + { + case_failures.push("fresh-baseline-epoch-required"); + } + } + for (session_id, body, digest) in &frozen { + let after: (String, String, String) = database + .query_row( + "SELECT body,payload_hash,state FROM outbox WHERE session_id=?1", + [session_id], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .unwrap(); + if after.0 != *body || after.1 != *digest || after.2 != "held" { + case_failures.push("frozen-body-held-unchanged"); + } + } + for (event, turn) in [("stop", "active_turn"), ("prompt", "new_turn")] { + let input = json!({"session_id":SESSION,"turn_id":turn,"prompt_id":turn,"cwd":fixture.repo,"transcript_path":fixture.source(selected)}); + let output = fixture + .cli() + .args([ + "capture", + "hook", + "--agent", + selected, + "--event", + event, + "--harness-version", + selected_version, + ]) + .write_stdin(input.to_string()) + .output() + .unwrap(); + assert!(output.status.success()); + fixture.assert_no_raw_leak(&output); + } + let new_active:i64=database.query_row("SELECT COUNT(*) FROM sessions WHERE binding_id=?1 AND json_type(data,'$.active')='object'",[&binding.id],|row|row.get(0)).unwrap(); + if new_active != 0 { + case_failures.push("restored-cannot-resume-or-start-clock"); + } + if r12_other_snapshot(&database, &other) != unrelated_before { + case_failures.push("unrelated-repository-unchanged"); + } + for (path, bytes) in canaries { + assert_eq!(fs::read(path).unwrap(), bytes); + } + assert!(!fixture.capture.join("profiles").exists()); + observations.push(json!({"namespace":selected,"mutation":mutation,"fixture_cleanup":"TempDir","failures":case_failures})); + failures.extend( + case_failures + .iter() + .map(|failure| format!("{selected}/{mutation}/{failure}")), + ); + } + } + eprintln!("R12_STATUS_FIRST_OBSERVATIONS {}", json!(observations)); + assert!( + failures.is_empty(), + "R12 durable usage-status restoration failed: {}", + failures.join(", ") + ); +} diff --git a/tests/cli_integration.rs b/tests/cli_integration.rs index e8bc7e2..7595548 100644 --- a/tests/cli_integration.rs +++ b/tests/cli_integration.rs @@ -1,11 +1,12 @@ #![allow(deprecated)] use assert_cmd::Command; +#[cfg(unix)] +#[path = "support/mutation_environment.rs"] +mod mutation_isolation; use chrono::Local; use predicates::prelude::*; use std::fs; use std::path::Path; -#[cfg(unix)] -use std::process::Command as StdCommand; use wiremock::matchers::{body_json, header, method, path, query_param}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -31,6 +32,7 @@ fn write_test_config(home: &Path, api_url: &str) { fn command_with_mock_config(home: &Path, api_url: &str) -> Command { let mut cmd = Command::cargo_bin("keito").unwrap(); cmd.env("HOME", home) + .env("KEITO_CAPTURE_HOME", home.join("capture")) .env("XDG_CONFIG_HOME", home.join("config")) .env("APPDATA", home.join("AppData").join("Roaming")) .env("KEITO_API_URL", api_url) @@ -40,84 +42,21 @@ fn command_with_mock_config(home: &Path, api_url: &str) -> Command { cmd } -#[cfg(unix)] -fn prepend_path(cmd: &mut Command, dir: &Path) { - let mut paths = vec![dir.to_path_buf()]; - if let Some(current_path) = std::env::var_os("PATH") { - paths.extend(std::env::split_paths(¤t_path)); - } - cmd.env("PATH", std::env::join_paths(paths).unwrap()); -} - #[cfg(unix)] fn write_fake_skill_tools(home: &Path) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; let bin = home.join("bin"); - fs::create_dir_all(&bin).unwrap(); - + fs::create_dir(&bin).unwrap(); let npx = bin.join("npx"); fs::write( &npx, - r#"#!/usr/bin/env bash -set -euo pipefail -printf '%s\n' "$*" >> "$KEITO_FAKE_NPX_LOG" -echo "fake npx install output" -agent="" -while [ "$#" -gt 0 ]; do - if [ "$1" = "-a" ]; then - shift - agent="${1:-}" - fi - shift || true -done - -case "$agent" in - codex) - root="$HOME/.agents/skills/keito-time-track" - mkdir -p "$root/installers" - cat > "$root/installers/install-codex.sh" <<'SH' -#!/usr/bin/env bash -set -euo pipefail -echo "fake codex installer output" -mkdir -p "$HOME/.codex" -printf '{"hooks":{"SessionStart":[{"hooks":[{"command":"keito-time-track/hooks/session-start.sh"}]}],"Stop":[{"hooks":[{"command":"keito-time-track/hooks/session-end.sh"}]}]}}\n' > "$HOME/.codex/hooks.json" -SH - chmod +x "$root/installers/install-codex.sh" - ;; - claude-code) - root="$HOME/.claude/skills/keito-time-track" - mkdir -p "$root/installers" - cat > "$root/installers/install-claude-code.sh" <<'SH' -#!/usr/bin/env bash -set -euo pipefail -echo "fake claude installer output" -mkdir -p "$HOME/.claude" -printf '{"hooks":{"SessionStart":[{"hooks":[{"command":"keito-time-track/hooks/session-start.sh"}]}],"Stop":[{"hooks":[{"command":"keito-time-track/hooks/session-end.sh"}]}]}}\n' > "$HOME/.claude/settings.json" -SH - chmod +x "$root/installers/install-claude-code.sh" - ;; - *) - echo "unexpected agent: $agent" >&2 - exit 2 - ;; -esac -"#, + "#!/bin/sh\nprintf forbidden > \"$KEITO_FAKE_NPX_LOG\"\nexit 89\n", ) .unwrap(); - set_executable(&npx); - - let jq = bin.join("jq"); - fs::write(&jq, "#!/usr/bin/env bash\nexit 0\n").unwrap(); - set_executable(&jq); - + fs::set_permissions(&npx, fs::Permissions::from_mode(0o700)).unwrap(); bin } -#[cfg(unix)] -fn set_executable(path: &Path) { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); -} - #[test] fn help_flag_works() { Command::cargo_bin("keito") @@ -248,73 +187,76 @@ fn skill_help_works() { #[test] #[cfg(unix)] -fn skill_install_configures_agent_hooks_with_fake_skills_cli() { +fn unqualified_source_build_refuses_before_external_installer_or_profile_mutation() { let temp_dir = tempfile::tempdir().unwrap(); - let bin = write_fake_skill_tools(temp_dir.path()); - let npx_log = temp_dir.path().join("npx.log"); - - let mut cmd = Command::cargo_bin("keito").unwrap(); - prepend_path(&mut cmd, &bin); - let output = cmd - .env("HOME", temp_dir.path()) - .env("XDG_CONFIG_HOME", temp_dir.path().join("config")) - .env("APPDATA", temp_dir.path().join("AppData").join("Roaming")) - .env("KEITO_FAKE_NPX_LOG", &npx_log) - .env("KEITO_API_KEY", "kto_test_key") - .env("KEITO_ACCOUNT_ID", "co_test") + let case = temp_dir.path().canonicalize().unwrap(); + let home = case.join("home"); + fs::create_dir(&home).unwrap(); + let capture = home.join("capture"); + fs::create_dir(&capture).unwrap(); + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&capture, fs::Permissions::from_mode(0o700)).unwrap(); + let core = case.join("keito"); + fs::copy(assert_cmd::cargo::cargo_bin!("keito"), &core).unwrap(); + let environment = + mutation_isolation::checked(&case, &case, Some(&home), Some(&capture), Some(&core)) + .unwrap(); + let bin = write_fake_skill_tools(&home); + let log = home.join("npx.log"); + let mut cmd = Command::new(&environment.core); + cmd.env_clear().env("PATH", &bin); + cmd.env("XDG_CONFIG_HOME", home.join("config")) + .env("APPDATA", home.join("AppData")) + .env("HOME", &environment.home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("KEITO_CAPTURE_HOME", &environment.capture) + .env("KEITO_FAKE_NPX_LOG", &log) .args([ - "--json", "skill", "install", "--source", - "/tmp/keito-skill", + "/tmp/inert-unread-source", "--agent", "codex", - "--agent", - "claude-code", ]) .assert() - .success() - .get_output() - .stdout - .clone(); - - let status_json: serde_json::Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(status_json["authenticated"], true); - assert_eq!(status_json["codex"]["hooks_configured"], true); - assert_eq!(status_json["claude_code"]["hooks_configured"], true); - - let output_text = String::from_utf8(output).unwrap(); - assert!(!output_text.contains("fake npx install output")); - assert!(!output_text.contains("fake codex installer output")); - assert!(!output_text.contains("fake claude installer output")); - - let log = fs::read_to_string(npx_log).unwrap(); - assert!(log.contains("skills@1.5.6 add /tmp/keito-skill")); - assert!(log.contains("-a codex")); - assert!(log.contains("-a claude-code")); - assert!(temp_dir.path().join(".codex/hooks.json").exists()); - assert!(temp_dir.path().join(".claude/settings.json").exists()); + .failure() + .stderr(predicate::str::contains( + "official keito / keito-capture-guard release pair", + )); + assert!(!log.exists()); + assert!(!home.join(".codex").exists()); + assert!(!home.join(".claude").exists()); } #[test] #[cfg(unix)] -fn skill_install_uses_bundled_skill_by_default() { - if StdCommand::new("jq").arg("--version").output().is_err() { - return; - } - +fn unqualified_source_build_refuses_bundled_install_without_touching_profiles() { let temp_dir = tempfile::tempdir().unwrap(); - - let output = Command::cargo_bin("keito") - .unwrap() - .env("HOME", temp_dir.path()) - .env("XDG_CONFIG_HOME", temp_dir.path().join("config")) - .env("APPDATA", temp_dir.path().join("AppData").join("Roaming")) - .env("KEITO_API_KEY", "kto_test_key") - .env("KEITO_ACCOUNT_ID", "co_test") + let case = temp_dir.path().canonicalize().unwrap(); + let home = case.join("home"); + fs::create_dir(&home).unwrap(); + let capture = home.join("capture"); + fs::create_dir(&capture).unwrap(); + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&capture, fs::Permissions::from_mode(0o700)).unwrap(); + let core = case.join("keito"); + fs::copy(assert_cmd::cargo::cargo_bin!("keito"), &core).unwrap(); + let environment = + mutation_isolation::checked(&case, &case, Some(&home), Some(&capture), Some(&core)) + .unwrap(); + let bin = write_fake_skill_tools(&home); + Command::new(&environment.core) + .env_clear() + .env("XDG_CONFIG_HOME", home.join("config")) + .env("APPDATA", home.join("AppData")) + .env("PATH", &bin) + .env("HOME", &environment.home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("KEITO_CAPTURE_HOME", &environment.capture) .args([ - "--json", "skill", "install", "--agent", @@ -323,26 +265,12 @@ fn skill_install_uses_bundled_skill_by_default() { "claude-code", ]) .assert() - .success() - .get_output() - .stdout - .clone(); - - let status_json: serde_json::Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(status_json["authenticated"], true); - assert_eq!(status_json["codex"]["skill_installed"], true); - assert_eq!(status_json["codex"]["hooks_configured"], true); - assert_eq!(status_json["claude_code"]["skill_installed"], true); - assert_eq!(status_json["claude_code"]["hooks_configured"], true); - - assert!(temp_dir - .path() - .join(".codex/skills/keito-time-track/SKILL.md") - .exists()); - assert!(temp_dir - .path() - .join(".claude/skills/keito-time-track/SKILL.md") - .exists()); + .failure() + .stderr(predicate::str::contains( + "official keito / keito-capture-guard release pair", + )); + assert!(!home.join(".codex").exists()); + assert!(!home.join(".claude").exists()); } #[tokio::test] @@ -397,6 +325,7 @@ fn whoami_without_auth_fails() { .unwrap() .args(["auth", "whoami"]) .env("HOME", temp_dir.path()) + .env("KEITO_CAPTURE_HOME", temp_dir.path().join("capture")) .env("XDG_CONFIG_HOME", temp_dir.path().join("config")) .env_remove("KEITO_API_KEY") .env_remove("KEITO_ACCOUNT_ID") diff --git a/tests/fixtures/capture_native_origin.rs b/tests/fixtures/capture_native_origin.rs new file mode 100644 index 0000000..ac994ea --- /dev/null +++ b/tests/fixtures/capture_native_origin.rs @@ -0,0 +1,713 @@ +//! Cargo-linked inert SOURCE-FIXTURE native ancestor, never a real harness. +//! The two Cargo entrypoints bind their own literal supported version. +#[path = "../support/mutation_environment.rs"] +mod isolation; +use keito_cli::process_ownership::{ + io::IoPlan, + protocol::ProtocolError, + scope::{Scope, SlotId}, +}; +use std::{ + fs::{self, OpenOptions}, + io::{self, Read, Write}, + os::unix::fs::{MetadataExt, OpenOptionsExt}, + path::{Path, PathBuf}, + process::{Command, ExitStatus, Stdio}, + time::{Duration, Instant}, +}; +fn error() -> io::Error { + io::Error::other("OWNED_SOURCE_FIXTURE") +} +fn owned(path: &Path) -> PathBuf { + let canonical = path.canonicalize().expect("owned fixture path unavailable"); + assert_eq!(canonical, path, "owned fixture aliases are unsupported"); + let metadata = fs::symlink_metadata(path).unwrap(); + assert!(metadata.is_dir() && !metadata.file_type().is_symlink()); + assert_eq!(metadata.uid(), unsafe { libc::geteuid() }); + assert_eq!(metadata.mode() & 0o777, 0o700); + canonical +} +fn bounded(path: &Path, root: &Path, limit: u64) -> Vec { + assert!(path.starts_with(root)); + assert_eq!(path.canonicalize().unwrap(), path); + let metadata = fs::symlink_metadata(path).unwrap(); + assert!(metadata.is_file() && !metadata.file_type().is_symlink()); + assert_eq!(metadata.uid(), unsafe { libc::geteuid() }); + assert_eq!(metadata.nlink(), 1); + assert!(metadata.len() <= limit); + let mut bytes = Vec::new(); + fs::File::open(path) + .unwrap() + .take(limit + 1) + .read_to_end(&mut bytes) + .unwrap(); + assert!(bytes.len() as u64 <= limit); + bytes +} +fn environment(command: &mut Command, case: &Path, home: &Path, capture: &Path) { + command + .env_clear() + .current_dir(owned(&case.join("repo"))) + .env("HOME", home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("KEITO_CAPTURE_HOME", capture) + .env("XDG_CONFIG_HOME", home.join("config")) + .env("XDG_STATE_HOME", home.join("state")) + .env("APPDATA", home.join("AppData")) + .env("TMPDIR", owned(&case.join("tmp"))) + .env("PATH", owned(&case.join("bin"))) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null"); + #[cfg(target_os = "macos")] + command.env( + "__CF_USER_TEXT_ENCODING", + format!("0x{:X}:0:0", unsafe { libc::getuid() }), + ); +} +fn complete(scope: &mut Scope, slot: &SlotId) -> io::Result { + loop { + scope.poll(); + if scope.slot_complete(slot) { + return scope.slot_status(slot).ok_or_else(error); + } + if scope.failed() { + return Err(error()); + } + std::thread::sleep(Duration::from_millis(1)); + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum OpaqueDiagnostic { + NoOp, + GitDirect, + GitShim, +} +impl OpaqueDiagnostic { + fn parse(value: &std::ffi::OsStr) -> io::Result { + match value.to_str() { + Some("no-op") => Ok(Self::NoOp), + Some("git-direct") => Ok(Self::GitDirect), + Some("git-shim") => Ok(Self::GitShim), + _ => Err(error()), + } + } + fn code(self) -> u8 { + match self { + Self::NoOp => 1, + Self::GitDirect => 2, + Self::GitShim => 3, + } + } + fn command(self) -> Command { + let mut command = Command::new(match self { + Self::NoOp => "/usr/bin/true", + Self::GitDirect => "/Applications/Xcode.app/Contents/Developer/usr/bin/git", + Self::GitShim => "/usr/bin/git", + }); + if self != Self::NoOp { + command.args(["init", "--quiet"]); + } + command + } +} +fn diagnostic_clock() -> io::Result { + let mut value = unsafe { std::mem::zeroed::() }; + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut value) } != 0 + || !(0..1_000_000_000).contains(&value.tv_nsec) + { + return Err(error()); + } + u64::try_from(value.tv_sec) + .ok() + .and_then(|s| s.checked_mul(1_000_000_000)) + .and_then(|s| s.checked_add(value.tv_nsec as u64)) + .ok_or_else(error) +} +fn opaque_diagnostic( + scope: &mut Scope, + fields: &[std::ffi::OsString], + case: &Path, + home: &Path, + capture: &Path, + core: &Path, +) -> io::Result { + if fields.len() != 4 { + return Err(error()); + } + // No caller-selected executable, argv, environment or timeout. + let selected = OpaqueDiagnostic::parse(&fields[3])?; + let mut command = selected.command(); + environment(&mut command, case, home, capture); + let before = diagnostic_clock()?; + let prior_end = scope.hard_end(); + let result = keito_cli::source_qa_scope::run_fixture_opaque( + scope, + command, + IoPlan::new(Vec::new(), 8192, 8192)?, + core, + ); + let receipt = (|| -> io::Result<()> { + use std::os::unix::process::ExitStatusExt; + let after = diagnostic_clock()?; + let report = scope.report(); + let slots: Vec<_> = report + .slots + .iter() + .map(|slot| { + serde_json::json!({ + "slot":slot.slot, "status_code":slot.status.and_then(|s| s.code()), + "status_signal":slot.status.and_then(|s| s.signal()), + "status_raw":slot.status.map(|s| s.into_raw()), + "waits_known":slot.waits_known, "group_absent":slot.group_absent, + "terminal_eof":slot.terminal_eof, "io_required":slot.io_required, + "stdin_closed":slot.io.stdin_closed, "stdout_eof":slot.io.stdout_eof, + "stderr_eof":slot.io.stderr_eof, "accepted_at":slot.accepted_at, + "completion_end":slot.completion_end, "first_fault":slot.first_fault, + }) + }) + .collect(); + let value = serde_json::json!({"diagnostic_only":true, "selector_code":selected.code(), + "before_ns":before, "after_ns":after, "hard_end_before_ns":prior_end, + "hard_end_after_ns":scope.hard_end(), "operation_ok":result.is_ok(), + "first_fault":report.first_fault.map(|s| s.0), "finish_called":report.finish_called, + "all_resources":report.all_resources, "clean":report.clean, "slots":slots}); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(case.join("opaque-diagnostic.json"))?; + serde_json::to_writer(&mut file, &value)?; + file.write_all(b"\n")?; + file.sync_all() + })(); + match result { + Err(primary) => { + let _ = receipt; + Err(primary) + } + Ok(value) => { + receipt?; + Ok(value.status.code().unwrap_or(125)) + } + } +} +fn hook_probe_diagnostic(scope: &mut Scope, case: &Path, core: &Path) -> io::Result { + let mut count = 0u8; + let entry_end = scope.hard_end(); + let result = keito_cli::source_qa_scope::diagnose_fixture_hook_probes( + scope, + core, + &case.join("repo"), + |ordinal, before, after, operation_ok, report| { + if count >= 4 || ordinal != count + 1 { + return Err(error()); + } + count = ordinal; + let slots: Vec<_> = report + .slots + .iter() + .map(|slot| { + serde_json::json!({ + "slot":slot.slot, "status":slot.status.and_then(|s| s.code()), + "waits_known":slot.waits_known, "group_absent":slot.group_absent, + "terminal_eof":slot.terminal_eof, "io_required":slot.io_required, + "stdin_closed":slot.io.stdin_closed, "stdout_eof":slot.io.stdout_eof, + "stderr_eof":slot.io.stderr_eof, "accepted_at":slot.accepted_at, + "completion_end":slot.completion_end, "first_fault":slot.first_fault, + }) + }) + .collect(); + let value = serde_json::json!({"diagnostic_only":true, "ordinal":ordinal, + "before_ns":before, "after_ns":after, "operation_ok":operation_ok, + "entry_end_ns":entry_end, + "first_fault":report.first_fault.map(|s| s.0), + "finish_called":report.finish_called, "all_resources":report.all_resources, + "clean":report.clean, "slots":slots}); + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(case.join(format!("hook-probe-{ordinal:02}.json")))?; + serde_json::to_writer(&mut output, &value)?; + output.write_all(b"\n")?; + output.sync_all() + }, + ); + let report = scope.report(); + let summary = serde_json::json!({"diagnostic_only":true, "probes_observed":count, + "operation_ok":result.is_ok(), "first_fault":report.first_fault.map(|s| s.0), + "hard_end_ns":scope.hard_end(), "finish_called":report.finish_called, + "all_resources":report.all_resources, "clean":report.clean}); + let saved = (|| -> io::Result<()> { + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(case.join("hook-probe-summary.json"))?; + serde_json::to_writer(&mut output, &summary)?; + output.write_all(b"\n")?; + output.sync_all() + })(); + if saved.is_err() { + scope.begin_cancel(ProtocolError("QA_PROBE_SUMMARY"), scope.hard_end()); + } + match result { + Err(_) => Err(error()), + Ok(()) => { + saved?; + Ok(0) + } + } +} +fn repository_cohort_diagnostic(scope: &mut Scope, case: &Path, core: &Path) -> io::Result { + let entry_end = scope.hard_end(); + let mut observed = false; + let result = keito_cli::source_qa_scope::diagnose_fixture_repository_cohort( + scope, + core, + &case.join("repo"), + |before, after, operation_ok, report| { + if observed { + return Err(error()); + } + observed = true; + let slots: Vec<_> = report + .slots + .iter() + .map(|slot| { + serde_json::json!({ + "slot":slot.slot, "status":slot.status.and_then(|s| s.code()), + "setup_trace":slot.setup_trace.map(|trace| serde_json::json!({ + "setup_start_ns":trace.setup_start_ns, "ready_end_ns":trace.ready_end_ns, + "pre_spawn_ns":trace.pre_spawn_ns, "spawn_return_ns":trace.spawn_return_ns, + "first_ready_poll_ns":trace.first_ready_poll_ns, + "last_ready_before_ns":trace.last_ready_before_ns, + "last_ready_after_ns":trace.last_ready_after_ns, + "ready_frame_observed":trace.ready_frame_observed, + "ready_eof_observed":trace.ready_eof_observed, + "deadline_observed":trace.deadline_observed, + })), + "waits_known":slot.waits_known, "group_absent":slot.group_absent, + "terminal_eof":slot.terminal_eof, "io_required":slot.io_required, + "stdin_closed":slot.io.stdin_closed, "stdout_eof":slot.io.stdout_eof, + "stderr_eof":slot.io.stderr_eof, "accepted_at":slot.accepted_at, + "completion_end":slot.completion_end, "first_fault":slot.first_fault, + }) + }) + .collect(); + let value = serde_json::json!({"diagnostic_only":true, "repository_cohort":true, + "before_ns":before, "after_ns":after, "operation_ok":operation_ok, + "entry_end_ns":entry_end, "first_fault":report.first_fault.map(|s| s.0), + "finish_called":report.finish_called, "all_resources":report.all_resources, + "clean":report.clean, "slots":slots}); + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(case.join("repository-cohort.json"))?; + serde_json::to_writer(&mut output, &value)?; + output.write_all(b"\n")?; + output.sync_all() + }, + ); + let report = scope.report(); + let summary = serde_json::json!({"diagnostic_only":true, "repository_cohort":true, + "observed":observed, "operation_ok":result.is_ok(), + "first_fault":report.first_fault.map(|s| s.0), "hard_end_ns":scope.hard_end(), + "finish_called":report.finish_called, "all_resources":report.all_resources, + "clean":report.clean}); + let saved = (|| -> io::Result<()> { + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(case.join("repository-cohort-summary.json"))?; + serde_json::to_writer(&mut output, &summary)?; + output.write_all(b"\n")?; + output.sync_all() + })(); + if saved.is_err() { + scope.begin_cancel(ProtocolError("QA_PROBE_SUMMARY"), scope.hard_end()); + } + match result { + Err(_) => Err(error()), + Ok(()) => { + saved?; + Ok(0) + } + } +} + +// Developer-only failure diagnosis. Never serialize argv, environment, command +// output or arbitrary io::Error text; keep the original operation error primary. +fn failure_receipt( + arguments: &[std::ffi::OsString], + scope: &Scope, + finality: bool, +) -> io::Result<()> { + let mode = arguments + .first() + .and_then(|s| s.to_str()) + .ok_or_else(error)?; + let offset = match mode { + "--chain" => 2, + "--cli" + | "--installer-phases-diagnostic" + | "--run" + | "--git-init" + | "--opaque-diagnostic" + | "--hook-probe-diagnostic" + | "--repository-cohort-diagnostic" => 1, + _ => return Err(error()), + }; + let fields = arguments.get(offset..offset + 3).ok_or_else(error)?; + let root = Path::new(&fields[0]); + let case = Path::new(&fields[1]); + let home = case.join("home"); + let capture = home.join("capture"); + isolation::checked( + root, + case, + Some(&home), + Some(&capture), + Some(Path::new(&fields[2])), + ) + .map_err(|_| error())?; + let report = scope.report(); + let slots: Vec<_> = report + .slots + .iter() + .map(|slot| { + serde_json::json!({ + "slot": slot.slot, "status": slot.status.and_then(|status| status.code()), + "waits_known": slot.waits_known, "group_absent": slot.group_absent, + "terminal_eof": slot.terminal_eof, "io_required": slot.io_required, + "stdin_closed": slot.io.stdin_closed, "stdout_eof": slot.io.stdout_eof, + "stderr_eof": slot.io.stderr_eof, "accepted_at": slot.accepted_at, + "completion_end": slot.completion_end, "first_fault": slot.first_fault, + }) + }) + .collect(); + let value = serde_json::json!({"source_fixture_diagnosis_only": true, + "late_final_facts": finality, "first_fault": report.first_fault.map(|fault| fault.0), + "hard_end_ns": scope.hard_end(), "finish_called": report.finish_called, + "all_resources": report.all_resources, "clean": report.clean, "slots": slots}); + let name = if finality { + "native-owner-FINAL.json" + } else { + "native-owner-FIRST.json" + }; + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(case.join(name))?; + serde_json::to_writer(&mut output, &value)?; + output.write_all(b"\n")?; + output.sync_all() +} +fn execute(scope: &mut Scope, arguments: &[std::ffi::OsString]) -> io::Result { + let mode = arguments + .first() + .and_then(|s| s.to_str()) + .ok_or_else(error)?; + let chain = mode == "--chain"; + let depth = if chain { + assert_eq!(arguments.len(), 8); + let depth = arguments[1].to_str().unwrap().parse::().unwrap(); + assert!(depth <= 8); + Some(depth) + } else { + None + }; + let fields = if chain { + &arguments[2..] + } else { + &arguments[1..] + }; + assert!(matches!( + mode, + "--cli" + | "--installer-phases-diagnostic" + | "--run" + | "--chain" + | "--git-init" + | "--opaque-diagnostic" + | "--hook-probe-diagnostic" + | "--repository-cohort-diagnostic" + )); + assert!(fields.len() >= 3); + let root = owned(Path::new(&fields[0])); + let case = owned(Path::new(&fields[1])); + assert!(case.starts_with(&root)); + let home = owned(&case.join("home")); + let capture = owned(&home.join("capture")); + let core = PathBuf::from(&fields[2]); + let marker = case.join("constructor-must-not-run"); + for absent in [0, 1, 2] { + let invalid = isolation::checked( + &root, + &case, + (absent != 0).then_some(home.as_path()), + (absent != 1).then_some(capture.as_path()), + (absent != 2).then_some(core.as_path()), + ); + if invalid.is_ok() { + fs::write(&marker, b"unsafe").unwrap(); + } + assert!(!marker.exists()); + } + let checked = + isolation::checked(&root, &case, Some(&home), Some(&capture), Some(&core)).unwrap(); + assert_eq!(checked.core, core); + assert_eq!(checked.home, home); + assert_eq!(checked.capture, capture); + for relative in [".codex", ".claude", "config", "state", "AppData"] { + owned(&home.join(relative)); + } + if mode == "--hook-probe-diagnostic" { + assert_eq!(fields.len(), 3); + return hook_probe_diagnostic(scope, &case, &core); + } + if mode == "--repository-cohort-diagnostic" { + assert_eq!(fields.len(), 3); + return repository_cohort_diagnostic(scope, &case, &core); + } + if mode == "--opaque-diagnostic" { + return opaque_diagnostic(scope, fields, &case, &home, &capture, &core); + } + if mode == "--git-init" { + assert_eq!(fields.len(), 3); + let mut command = Command::new(if cfg!(target_os = "macos") { + "/Applications/Xcode.app/Contents/Developer/usr/bin/git" + } else { + "/usr/bin/git" + }); + environment(&mut command, &case, &home, &capture); + command.args(["init", "--quiet"]); + let result = keito_cli::source_qa_scope::run_fixture_opaque( + scope, + command, + IoPlan::new(Vec::new(), 8192, 8192)?, + &core, + )?; + return Ok(result.status.code().unwrap_or(125)); + } + if mode == "--cli" || mode == "--installer-phases-diagnostic" { + let mut command = Command::new(&checked.core); + environment(&mut command, &case, &home, &capture); + if mode == "--installer-phases-diagnostic" { + assert_eq!(fields.len(), 3); + command + .args([ + "--quiet", + "skill", + "install", + "--source", + "bundled", + "--agent", + "codex", + "--agent", + "claude-code", + ]) + .env("KEITO_SOURCE_QA_INSTALL_PHASE_TRACE", "v1"); + } else { + assert!(fields.len() >= 4); + command.args(&fields[3..]); + } + command + .stdin(Stdio::null()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()); + let child = scope.start_cooperative(command)?; + return Ok(complete(scope, &child)?.code().unwrap_or(125)); + } + assert_eq!(fields.len(), 6, "run root case core command event result"); + if let Some(depth) = depth.filter(|depth| *depth > 0) { + let image = std::env::current_exe().unwrap(); + assert!(image.starts_with(&root) && image.canonicalize().unwrap() == image); + let metadata = fs::symlink_metadata(&image).unwrap(); + assert!(metadata.is_file() && !metadata.file_type().is_symlink() && metadata.nlink() == 1); + assert_eq!(metadata.uid(), unsafe { libc::geteuid() }); + let mut next = Command::new(&image); + environment(&mut next, &case, &home, &capture); + next.arg("--chain") + .arg((depth - 1).to_string()) + .args(fields) + .stdin(Stdio::null()); + let child = scope.start_cooperative(next)?; + return Ok(complete(scope, &child)?.code().unwrap_or(125)); + } + let command = String::from_utf8(bounded(Path::new(&fields[3]), &case, 64 * 1024)).unwrap(); + let event = bounded(Path::new(&fields[4]), &case, 1024 * 1024); + let result = PathBuf::from(&fields[5]); + assert_eq!(result.parent().unwrap(), case); + // Exclusive receipt failure occurs at actual completion, never pre-launch. + let mut process = Command::new("/bin/bash"); + environment(&mut process, &case, &home, &capture); + process.args(["-c", &command]); + let started = Instant::now(); + let child = scope.start_cooperative_with_io(process, IoPlan::new(event, 0, 0)?)?; + let status = complete(scope, &child)?; + let resources = scope.finish().clean; + let elapsed = started.elapsed().as_secs_f64() * 1000.0; + let value = serde_json::json!({"source_fixture_only":true,"exit_code":status.code(), + "host_timeout":elapsed >= 1000.0,"elapsed_ms":elapsed,"resources_clean":resources}); + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .open(result)?; + serde_json::to_writer(&mut output, &value)?; + output.write_all(b"\n")?; + output.sync_all()?; + if !resources || elapsed >= 1000.0 || !status.success() { + return Err(error()); + } + Ok(0) +} +fn operation_duration(arguments: &[std::ffi::OsString]) -> u64 { + if arguments.len() == 4 + && arguments[0] == "--installer-phases-diagnostic" + && arguments[1..] + .iter() + .all(|value| Path::new(value).is_absolute()) + { + return keito_cli::process_ownership::scope::INSTALL_OPERATION_NS; + } + let hook = arguments + .first() + .is_some_and(|mode| mode == "--run" || mode == "--chain"); + if arguments.first().is_some_and(|mode| { + mode == "--hook-probe-diagnostic" || mode == "--repository-cohort-diagnostic" + }) { + 500_000_000 + } else if hook { + 1_000_000_000 + } else { + 4_000_000_000 + } +} +pub(super) fn run(version: &'static str) -> i32 { + let arguments: Vec<_> = std::env::args_os().skip(1).collect(); + let duration = operation_duration(&arguments); + let mut scope = match Scope::entry_from_environment(duration) { + Ok(Some(scope)) => scope, + Ok(None) => { + let mut clock = unsafe { std::mem::zeroed::() }; + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut clock) } != 0 { + return 1; + } + let at = (clock.tv_sec as u64) + .saturating_mul(1_000_000_000) + .saturating_add(clock.tv_nsec as u64); + match Scope::local_entry(at.saturating_add(duration)) { + Ok(scope) => scope, + Err(_) => return 1, + } + } + Err(_) => return 1, + }; + let result = if arguments.len() == 1 && arguments[0] == "--version" { + println!("owned-inert-source-fixture {version}"); + Ok(0) + } else { + execute(&mut scope, &arguments) + }; + if result.is_err() { + let _ = failure_receipt(&arguments, &scope, false); + scope.begin_cancel( + ProtocolError("FIXTURE_OPERATION_OR_RECEIPT"), + scope.hard_end(), + ); + } + let clean = scope.finish().clean && result.as_ref().is_ok_and(|code| *code == 0); + if result.is_err() { + let _ = failure_receipt(&arguments, &scope, true); + } + if !scope.publish_terminal(clean) { + return 1; + } + result.unwrap_or(1) +} + +#[cfg(test)] +mod diagnostic_tests { + use super::*; + #[test] + fn installer_policy_fixture_selects_only_the_closed_installation_route() { + let args = |values: &[&str]| { + values + .iter() + .map(std::ffi::OsString::from) + .collect::>() + }; + assert_eq!( + operation_duration(&args(&[ + "--installer-phases-diagnostic", + "/owned/root", + "/owned/root/case", + "/owned/root/pair/keito" + ])), + 30_000_000_000 + ); + for values in [ + vec!["--installer-phases-diagnostic"], + vec![ + "--installer-phases-diagnostic", + "relative", + "/case", + "/core", + ], + vec![ + "--installer-phases-diagnostic", + "/root", + "/case", + "/core", + "extra", + ], + vec!["--cli", "/root", "/case", "/core", "capture", "status"], + vec!["--opaque-diagnostic", "/root", "/case", "/core", "no-op"], + vec!["--version"], + ] { + assert_eq!(operation_duration(&args(&values)), 4_000_000_000); + } + assert_eq!(operation_duration(&args(&["--run"])), 1_000_000_000); + assert_eq!(operation_duration(&args(&["--chain"])), 1_000_000_000); + assert_eq!( + operation_duration(&args(&["--hook-probe-diagnostic"])), + 500_000_000 + ); + } + #[test] + fn opaque_diagnostic_selector_refuses_programs_and_extra_arguments() { + for value in [ + "", + "/bin/sh", + "git", + "git-direct --version", + "git-shim;true", + "NO-OP", + ] { + assert!(OpaqueDiagnostic::parse(std::ffi::OsStr::new(value)).is_err()); + } + assert_eq!( + OpaqueDiagnostic::parse(std::ffi::OsStr::new("no-op")).unwrap(), + OpaqueDiagnostic::NoOp + ); + assert_eq!( + OpaqueDiagnostic::parse(std::ffi::OsStr::new("git-direct")).unwrap(), + OpaqueDiagnostic::GitDirect + ); + assert_eq!( + OpaqueDiagnostic::parse(std::ffi::OsStr::new("git-shim")).unwrap(), + OpaqueDiagnostic::GitShim + ); + } +} diff --git a/tests/fixtures/claude_native_origin.rs b/tests/fixtures/claude_native_origin.rs new file mode 100644 index 0000000..f6e1711 --- /dev/null +++ b/tests/fixtures/claude_native_origin.rs @@ -0,0 +1,9 @@ +#[cfg(unix)] +#[path = "capture_native_origin.rs"] +mod origin; +fn main() { + #[cfg(unix)] + std::process::exit(origin::run("2.1.319")); + #[cfg(not(unix))] + std::process::exit(1); +} diff --git a/tests/fixtures/codex_native_origin.rs b/tests/fixtures/codex_native_origin.rs new file mode 100644 index 0000000..2918dc5 --- /dev/null +++ b/tests/fixtures/codex_native_origin.rs @@ -0,0 +1,9 @@ +#[cfg(unix)] +#[path = "capture_native_origin.rs"] +mod origin; +fn main() { + #[cfg(unix)] + std::process::exit(origin::run("0.167.0")); + #[cfg(not(unix))] + std::process::exit(1); +} diff --git a/tests/fixtures/source_qa_protocol_vectors.json b/tests/fixtures/source_qa_protocol_vectors.json new file mode 100644 index 0000000..479b868 --- /dev/null +++ b/tests/fixtures/source_qa_protocol_vectors.json @@ -0,0 +1,181 @@ +{ + "schema": 1, + "cases": [ + { + "name": "empty-child-eof", + "parent": false, + "close_writer": true, + "expected": "fault", + "chunks": [] + }, + { + "name": "parent-eof-before-live", + "parent": true, + "close_writer": true, + "expected": "cancel", + "chunks": [] + }, + { + "name": "live-open", + "parent": false, + "close_writer": false, + "expected": "pending", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n" + ] + }, + { + "name": "terminal-open", + "parent": false, + "close_writer": false, + "expected": "pending", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|SETTLED|12345\n" + ] + }, + { + "name": "clean-zero-children", + "parent": false, + "close_writer": true, + "expected": "clean", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|SETTLED|12345\n" + ] + }, + { + "name": "valid-depth-eight", + "parent": false, + "close_writer": true, + "expected": "clean", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12345|12346|00000000000000000000000000000001|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12346|12347|00000000000000000000000000000002|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12347|12348|00000000000000000000000000000003|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12348|12349|00000000000000000000000000000004|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12349|12350|00000000000000000000000000000005|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12350|12351|00000000000000000000000000000006|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12351|12352|00000000000000000000000000000007|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12352|12353|00000000000000000000000000000008|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12352|12353|00000000000000000000000000000008|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12351|12352|00000000000000000000000000000007|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12350|12351|00000000000000000000000000000006|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12349|12350|00000000000000000000000000000005|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12348|12349|00000000000000000000000000000004|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12347|12348|00000000000000000000000000000003|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12346|12347|00000000000000000000000000000002|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12345|12346|00000000000000000000000000000001|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|SETTLED|12345\n" + ] + }, + { + "name": "reused-pid-new-nonce-after-wait", + "parent": false, + "close_writer": true, + "expected": "clean", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12345|12346|00000000000000000000000000000001|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12345|12346|00000000000000000000000000000001|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12345|12346|00000000000000000000000000000002|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12345|12346|00000000000000000000000000000002|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|SETTLED|12345\n" + ] + }, + { + "name": "duplicate-open-pid-new-nonce", + "parent": false, + "close_writer": true, + "expected": "fault", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12345|12346|00000000000000000000000000000001|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12345|12346|00000000000000000000000000000002|1\n" + ] + }, + { + "name": "closed-child-cannot-register", + "parent": false, + "close_writer": true, + "expected": "fault", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12345|12346|00000000000000000000000000000001|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|WAITED|12345|12346|00000000000000000000000000000001|0\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12346|12347|00000000000000000000000000000002|1\n" + ] + }, + { + "name": "cycle-to-root", + "parent": false, + "close_writer": true, + "expected": "fault", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12345|12346|00000000000000000000000000000001|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12346|12345|00000000000000000000000000000002|1\n" + ] + }, + { + "name": "unwaited-child-terminal", + "parent": false, + "close_writer": true, + "expected": "fault", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|REGISTER|12345|12346|00000000000000000000000000000001|1\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|SETTLED|12345\n" + ] + }, + { + "name": "noncanonical-integer", + "parent": false, + "close_writer": true, + "expected": "fault", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|012345\n" + ] + }, + { + "name": "failed-terminal", + "parent": false, + "close_writer": true, + "expected": "fault", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|FAILED|12345\n" + ] + }, + { + "name": "deadline-cancel", + "parent": true, + "close_writer": true, + "expected": "cancel", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|CANCEL|12345|100\n" + ] + }, + { + "name": "legacy-cancel-missing-deadline", + "parent": true, + "close_writer": true, + "expected": "fault", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|CANCEL|12345\n" + ] + }, + { + "name": "terminal-trailing-raw", + "parent": false, + "close_writer": true, + "expected": "fault", + "chunks": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|LIVE|12345\n", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|SETTLED|12345\n", + "trailing" + ] + } + ] +} diff --git a/tests/fixtures/table-output-controls.json b/tests/fixtures/table-output-controls.json new file mode 100644 index 0000000..cfb9b77 --- /dev/null +++ b/tests/fixtures/table-output-controls.json @@ -0,0 +1,107 @@ +[ + { + "expected": "╭────┬───────┬──────┬───────────┬──────────┬────────╮\n│ ID │ Name │ Code │ Client │ Billable │ Active │\n├────┼───────┼──────┼───────────┼──────────┼────────┤\n│ p1 │ Build │ K1 │ Synthetic │ Yes │ No │\n╰────┴───────┴──────┴───────────┴──────────┴────────╯", + "items": [ + { + "client": { + "id": "c1", + "name": "Synthetic" + }, + "code": "K1", + "id": "p1", + "is_active": false, + "is_billable": true, + "name": "Build" + } + ], + "name": "projects" + }, + { + "expected": "╭────┬───────────┬──────────┬────────╮\n│ ID │ Name │ Currency │ Active │\n├────┼───────────┼──────────┼────────┤\n│ c1 │ Synthetic │ GBP │ Yes │\n╰────┴───────────┴──────────┴────────╯", + "items": [ + { + "currency": "GBP", + "id": "c1", + "is_active": true, + "name": "Synthetic" + } + ], + "name": "clients" + }, + { + "expected": "╭────┬────────┬──────────╮\n│ ID │ Name │ Billable │\n├────┼────────┼──────────┤\n│ t1 │ Design │ Yes │\n╰────┴────────┴──────────╯", + "items": [ + { + "billable_by_default": true, + "currency": "GBP", + "id": "t1", + "is_active": true, + "name": "Design" + } + ], + "name": "tasks" + }, + { + "expected": "╭────┬────────────┬─────────┬────────┬────────────┬────────────────────────────────────────────────────┬─────────╮\n│ ID │ Date │ Project │ Task │ Duration │ Notes │ Running │\n├────┼────────────┼─────────┼────────┼────────────┼────────────────────────────────────────────────────┼─────────┤\n│ e1 │ 2026-11-08 │ Build │ Design │ 2m │ Synthetic │ │\n│ │ │ │ │ │ second line │ │\n│ e2 │ │ │ │ running... │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx │ Yes │\n╰────┴────────────┴─────────┴────────┴────────────┴────────────────────────────────────────────────────┴─────────╯", + "items": [ + { + "duration_seconds": 90, + "id": "e1", + "is_running": false, + "notes": "Synthetic\nsecond line", + "project": { + "id": "p1", + "name": "Build" + }, + "spent_date": "2026-11-08", + "task": { + "id": "t1", + "name": "Design" + } + }, + { + "id": "e2", + "is_running": true, + "notes": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + } + ], + "name": "entries" + }, + { + "expected": "╭────────────────┬───────────────────────────╮\n│ key │ value │\n├────────────────┼───────────────────────────┤\n│ User ID │ u1 │\n│ Name │ Synthetic Person │\n│ Email │ synthetic@example.invalid │\n│ Credential │ full access │\n│ Company │ Synthetic │\n│ Company ID │ w1 │\n│ Can track time │ Yes │\n╰────────────────┴───────────────────────────╯", + "items": [ + { + "capabilities": { + "can_track_time": true + }, + "company": { + "id": "w1", + "name": "Synthetic" + }, + "email": "synthetic@example.invalid", + "first_name": "Synthetic", + "id": "u1", + "last_name": "Person", + "roles": [ + "admin" + ] + } + ], + "name": "identity" + }, + { + "expected": "╭───────┬───────╮\n│ key │ value │\n├───────┼───────┤\n│ alpha │ Hello │\n│ count │ 2 │\n╰───────┴───────╯", + "items": [ + { + "alpha": "Hello", + "count": 2 + } + ], + "name": "fallback" + }, + { + "expected": "No results.", + "items": [], + "name": "empty" + } +] diff --git a/tests/man_pages.rs b/tests/man_pages.rs index f5a665a..0f95dfc 100644 --- a/tests/man_pages.rs +++ b/tests/man_pages.rs @@ -1,3 +1,4 @@ +#![cfg(feature = "dev-tools")] #![allow(deprecated)] use assert_cmd::Command; @@ -7,6 +8,19 @@ use std::fs; const EXPECTED_PAGES: &[&str] = &[ "keito.1", "keito-help.1", + "keito-capture.1", + "keito-capture-setup.1", + "keito-capture-worker.1", + "keito-capture-worker-status.1", + "keito-capture-worker-uninstall.1", + "keito-capture-status.1", + "keito-capture-preview.1", + "keito-capture-sync.1", + "keito-capture-hook.1", + "keito-capture-pause.1", + "keito-capture-resume.1", + "keito-capture-disable.1", + "keito-capture-disable-all.1", "keito-auth.1", "keito-auth-help.1", "keito-auth-login.1", @@ -26,8 +40,10 @@ const EXPECTED_PAGES: &[&str] = &[ "keito-skill.1", "keito-skill-help.1", "keito-skill-doctor.1", + "keito-skill-uninstall.1", "keito-skill-install.1", "keito-skill-status.1", + "keito-skill-runtime.1", "keito-skill-team-init.1", "keito-time.1", "keito-time-help.1", diff --git a/tests/mutation_environment.rs b/tests/mutation_environment.rs new file mode 100644 index 0000000..4ad7405 --- /dev/null +++ b/tests/mutation_environment.rs @@ -0,0 +1,66 @@ +//! Marker-only regression: no installer, hook, provider or real profile calls. +#![cfg(unix)] +#[path = "support/mutation_environment.rs"] +mod isolation; +use std::{fs, path::Path}; +#[test] +fn missing_or_foreign_mutation_environment_never_reaches_a_write() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let home = root.join("home"); + let capture = home.join("capture"); + fs::create_dir_all(&capture).unwrap(); + let core = root.join("owned-core"); + fs::write(&core, b"developer fixture, never executed").unwrap(); + let marker = capture.join("mutation-must-not-happen"); + let cases = [ + (None, Some(capture.as_path()), Some(core.as_path())), + (Some(home.as_path()), None, Some(core.as_path())), + ( + Some(Path::new("/foreign-profile")), + Some(capture.as_path()), + Some(core.as_path()), + ), + ( + Some(home.as_path()), + Some(Path::new("/foreign-capture")), + Some(core.as_path()), + ), + ( + Some(home.as_path()), + Some(capture.as_path()), + Some(Path::new("/foreign-real-cli")), + ), + ]; + for (home, capture, core) in cases { + let result = isolation::checked(&root, &root, home, capture, core); + assert!(result.is_err()); + if result.is_ok() { + fs::write(&marker, b"unsafe").unwrap(); + } + assert!(!marker.exists()); + } + let valid = isolation::checked(&root, &root, Some(&home), Some(&capture), Some(&core)).unwrap(); + assert_eq!(valid.home, home); + assert_eq!(valid.core, core); + fs::write(valid.capture.join("valid-fixture-marker"), b"isolated").unwrap(); +} +#[test] +fn owned_temporary_harness_symlinks_are_refused_before_mutation() { + for name in [".codex", ".claude"] { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let home = root.join("home"); + let capture = home.join("capture"); + fs::create_dir_all(&capture).unwrap(); + let core = root.join("owned-core"); + fs::write(&core, b"never executed").unwrap(); + let other = root.join("other-owned-fixture"); + fs::create_dir(&other).unwrap(); + std::os::unix::fs::symlink(&other, home.join(name)).unwrap(); + assert!( + isolation::checked(&root, &root, Some(&home), Some(&capture), Some(&core)).is_err() + ); + assert_eq!(fs::read_dir(other).unwrap().count(), 0); + } +} diff --git a/tests/native-adapter-tests.sh b/tests/native-adapter-tests.sh new file mode 100755 index 0000000..d395d7e --- /dev/null +++ b/tests/native-adapter-tests.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Development only. Public services receive explicit TempDir profile roots; +# fault-process tests additionally validate HOME/CAPTURE before constructing a child. +set -euo pipefail +repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) +profile=${KEITO_TEST_REAL_PROFILE_HOME:?Set the original user-profile anchor for digest-only verification} +profile_fingerprint() { + local file + for file in "$profile/.codex/hooks.json" "$profile/.claude/settings.json"; do + [ ! -L "$file" ] || return 1 + if [ -f "$file" ]; then + shasum -a 256 < "$file" || return 1 + elif [ ! -e "$file" ]; then + printf '%s\n' MISSING + else + return 1 + fi + done +} +[ -d "$profile" ] || exit 1 +baseline=$(profile_fingerprint) +readonly profile baseline +verify_baseline() { + local result=$? after + after=$(profile_fingerprint) || result=98 + if [ "$after" != "$baseline" ]; then + echo 'Global profile changed during local verification; stop and preserve evidence.' >&2 + result=98 + fi + exit "$result" +} +trap verify_baseline EXIT +cd "$repo" +cargo test --offline --lib skill_adapter::implementation::tests:: -- --nocapture +cargo test --offline --lib capture_mapping::implementation::tests:: -- --nocapture diff --git a/tests/native_capture_guard.rs b/tests/native_capture_guard.rs new file mode 100644 index 0000000..ca2905c --- /dev/null +++ b/tests/native_capture_guard.rs @@ -0,0 +1,348 @@ +//! Native guard acceptance. Every process, even a fail-before-write case, must +//! receive explicit temporary HOME/capture roots and a run-owned core path. +#![cfg(unix)] +#[path = "support/mutation_environment.rs"] +mod isolation; +use std::{ + fs, + io::Write, + path::{Path, PathBuf}, + process::{Command, Stdio}, + sync::OnceLock, + time::{Duration, Instant}, +}; +struct Run { + _temp: tempfile::TempDir, + root: PathBuf, + core: PathBuf, +} +fn run() -> &'static Run { + static RUN: OnceLock = OnceLock::new(); + RUN.get_or_init(||{ + let temp=tempfile::tempdir().unwrap();let root=temp.path().canonicalize().unwrap();let source=root.join("fake-core.rs");let core=root.join("fake-core"); + fs::write(&source,r#"use std::{fs::{self,File,OpenOptions},io::{Read,Write},os::{fd::FromRawFd,unix::net::UnixStream},net::Shutdown,time::Duration}; +unsafe extern "C"{fn fcntl(fd:i32,cmd:i32,...)->i32;} +fn main(){ +assert_eq!(std::env::var("KEITO_PROCESS_OWNER_FD").unwrap(),"4"); +assert_eq!(std::env::var("KEITO_PROCESS_OWNER_CONTRACT").unwrap(),"2"); +let owner_nonce=std::env::var("KEITO_PROCESS_OWNER_NONCE").unwrap(); +assert_eq!(owner_nonce.len(),32); +let mut owner=unsafe{UnixStream::from_raw_fd(4)}; +owner.write_all(format!("{}|LIVE|{}\n",owner_nonce,std::process::id()).as_bytes()).unwrap(); +let image_fd=std::env::var("KEITO_CAPTURE_IMAGE_FD").unwrap().parse::().unwrap();for fd in 4..256{if fd!=image_fd && fd!=4{assert_eq!(unsafe{fcntl(fd,1)},-1,"unexpected inherited descriptor {fd}");}}let image=unsafe{File::from_raw_fd(image_fd)};assert!(image.metadata().unwrap().is_file());drop(image);assert_eq!(unsafe{fcntl(image_fd,1)},-1,"image descriptor must close before core parsing");let mode=std::env::var("NATIVE_TEST_CORE_MODE").unwrap();let home=std::path::PathBuf::from(std::env::var_os("KEITO_CAPTURE_HOME").unwrap());let nonce=std::env::var("KEITO_CAPTURE_INVOCATION_NONCE").unwrap();let flag=home.join("capture-invocations").join(format!("{nonce}.pending"));assert!(flag.exists(),"core entered before durable flag");if mode=="stall"{std::thread::sleep(Duration::from_secs(5));return;}let mut bytes=Vec::new();std::io::stdin().read_to_end(&mut bytes).unwrap();if let Some(path)=std::env::var_os("NATIVE_TEST_INPUT_LOG"){fs::write(path,bytes).unwrap();}if mode=="edit"{let mut file=OpenOptions::new().write(true).truncate(true).open(&flag).unwrap();file.write_all(b"UNEXPECTED_SAME_INODE_EDIT").unwrap();file.sync_all().unwrap();}if mode!="missing"{let fd=std::env::var("KEITO_CAPTURE_ACK_FD").unwrap().parse::().unwrap();let mut file=unsafe{File::from_raw_fd(fd)};file.write_all(b"KEITO_CAPTURE_DURABLE_V1\n").unwrap();if mode=="extra"{file.write_all(b"extra").unwrap();}}if mode=="ack-stall"{std::thread::sleep(Duration::from_secs(5));}if mode=="nonzero"{std::process::exit(23);} +// This inert core owns no descendants. A valid durable ACK alone is still +// insufficient: separately settle its cooperative resource endpoint. +if mode!="missing-terminal"{ +owner.write_all(format!("{}|SETTLED|{}\n",owner_nonce,std::process::id()).as_bytes()).unwrap(); +owner.shutdown(Shutdown::Write).unwrap(); +}} + +"#).unwrap();assert!(Command::new("rustc").args(["--edition=2021","-C","opt-level=s","-C","strip=symbols"]).arg(&source).arg("-o").arg(&core).status().unwrap().success());Run{_temp:temp,root,core} +}) +} +struct Scope { + _temp: tempfile::TempDir, + root: PathBuf, + home: PathBuf, + capture: PathBuf, +} +impl Scope { + fn new() -> Self { + let temp = tempfile::Builder::new() + .prefix("case-") + .tempdir_in(&run().root) + .unwrap(); + let root = temp.path().canonicalize().unwrap(); + let home = root.join("home"); + fs::create_dir(&home).unwrap(); + let capture = home.join("capture"); + fs::create_dir(&capture).unwrap(); + let bin = root.join("bin"); + fs::create_dir(&bin).unwrap(); + let poison = bin.join("keito"); + fs::write( + &poison, + "#!/bin/sh\nprintf forbidden > REAL_CLI_FALLBACK_CALLED\nexit 89\n", + ) + .unwrap(); + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&capture, fs::Permissions::from_mode(0o700)).unwrap(); + fs::set_permissions(poison, fs::Permissions::from_mode(0o700)).unwrap(); + Self { + _temp: temp, + root, + home, + capture, + } + } + fn command(&self, core: &Path, mode: &str) -> Command { + let environment = isolation::checked( + &run().root, + &self.root, + Some(&self.home), + Some(&self.capture), + Some(core), + ) + .expect("refusing non-isolated mutation command"); + let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("keito-capture-guard")); + cmd.env_clear() + .current_dir(&self.root) + .env("PATH", self.root.join("bin")) + .env("HOME", &environment.home) + .env("CODEX_HOME", environment.home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", environment.home.join(".claude")) + .env("KEITO_CAPTURE_HOME", &environment.capture) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env_remove("KEITO_CLI_BIN") + .env_remove("KEITO_CAPTURE_INVOCATION_NONCE") + .env_remove("KEITO_CAPTURE_ACK_FD") + .env( + "KEITO_CAPTURE_CORE_SHA256", + keito_cli::capture::hash(fs::read(&run().core).unwrap()), + ) + .env("NATIVE_TEST_CORE_MODE", mode) + .env_remove("KEITO_API_KEY") + .env_remove("KEITO_ACCOUNT_ID") + .args(["--core"]) + .arg(&environment.core) + .args([ + "--agent", + "codex", + "--event", + "stop", + "--harness-version", + "0.167.0", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + cmd + } + fn invoke(&self, mode: &str) -> std::process::Output { + let mut child = self.command(&run().core, mode).spawn().unwrap(); + let _ = child + .stdin + .take() + .unwrap() + .write_all(b"PRIVATE_NATIVE_HOOK_CANARY"); + let output = child.wait_with_output().unwrap(); + assert!(!self.root.join("REAL_CLI_FALLBACK_CALLED").exists()); + output + } + fn flags(&self) -> Vec { + match fs::read_dir(self.capture.join("capture-invocations")) { + Ok(entries) => entries.map(|entry| entry.unwrap().path()).collect(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => vec![], + Err(error) => panic!("fixture capture inventory failed: {error}"), + } + } +} +#[test] +fn native_guard_publishes_before_core_and_cleans_only_exact_zero_exit_ack() { + for mode in [ + "ack", + "missing", + "extra", + "nonzero", + "edit", + "missing-terminal", + ] { + let scope = Scope::new(); + let log = scope.root.join("input.log"); + let mut command = scope.command(&run().core, mode); + command.env("NATIVE_TEST_INPUT_LOG", &log); + let mut child = command.spawn().unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(b"PRIVATE_NATIVE_HOOK_CANARY") + .unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success()); + assert!( + output.stdout.is_empty() && output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fs::read(log).unwrap(), b"PRIVATE_NATIVE_HOOK_CANARY"); + assert_eq!(scope.flags().len(), usize::from(mode != "ack"), "{mode}"); + } +} +#[test] +fn native_guard_never_entered_core_deadline_retains_durable_unknown() { + let scope = Scope::new(); + let started = Instant::now(); + let output = scope.invoke("stall"); + assert!(output.status.success()); + assert!(started.elapsed() < Duration::from_secs(1)); + assert_eq!(scope.flags().len(), 1); + assert_eq!( + fs::read(&scope.flags()[0]).unwrap(), + b"KEITO_CAPTURE_PENDING_V1\n" + ); +} +#[test] +fn native_guard_parallel_flags_are_distinct_and_visible_within_existing_budget() { + let scope = Scope::new(); + let mut children = Vec::new(); + for _ in 0..2 { + let mut child = scope.command(&run().core, "stall").spawn().unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(b"PRIVATE_NATIVE_HOOK_CANARY") + .unwrap(); + children.push(child); + } + let started = Instant::now(); + loop { + let pending = scope.capture.join("capture-invocations"); + let count = fs::read_dir(&pending) + .map(|entries| { + entries + .filter_map(Result::ok) + .filter(|e| e.file_name().to_string_lossy().ends_with(".pending")) + .count() + }) + .unwrap_or(0); + if count == 2 { + break; + } + if started.elapsed() >= Duration::from_millis(500) { + let flags = scope.flags(); + for child in children { + let output = child.wait_with_output().unwrap(); + eprintln!("guard stderr={}", String::from_utf8_lossy(&output.stderr)); + } + panic!("two ordinary pending flags must appear without warming; flags={flags:?}"); + } + std::thread::sleep(Duration::from_millis(5)); + } + for child in children { + assert!(child.wait_with_output().unwrap().status.success()); + } + assert_eq!(scope.flags().len(), 2); +} +#[test] +fn missing_run_owned_core_never_falls_back_to_a_real_cli() { + let scope = Scope::new(); + let missing = scope.root.join("missing-core"); + let output = scope.command(&missing, "missing").output().unwrap(); + assert!(output.status.success()); + assert_eq!(scope.flags().len(), 1); +} + +#[test] +fn an_ack_without_child_exit_never_clears_uncertainty() { + let scope = Scope::new(); + let started = Instant::now(); + assert!(scope.invoke("ack-stall").status.success()); + assert!(started.elapsed() < Duration::from_secs(1)); + assert_eq!(scope.flags().len(), 1); +} +#[test] +fn invocation_capacity_publishes_global_refusal_without_core_launch_or_eviction() { + use std::os::unix::fs::PermissionsExt; + let scope = Scope::new(); + let flags = scope.capture.join("capture-invocations"); + fs::create_dir(&flags).unwrap(); + fs::set_permissions(&flags, fs::Permissions::from_mode(0o700)).unwrap(); + for i in 0..1024 { + let path = flags.join(format!("{i:064x}.pending")); + fs::write(&path, b"KEITO_CAPTURE_PENDING_V1\n").unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap(); + } + let log = scope.root.join("MUST_NOT_ENTER_CORE"); + let mut command = scope.command(&run().core, "ack"); + command.env("NATIVE_TEST_INPUT_LOG", &log); + assert!(command.output().unwrap().status.success()); + assert!(!log.exists()); + assert_eq!(scope.flags().len(), 1024); + let refusals: Vec<_> = fs::read_dir(&scope.capture) + .unwrap() + .filter_map(Result::ok) + .filter(|e| { + e.file_name() + .to_string_lossy() + .starts_with("capture-refusal-") + }) + .collect(); + assert_eq!(refusals.len(), 1); + let value: serde_json::Value = + serde_json::from_slice(&fs::read(refusals[0].path()).unwrap()).unwrap(); + assert_eq!(value["reason"], "QUEUE_LIMIT_REACHED"); + assert_eq!(value.as_object().unwrap().len(), 3); +} + +#[test] +fn native_guard_timeout_handoff_reconciles_prior_open_turn_as_incomplete() { + use keito_cli::capture::{self, Binding, Clock, Repository, Signal, Store}; + use keito_cli::cli::capture::CaptureEvent::{Prompt, Stop}; + let scope = Scope::new(); + let repo = Repository { + key: capture::hash("native-handoff-repo"), + remote_hash: capture::hash("remote"), + hint_hash: capture::hash("hint"), + linked_without_hint: false, + disabled: false, + }; + let mut store = Store::open(&scope.capture).unwrap(); + store + .approve(Binding { + repository_key: repo.key.clone(), + remote_hash: repo.remote_hash.clone(), + hint_hash: repo.hint_hash.clone(), + id: String::new(), + version: 0, + workspace_id: "co_test".into(), + owner_id: "owner".into(), + origin_hash: capture::hash("origin"), + project_id: "p".into(), + task_id: "t".into(), + agents: vec!["codex".into()], + paused: false, + revoked: false, + }) + .unwrap(); + let mut opened = Clock::now().unwrap(); + opened.wall -= 90; + opened.monotonic -= 90; + store + .event( + &repo, + Signal { + source: "codex", + resumed: false, + source_id: "native", + turn_id: Some("turn"), + version: "0.167.0", + event: Prompt, + clock: &opened, + }, + ) + .unwrap(); + assert!(scope.invoke("stall").status.success()); + assert_eq!(scope.flags().len(), 1); + store + .event( + &repo, + Signal { + source: "codex", + resumed: false, + source_id: "native", + turn_id: Some("turn"), + version: "0.167.0", + event: Stop, + clock: &Clock::now().unwrap(), + }, + ) + .unwrap(); + let session = &store.preview("native").unwrap()[0]; + assert_eq!(session.segments[0].duration_seconds, 0); + assert_eq!(session.segments[0].completeness, "INCOMPLETE"); + assert!(session.needs_attention); + assert!(store.status().unwrap().storage_paused); +} diff --git a/tests/native_runtime_pair.rs b/tests/native_runtime_pair.rs new file mode 100644 index 0000000..96145e6 --- /dev/null +++ b/tests/native_runtime_pair.rs @@ -0,0 +1,96 @@ +//! Native replacement for abandoned Python-pin tests. No installed profile, +//! interpreter, harness, or executable is ever invoked by these fixtures. +#![cfg(unix)] +use keito_cli::{capture, capture_runtime_pair::verify}; +use serde_json::json; +use std::{ + fs, + os::unix::fs::{symlink, PermissionsExt}, + path::PathBuf, +}; +struct Pair { + _temp: tempfile::TempDir, + core: PathBuf, + guard: PathBuf, + manifest: PathBuf, + hash: String, +} +impl Pair { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let core = root.join("keito"); + let guard = root.join("keito-capture-guard"); + let manifest = root.join("capture-runtime-manifest.json"); + fs::write(&core, b"inert core fixture; must never execute").unwrap(); + fs::write(&guard, b"inert guard fixture; must never execute").unwrap(); + for path in [&core, &guard] { + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + } + let hash = capture::hash(fs::read(&guard).unwrap()); + fs::write(&manifest, json!({"manifest_contract":1,"version":"0.2.0","target":"test-target","guard_contract":2,"files":{"keito":capture::hash(fs::read(&core).unwrap()),"keito-capture-guard":hash}}).to_string()).unwrap(); + Self { + _temp: temp, + core, + guard, + manifest, + hash, + } + } + fn valid(&self) -> bool { + verify(&self.core, &self.hash, "0.2.0", "test-target").is_ok() + } +} +#[test] +fn exact_compiled_anchor_and_manifest_qualify_without_execution() { + let p = Pair::new(); + assert!(p.valid()); +} +#[test] +fn unsigned_adjacent_manifest_cannot_replace_compiled_anchor() { + let p = Pair::new(); + assert!(verify(&p.core, &"0".repeat(64), "0.2.0", "test-target").is_err()); + assert!(verify(&p.core, "", "0.2.0", "test-target").is_err()); +} +#[test] +fn changed_or_missing_guard_stays_unqualified() { + let p = Pair::new(); + fs::write(&p.guard, b"changed").unwrap(); + assert!(!p.valid()); + fs::remove_file(&p.guard).unwrap(); + assert!(!p.valid()); +} +#[test] +fn altered_core_or_manifest_is_unqualified() { + let p = Pair::new(); + fs::write(&p.core, b"changedcore").unwrap(); + assert!(!p.valid()); + let p = Pair::new(); + fs::write(&p.manifest, b"{}").unwrap(); + assert!(!p.valid()); +} +#[test] +fn target_version_contract_and_extra_manifest_fields_refuse() { + let p = Pair::new(); + assert!(verify(&p.core, &p.hash, "0.2.1", "test-target").is_err()); + assert!(verify(&p.core, &p.hash, "0.2.0", "other-target").is_err()); + let mut v: serde_json::Value = serde_json::from_slice(&fs::read(&p.manifest).unwrap()).unwrap(); + v["untrusted_extra"] = json!(true); + fs::write(&p.manifest, v.to_string()).unwrap(); + assert!(!p.valid()); + v.as_object_mut().unwrap().remove("untrusted_extra"); + v["guard_contract"] = json!(1); + fs::write(&p.manifest, v.to_string()).unwrap(); + assert!(!p.valid()); +} +#[test] +fn symlinked_or_writable_guard_refuses() { + let p = Pair::new(); + fs::set_permissions(&p.guard, fs::Permissions::from_mode(0o777)).unwrap(); + assert!(!p.valid()); + let p = Pair::new(); + let replacement = p.guard.with_extension("replacement"); + fs::rename(&p.guard, &replacement).unwrap(); + symlink(&replacement, &p.guard).unwrap(); + assert!(!p.valid()); +} diff --git a/tests/run-macos-isolated.sh b/tests/run-macos-isolated.sh new file mode 100755 index 0000000..a92f29d --- /dev/null +++ b/tests/run-macos-isolated.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# Single inherited policy; never nest sandbox-exec inside an existing sandbox. +set -euo pipefail +repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) +profile=${KEITO_TEST_REAL_PROFILE_HOME:?Set the original profile for digest-only verification} +original_home=${HOME:?} +cargo_home=${CARGO_HOME:-$original_home/.cargo} +rustup_home=${RUSTUP_HOME:-$original_home/.rustup} +cargo_bin=${KEITO_TEST_CARGO_BIN:-} +rustc_bin=${KEITO_TEST_RUSTC_BIN:-} +if [ -z "$cargo_bin" ]; then cargo_bin=$(rustup which cargo); fi +if [ -z "$rustc_bin" ]; then rustc_bin=$(rustup which rustc); fi +cargo_jobs=${CARGO_BUILD_JOBS:-2} +test_threads=${RUST_TEST_THREADS:-1} +case "$cargo_jobs:$test_threads" in *[!0-9:]*|:*|*:) echo 'Concurrency bounds must be positive integers' >&2; exit 2;; esac +[ "$cargo_jobs" -ge 1 ] && [ "$cargo_jobs" -le 2 ] && [ "$test_threads" -eq 1 ] || { echo 'Use at most two Cargo jobs and exactly one test thread' >&2; exit 2; } +export CARGO_BUILD_JOBS="$cargo_jobs" RUST_TEST_THREADS="$test_threads" +profile_fingerprint() { + local relative file + for relative in .codex/hooks.json .codex/config.toml .claude/settings.json; do + file="$profile/$relative" + [ ! -L "$file" ] || return 1 + if [ -f "$file" ]; then shasum -a 256 < "$file"; elif [ ! -e "$file" ]; then printf '%s\n' MISSING; else return 1; fi + done +} +before=$(profile_fingerprint) +readonly profile before +source_manifest_parent= +verify_profile() { + local result=$? after complete_result=0 + if [ -n "$source_manifest_parent" ]; then + if PYTHONDONTWRITEBYTECODE=1 python3 "$repo/tests/support/source_qa_manifest.py" verify-complete \ + "$repo" "$source_manifest_parent" > "$source_manifest_parent/source-qa-outer-complete.log" 2>&1; then + complete_result=0 + else + complete_result=$? + fi + printf 'original_exit=%s\nsource_complete_exit=%s\n' "$result" "$complete_result" > "$source_manifest_parent/source-qa-outer-result.txt" + if [ "$result" -eq 0 ] && [ "$complete_result" -ne 0 ]; then result=$complete_result; fi + fi + after=$(profile_fingerprint) || result=98 + if [ "$after" != "$before" ]; then echo 'Operator profile changed; preserve evidence and stop.' >&2; result=98; fi + exit "$result" +} +trap verify_profile EXIT +cd "$repo" +target_dir=${CARGO_TARGET_DIR:-$repo/target} +mkdir -p "$target_dir" +target_dir=$(cd "$target_dir" && pwd -P) +CARGO_TARGET_DIR="$target_dir" CARGO_NET_OFFLINE=true cargo build --locked --features dev-tools --bin check-service-boundary +root=$(mktemp -d /tmp/keito-native-tests.XXXXXX) +root=$(cd "$root" && pwd -P) +chmod 700 "$root" +"$target_dir/debug/check-service-boundary" prepare "$root" +printf 'Owned test boundary: %s\n' "$root" +# Read-only source Git membership is collected before the kernel boundary. +PYTHONDONTWRITEBYTECODE=1 python3 "$repo/tests/support/source_qa_manifest.py" collect \ + "$repo" "$root" > "$root/source-qa-outer-collect.log" +source_manifest_parent=$root +# This is the only sandbox application. Both checker and Cargo inherit it. +env -i HOME="$root/home" CODEX_HOME="$root/home/.codex" CLAUDE_CONFIG_DIR="$root/home/.claude" \ + KEITO_CAPTURE_HOME="$root/home/capture" XDG_CONFIG_HOME="$root/home/config" APPDATA="$root/home/AppData" \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null PATH="$PATH" \ + CARGO_HOME="$cargo_home" RUSTUP_HOME="$rustup_home" CARGO_TARGET_DIR="$target_dir" \ + CARGO_NET_OFFLINE=true CARGO_BUILD_JOBS="$cargo_jobs" RUST_TEST_THREADS="$test_threads" RUSTFLAGS="${RUSTFLAGS:-}" RUSTUP_TOOLCHAIN="${RUSTUP_TOOLCHAIN:-stable}" \ + KEITO_TEST_RUSTC_BIN="$rustc_bin" \ + /usr/bin/sandbox-exec -f "$root/boundary.sb" /bin/bash "$repo/tests/support/run-inherited-suite.sh" \ + "$root/owned-checker" "$root" "$cargo_bin" "$@" diff --git a/tests/skill_hooks.rs b/tests/skill_hooks.rs index 18a193c..f311997 100644 --- a/tests/skill_hooks.rs +++ b/tests/skill_hooks.rs @@ -1,13 +1,21 @@ -#![allow(deprecated)] - -#[cfg(unix)] -use assert_cmd::Command; - +//! The former Python integration wrapper is preserved in the dated evidence +//! archive. Native installer/mapping acceptance lives in the Rust module tests; +//! process/ACK/deadline acceptance lives in native_capture_guard.rs. #[test] -#[cfg(unix)] -fn bundled_skill_hooks_record_sessions_with_fake_keito() { - Command::new("bash") - .arg("tests/skill_hooks.sh") - .assert() - .success(); +fn active_capture_bundle_contains_no_python_or_development_test_payload() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("skills/keito-time-track"); + fn visit(path: &std::path::Path) { + for entry in std::fs::read_dir(path).unwrap() { + let path = entry.unwrap().path(); + assert_ne!(path.extension().and_then(|s| s.to_str()), Some("py")); + assert_ne!(path.file_name().and_then(|s| s.to_str()), Some("tests")); + if path.is_dir() { + visit(&path); + } + } + } + visit(&root); + let dispatch = std::fs::read_to_string(root.join("hooks/dispatch.sh")).unwrap(); + assert!(dispatch.contains("KEITO_CAPTURE_GUARD_BIN")); + assert!(!dispatch.contains("python")); } diff --git a/tests/skill_hooks.sh b/tests/skill_hooks.sh index a078bf5..766bcb2 100755 --- a/tests/skill_hooks.sh +++ b/tests/skill_hooks.sh @@ -1,248 +1,6 @@ #!/usr/bin/env bash +# Development-only entry point; native focused tests are run directly, never +# recursively from a cargo test process. set -euo pipefail - repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) -skill_root="$repo_root/skills/keito-time-track" -tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT - -export HOME="$tmp/home" -export KEITO_SKILL_HOME="$tmp/skill-home" -mkdir -p "$HOME" "$KEITO_SKILL_HOME" "$tmp/bin" "$tmp/repo/.keito" - -cat > "$tmp/repo/.keito/config.yml" <<'YAML' -version: 1 -workspace_id: co_test -project_id: p1 -project_name: "Project A" -task_id: t1 -task_name: "Development" -agent_tracking: - enabled: true - source: agent - draft: true - min_duration_seconds: 60 - max_duration_seconds: 28800 - redact_notes: false -metadata: - env: test -YAML - -cat > "$tmp/bin/keito" <<'SH' -#!/usr/bin/env bash -printf '%s\n' "$*" >> "$KEITO_FAKE_CALLS" -case "$*" in - *"time session-record"*) - printf '{"status":"created","entry_id":"te_test","source":"agent","session_id":"sess_test"}\n' - ;; - *"auth status"*) - printf '{"authenticated":true,"api_key_valid":true,"account_id":"co_test"}\n' - ;; - *"clients list"*) - printf '[{"id":"c1","name":"Client A"}]\n' - ;; - *"clients create"*) - printf '{"id":"c_new","name":"New Client"}\n' - ;; - *"projects list"*"--client c_new"*) - printf '[]\n' - ;; - *"projects list"*) - printf '[{"id":"p1","name":"Project A","code":"PA"}]\n' - ;; - *"projects create"*) - if [ "${KEITO_FAKE_BAD_PROJECT_CREATE:-}" = "1" ]; then - printf '{"name":"New Project"}\n' - exit 0 - fi - printf '{"id":"p_new","name":"New Project","client":{"id":"c_new","name":"New Client"}}\n' - ;; - *"projects tasks"*) - printf '[{"id":"t1","name":"Development"}]\n' - ;; - *"time list"*) - printf '[]\n' - ;; - *) - printf '{}\n' - ;; -esac -SH -chmod +x "$tmp/bin/keito" - -export PATH="$tmp/bin:$PATH" -export KEITO_FAKE_CALLS="$tmp/keito-calls.log" -export KEITO_CLI_BIN="$tmp/bin/keito" - -payload=$(jq -n --arg cwd "$tmp/repo" --arg session_id "sess_test" \ - '{cwd: $cwd, session_id: $session_id, last_assistant_message: "Implemented a local test feature."}') - -"$skill_root/hooks/session-start.sh" <<< "$payload" -state_file=$(find "$KEITO_SKILL_HOME/sessions" -type f -name '*.json' | head -n 1) -[ -f "$state_file" ] - -jq '.started_epoch = (.started_epoch - 65)' "$state_file" > "$state_file.tmp" -mv "$state_file.tmp" "$state_file" - -"$skill_root/hooks/session-end.sh" <<< "$payload" - -if find "$KEITO_SKILL_HOME/sessions" -type f -name '*.json' | grep -q .; then - echo "Expected session state to be removed after successful logging" >&2 - exit 1 -fi - -grep -q -- "time session-record" "$KEITO_FAKE_CALLS" -grep -q -- "--workspace co_test" "$KEITO_FAKE_CALLS" -grep -q -- "--project p1" "$KEITO_FAKE_CALLS" -grep -q -- "--task t1" "$KEITO_FAKE_CALLS" -grep -q -- "--session-id sess_test" "$KEITO_FAKE_CALLS" -grep -q -- "--source agent" "$KEITO_FAKE_CALLS" - -short_payload=$(jq -n --arg cwd "$tmp/repo" --arg session_id "short_session" \ - '{cwd: $cwd, session_id: $session_id}') -"$skill_root/hooks/session-start.sh" <<< "$short_payload" -"$skill_root/hooks/session-end.sh" <<< "$short_payload" -if grep -q -- "short_session" "$KEITO_FAKE_CALLS"; then - echo "Expected short session to be skipped" >&2 - exit 1 -fi - -mkdir -p "$tmp/repo-alpha/.keito" "$tmp/repo-beta/.keito" "$tmp/untracked-repo" -cat > "$tmp/repo-alpha/.keito/config.yml" <<'YAML' -version: 1 -workspace_id: co_test -client_id: c_alpha -project_id: p_alpha -project_name: "Project Alpha" -task_id: t_alpha -task_name: "Development" -agent_tracking: - enabled: true - source: agent - draft: true - min_duration_seconds: 60 - max_duration_seconds: 28800 - redact_notes: false -metadata: - env: alpha -YAML -cat > "$tmp/repo-beta/.keito/config.yml" <<'YAML' -version: 1 -workspace_id: co_test -client_id: c_beta -project_id: p_beta -project_name: "Project Beta" -task_id: t_beta -task_name: "Development" -agent_tracking: - enabled: true - source: agent - draft: true - min_duration_seconds: 60 - max_duration_seconds: 28800 - redact_notes: false -metadata: - env: beta -YAML - -alpha_payload=$(jq -n --arg cwd "$tmp/repo-alpha" --arg session_id "sess_alpha" \ - '{cwd: $cwd, session_id: $session_id, last_assistant_message: "Alpha repo work."}') -beta_payload=$(jq -n --arg cwd "$tmp/repo-beta" --arg session_id "sess_beta" \ - '{cwd: $cwd, session_id: $session_id, last_assistant_message: "Beta repo work."}') -untracked_payload=$(jq -n --arg cwd "$tmp/untracked-repo" --arg session_id "sess_untracked" \ - '{cwd: $cwd, session_id: $session_id}') - -"$skill_root/hooks/session-start.sh" <<< "$alpha_payload" -"$skill_root/hooks/session-start.sh" <<< "$beta_payload" -"$skill_root/hooks/session-start.sh" <<< "$untracked_payload" - -for tracked_state in "$KEITO_SKILL_HOME/sessions/sess_alpha.json" "$KEITO_SKILL_HOME/sessions/sess_beta.json"; do - [ -f "$tracked_state" ] - jq '.started_epoch = (.started_epoch - 65)' "$tracked_state" > "$tracked_state.tmp" - mv "$tracked_state.tmp" "$tracked_state" -done - -"$skill_root/hooks/session-end.sh" <<< "$alpha_payload" -"$skill_root/hooks/session-end.sh" <<< "$beta_payload" -"$skill_root/hooks/session-end.sh" <<< "$untracked_payload" - -alpha_call=$(grep -- "--session-id sess_alpha" "$KEITO_FAKE_CALLS") -beta_call=$(grep -- "--session-id sess_beta" "$KEITO_FAKE_CALLS") -if [[ "$alpha_call" != *"--project p_alpha"* ]] || [[ "$alpha_call" == *"--project p_beta"* ]]; then - echo "Expected alpha repo session to use only alpha project config" >&2 - exit 1 -fi -if [[ "$beta_call" != *"--project p_beta"* ]] || [[ "$beta_call" == *"--project p_alpha"* ]]; then - echo "Expected beta repo session to use only beta project config" >&2 - exit 1 -fi -if grep -q -- "sess_untracked" "$KEITO_FAKE_CALLS"; then - echo "Expected untracked repo session not to log time" >&2 - exit 1 -fi - -mkdir -p "$tmp/setup-repo" -( - cd "$tmp/setup-repo" - printf '1\n1\n1\nY\nY\n' | "$skill_root/scripts/setup-wizard.sh" >/dev/null -) -[ -f "$tmp/setup-repo/.keito/config.yml" ] -grep -q -- "client_id: c1" "$tmp/setup-repo/.keito/config.yml" -grep -q -- "project_id: p1" "$tmp/setup-repo/.keito/config.yml" -grep -q -- "task_id: t1" "$tmp/setup-repo/.keito/config.yml" -grep -q -- "integration: keito_skill" "$tmp/setup-repo/.keito/config.yml" - -status_output=$( - cd "$tmp/setup-repo" - "$skill_root/scripts/status.sh" -) -grep -q -- "Workspace: co_test" <<< "$status_output" -grep -q -- "Client: Client A (c1)" <<< "$status_output" -grep -q -- "Project: Project A (p1)" <<< "$status_output" - -( - cd "$tmp/setup-repo" - printf 'Y\n' | "$skill_root/scripts/disable.sh" >/dev/null -) -[ ! -f "$tmp/setup-repo/.keito/config.yml" ] -find "$tmp/setup-repo/.keito" -name 'config.yml.disabled*' | grep -q . - -mkdir -p "$tmp/setup-create-repo" -( - cd "$tmp/setup-create-repo" - printf '2\nNew Client\n1\nNew Project\n1\nY\nY\n' | "$skill_root/scripts/setup-wizard.sh" >/dev/null -) -[ -f "$tmp/setup-create-repo/.keito/config.yml" ] -grep -q -- "client_id: c_new" "$tmp/setup-create-repo/.keito/config.yml" -grep -q -- "project_id: p_new" "$tmp/setup-create-repo/.keito/config.yml" -grep -q -- "integration: keito_skill" "$tmp/setup-create-repo/.keito/config.yml" - -mkdir -p "$tmp/setup-cancel-repo" -( - cd "$tmp/setup-cancel-repo" - printf '1\n1\n1\nY\nn\n' | "$skill_root/scripts/setup-wizard.sh" >/dev/null -) -if [ -e "$tmp/setup-cancel-repo/.keito/config.yml" ]; then - echo "Expected setup wizard cancellation not to write config" >&2 - exit 1 -fi - -mkdir -p "$tmp/setup-fail-repo" -set +e -( - cd "$tmp/setup-fail-repo" - printf '2\nNew Client\n1\nNew Project\n' | KEITO_FAKE_BAD_PROJECT_CREATE=1 "$skill_root/scripts/setup-wizard.sh" >/dev/null 2>"$tmp/setup-fail.err" -) -setup_fail_status=$? -set -e -if [ "$setup_fail_status" -eq 0 ]; then - echo "Expected setup wizard to fail when project create response has no id" >&2 - exit 1 -fi -if [ -e "$tmp/setup-fail-repo/.keito/config.yml" ]; then - echo "Expected setup wizard not to write config after failed project creation" >&2 - exit 1 -fi -grep -q -- "created project id" "$tmp/setup-fail.err" - -echo "skill hook tests passed" +exec "$repo_root/tests/native-adapter-tests.sh" diff --git a/tests/support/guarded_usage_acceptance.py b/tests/support/guarded_usage_acceptance.py new file mode 100644 index 0000000..9621c91 --- /dev/null +++ b/tests/support/guarded_usage_acceptance.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +"""Developer-only normal-route SOURCE-FIXTURE acceptance, never production code. + +Requires an already built, truly embedded-anchor owned pair and owned inert Rust +native fixtures. No synthetic Rust approval constructor, provider, auth, actual +harness, original profile or release-candidate qualification is involved. +Run inside the one proved inherited source-test kernel policy, never nested. +""" +from pathlib import Path +import hashlib +import json +import os +import sqlite3 +import subprocess +import sys +import time +import uuid +from source_qa_children import OwnedChildren, diagnosed_owned_operation +from source_qa_protocol import SourceOwner + +ROOT, PAIR, NATIVES, OUTPUT = (Path(value) for value in sys.argv[1:]) +for path in [ROOT, PAIR, NATIVES, OUTPUT]: + assert path.is_absolute() and path.resolve(strict=True) == path + assert path.stat().st_uid == os.getuid() and path.stat().st_mode & 0o777 == 0o700 +assert PAIR.is_relative_to(ROOT) and NATIVES.is_relative_to(ROOT) and OUTPUT.is_relative_to(ROOT) +CORE = PAIR / "keito" +CONTROLLER = NATIVES / "codex-inert-source-only" +assert CORE.is_file() and CORE.resolve() == CORE +sequence = 0 + + +def sha(value): + return hashlib.sha256(value).hexdigest() + + +def observe(value): + global sequence + sequence += 1 + with (OUTPUT / f"{sequence:04d}.json").open("x") as output: + json.dump({"source_fixture_only": True, **value}, output, indent=2) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + + +def environment(case): + home = case / "home" + result = {"HOME": str(home), "CODEX_HOME": str(home / ".codex"), + "CLAUDE_CONFIG_DIR": str(home / ".claude"), + "KEITO_CAPTURE_HOME": str(home / "capture"), + "XDG_CONFIG_HOME": str(home / "config"), "XDG_STATE_HOME": str(home / "state"), + "APPDATA": str(home / "AppData"), "TMPDIR": str(case / "tmp"), + "PATH": str(case / "bin"), "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"} + if sys.platform == "darwin": + result["__CF_USER_TEXT_ENCODING"] = f"0x{os.getuid():X}:0:0" + return result + + +def owned_runtime(case, arguments, seconds, limit=0, diagnostic=None): + label = "runtime-" + uuid.uuid4().hex + manager = OwnedChildren(case, environment(case), case, owner=OWNER) + def operation(active): + slot = active.start(label, arguments, seconds, capture_limit=limit) + output = active.complete(slot) + return subprocess.CompletedProcess(arguments, slot["child"].returncode, output or b"", b"") + if diagnostic is None: + with manager: + return operation(manager) + return diagnosed_owned_operation( + manager, operation, diagnostic, + lambda record: print(json.dumps({"guarded_failure_diagnostic": record}, sort_keys=True), + file=sys.stderr, flush=True)) + + +def cli(case, arguments): + # The owned Rust --cli gateway calls actual isolation::checked plus inert + # missing-operand negatives before it constructs the product Command. + result = owned_runtime(case, [str(CONTROLLER), "--cli", str(ROOT), str(case), str(CORE), *arguments], 4, 8192) + return result + + +def make_case(namespace): + case = ROOT / ("numeric-" + namespace + "-" + uuid.uuid4().hex) + case.mkdir(mode=0o700) + for relative in ["home", "home/.claude", "home/.codex", "home/capture", "home/config", + "home/state", "home/AppData", "bin", "tmp", "repo", "escape"]: + path = case / relative + path.mkdir(parents=True, exist_ok=True) + path.chmod(0o700) + assert path.resolve() == path and path.stat().st_uid == os.getuid() + for name, path in [("git", Path("/usr/bin/git")), ("bash", Path("/bin/bash")), + ("sleep", Path("/bin/sleep")), ("codex", CONTROLLER), + ("claude", NATIVES / "claude-inert-source-only")]: + (case / "bin" / name).symlink_to(path.resolve(strict=True)) + result = cli(case, ["skill", "runtime", "--json"]) + assert result.returncode == 0, "owned embedded-anchor source pair unavailable" + result = cli(case, ["--quiet", "skill", "install", "--source", "bundled", + "--agent", "codex", "--agent", "claude-code"]) + observe({"namespace": namespace, "case": "quiet-private-install", "exit": result.returncode}) + assert result.returncode == 0 and not result.stdout, "private managed installation failed" + git = owned_runtime(case, [str(CONTROLLER), "--git-init", str(ROOT), str(case), str(CORE)], 4) + assert git.returncode == 0 + result = cli(case, ["capture", "status", "--json"]) + assert result.returncode == 0 + database = sqlite3.connect(case / "home/capture/capture.sqlite3") + binding = {"repository_key": sha(str((case / "repo/.git").resolve()).encode()), + "remote_hash": sha(b""), "hint_hash": sha(b"no-mapping-hint"), + "id": sha(("synthetic-binding-" + namespace).encode()), "version": 1, + "workspace_id": "co_synthetic", "owner_id": "owner_synthetic", + "origin_hash": sha(b"synthetic-origin"), "project_id": "project_synthetic", + "task_id": "task_synthetic", "agents": ["codex", "claude-code"], + "paused": False, "revoked": False} + database.execute("INSERT INTO bindings(repo_key,data) VALUES(?,?)", + (binding["repository_key"], json.dumps(binding))) + database.commit() + return case, database + + +def write_source(path, records): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(json.dumps(record) + "\n" for record in records)) + path.chmod(0o600) + + +def dispatch(case, namespace, session, source, event, turn, *, program_override=None, chain_depth=None, overrides=None, remove_fields=(), diagnostic_label="positive", diagnostic_phase="normal-dispatch"): + config = json.loads((case / ("home/.codex/hooks.json" if namespace == "codex" + else "home/.claude/settings.json")).read_text()) + native_event = "UserPromptSubmit" if event == "prompt" else "Stop" + command = config["hooks"][native_event][0]["hooks"][0]["command"] + label = event + "-" + uuid.uuid4().hex + command_file, event_file, result_file = (case / (label + suffix) + for suffix in ["-command.txt", "-input.json", "-result.json"]) + command_file.write_text(command) + command_file.chmod(0o600) + body = {"session_id": session, "turn_id": turn, "prompt_id": turn, + "cwd": str(case / "repo"), "transcript_path": str(source), + "prompt": "PRIVATE_NORMAL_PROMPT_CANARY"} + if overrides: + body.update(overrides) + for field in remove_fields: + body.pop(field, None) + event_file.write_text(json.dumps(body)) + event_file.chmod(0o600) + program = program_override or (CONTROLLER if namespace == "codex" else NATIVES / "claude-inert-source-only") + mode = ["--run"] if chain_depth is None else ["--chain", str(chain_depth)] + started = time.monotonic() + result = owned_runtime(case, [str(program), *mode, str(ROOT), str(case), str(CORE), + str(command_file), str(event_file), str(result_file)], 1, + diagnostic={"namespace": namespace, "matrix_label": diagnostic_label, + "phase": diagnostic_phase, "event": event}) + outcome = json.loads(result_file.read_text()) if result_file.exists() else {"missing_result": True} + flags = list((case / "home/capture/capture-invocations").glob("*.pending")) + flags += list((case / "home/capture/capture-invocations").glob("*.preparing")) + observe({"namespace": namespace, "case": "normal-guarded-" + event, "exit": result.returncode, + "outcome": outcome, "pending_flags": len(flags), + "outer_elapsed_ms": (time.monotonic() - started) * 1000}) + assert result.returncode == 0 and not outcome.get("host_timeout", True) + assert outcome["elapsed_ms"] < 1000 and not flags, "retain genuine guard/ACK failure before numeric assertions" + + +def main(): + global OWNER + failures = [] + for namespace, version, filename in [("codex", "0.167.0", "codex-inert-source-only"), + ("claude-code", "2.1.319", "claude-inert-source-only")]: + with SourceOwner() as OWNER: + case, database = make_case(namespace) + session = str(uuid.uuid4()) + if namespace == "codex": + source = case / "home/.codex/sessions/2026/11/08" / ("rollout-synthetic-" + session + ".jsonl") + meta = {"type": "session_meta", "payload": {"id": session, "session_id": session, "cli_version": version}} + context = lambda turn: {"type": "turn_context", "payload": {"turn_id": turn, "model": "gpt-6.1-sol"}} + response = lambda identity, turn, usage: {"type": "token_usage_record", "payload": { + "thread_id": session, "session_id": session, "turn_id": turn, "root_turn_id": turn, + "response_id": identity, "usage": usage}} + old_id, new_id = "resp_before_consent", "resp_after_consent" + initial = [meta, context("old_turn"), response(old_id, "old_turn", None)] + final = [meta, context("old_turn"), response(old_id, "old_turn", {"input_tokens": "PRIVATE_OLD_COUNTER_CANARY"}), + context("turn_synthetic"), response(new_id, "turn_synthetic", { + "input_tokens": 101, "cached_input_tokens": 80, "cache_write_input_tokens": 0, + "output_tokens": 5, "reasoning_output_tokens": 2})] + else: + source = case / "home/.claude/projects/synthetic" / (session + ".jsonl") + response = lambda identity, usage: {"type": "assistant", "sessionId": session, "message": { + "id": identity, "model": "claude-opus-5-5", "stop_reason": "end_turn", "usage": usage, + "content": [{"text": "PRIVATE_NORMAL_SOURCE_CANARY"}]}} + old_id, new_id = "msg_before_consent", "msg_after_consent" + initial = [response(old_id, {"input_tokens": "PRIVATE_OLD_COUNTER_CANARY"})] + final = initial + [response(new_id, {"input_tokens": 2, "cache_read_input_tokens": None, + "cache_creation_input_tokens": 2280, "output_tokens": 5})] + write_source(source, initial) + before_enable = source.read_bytes() + result = cli(case, ["capture", "usage", "enable", "--repo", "--agent", namespace, + "--profile-home", str(case / "home"), "--harness-executable", str(NATIVES / filename), + "--native-executable", str(NATIVES / filename), "--confirm", "--json"]) + observe({"namespace": namespace, "case": "explicit-normal-enable", "exit": result.returncode, + "stdout_bytes": len(result.stdout), "source_bytes_unchanged": source.read_bytes() == before_enable}) + assert result.returncode == 0, "normal numeric consent publication failed before factory acceptance" + enabled = json.loads(result.stdout) + assert enabled["enabled"] is True and enabled["status"] == "UNAVAILABLE" + policy = json.loads(database.execute("SELECT data FROM usage_consents WHERE namespace=?", (namespace,)).fetchone()[0]) + assert policy["enabled"] and policy["epoch"] > 0 and str(case) not in json.dumps(policy) + profiles = list((case / "home/capture/profiles").glob("*.json")) + assert len(profiles) == 1 and profiles[0].stat().st_mode & 0o777 == 0o600 + assert str(source) not in profiles[0].read_text(), "functional record retained an exact transcript path" + dispatch(case, namespace, session, source, "prompt", "turn_synthetic") + write_source(source, final) + dispatch(case, namespace, session, source, "stop", "turn_synthetic") + bodies = [json.loads(row[0]) for row in database.execute("SELECT body FROM outbox ORDER BY revision")] + observed_ids = [record["source_record_id"] for body in bodies for record in body["usage"].get("records", [])] + statuses = [body["usage"]["status"] for body in bodies] + observe({"namespace": namespace, "case": "normal-numeric-acceptance", "status": statuses, + "request_ids": observed_ids, "expected_request_ids": [new_id], + "timing_segments_preserved": bool(bodies) and bool(bodies[0]["segments"])}) + assert bodies and bodies[0]["segments"], "normal numeric path discarded legitimate timing" + for raw, in database.execute("SELECT data FROM sessions UNION ALL SELECT body FROM outbox"): + assert "PRIVATE_" not in raw and str(case) not in raw + if observed_ids != [new_id] or "PARTIAL" not in statuses: + failures.append(namespace + ": normal guarded route did not capture the new request delta") + database.close() + + assert not failures, "; ".join(failures) + print(json.dumps({"source_fixture_only": True, "both_namespaces_numeric_normal_route": True, + "real_harness_provider_or_release_qualification": False})) + + +if __name__ == "__main__": + main() diff --git a/tests/support/guarded_usage_negatives.py b/tests/support/guarded_usage_negatives.py new file mode 100644 index 0000000..d295c6c --- /dev/null +++ b/tests/support/guarded_usage_negatives.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Owned actual normal-route negatives; no real harness/provider/release claim.""" +from pathlib import Path +import json +import os +import shutil +import uuid +import sys +sys.dont_write_bytecode = True +import guarded_usage_acceptance as qa +from source_qa_protocol import SourceOwner + + +def source_records(namespace, session, version): + if namespace == "codex": + initial = [{"type": "session_meta", "payload": {"id": session, "session_id": session, "cli_version": version}}] + final = initial + [{"type": "turn_context", "payload": {"turn_id": "turn_synthetic", "model": "gpt-6.1-sol"}}, + {"type": "token_usage_record", "payload": {"session_id": session, "thread_id": session, + "turn_id": "turn_synthetic", "root_turn_id": "turn_synthetic", "response_id": "resp_after_prompt", + "usage": {"input_tokens": 101, "output_tokens": 5}}}] + else: + initial = [] + final = [{"type": "assistant", "sessionId": session, "message": {"id": "msg_after_prompt", + "model": "claude-opus-5-5", "stop_reason": "end_turn", "usage": {"input_tokens": 2, "output_tokens": 5}}}] + return initial, final + + +def setup(namespace, version, filename): + case, database = qa.make_case(namespace) + image = case / "native-pinned-owned" + shutil.copyfile(qa.NATIVES / filename, image) + image.chmod(0o700) + session = str(uuid.uuid4()) + source = (case / "home/.codex/sessions/2026/11/08" / ("rollout-owned-" + session + ".jsonl") if namespace == "codex" + else case / "home/.claude/projects/owned" / (session + ".jsonl")) + initial, final = source_records(namespace, session, version) + qa.write_source(source, initial) + result = qa.cli(case, ["capture", "usage", "enable", "--repo", "--agent", namespace, + "--profile-home", str(case / "home"), "--harness-executable", str(image), + "--native-executable", str(image), "--confirm", "--json"]) + qa.observe({"namespace": namespace, "case": "negative-explicit-enable", "exit": result.returncode}) + assert result.returncode == 0 + return case, database, image, session, source, final + + +def assert_time_unknown(case, database, namespace, label, expected): + bodies = [json.loads(row[0]) for row in database.execute("SELECT body FROM outbox ORDER BY revision")] + assert bodies and bodies[0]["segments"], "negative discarded legitimate timing" + assert all(not body["usage"].get("records") for body in bodies), "negative accepted uncertain numeric evidence" + result = qa.cli(case, ["capture", "usage", "status", "--repo", "--agent", namespace, "--json"]) + assert result.returncode == 0 + status = json.loads(result.stdout) + qa.observe({"namespace": namespace, "case": label, "reason": status["reason"], + "enabled": status["enabled"], "timing_preserved": True, "numeric_records": 0}) + assert status["reason"] == expected, (namespace, label, status) + for raw, in database.execute("SELECT data FROM sessions UNION ALL SELECT body FROM outbox"): + assert "PRIVATE_" not in raw and str(case) not in raw + + +MATRIX = { + "profile-record-changed": "PROFILE_CHANGED", "managed-root-recreated": "PROFILE_CHANGED", + "native-image-changed": "HARNESS_CHANGED", "registration-changed": "REGISTRATION_CHANGED", + "generation-changed": "REGISTRATION_CHANGED", "generation-receipt-changed": "REGISTRATION_CHANGED", + "source-replaced": "SOURCE_CHANGED", "source-symlink": "SOURCE_PARSE_UNAVAILABLE", + "source-fifo": "SOURCE_PARSE_UNAVAILABLE", "source-hardlink": "SOURCE_PARSE_UNAVAILABLE", + "source-directory": "SOURCE_PARSE_UNAVAILABLE", "source-wrong-session": "SOURCE_PARSE_UNAVAILABLE", + "path-missing": "ACTIVE_SOURCE_UNAVAILABLE", "path-null": "ACTIVE_SOURCE_UNAVAILABLE", + "path-wrong-namespace": "ACTIVE_SOURCE_UNAVAILABLE", "path-wrong-session": "ACTIVE_SOURCE_UNAVAILABLE", + "numeric-revoked": "NUMERIC_CAPTURE_DISABLED", "metadata-paused": "NUMERIC_CAPTURE_DISABLED", +} +def main(): + for namespace, version, filename in [("codex", "0.167.0", "codex-inert-source-only"), + ("claude-code", "2.1.319", "claude-inert-source-only")]: + for label, expected in MATRIX.items(): + with SourceOwner() as owner: + qa.OWNER = owner + case, database, image, session, source, final = setup(namespace, version, filename) + qa.dispatch(case, namespace, session, source, "prompt", "turn_synthetic", program_override=image, + diagnostic_label=label, diagnostic_phase="pre-mutation-prompt") + qa.write_source(source, final) + options = {} + profile_path = next((case / "home/capture/profiles").glob("*.json")) + profile = json.loads(profile_path.read_text()) + if label == "profile-record-changed": + profile_path.write_text(profile_path.read_text() + " ") + elif label == "managed-root-recreated": + managed = Path(profile["managed_root"]) + managed.rename(managed.with_name(managed.name + "-previous")) + managed.mkdir(mode=0o700) + elif label == "native-image-changed": + os.utime(image, ns=(image.stat().st_atime_ns, image.stat().st_mtime_ns + 1_000_000_000)) + elif label == "registration-changed": + config = case / ("home/.codex/hooks.json" if namespace == "codex" else "home/.claude/settings.json") + config.write_text(config.read_text() + " ") + elif label == "generation-changed": + Path(profile["generation_root"]).chmod(0o500) + elif label == "generation-receipt-changed": + receipt = Path(profile["generation_root"]) / "capture-install.json" + os.utime(receipt, ns=(receipt.stat().st_atime_ns, receipt.stat().st_mtime_ns + 1_000_000_000)) + elif label.startswith("source-") and label != "source-wrong-session": + previous = source.with_suffix(".previous") + source.rename(previous) + if label == "source-replaced": + source.write_text("PRIVATE_REPLACED_INVALID_SOURCE") + elif label == "source-symlink": + source.symlink_to(previous) + elif label == "source-fifo": + os.mkfifo(source, 0o600) + elif label == "source-hardlink": + os.link(previous, source) + elif label == "source-directory": + source.mkdir(mode=0o700) + elif label == "source-wrong-session": + source.write_text(source.read_text().replace(session, str(uuid.uuid4()))) + elif label == "path-null": + options["overrides"] = {"transcript_path": None} + elif label == "path-missing": + options["remove_fields"] = ["transcript_path"] + elif label == "path-wrong-namespace": + options["overrides"] = {"transcript_path": str(case / "home" / (".claude/projects/owned" if namespace == "codex" else ".codex/sessions/2026/11/08") / source.name)} + elif label == "path-wrong-session": + options["overrides"] = {"transcript_path": str(source.with_name(str(uuid.uuid4()) + ".jsonl"))} + elif label == "numeric-revoked": + result = qa.cli(case, ["capture", "usage", "disable", "--repo", "--agent", namespace, "--json"]) + assert result.returncode == 0 + elif label == "metadata-paused": + result = qa.cli(case, ["capture", "pause", "--repo", "--json"]) + assert result.returncode == 0 + qa.dispatch(case, namespace, session, source, "stop", "turn_synthetic", program_override=image, + diagnostic_label=label, diagnostic_phase="post-mutation-stop", **options) + assert_time_unknown(case, database, namespace, label, expected) + database.close() + # The wrong native-image chain is entirely run-owned. Eight added native + # ancestors ensure no observation reaches the QA runner or operator process. + with SourceOwner() as owner: + qa.OWNER = owner + case, database, image, session, source, final = setup(namespace, version, filename) + wrong = case / "native-wrong-owned" + shutil.copyfile(qa.NATIVES / filename, wrong) + wrong.chmod(0o700) + qa.dispatch(case, namespace, session, source, "prompt", "turn_synthetic", program_override=wrong, chain_depth=8, + diagnostic_label="wrong-owned-native-image-bounded-chain", + diagnostic_phase="wrong-origin-prompt") + status = json.loads(qa.cli(case, ["capture", "usage", "status", "--repo", "--agent", namespace, "--json"]).stdout) + assert status["reason"] == "HARNESS_ORIGIN_UNAVAILABLE", status + qa.observe({"namespace": namespace, "case": "wrong-owned-native-image-bounded-chain", "reason": status["reason"], "owned_chain_depth": 8}) + qa.write_source(source, final) + qa.dispatch(case, namespace, session, source, "stop", "turn_synthetic", program_override=image, + diagnostic_label="wrong-owned-native-image-bounded-chain", + diagnostic_phase="terminal-after-wrong-origin") + assert_time_unknown(case, database, namespace, "terminal-cannot-repair-wrong-origin", "MISSING_QUALIFIED_PROMPT") + database.close() + print(json.dumps({"source_fixture_only": True, "normal_guarded_negative_cases": 2 * (len(MATRIX) + 1), + "real_harness_provider_or_release_qualification": False})) + + +if __name__ == "__main__": + main() diff --git a/tests/support/mutation_environment.rs b/tests/support/mutation_environment.rs new file mode 100644 index 0000000..eca3bcd --- /dev/null +++ b/tests/support/mutation_environment.rs @@ -0,0 +1,61 @@ +//! Development-only preflight. Call before constructing any mutation command. +use std::path::{Path, PathBuf}; +pub struct CheckedEnvironment { + pub home: PathBuf, + pub capture: PathBuf, + pub core: PathBuf, +} +pub fn checked( + run_root: &Path, + case_root: &Path, + home: Option<&Path>, + capture: Option<&Path>, + core: Option<&Path>, +) -> Result { + let run_root = run_root + .canonicalize() + .map_err(|_| "run-owned root unavailable")?; + let case_root = case_root + .canonicalize() + .map_err(|_| "case root unavailable")?; + if !case_root.starts_with(&run_root) { + return Err("foreign case refused before mutation"); + } + let home = home.ok_or("missing explicit isolated HOME")?; + let capture = capture.ok_or("missing explicit isolated capture root")?; + let core = core.ok_or("missing explicit run-owned core")?; + if home != case_root.join("home") + || capture != home.join("capture") + || !core.is_absolute() + || !core.starts_with(&run_root) + { + return Err("foreign environment refused before mutation"); + } + if home.canonicalize().ok().as_deref() != Some(home) + || capture.canonicalize().ok().as_deref() != Some(capture) + { + return Err("aliased or missing environment refused before mutation"); + } + for name in [".codex", ".claude"] { + let path = home.join(name); + if (path.exists() || path.is_symlink()) + && (path.is_symlink() + || !path.is_dir() + || path.canonicalize().ok().as_deref() != Some(path.as_path())) + { + return Err("harness profile escape refused before mutation"); + } + } + let parent = core.parent().ok_or("missing run-owned core parent")?; + if parent.canonicalize().ok().as_deref() != Some(parent) + || core.is_symlink() + || (core.exists() && core.canonicalize().ok().as_deref() != Some(core)) + { + return Err("core escape refused before mutation"); + } + Ok(CheckedEnvironment { + home: home.to_owned(), + capture: capture.to_owned(), + core: core.to_owned(), + }) +} diff --git a/tests/support/run-inherited-suite.sh b/tests/support/run-inherited-suite.sh new file mode 100755 index 0000000..b11656c --- /dev/null +++ b/tests/support/run-inherited-suite.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Already inside the single proved OS policy; never applies another sandbox. +set -euo pipefail +checker=$1 +root=$2 +cargo_bin=$3 +shift 3 +"$checker" verify "$root" +export KEITO_TEST_SERVICE_BOUNDARY_RECEIPT="$root/service-boundary-receipt.json" +python3 -I -S -B tests/support/test_paired_test_runner.py +python3 -I -S -B tests/support/run_paired_tests.py "$cargo_bin" \ + "${KEITO_TEST_RUSTC_BIN:?Canonical rustc must be prepared before the boundary}" "$@" +if [ "$#" -eq 0 ]; then + mkdir -m 700 "$root/finite-manager-tmp" + export TMPDIR="$root/finite-manager-tmp" + # Finite protocol and bootstrap fake/metadata tests; isolated startup. + python3 -I -S -B tests/support/test_source_qa_protocol.py + python3 -I -S -B tests/support/test_source_qa_protocol_review_regressions.py + python3 -I -S -B tests/support/test_source_owner_finalizer.py + python3 -I -S -B tests/support/test_source_owner_finalizer_review_regressions.py + python3 -I -S -B tests/support/test_runtime_children_finite.py + python3 -I -S -B tests/support/test_source_clock_domain.py + python3 -I -S -B tests/support/test_source_qa_build_owner.py + # Developer-only owned pair QA inherits this same proved policy; never nest it. + PYTHONDONTWRITEBYTECODE=1 python3 tests/support/test_source_qa_contract.py "$root" + PYTHONDONTWRITEBYTECODE=1 python3 tests/support/run_guarded_usage_qa.py \ + "$root" "$cargo_bin" "${KEITO_TEST_RUSTC_BIN:?Canonical toolchain rustc must be prepared before the boundary}" +fi diff --git a/tests/support/run_guarded_usage_qa.py b/tests/support/run_guarded_usage_qa.py new file mode 100644 index 0000000..a2aa0f6 --- /dev/null +++ b/tests/support/run_guarded_usage_qa.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Build and verify an isolated opt2 SOURCE-FIXTURE pair, never a release candidate. + +Run inside the existing macOS inherited test boundary, or the Linux source-test +job. Linux uses private checked operands/environment and makes no kernel service +or network denial claim. Every product Command passes actual Rust isolation::checked. +No real harness, credentials, trust override, provider or service is used. +""" +from pathlib import Path +import hashlib +import json +import os +import shutil +import stat +import sys + +sys.dont_write_bytecode = True +from source_qa_cargo import build_script_target, cargo +from source_qa_manifest import ManifestLease +assert sys.platform in ("darwin", "linux"), "Unix source QA is unsupported here" +assert len(sys.argv) == 4, "run_guarded_usage_qa.py " +REPO = Path(__file__).resolve().parents[2] +PARENT = Path(sys.argv[1]) +assert PARENT.is_absolute() and PARENT.resolve(strict=True) == PARENT +metadata = PARENT.lstat() +assert stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() +assert stat.S_IMODE(metadata.st_mode) == 0o700 +ROOT = PARENT / "guarded-usage-source-qa" +ROOT.mkdir(mode=0o700) # Never replace an earlier run or its first observations. +os.umask(0o077) +for relative in ("home", "home/.codex", "home/.claude", "home/capture", "home/config", + "home/state", "home/AppData", "tmp", "target-source-only", "owned-native", + "pair-source-only", "qa-positives", "qa-negatives"): + (ROOT / relative).mkdir(parents=True, exist_ok=True, mode=0o700) +CARGO, RUSTC = sys.argv[2:] +assert Path(CARGO).is_absolute() and Path(RUSTC).is_absolute() + + +def digest(path): + value = hashlib.sha256() + with path.open("rb") as source: + for block in iter(lambda: source.read(64 * 1024), b""): + value.update(block) + return value.hexdigest() + + +def record(name, value): + with (ROOT / name).open("x") as output: + json.dump(value, output, indent=2) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + + +if sys.platform == "darwin": + # The caller has already proved and inherited the single kernel policy. + # This runner must never launch a second sandbox or relax its restrictions. + receipt = Path(os.environ["KEITO_TEST_SERVICE_BOUNDARY_RECEIPT"]) + assert json.loads(receipt.read_text())["passed"] is True + +BUILD_ENV = {key: os.environ[key] for key in + ("PATH", "CARGO_HOME", "RUSTUP_HOME", "RUSTUP_TOOLCHAIN", + "KEITO_TEST_SERVICE_BOUNDARY_RECEIPT") if key in os.environ} +BUILD_ENV.update({"HOME": str(ROOT / "home"), "CODEX_HOME": str(ROOT / "home/.codex"), + "CLAUDE_CONFIG_DIR": str(ROOT / "home/.claude"), + "KEITO_CAPTURE_HOME": str(ROOT / "home/capture"), + "XDG_CONFIG_HOME": str(ROOT / "home/config"), + "XDG_STATE_HOME": str(ROOT / "home/state"), "APPDATA": str(ROOT / "home/AppData"), + "TMPDIR": str(ROOT / "tmp"), "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null", + "CARGO_HOME": os.environ["CARGO_HOME"], + "RUSTUP_HOME": os.environ["RUSTUP_HOME"], + "CARGO_TARGET_DIR": str(ROOT / "target-source-only"), "CARGO_NET_OFFLINE": "true", + "CARGO_BUILD_JOBS": "2", "RUST_TEST_THREADS": "1", "RUSTFLAGS": "-D warnings", + "CARGO_PROFILE_DEV_OPT_LEVEL": "2", "CARGO_PROFILE_DEV_LTO": "false", + "CARGO_PROFILE_DEV_CODEGEN_UNITS": "8", "CARGO_PROFILE_DEV_STRIP": "symbols", + "CARGO_PROFILE_DEV_DEBUG": "0", "PYTHONDONTWRITEBYTECODE": "1"}) + + +def invoke(label, arguments, timeout, extra=None): + assert arguments[0] == CARGO and timeout <= 900 + config = ["--config", "profile.dev.opt-level=2", "--config", 'profile.dev.debug=0', + "--config", "profile.dev.codegen-units=8", "--config", 'profile.dev.strip="symbols"'] + if extra: + assert set(extra) == {"KEITO_RELEASE_GUARD_SHA256"} + value = extra["KEITO_RELEASE_GUARD_SHA256"] + assert len(value) == 64 and all(c in "0123456789abcdef" for c in value) + config += ["--config", 'env.KEITO_RELEASE_GUARD_SHA256="' + value + '"'] + return cargo(ROOT, REPO, CARGO, BUILD_ENV, label, [*config, *arguments[1:]]) + + +def source_snapshot(): + # Source membership was collected OUTSIDE the inherited policy. No Git or + # original common-directory access is attempted by this verifier. + return manifest.verify() + + +manifest = ManifestLease(REPO, PARENT) +BOUNDARY = ("macOS: existing proved inherited kernel service/network policy" if sys.platform == "darwin" + else "Linux: private checked operands and environment; no kernel service/network denial claim") +snapshot = source_snapshot() +record("source-before.json", {"source_fixture_only": True, "files": snapshot, "execution_boundary": BOUNDARY, + "outer_manifest_sha256": manifest.raw_sha256, + "source_set_sha256": manifest.value["source_set_sha256"], + "collector": manifest.value["collector"], "deleted_paths": manifest.value["deleted_paths"], + "not_final_release_qualification": True}) +with manifest: + import tomllib + package = tomllib.loads((REPO / "Cargo.toml").read_text()) + version = package["package"]["version"] + # Pair target comes from Cargo's source-bound build-script output below, + # never an unowned rustc --version child or a caller-supplied namespace. + guard_target = invoke("source-guard-build", [CARGO, "build", "--locked", "--offline", "--features", "dev-tools", "--bin", "keito-capture-guard"], 600) + pair = ROOT / "pair-source-only" + shutil.copyfile(guard_target / "keito-capture-guard", pair / "keito-capture-guard") + (pair / "keito-capture-guard").chmod(0o700) + guard_digest = digest(pair / "keito-capture-guard") + core_target = invoke("source-core-build", [CARGO, "build", "--locked", "--offline", "--features", "dev-tools", "--bin", "keito"], + 600, {"KEITO_RELEASE_GUARD_SHA256": guard_digest}) + shutil.copyfile(core_target / "keito", pair / "keito") + (pair / "keito").chmod(0o700) + host = build_script_target(core_target) + pair_manifest = {"manifest_contract": 1, "version": version, "target": host, "guard_contract": 2, + "files": {"keito": digest(pair / "keito"), "keito-capture-guard": guard_digest}} + with (pair / "capture-runtime-manifest.json").open("x") as output: + json.dump(pair_manifest, output, indent=2) + output.write("\n") + for name in ("codex-inert-source-only", "claude-inert-source-only"): + image = ROOT / "owned-native" / name + fixture_target = invoke("build-" + name, [CARGO, "build", "--locked", "--offline", "--features", "dev-tools", "--bin", name], + 600, {"KEITO_RELEASE_GUARD_SHA256": guard_digest}) + shutil.copyfile(fixture_target / name, image) + image.chmod(0o700) + assert source_snapshot() == snapshot, "source changed during source-fixture builds" + record("pair-and-native-identities.json", {"source_fixture_only": True, "manifest": pair_manifest, + "outer_manifest_sha256": manifest.raw_sha256, + "manifest_sha256": digest(pair / "capture-runtime-manifest.json"), + "native_files": {path.name: digest(path) for path in (ROOT / "owned-native").iterdir()}}) + for label, script, output in (("normal-positive-first", "guarded_usage_acceptance.py", "qa-positives"), + ("normal-negative-first", "guarded_usage_negatives.py", "qa-negatives")): + # Execute Python acceptance on THIS thread. Every actual runtime Child + # is retained by its registered multi-slot manager; no opaque subprocess + # around the whole script and no second source ownership implementation. + import runpy + old_argv = sys.argv + sys.argv = [str(REPO / "tests/support" / script), str(ROOT), str(pair), + str(ROOT / "owned-native"), str(ROOT / output)] + try: + runpy.run_path(str(REPO / "tests/support" / script), run_name="__main__") + finally: + sys.argv = old_argv + assert source_snapshot() == snapshot, "source changed during source-fixture verification" + record("source-qa-complete.json", {"source_fixture_only": True, "positive_namespaces": 2, + "negative_cases": 38, "not_real_harness_provider_or_release_qualification": True, + "all_tracked_direct_handles_waited": "see each retained runtime manager receipt and compiler FIRST/FINAL", + "outer_manifest_sha256": manifest.raw_sha256, + "source_set_sha256": manifest.value["source_set_sha256"], + "execution_boundary": BOUNDARY}) + print("Owned normal numeric SOURCE-FIXTURE QA passed; retained at " + str(ROOT)) diff --git a/tests/support/run_paired_tests.py b/tests/support/run_paired_tests.py new file mode 100644 index 0000000..85b7c15 --- /dev/null +++ b/tests/support/run_paired_tests.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Run Unix integration tests with real, source-built release-pair verification. + +No product verifier override: the guard digest is compiled into the test/core, +and each test image that uses capture convenience APIs has its own manifest. +Other tests still use the unpaired Cargo binary to exercise refusal paths. +The macOS caller must already be inside run-macos-isolated.sh's boundary. +""" +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import shutil +import subprocess +import sys +import tempfile + +PAIRED_TESTS = {"capture_processes", "capture_store", "capture_transport", "native_capture_guard"} + + +def digest(path): + with open(path, "rb") as source: + return hashlib.sha256(source.read()).hexdigest() + + +def stage_pair(directory, core, guard, version, target): + directory.mkdir(mode=0o700) + for source, name in [(core, "keito"), (guard, "keito-capture-guard")]: + shutil.copyfile(source, directory / name) + (directory / name).chmod(0o700) + manifest = {"manifest_contract": 1, "version": version, "target": target, + "guard_contract": 2, "files": { + name: digest(directory / name) for name in ("keito", "keito-capture-guard")}} + path = directory / "capture-runtime-manifest.json" + with path.open("x") as output: + path.chmod(0o600) + json.dump(manifest, output) + return directory / "keito" + + +def run_test(executable, arguments): + # Cargo calls this runner for every target; only these four suites call + # current() from the test executable itself. Never share their manifests. + name = Path(executable).name.rsplit("-", 1)[0] + if name in PAIRED_TESTS: + root = Path(os.environ["KEITO_TEST_PAIR_ROOT"]) + directory = Path(tempfile.mkdtemp(prefix=name + "-", dir=root)) + executable = stage_pair(directory / "pair", executable, + root / "guard", os.environ["KEITO_TEST_PAIR_VERSION"], + os.environ["KEITO_TEST_PAIR_TARGET"]) + os.execv(str(executable), [str(executable), *arguments]) + + +def main(arguments): + if arguments[:1] == ["--run"]: + run_test(arguments[1], arguments[2:]) + return + cargo, rustc, *test_arguments = arguments + root = Path(tempfile.mkdtemp(prefix="keito-paired-tests-")).resolve(strict=True) + root.chmod(0o700) + print("Source-fixture test pairs: " + str(root), flush=True) + (root / "tmp").mkdir(mode=0o700) + os.environ["TMPDIR"] = str(root / "tmp") + environment = dict(os.environ) + environment.pop("KEITO_RELEASE_GUARD_SHA256", None) + # The caller resolves the toolchain before entering this runner. Cargo + # otherwise finds rustc through PATH, where parallel rustup proxies may + # attempt component installation during the first guard build. + environment["RUSTC"] = rustc + # /usr/bin/git on macOS is an xcrun shim, not the Git image. Resolve the + # tool once during fixture preparation instead of charging shim discovery + # to every short owned leaf after env_clear(). + git = (subprocess.check_output(["/usr/bin/xcrun", "--find", "git"], + env=environment, text=True).strip() + if sys.platform == "darwin" else shutil.which("git", path=environment["PATH"])) + if not git or not Path(git).is_file(): + raise RuntimeError("fixture Git executable unavailable") + git_directory = str(Path(git).resolve(strict=True).parent) + environment["KEITO_TEST_PROCESS_PATH"] = os.pathsep.join([git_directory, "/usr/bin", "/bin"]) + environment["PATH"] = environment["KEITO_TEST_PROCESS_PATH"] + os.pathsep + environment["PATH"] + # Exercise the production optimization/LTO/codegen footprint without changing + # fixture checked semantics, dev-tools negative seams, or any runtime bound. + # DEV/TEST keep their debug assertions and overflow checks explicitly; this + # remains a source-fixture pair, not the normal release artifact. + for profile in ("DEV", "TEST"): + for key, value in {"OPT_LEVEL": "z", "DEBUG": "0", "STRIP": "symbols", + "LTO": "true", "CODEGEN_UNITS": "1", + "DEBUG_ASSERTIONS": "true", "OVERFLOW_CHECKS": "true"}.items(): + environment["CARGO_PROFILE_" + profile + "_" + key] = value + environment.setdefault("RUST_TEST_THREADS", "1") + target = next(line.split(": ", 1)[1] for line in subprocess.check_output( + [rustc, "-vV"], text=True).splitlines() if line.startswith("host: ")) + version = re.search(r'^version = "([^"]+)"$', Path("Cargo.toml").read_text(), re.M)[1] + subprocess.run([cargo, "build", "--locked", "--all-features", "--bin", + "keito-capture-guard", "--message-format=json"], env=environment, + stdout=(root / "guard-build.jsonl").open("x"), check=True) + guard = artifact(root / "guard-build.jsonl", "keito-capture-guard") + shutil.copyfile(guard, root / "guard") + (root / "guard").chmod(0o700) + environment["KEITO_RELEASE_GUARD_SHA256"] = digest(root / "guard") + subprocess.run([cargo, "build", "--locked", "--all-features", "--bin", "keito", + "--message-format=json"], env=environment, + stdout=(root / "core-build.jsonl").open("x"), check=True) + core = artifact(root / "core-build.jsonl", "keito") + pair = stage_pair(root / "cli", core, root / "guard", version, target) + environment.update(KEITO_TEST_PAIR_ROOT=str(root), KEITO_TEST_PAIR_CORE=str(pair), + KEITO_TEST_PAIR_VERSION=version, KEITO_TEST_PAIR_TARGET=target) + runner = shlex.join([sys.executable, "-I", "-S", "-B", str(Path(__file__).resolve()), "--run"]) + environment["CARGO_TARGET_" + target.upper().replace("-", "_") + "_RUNNER"] = runner + selection = {"--all-targets", "--lib", "--test", "--tests", "--bin", "--bins", "--example", "--examples", + "--bench", "--benches", "--doc"} + targets = [] if selection.intersection(test_arguments) else ["--all-targets"] + command = [cargo, "test", "--locked", "--all-features", *targets, *test_arguments] + subprocess.run(command, env=environment, check=True) + + +def artifact(path, name): + matches = [] + for line in path.read_text().splitlines(): + value = json.loads(line) + if (value.get("reason") == "compiler-artifact" and value["target"]["name"] == name + and value.get("executable") and not value["profile"]["test"]): + matches.append(value["executable"]) + if len(matches) != 1: + raise RuntimeError("expected exactly one executable artifact for " + name) + return matches[0] + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/tests/support/runtime_pair.rs b/tests/support/runtime_pair.rs new file mode 100644 index 0000000..5c708c2 --- /dev/null +++ b/tests/support/runtime_pair.rs @@ -0,0 +1,19 @@ +//! Test fixture only. Uses the same compiled-anchor verifier as production. +use keito_cli::capture_runtime_pair::{self, CaptureRuntimeIdentity}; +pub fn process_path() -> std::ffi::OsString { + std::env::var_os("KEITO_TEST_PROCESS_PATH").expect("fixture Git PATH was not prepared") +} +pub fn pair() -> CaptureRuntimeIdentity { + let core = std::env::var_os("KEITO_TEST_PAIR_CORE").expect( + "Run Unix tests with tests/run-macos-isolated.sh or tests/support/run_paired_tests.py", + ); + capture_runtime_pair::verify( + std::path::Path::new(&core), + // Plain cargo check/clippy must compile; the verifier rejects a missing + // anchor at runtime just as it rejects a wrong digest. + option_env!("KEITO_RELEASE_GUARD_SHA256").unwrap_or(""), + env!("CARGO_PKG_VERSION"), + env!("KEITO_BUILD_TARGET"), + ) + .expect("invalid source-fixture runtime pair") +} diff --git a/tests/support/service_boundary.rs b/tests/support/service_boundary.rs new file mode 100644 index 0000000..0c0420c --- /dev/null +++ b/tests/support/service_boundary.rs @@ -0,0 +1,114 @@ +//! Test-only proof receipt plus current-process kernel-denial sentinel. +//! Direct macOS Cargo runs fail before any actual CLI observer can spawn. +use assert_cmd::Command; +use std::ffi::OsStr; +pub fn command(program: impl AsRef) -> Command { + #[cfg(target_os = "macos")] + { + static VERIFIED: std::sync::OnceLock> = std::sync::OnceLock::new(); + if let Err(reason) = VERIFIED.get_or_init(verify) { + panic!("Use tests/run-macos-isolated.sh: {reason}"); + } + } + Command::new(program) +} +#[cfg(target_os = "macos")] +fn verify() -> Result<(), &'static str> { + use sha2::{Digest, Sha256}; + use std::{fs, os::unix::fs::MetadataExt, path::PathBuf}; + let file = PathBuf::from( + std::env::var_os("KEITO_TEST_SERVICE_BOUNDARY_RECEIPT") + .ok_or("missing owned boundary receipt")?, + ); + if file.file_name().and_then(|v| v.to_str()) != Some("service-boundary-receipt.json") { + return Err("invalid receipt name"); + } + let root = file.parent().ok_or("missing receipt root")?; + if root.canonicalize().ok().as_deref() != Some(root) { + return Err("noncanonical receipt root"); + } + let m = fs::symlink_metadata(root).map_err(|_| "missing receipt root")?; + if !m.is_dir() || m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o777 != 0o700 { + return Err("foreign receipt root"); + } + let m = fs::symlink_metadata(&file).map_err(|_| "missing receipt")?; + if !m.is_file() + || m.file_type().is_symlink() + || m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != 0o600 + || m.nlink() != 1 + || m.len() > 16384 + { + return Err("unsafe receipt"); + } + let value: serde_json::Value = + serde_json::from_slice(&fs::read(&file).map_err(|_| "unreadable receipt")?) + .map_err(|_| "invalid receipt")?; + if value["schema"] != 1 + || value["passed"] != true + || value["actual_service_utility_executed"] != false + { + return Err("unproven receipt"); + } + let digest = |bytes: &[u8]| { + Sha256::digest(bytes) + .iter() + .map(|v| format!("{v:02x}")) + .collect::() + }; + for (name, key) in [ + ("boundary.sb", "policy_sha256"), + ("owned-checker", "checker_sha256"), + ("blocked-native-marker", "blocked_sha256"), + ] { + let path = root.join(name); + let m = fs::symlink_metadata(&path).map_err(|_| "missing proof input")?; + if !m.is_file() + || m.file_type().is_symlink() + || m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != if name == "boundary.sb" { 0o600 } else { 0o700 } + || m.len() > 128 * 1024 * 1024 + { + return Err("unsafe proof input"); + } + if value[key].as_str() + != Some(digest(&fs::read(path).map_err(|_| "unreadable proof input")?).as_str()) + { + return Err("changed proof input"); + } + } + if value["helper_source_sha256"].as_str() + != Some(digest(include_bytes!("service_boundary.rs")).as_str()) + || value["checker_source_sha256"].as_str() + != Some(digest(include_bytes!("../../src/bin/check-service-boundary.rs")).as_str()) + { + return Err("proof source changed"); + } + // A stale receipt outside the inherited policy must never authorize a CLI. + // Only this owned inert marker executable is probed, never launchctl. + let marker = root.join("native.marker"); + if marker.exists() { + return Err("prior unprotected sentinel execution"); + } + let mut child = std::process::Command::new(root.join("blocked-native-marker")); + let home = root.join("home"); + child + .env_clear() + .current_dir(root) + .env("HOME", &home) + .env("CODEX_HOME", home.join(".codex")) + .env("CLAUDE_CONFIG_DIR", home.join(".claude")) + .env("KEITO_CAPTURE_HOME", home.join("capture")) + .env("XDG_CONFIG_HOME", home.join("config")) + .env("APPDATA", home.join("AppData")) + .env("PATH", root.join("empty-bin")) + .arg("marker") + .arg(root); + let denied = child + .output() + .is_err_and(|e| e.kind() == std::io::ErrorKind::PermissionDenied); + if !denied || marker.exists() { + return Err("current process lacks inherited execution denial"); + } + Ok(()) +} diff --git a/tests/support/source_qa_build_owner.py b/tests/support/source_qa_build_owner.py new file mode 100644 index 0000000..fba03c8 --- /dev/null +++ b/tests/support/source_qa_build_owner.py @@ -0,0 +1,771 @@ +"""Developer-only compiler bootstrap owner. Never installed in the Rust CLI. + +One opaque command, one immutable CLEAN end (later requests are refused). The +forked sibling keeper alone addresses its own PID-reserved group. This is not +Scope, an arbitrary daemon/subtree proof, or the real-harness qualification. +""" +import hashlib +import json +import os +from pathlib import Path +import resource +import signal +import socket +import stat +import subprocess +import sys +import time + +CAP = 1_800_000_000 +TERM = 15_000_000 +FRAME = 256 +WIRE = 4096 + + +class Refused(RuntimeError): + pass + + +def integer(value): + if not value or len(value) > 20 or not value.isascii() or not value.isdigit(): + raise Refused("INTEGER") + n = int(value) + if str(n) != value or n > 2**64 - 1: + raise Refused("INTEGER") + return n + + +class Channel: + def __init__(self, stream, nonce): + if len(nonce) != 32 or any(c not in "0123456789abcdef" for c in nonce): + raise Refused("NONCE") + self.stream, self.nonce = stream, nonce + self.pending = bytearray() + self.wire = 0 + self.eof = False + stream.setblocking(False) + + def charge(self, count): + if self.wire + count > WIRE: + raise Refused("WIRE_LIMIT") + self.wire += count + + def send(self, body): + if not body.isascii() or "\n" in body or "\r" in body: + raise Refused("FRAME") + data = (self.nonce + "|" + body + "\n").encode("ascii") + if self.eof or len(data) > FRAME: + raise Refused("FRAME") + self.charge(len(data)) + try: + count = self.stream.send(data) + except OSError: + raise Refused("WRITE") from None + if count != len(data): + raise Refused("SHORT_WRITE") + + def receive(self): + for _ in range(8): + end = self.pending.find(b"\n") + if end >= 0: + line = bytes(self.pending[:end + 1]) + del self.pending[:end + 1] + if len(line) > FRAME or not line.isascii(): + return "rejected", "FRAME" + fields = line[:-1].decode("ascii").split("|", 1) + if len(fields) != 2 or fields[0] != self.nonce or "\r" in fields[1]: + return "rejected", "FRAME_IDENTITY" + return "frame", fields[1] + if len(self.pending) >= FRAME: + raise Refused("FRAME_LIMIT") + if self.eof: + return "eof", None + try: + data = self.stream.recv(FRAME) + except BlockingIOError: + return ("yield" if self.pending else "quiescent"), None + except InterruptedError: + continue + except OSError: + raise Refused("READ") from None + if not data: + self.eof = True + if self.pending: + raise Refused("TRUNCATED") + return "eof", None + self.charge(len(data)) + self.pending.extend(data) + return "yield", None + + +class Keeper: + """Same-runtime bootstrap only; real syscalls live in child-only Kernel.""" + def __init__(self, kernel, hard): + self.kernel, self.hard, self.end = kernel, hard, hard + self.operation_end = hard - CAP + self.first = None + self.cleaning = self.clean_seen = self.intent = self.parked = False + self.gone = self.released = self.stopped = self.abandoned = False + self.term_end = None + self.killed = False + + def fail(self, reason, at): + if self.first is None: + self.first = reason + if not self.cleaning and not self.gone: + self.cleaning = True + self.end = min(self.end, at + CAP) + + def check(self, clock): + if self.stopped or self.abandoned: + raise Refused(self.first or "AUTHORITY_STOPPED") + at = clock() + if at >= self.end: + raise Refused("DEADLINE") + return at + + def stop(self, at): + self.fail("CHANNEL", at) + if not self.stopped: + self.stopped, self.intent = True, False + self.kernel.disable() + + def control(self, body, at): + if self.stopped or self.released or at >= self.end: + raise Refused("STATE") + if body.startswith("CLEAN|"): + # A standalone build has exactly one cleanup broadcast. Its bound + # is immutable: a second request is rejected, never parent-only min. + if self.clean_seen: + raise Refused("CLEAN_ALREADY_BOUND") + self.end = min(self.end, integer(body[6:]), at + CAP) + self.clean_seen = self.cleaning = True + elif self.first is not None: + return + elif body == "PARK" and not (self.intent or self.parked or self.cleaning): + self.intent = True + elif body == "RELEASE" and self.gone: + self.released = True + else: + raise Refused("STATE") + + def park(self, clock): + self.check(clock) + try: + self.kernel.park() + except OSError: + self.fail("PARK", clock()) + self.check(clock) + self.abandoned = True + self.kernel.abandon() + raise Refused("SELF_GROUP_UNPROVEN") from None + self.parked = True + + def step(self, clock): + at = clock() + if not self.cleaning and at >= self.operation_end: + self.fail("LIFETIME", at) + self.check(clock) + if not self.cleaning or self.gone: + return False + if not self.parked: + self.park(clock) + self.check(clock) + if self.kernel.absent(): + self.kernel.disable() + self.gone = True + return True + if self.term_end is None: + at = self.check(clock) + self.term_end = at + TERM + self.kernel.send(signal.SIGTERM) + elif not self.killed and clock() >= self.term_end: + self.check(clock) + self.killed = True + self.kernel.send(signal.SIGKILL) + return False + + def turn(self, channel, clock): + self.check(clock) + drained = False + for _ in range(8): + try: + kind, body = channel.receive() + except Refused: + self.stop(clock()) + raise Refused(self.first) from None + if kind == "frame": + try: + self.control(body, clock()) + except Refused: + self.fail("CONTROL", clock()) + elif kind == "rejected": + self.fail("CHANNEL", clock()) + elif kind == "yield": + return False + elif kind in ("eof", "quiescent"): + drained = True + break + else: + self.stop(clock()) + raise Refused(self.first) + if channel.eof: + if self.released and self.first is None: + self.check(clock) + return True + self.fail("OWNER_EOF", clock()) + if not drained: + return False + if self.intent: + self.intent = False + if self.first is None: + self.park(clock) + self.check(clock) + try: + channel.send("PARKED") + except Refused: + self.fail("WRITE", clock()) + if self.step(clock) and self.first is None: + channel.send("GONE") + if self.gone and self.first: + raise Refused(self.first) + return False + + +class Kernel: + def __init__(self, park): + self.pid, self.destination = os.getpid(), park + self.parked = self.disabled = False + + def park(self): + if self.disabled: + raise Refused("AUTHORITY") + if not self.parked: + os.setpgid(0, self.destination) + self.parked = True + + def absent(self): + if self.disabled or not self.parked: + raise Refused("AUTHORITY") + try: + os.killpg(self.pid, 0) + return False + except ProcessLookupError: + return True + + def send(self, signum): + if self.disabled or not self.parked: + raise Refused("AUTHORITY") + try: + os.killpg(self.pid, signum) + except ProcessLookupError: + pass + + def abandon(self): + if self.disabled or self.parked or os.getpid() != self.pid or os.getpgrp() != self.pid: + raise Refused("SELF_GROUP_AUTHORITY") + self.disabled = True + os.killpg(self.pid, signal.SIGKILL) + raise Refused("SELF_GROUP_UNPROVEN") + + def disable(self): + self.disabled = True + + +def private_dir(path, root): + path = Path(path) + if not path.is_absolute() or path.resolve(strict=True) != path or not path.is_relative_to(root): + raise Refused("PRIVATE_PATH") + info = path.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700: + raise Refused("PRIVATE_MODE") + return path + + +def file_hash(path): + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "rb") as source: + before = os.fstat(source.fileno()) + if not stat.S_ISREG(before.st_mode) or before.st_size > 128 * 1024 * 1024: + raise Refused("HASH_FILE") + digest = hashlib.sha256() + count = 0 + while True: + data = source.read(65536) + if not data: + break + count += len(data) + if count > 128 * 1024 * 1024: + raise Refused("HASH_LIMIT") + digest.update(data) + after = os.fstat(source.fileno()) + if (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns): + raise Refused("HASH_DRIFT") + return digest.hexdigest() + + +def spec_read(path): + path = Path(path) + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size > 65536: + raise Refused("SPEC_FILE") + def unique(pairs): + result = {} + for key, value in pairs: + if key in result: + raise Refused("SPEC_DUPLICATE") + result[key] = value + return result + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "r", encoding="utf-8") as source: + opened = os.fstat(source.fileno()) + if (opened.st_dev, opened.st_ino, opened.st_size) != (info.st_dev, info.st_ino, info.st_size): + raise Refused("SPEC_DRIFT") + spec = json.load(source, object_pairs_hook=unique) + if type(spec) is not dict or set(spec) != {"root", "cwd", "argv", "env", "seconds", "image_sha256", "owner_sha256"}: + raise Refused("SPEC_SCHEMA") + root = Path(spec["root"]) + private_dir(root, root) + for relative in ("home", "home/.codex", "home/.claude", "home/config", "home/state", "home/capture", "home/AppData", "tmp"): + private_dir(root / relative, root) + argv = spec["argv"] + if type(argv) is not list or not 1 <= len(argv) <= 64 or any(type(v) is not str or not v or "\0" in v or len(v) > 4096 for v in argv): + raise Refused("ARGV") + image = Path(argv[0]) + if not image.is_absolute() or image.resolve(strict=True) != image or not image.is_file() or not os.access(image, os.X_OK): + raise Refused("IMAGE") + if image.name != "cargo": + raise Refused("BUILD_IMAGE") + if file_hash(image) != spec["image_sha256"] or file_hash(Path(__file__).resolve()) != spec["owner_sha256"]: + raise Refused("SOURCE_BINDING") + cwd = Path(spec["cwd"]) + if not cwd.is_absolute() or cwd.resolve(strict=True) != cwd or not cwd.is_dir(): + raise Refused("CWD") + if type(spec["seconds"]) is not int or not 3 <= spec["seconds"] <= 600: + raise Refused("LIFETIME") + env = spec["env"] + allowed = {"HOME", "CODEX_HOME", "CLAUDE_CONFIG_DIR", "KEITO_CAPTURE_HOME", "XDG_CONFIG_HOME", "XDG_STATE_HOME", "APPDATA", "TMPDIR", "PATH", "CARGO_HOME", "RUSTUP_HOME", "CARGO_TARGET_DIR", "CARGO_BUILD_JOBS", "CARGO_NET_OFFLINE", "RUST_TEST_THREADS", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_CONFIG_NOSYSTEM"} + if type(env) is not dict or set(env) != allowed or any(type(v) is not str or not v or "\0" in v or len(v) > 4096 for v in env.values()): + raise Refused("ENV") + for key, relative in (("HOME", "home"), ("CODEX_HOME", "home/.codex"), ("CLAUDE_CONFIG_DIR", "home/.claude"), ("KEITO_CAPTURE_HOME", "home/capture"), ("XDG_CONFIG_HOME", "home/config"), ("XDG_STATE_HOME", "home/state"), ("APPDATA", "home/AppData"), ("TMPDIR", "tmp")): + if env[key] != str(root / relative): + raise Refused("PRIVATE_ENV") + if env["PATH"] != ":".join((str(image.parent), "/usr/bin", "/bin", "/usr/sbin", "/sbin")): + raise Refused("TOOLCHAIN_PATH") + if env["CARGO_NET_OFFLINE"] != "true" or env["CARGO_BUILD_JOBS"] != "2" or env["RUST_TEST_THREADS"] != "1" or env["GIT_CONFIG_GLOBAL"] != "/dev/null" or env["GIT_CONFIG_SYSTEM"] != "/dev/null" or env["GIT_CONFIG_NOSYSTEM"] != "1": + raise Refused("BUILD_ENV") + # Only the caller's exact recorded toolchain/cache paths, never PATH lookup. + for key in ("CARGO_HOME", "RUSTUP_HOME", "CARGO_TARGET_DIR"): + candidate = Path(env[key]) + if not candidate.is_absolute() or candidate.resolve(strict=True) != candidate or not candidate.is_dir(): + raise Refused("BUILD_PATH") + if not Path(env["CARGO_TARGET_DIR"]).is_relative_to(root): + raise Refused("PRIVATE_TARGET") + return spec + + +def exclusive(path): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + return os.fdopen(fd, "w", encoding="utf-8") + + +class BuildRun: + def __init__(self, root, hard): + self.root, self.hard = root, hard + self.keeper = self.child = self.keeper_status = self.child_status = None + self.child_attempted = False + self.first = None + self.secondary = [] + self.cancelled = False + self.end = None + self.gone = self.release = self.proof = False + self.channel = None + self.writer_attempted = self.writer_shutdown_ok = False + self.trace = exclusive(root / "events.jsonl") + self.output = exclusive(root / "output.log") + + def fail(self, reason): + if self.first is None: + self.first = reason + elif reason != self.first and reason not in self.secondary and len(self.secondary) < 8: + self.secondary.append(reason) + + def note_cancelled(self): + if getattr(self, "cancelled", False): + self.fail("CANCELLED") + + def checkpoint(self): + self.note_cancelled() + if getattr(self, "cancelled", False): + raise Refused(self.first or "CANCELLED") + + def event(self, tag): + try: + self.trace.write(json.dumps({"event": tag, "at": time.monotonic_ns()}) + "\n") + self.trace.flush() + os.fsync(self.trace.fileno()) + except OSError: + raise Refused("RECEIPT") from None + self.checkpoint() + + def collect(self): + self.note_cancelled() + if self.child is not None and self.child_status is None: + try: + self.child_status = self.child.poll() + except BaseException: + self.fail("CHILD_WAIT") + if self.keeper is not None and self.keeper_status is None: + try: + pid, status = os.waitpid(self.keeper, os.WNOHANG) + if pid: + self.keeper_status = os.waitstatus_to_exitcode(status) + except BaseException: + self.fail("KEEPER_WAIT") + if self.keeper_status is not None and not self.release: + self.fail("KEEPER_EXIT_EARLY") + + def all_waited(self): + return (self.child is None or self.child_status is not None) and (self.keeper is None or self.keeper_status is not None) + + def close_writer(self): + if self.channel and not self.writer_attempted: + self.writer_attempted = True + try: + self.channel.stream.shutdown(socket.SHUT_WR) + self.writer_shutdown_ok = True + except BaseException: + self.fail("SHUTDOWN") + try: + self.channel.stream.close() + except BaseException: + self.fail("SHUTDOWN_CLOSE") + + def wait_frame(self, body, end): + while time.monotonic_ns() < end: + self.checkpoint() + kind, value = self.channel.receive() + if kind == "frame": + if value != body: + raise Refused("HANDSHAKE") + if time.monotonic_ns() >= end: + raise Refused("HANDSHAKE_LATE") + self.checkpoint() + return + if kind in ("eof", "rejected"): + raise Refused("HANDSHAKE") + time.sleep(0.001) + raise Refused("HANDSHAKE_DEADLINE") + + def begin(self): + self.note_cancelled() + # Single immutable broadcast, before cancellation wait collection. + if self.end is not None: + raise Refused("CLEAN_ALREADY_BOUND") + self.end = min(self.hard, time.monotonic_ns() + CAP) + self.channel.send("CLEAN|" + str(self.end)) + if self.first: + self.close_writer() + + def settle(self): + while True: + self.collect() # Available wait facts survive every previous fault. + if self.first: + self.close_writer() + at = time.monotonic_ns() + if at >= self.end: + self.fail("CLEANUP_DEADLINE") + break + try: + kind, body = self.channel.receive() + if kind == "rejected": + raise Refused("CHANNEL") + if kind == "frame": + if self.first or body != "GONE" or self.gone: + raise Refused("TERMINAL") + self.gone = True + if self.gone and not self.release and self.child_status is not None and not self.first: + if time.monotonic_ns() >= self.end: + raise Refused("CLEANUP_DEADLINE") + self.channel.send("RELEASE") + self.close_writer() + self.release = True + if kind == "eof": + if not self.release: + self.fail("EARLY_EOF") + if self.all_waited(): + if self.keeper_status != 0: + self.fail("KEEPER_FAILED") + self.proof = not self.first and self.gone and self.release and not self.channel.pending and time.monotonic_ns() < self.end + break + except (Refused, OSError) as error: + self.fail(str(error) if isinstance(error, Refused) else "CHANNEL_IO") + self.close_writer() + time.sleep(0.001) + self.collect() + + def retain_waits(self): + # After a failed proof deadline, only immediately available direct wait + # collection continues, inside the ORIGINAL immutable operation lifetime. + # No new signalling, retry budget, or proof upgrade occurs here. + while not self.all_waited() and time.monotonic_ns() < self.hard: + self.collect() + time.sleep(0.001) + self.collect() + + def cancel_signal(self, _signum, _frame): + # Existing-key, fixed-value latch only. No exception, I/O, or waits in a + # handler; explicit normal-work checkpoints stop later admissions. + self.cancelled = True + + def guard(self, reason, action): + try: + return True, action() + except BaseException as error: + if isinstance(error, KeyboardInterrupt): + # Restored default INT handlers can throw in ANY guarded tail + # stage, including stdout/stderr. Normalize before rebuilding + # a fallback packet; the stage code is additional evidence. + self.cancel_signal(None, None) + self.note_cancelled() + self.fail(reason) + return False, None + + def finalize(self, parent, child, result_saved, saved_handlers, cutpoint=None): + self.note_cancelled() + # Freeze pre-fallback facts even if FIRST publication failed. facts() + # copies its secondary list, so late observations cannot mutate it. + if cutpoint is None: + cutpoint = self.facts() + self.guard("FINAL_SHUTDOWN", self.close_writer) + if child is not None: + self.guard("CHILD_END_CLOSE", child.close) + if not result_saved: + self.proof = False + self.guard("AVAILABLE_WAITS", self.collect) + self.guard("FINAL_WAIT", self.retain_waits) + self.note_cancelled() + after = self.facts() + after.update(first_preserved=result_saved, first_result_write_failed=not result_saved, + cutpoint=cutpoint, handler_restoration_pending=True, + mask_restoration_pending=True, handoff_complete=False) + def save(): + with exclusive(self.root / "FINAL.json") as output: + json.dump(after, output, indent=2) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + final_saved, _ = self.guard("FINAL_RECEIPT", save) + if parent is not None: + self.guard("PARENT_END_CLOSE", parent.close) + self.guard("OUTPUT_CLOSE", self.output.close) + self.guard("TRACE_CLOSE", self.trace.close) + self.note_cancelled() + def publish(pending, mask_pending=True): + packet = json.dumps({"owner_result": self.facts(), "cutpoint": cutpoint, + "first_saved": result_saved, "final_saved": final_saved, + "handler_restoration_pending": pending, + "mask_restoration_pending": mask_pending, + "handoff_complete": not pending and not mask_pending}) + if len(packet.encode("utf-8")) > 16384: + raise Refused("FACT_LIMIT") + ok, _ = self.guard("FACT_STDOUT", lambda: print(packet, flush=True)) + if not ok: + # A second catchable signal/output failure cannot skip an + # alternate bounded fact sink or handler restoration. + packet = json.dumps({"owner_result": self.facts(), "cutpoint": cutpoint, + "first_saved": result_saved, "final_saved": final_saved, + "handler_restoration_pending": pending, + "mask_restoration_pending": mask_pending, + "handoff_complete": not pending and not mask_pending}) + self.guard("FACT_STDERR", lambda: print(packet, file=sys.stderr, flush=True)) + self.guard("FACT_PUBLICATION", lambda: publish(True)) + # Only the final handler handoff is masked, after waits/closes/facts; + # the long bounded cleanup itself uses the non-throwing latch. + masked, previous_mask = self.guard("HANDOFF_MASK", lambda: signal.pthread_sigmask( + signal.SIG_BLOCK, (signal.SIGINT, signal.SIGTERM))) + restored, unmasked = False, False + if masked: + try: + ok, pending = self.guard("PENDING_CANCEL", signal.sigpending) + if ok and pending.intersection((signal.SIGINT, signal.SIGTERM)): + self.cancel_signal(None, None) + restored = True + for signum, handler in saved_handlers.items(): + ok, _ = self.guard("RESTORE_HANDLER", lambda s=signum, h=handler: signal.signal(s, h)) + restored = restored and ok + self.note_cancelled() + finally: + def restore_mask(): + try: + signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask) + except KeyboardInterrupt: + # A late pending INT can invoke the restored handler + # during unmask. Preserve cancellation as well as the + # uncertain mask disposition; never retry this handoff. + self.cancel_signal(None, None) + self.fail("HANDOFF_UNMASK") + raise + unmasked, _ = self.guard("HANDOFF_UNMASK", restore_mask) + # If masking failed, leave this standalone helper's latch installed + # until failed exit. FINAL stays an immutable pre-handoff snapshot. + # The LAST bounded packet follows the actual unmask attempt, including + # its first/secondary failure and explicit uncertainty, not just intent. + self.note_cancelled() + self.guard("FINAL_FACT_PUBLICATION", lambda: publish(not restored, not unmasked)) + + def facts(self): + return {"first_fault": self.first, "secondary_faults": list(self.secondary), + "cancelled": getattr(self, "cancelled", False), + "keeper_spawned": self.keeper is not None, "child_spawned": self.child is not None, + "keeper_pid": self.keeper, "child_pid": getattr(self.child, "pid", None), + "child_spawn_attempted": self.child_attempted, + "missing_handle_after_attempt_is_unknown": self.child_attempted and self.child is None, + "keeper_wait": self.keeper_status, "child_wait": self.child_status, + "group_absence_asserted_by_keeper": self.gone, + "raw_esrch_independently_observed": False, + "release_sent": self.release, "writer_shutdown_ok": self.writer_shutdown_ok, "terminal_eof": bool(self.channel and self.channel.eof and not self.channel.pending), + "cleanup_proof": self.proof, "hard_end": self.hard, "cleanup_end": self.end} + + +def child_keeper(stream, other, nonce, park, hard, maxfd, inherited_mask): + other.close() + try: + # External cancellation of the owner's group must close the lifeline, + # not kill its parked keeper before it can clean the reserved group. + signal.signal(signal.SIGINT, signal.SIG_IGN) + signal.signal(signal.SIGTERM, signal.SIG_IGN) + signal.pthread_sigmask(signal.SIG_SETMASK, inherited_mask) + os.setpgid(0, 0) + fd = stream.fileno() + null = os.open("/dev/null", os.O_RDWR) + for target in (0, 1, 2): + os.dup2(null, target) + if null > 2 and null != fd: + os.close(null) + os.closerange(3, fd) + os.closerange(fd + 1, maxfd) + channel = Channel(stream, nonce) + machine = Keeper(Kernel(park), hard) + channel.send("READY") + while not machine.turn(channel, time.monotonic_ns): + time.sleep(0.001) + os._exit(0) + except BaseException: + os._exit(1) + + +def run(spec): + if os.environ.get("KEITO_BOOTSTRAP_POLICY_CONFIRMED") != "source-group-build-only": + raise Refused("POLICY_PREREQUISITE") + root = Path(spec["root"]) + hard = time.monotonic_ns() + spec["seconds"] * 1_000_000_000 + state = BuildRun(root, hard) + parent = child = None + first_facts = None + result_saved = False + saved_handlers = {} + try: + for signum in (signal.SIGINT, signal.SIGTERM): + saved_handlers[signum] = signal.signal(signum, state.cancel_signal) + state.checkpoint() + parent, child = socket.socketpair() + nonce = os.urandom(16).hex() + state.channel = Channel(parent, nonce) # Before fork: no lost child on setup error. + maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + if not 3 <= maxfd <= 1_048_576: + raise Refused("FD_BOUND") + park = os.getpgrp() + # A caught cancellation cannot interrupt fork/returned-handle assignment. + # Uncatchable parent death cannot supply direct waits and is not proof. + mask = signal.pthread_sigmask(signal.SIG_BLOCK, (signal.SIGINT, signal.SIGTERM)) + try: + # Masking prevents a NEW callback during assignment; it does not + # revoke a cancellation already accepted during setup. + state.checkpoint() + pid = os.fork() + if pid == 0: + child_keeper(child, parent, nonce, park, hard, maxfd, mask) + state.keeper = pid # BEFORE unmasking or any READY/receipt I/O. + finally: + signal.pthread_sigmask(signal.SIG_SETMASK, mask) + child.close() + child = None + try: + state.event("KEEPER_REGISTERED") + state.wait_frame("READY", min(hard - CAP, time.monotonic_ns() + CAP)) + state.checkpoint() + mask = signal.pthread_sigmask(signal.SIG_BLOCK, (signal.SIGINT, signal.SIGTERM)) + try: + state.checkpoint() + state.child_attempted = True + def join_group(): + os.setpgid(0, pid) + signal.pthread_sigmask(signal.SIG_SETMASK, mask) + state.child = subprocess.Popen(spec["argv"], cwd=spec["cwd"], env=spec["env"], + stdin=subprocess.DEVNULL, stdout=state.output, + stderr=state.output, close_fds=True, + preexec_fn=join_group) + except OSError: + state.fail("SPAWN") + raise Refused("SPAWN") from None + finally: + signal.pthread_sigmask(signal.SIG_SETMASK, mask) + state.event("CHILD_REGISTERED") + state.channel.send("PARK") + state.wait_frame("PARKED", min(hard - CAP, time.monotonic_ns() + CAP)) + # Normal completion is not group proof. A collected leader still + # requires CLEAN, keeper absence assertion and clean terminal EOF. + while state.child_status is None and time.monotonic_ns() < hard - CAP: + state.collect() + if state.first: + raise Refused(state.first) + time.sleep(0.001) + if state.child_status is None: + raise Refused("BUILD_LIFETIME") + except (Refused, OSError) as error: + state.fail(str(error) if isinstance(error, Refused) else "OWNER_IO") + try: + state.begin() + except (Refused, OSError): + state.fail("BEGIN") + state.end = min(hard, time.monotonic_ns() + CAP) if state.end is None else state.end + state.close_writer() + state.settle() + first_facts = state.facts() + first_facts["command_success"] = state.child_status == 0 + try: + with exclusive(root / "FIRST.json") as output: + json.dump(first_facts, output, indent=2) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + except OSError: + raise Refused("FIRST_RECEIPT") from None + result_saved = True + except BaseException as error: + # Receipt/setup failures cannot discard registered handles or replace + # the first reason with a later success. No raw exception text escapes. + state.fail(str(error) if isinstance(error, Refused) else "OWNER_INTERNAL") + finally: + state.finalize(parent, child, result_saved, saved_handlers, first_facts) + return bool(result_saved and first_facts["cleanup_proof"] and first_facts["command_success"] + and not state.first and state.all_waited()) + + +if __name__ == "__main__": + try: + if len(sys.argv) != 2: + raise Refused("ARGS") + prepared = spec_read(sys.argv[1]) + except BaseException as error: + code = str(error) if isinstance(error, Refused) else "SETUP" + print(json.dumps({"setup_refused": code, "actors_started": False}), flush=True) + sys.exit(1) + try: + success = run(prepared) + except BaseException: + # Do not call a post-entry error a preflight refusal or fabricate waits. + print(json.dumps({"owner_entry_failed": True, "cleanup_qualified": False}), flush=True) + success = False + sys.exit(0 if success else 1) diff --git a/tests/support/source_qa_cargo.py b/tests/support/source_qa_cargo.py new file mode 100644 index 0000000..e6237c0 --- /dev/null +++ b/tests/support/source_qa_cargo.py @@ -0,0 +1,63 @@ +"""Use the separately reviewed opaque COMPILER owner, never runtime Scope. + +Only preparation/argv changed here; source_qa_build_owner.py stays unchanged. +Compiler-tree cancellation remains outside the runtime qualification claim. +""" +from pathlib import Path +import hashlib +import json +import os + + +def build_script_target(profile): + # Cargo's build-unit layout stores script stdout under run/stdout. + # Only this private source build's Keito package may name the pair target; + # inspect both layouts together so conflicting outputs still refuse. + outputs = [path for pattern in ("keito-cli-*/output", "keito-cli/*/run/stdout") + for path in (profile / "build").glob(pattern)] + targets = {line.split("=", 2)[2] for path in outputs for line in path.read_text().splitlines() + if line.startswith("cargo:rustc-env=KEITO_BUILD_TARGET=")} + if len(targets) != 1: + raise RuntimeError("Expected exactly one source-build target; found " + str(len(targets))) + return targets.pop() + + +def cargo(root, repo, image, base_environment, label, arguments): + from source_qa_build_owner import run, spec_read + import source_qa_build_owner as owner_source + assert label and all(c.isalnum() or c == "-" for c in label) + image = Path(image).resolve(strict=True) + assert image.name == "cargo" and image.is_file() + build = root / ("compiler-" + label) + build.mkdir(mode=0o700) + for relative in ("home", "home/.codex", "home/.claude", "home/config", "home/state", + "home/capture", "home/AppData", "tmp", "target"): + (build / relative).mkdir(mode=0o700) + env = {"HOME": str(build / "home"), "CODEX_HOME": str(build / "home/.codex"), + "CLAUDE_CONFIG_DIR": str(build / "home/.claude"), "KEITO_CAPTURE_HOME": str(build / "home/capture"), + "XDG_CONFIG_HOME": str(build / "home/config"), "XDG_STATE_HOME": str(build / "home/state"), + "APPDATA": str(build / "home/AppData"), "TMPDIR": str(build / "tmp"), + "PATH": ":".join((str(image.parent), "/usr/bin", "/bin", "/usr/sbin", "/sbin")), + "CARGO_HOME": base_environment["CARGO_HOME"], "RUSTUP_HOME": base_environment["RUSTUP_HOME"], + "CARGO_TARGET_DIR": str(build / "target"), "CARGO_BUILD_JOBS": "2", + "CARGO_NET_OFFLINE": "true", "RUST_TEST_THREADS": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"} + digest = lambda p: hashlib.sha256(Path(p).read_bytes()).hexdigest() + spec = {"root": str(build), "cwd": str(repo), "argv": [str(image), *arguments], "env": env, + "seconds": 600, "image_sha256": digest(image), "owner_sha256": digest(owner_source.__file__)} + spec_path = build / "spec.json" + fd = os.open(spec_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "w") as output: + json.dump(spec, output, indent=2); output.write("\n"); output.flush(); os.fsync(output.fileno()) + old = os.environ.get("KEITO_BOOTSTRAP_POLICY_CONFIRMED") + os.environ["KEITO_BOOTSTRAP_POLICY_CONFIRMED"] = "source-group-build-only" + try: + if not run(spec_read(spec_path)): + raise RuntimeError("first compiler command failed; preserve evidence") + finally: + if old is None: + os.environ.pop("KEITO_BOOTSTRAP_POLICY_CONFIRMED", None) + else: + os.environ["KEITO_BOOTSTRAP_POLICY_CONFIRMED"] = old + return build / "target/debug" + diff --git a/tests/support/source_qa_children.py b/tests/support/source_qa_children.py new file mode 100644 index 0000000..514be29 --- /dev/null +++ b/tests/support/source_qa_children.py @@ -0,0 +1,795 @@ +"""Developer-only tracked direct children; no process discovery or product authority.""" +import datetime +import hashlib +import json +import os +import secrets +import signal +import subprocess +import time +from pathlib import Path + + +# One original installation maximum; inherited parents always clip it. +INSTALL_OPERATION_NS = 30_000_000_000 + + +def _stderr_category(block): + """Closed diagnostic from an already-read block; never retain its content.""" + if type(block) is not bytes or len(block) > 4096: + return None + try: + value = json.loads(block) + except (ValueError, UnicodeError, RecursionError): + return None + if (type(value) is not dict or value.get("error") is not True + or not set(value) <= {"error", "code", "message", "suggestion", "details"} + or type(value.get("code")) is not int or not 1 <= value["code"] <= 8): + return None + if value["code"] == 8: + messages = { + "Configuration error: Repository command ownership unavailable; capture paused": "REPOSITORY_OWNERSHIP", + "Configuration error: Capture command ownership unavailable; collection remains paused": "COMMAND_OWNERSHIP", + "Configuration error: Command ownership did not settle; collection remains paused": "TERMINAL_SETTLEMENT", + "Configuration error: Numeric profile qualification is unavailable; review the supported native version, managed installation and explicit profile approval. Metadata capture remains available.": "PROFILE_QUALIFICATION", + } + message = value.get("message") + if type(message) is str and message in messages: + return messages[message] + reasons = { + "admission_refused": ("ownership admission refused", "VERSION_PROBE_ADMISSION"), + "deadline": ("original deadline exceeded", "VERSION_PROBE_DEADLINE"), + "clock": ("monotonic clock unavailable", "VERSION_PROBE_CLOCK"), + "ownership": ("ownership proof unavailable", "VERSION_PROBE_OWNERSHIP"), + "unavailable": ("probe unavailable", "VERSION_PROBE_UNAVAILABLE"), + } + details = value.get("details") + if (type(details) is dict + and set(details) == {"kind", "reason", "cleanup_unverified", "cleanup_status"} + and details.get("kind") == "capture_version_probe" + and type(details.get("reason")) is str and details["reason"] in reasons + and type(details.get("cleanup_unverified")) is bool + and details.get("cleanup_status") == ("unverified" if details["cleanup_unverified"] else "not_reported")): + display, category = reasons[details["reason"]] + if message == "Coding-agent version probe refused: " + display: + return category + return (None, "APP_ERROR_1", "APP_ERROR_2", "APP_ERROR_3", "APP_ERROR_4", + "APP_ERROR_5", "APP_ERROR_6", "APP_ERROR_7", "APP_ERROR_8")[value["code"]] + + +class Cancelled(BaseException): + def __init__(self, signum): + self.signum = signum + + +class ChildFailure(RuntimeError): + pass + + +class RuntimeOutputLimit(ChildFailure): + """Expose bounded metadata in a traceback, never captured output content.""" + def __init__(self): + super().__init__("runtime output limit") + self.observation = None + + def __str__(self): + value = self.observation + categories = {"REPOSITORY_OWNERSHIP", "COMMAND_OWNERSHIP", "TERMINAL_SETTLEMENT", + "PROFILE_QUALIFICATION", "VERSION_PROBE_ADMISSION", "VERSION_PROBE_DEADLINE", + "VERSION_PROBE_CLOCK", "VERSION_PROBE_OWNERSHIP", "VERSION_PROBE_UNAVAILABLE"} + categories.update("APP_ERROR_" + str(code) for code in range(1, 9)) + if (type(value) is not dict + or set(value) != {"stream", "observed_bytes", "allowed_bytes", "error_category"} + or type(value["stream"]) is not str or value["stream"] not in ("stdout", "stderr") + or any(type(value[key]) is not int or not 0 <= value[key] <= 2**64 - 1 + for key in ("observed_bytes", "allowed_bytes")) + or (value["error_category"] is not None + and (type(value["error_category"]) is not str or value["error_category"] not in categories))): + return super().__str__() + return ("runtime output limit: stream=" + value["stream"] + + " observed_bytes=" + str(value["observed_bytes"]) + + " allowed_bytes=" + str(value["allowed_bytes"]) + + " category=" + (value["error_category"] or "UNKNOWN")) + + + +# Failure-only closed metadata; no child/path/payload reads or ownership actions. +_DIAGNOSTIC_FAULTS = frozenset({ + "PEER_FAILED", "RUNTIME_ENDPOINT", "RUNTIME_DEADLINE", "RUNTIME_OUTPUT_LIMIT", + "RUNTIME_INPUT_WRITE", "RUNTIME_INPUT_CLOSE", "RUNTIME_OUTPUT_READ", + "RUNTIME_DIRECT_WAIT", "RUNTIME_WAIT_RECEIPT", "RUNTIME_PIPE_FLAGS", + "RUNTIME_START_OR_RECEIPT", "RUNTIME_RESULT_RECEIPT", "RUNTIME_COMMAND_FAILED", + "RUNTIME_PARENT_OR_SIGNAL", "RUNTIME_SLOT_POLL", "RUNTIME_SLOT_COLLECTION", + "RUNTIME_CLEANUP_DEADLINE", "RUNTIME_CANCEL_WRITE", "RUNTIME_CONTROL_CLOSE", + "RUNTIME_OPERATION_OR_RECEIPT", "RUNTIME_EXIT_COLLECTION", "RUNTIME_OWNER_EXIT", + "RUNTIME_SIGNAL", "OWNER_CLOCK", "EOF_WITHOUT_TERMINAL", "READ_FAILED", + "WRITE_FAILED", "TRUNCATED_FRAME", "POST_TERMINAL_DATA", "PEER_IDENTITY", +}) +_DIAGNOSTIC_MATRIX = frozenset({ + "positive", "profile-record-changed", "managed-root-recreated", + "native-image-changed", "registration-changed", "generation-changed", + "generation-receipt-changed", "source-replaced", "source-symlink", "source-fifo", + "source-hardlink", "source-directory", "source-wrong-session", "path-missing", + "path-null", "path-wrong-namespace", "path-wrong-session", "numeric-revoked", + "metadata-paused", "wrong-owned-native-image-bounded-chain", +}) +_DIAGNOSTIC_PHASES = frozenset({ + "normal-dispatch", "pre-mutation-prompt", "post-mutation-stop", + "wrong-origin-prompt", "terminal-after-wrong-origin", +}) + + +def _closed_diagnostic_value(value, choices): + return value if type(value) is str and value in choices else "UNKNOWN" + + +def _closed_diagnostic_fault(value): + if value is None: + return None + return value if type(value) is str and value in _DIAGNOSTIC_FAULTS else "OTHER" + + +def owned_failure_snapshot(manager): + """Read only retained Python facts; never poll, wait, drain, clock or repr.""" + slots = manager.slots + slot = slots[-1] if slots else {} + endpoint = slot.get("endpoint") + child = slot.get("child") + status = child.returncode if child is not None else None + status = status if type(status) is int and -(2**31) <= status < 2**31 else None + def flag(value): + return value if type(value) is bool else None + def count(value): + return value if type(value) is int and 0 <= value <= 2**64 - 1 else None + return { + "slot_count": min(len(slots), 4096), + "direct_handle_retained": child is not None, + "direct_wait_known": status is not None, + "direct_returncode": status, + "accepted": slot.get("accepted") is not None, + "collected": flag(slot.get("collected")), + "waited_published": flag(slot.get("waited_published")), + "stdin_closed": (child.stdin is None) if child is not None else None, + "stdout_eof": flag(slot.get("stdout_eof")), + "stderr_eof": flag(slot.get("stderr_eof")), + "stdout_bytes": count(slot.get("stdout_count")), + "stderr_bytes": count(slot.get("stderr_count")), + "endpoint_live": flag(getattr(endpoint, "live", None)), + "endpoint_terminal": flag(getattr(endpoint, "terminal", None)), + "endpoint_eof": flag(getattr(endpoint, "eof", None)), + "endpoint_settled": flag(getattr(endpoint, "settled", None)), + "slot_fault": _closed_diagnostic_fault(slot.get("first_fault")), + "endpoint_fault": _closed_diagnostic_fault(getattr(endpoint, "first_fault", None)), + "owner_fault": _closed_diagnostic_fault(manager.owner.first_fault), + } + + +def diagnosed_owned_operation(manager, operation, context, emit): + """Preserve existing context cleanup and primary exception; emit only after it.""" + first = None + try: + with manager: + try: + return operation(manager) + except BaseException: + try: + first = owned_failure_snapshot(manager) + except BaseException: + pass + raise + except BaseException: + try: + record = { + "schema": 1, "source_fixture_only": True, + "namespace": _closed_diagnostic_value(context.get("namespace"), {"codex", "claude-code"}), + "matrix_label": _closed_diagnostic_value(context.get("matrix_label"), _DIAGNOSTIC_MATRIX), + "phase": _closed_diagnostic_value(context.get("phase"), _DIAGNOSTIC_PHASES), + "event": _closed_diagnostic_value(context.get("event"), {"prompt", "stop"}), + "first": first, "after_cleanup": owned_failure_snapshot(manager), + } + emit(record) + except BaseException: + pass # Diagnostics never replace the original exception or retry work. + raise + + +class LegacyDirectChildren: + """Historical direct/group tests only; never the actual capture runner. + + Preserved to keep its original regression assertions and failed history. + It does not supply the new cooperative descendant proof. + """ + def __init__(self, root, environment, cwd): + self.root, self.environment, self.cwd = root, environment, cwd + self.active = None + self.cleaning = False + self.spawning = False + self.pending_cancel = None + self.handlers = {} + + def __enter__(self): + for signum in (signal.SIGTERM, signal.SIGINT): + self.handlers[signum] = signal.signal(signum, self._cancel) + return self + + def _cancel(self, signum, _frame): + if self.cleaning: + return + if self.spawning: + self.pending_cancel = signum + return + raise Cancelled(signum) + + def __exit__(self, *_): + try: + if self.active is not None and "cleanup" not in self.active: + self._cleanup(self.active) + finally: + for signum, handler in self.handlers.items(): + signal.signal(signum, handler) + + def _record(self, name, value): + with (self.root / name).open("x") as output: + json.dump(value, output, indent=2) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + + def _cleanup(self, active): + self.cleaning = True + child = active["child"] + actions = [] + try: + # The Popen handle is still owned and unreaped. Its PID cannot be + # recycled before wait; never signal a reaped PID or discover others. + if child.returncode is None: + for signum, grace in ((signal.SIGTERM, 2), (signal.SIGKILL, 2)): + try: + os.killpg(child.pid, signum) + actions.append({"signal": signum, "owned_pgid": child.pid}) + except OSError as failure: + actions.append({"signal": signum, "signal_errno": failure.errno}) + try: + child.wait(timeout=grace) + break + except subprocess.TimeoutExpired: + continue + except OSError as failure: + actions.append({"wait_errno": failure.errno}) + continue + waited = child.returncode is not None + active["cleanup"] = {"actions": actions, "waited": waited, "returncode": child.returncode} + if waited: + self.active = None + return waited + finally: + self.cleaning = False + + def run(self, label, arguments, timeout, extra=None, capture_limit=0): + if self.active is not None or not label or any(not (value.isalnum() or value == "-") for value in label): + raise ChildFailure("invalid owned child operation") + started = time.monotonic() + active = None + error = None + waited = False + with (self.root / (label + ".log")).open("xb") as output, (self.root / (label + ".stderr.log")).open("xb") as errors: + try: + # Defer the handler only over spawn+assignment. An inherited + # OS signal mask would also block TERM in the executed child. + self.pending_cancel = None + self.spawning = True + try: + child = subprocess.Popen(arguments, cwd=self.cwd, + env={**self.environment, **(extra or {})}, stdin=subprocess.DEVNULL, + stdout=output, stderr=errors, start_new_session=True) + active = {"child": child, "pid": child.pid, "pgid": child.pid, + "launch_before_monotonic_ns": int(started * 1_000_000_000)} + self.active = active + finally: + self.spawning = False + if self.pending_cancel is not None: + raise Cancelled(self.pending_cancel) + active.update({"launch_nonce": secrets.token_hex(16), "launch_after_monotonic_ns": time.monotonic_ns(), + "started_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "observed_pgid": os.getpgid(child.pid)}) + if active["observed_pgid"] != child.pid: + raise ChildFailure("owned child process group mismatch") + self._record(label + "-child-started.json", {key: value for key, value in active.items() if key != "child"}) + child.wait(timeout=timeout) + waited = True + self.active = None # Only after the confirmed direct wait. + except BaseException as failure: + error = failure + finally: + if active is not None and not waited: + waited = self._cleanup(active) + result = {"source_fixture_only": True, "command": arguments, "timeout_seconds": timeout, + "elapsed_seconds": time.monotonic() - started, "waited": waited, + "returncode": active["child"].returncode if active else None, + "child": {key: value for key, value in active.items() if key != "child"} if active else None, + "error_type": type(error).__name__ if error else None, + "cancel_signal": error.signum if isinstance(error, Cancelled) else None, + "timed_out": isinstance(error, subprocess.TimeoutExpired)} + try: + for suffix in (".log", ".stderr.log"): + with (self.root / (label + suffix)).open("rb") as source: + digest = hashlib.sha256() + for block in iter(lambda: source.read(64 * 1024), b""): + digest.update(block) + result[suffix + "_sha256"] = digest.hexdigest() + self._record(label + "-result.json", result) + except BaseException as receipt_error: + # Cleanup and the original failure must survive a receipt fault. + if error is None: + error = receipt_error + try: + LegacyDirectChildren._record(self, label + "-cleanup-fallback.json", result) + except BaseException: + pass + if error is not None: + raise error + if not waited or result["returncode"] != 0: + raise ChildFailure("owned source child failed; preserve the first result") + if capture_limit: + path = self.root / (label + ".log") + if path.stat().st_size > capture_limit: + raise ChildFailure("owned metadata output exceeds bound") + return path.read_bytes() + return None + + +class OwnedChildren: + """Retained multi-slot COOPERATIVE runtime children, not compiler authority. + + No PID/group signalling and no raw output files. A terminal is accepted only + with actual read-zero EOF on each pipe/socket and the retained direct wait. + """ + def __init__(self, root, environment, cwd, owner=None): + from source_qa_protocol import SourceOwner + self.root, self.environment, self.cwd = root, environment, cwd + self.owner = owner if owner is not None else SourceOwner() + self.owns_owner = owner is None + self.slots = [] + self.handlers = {} + self.spawning = False + self.pending_cancel = None + self.cleanup_end = None + self.io_reserved = 0 + self.first_error = None + self.entered = False + self.hard_end = None + + @property + def active(self): + return next((slot for slot in self.slots if not slot["collected"]), None) + + def _record(self, name, value): + # Receipt contents are bounded metadata, never child input/output. + with (self.root / name).open("x") as output: + json.dump(value, output, indent=2) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + + def _fail(self, error, reason): + if self.first_error is None: + self.first_error = error + self.owner.fail_manager(self, reason) + + def _now(self): + at = self.owner.now() + if self.owner.deadline_ns == 0: + from source_qa_protocol import ProtocolError + self.hard_end = self.cleanup_end = 0 + self._fail(ProtocolError("OWNER_CLOCK"), "OWNER_CLOCK") + # begin_cleanup performs no clock read: a recovered later clock + # cannot reopen zero or replace the original operation exception. + self.begin_cleanup(0) + return at + + def _restore_handlers(self): + for signum, handler in self.handlers.items(): + try: + signal.signal(signum, handler) + except BaseException as error: + self._fail(error, "RUNTIME_SIGNAL_RESTORE") + + def _exit_owned_owner(self, exception): + if not self.owns_owner: + return + import source_qa_protocol as protocol + try: + self.owner.__exit__(type(exception) if exception is not None else None, + exception, exception.__traceback__ if exception is not None else None) + finally: + protocol.CURRENT = self.owner.previous + + def _cancel(self, signum, _frame): + self.pending_cancel = signum + if not self.spawning: + self.owner.fail("RUNTIME_SIGNAL") + + def __enter__(self): + if self.entered: + raise ChildFailure("runtime manager reused") + self.entered = True + try: + if self.owns_owner: + self.owner.__enter__() + self.owner.register_manager(self) + for signum in (signal.SIGTERM, signal.SIGINT): + self.handlers[signum] = signal.signal(signum, self._cancel) + except BaseException as error: + self._fail(error, "RUNTIME_ENTER") + try: + self._restore_handlers() + finally: + try: self._exit_owned_owner(error) + except BaseException as secondary: self._fail(secondary, "RUNTIME_OWNER_EXIT") + raise + return self + + def __exit__(self, kind, exception, traceback): + if exception is not None: + self._fail(exception, "RUNTIME_OPERATION_OR_RECEIPT") + try: + self.begin_cleanup(self.hard_end if self.hard_end is not None else self._now()) + while not self.poll_cleanup(self.cleanup_end): + if self._now() >= self.cleanup_end: + self.owner.fail("RUNTIME_CLEANUP_DEADLINE") + break + time.sleep(0.001) + except BaseException as error: + self._fail(error, "RUNTIME_EXIT_COLLECTION") + finally: + try: + self._restore_handlers() + finally: + try: self._exit_owned_owner(exception if exception is not None else self.first_error) + except BaseException as error: self._fail(error, "RUNTIME_OWNER_EXIT") + if exception is None and self.first_error is not None: + raise self.first_error + return False + + def _select_end(self, timeout, installer=False): + if installer and (self.owner.managers != [self] or self.slots + or self.hard_end is not None or self.owner.runtime_end_ns is not None): + raise ChildFailure("installer must be the first runtime admission") + self.owner.check() + at = self._now() + maximum = INSTALL_OPERATION_NS if installer else 4_000_000_000 + self.owner.limit_end(at + maximum) + end = min(at + int(timeout * 1_000_000_000), self.owner.deadline_ns, at + maximum) + if self.hard_end is not None: + end = min(end, self.hard_end) + if end <= at: + raise ChildFailure("expired cooperative operation") + self.hard_end = end + if self.owner.runtime_end_ns is None: + # Observe the actual owner admission; a shorter slot has its own end. + # This field never grants authority or changes cleanup tightening. + self.owner._runtime_end_ns = self.owner.deadline_ns + return at, end + + def start_installer(self, label, arguments, extra=None, capture_limit=0, input_bytes=b""): + case = Path(self.root) + prepared = case.parent + expected = [str(prepared / "natives/codex-inert-source-only"), + "--installer-phases-diagnostic", str(prepared), str(case), + str(prepared / "pair/keito")] + if (not case.is_absolute() or Path(self.cwd) != case or arguments != expected): + raise ChildFailure("invalid closed installer route") + return self._start(label, arguments, INSTALL_OPERATION_NS / 1_000_000_000, + extra, capture_limit, input_bytes, installer=True) + + def start(self, label, arguments, timeout, extra=None, capture_limit=0, input_bytes=b""): + return self._start(label, arguments, timeout, extra, capture_limit, input_bytes) + + def _start(self, label, arguments, timeout, extra=None, capture_limit=0, input_bytes=b"", installer=False): + import socket + import threading + if (not self.entered or self.cleanup_end is not None or len(self.slots) >= 4096 + or not label or any(not (c.isalnum() or c == "-") for c in label) + or any(slot["label"] == label for slot in self.slots) + or type(timeout) not in (int, float) or not 0 < timeout <= 600 + or type(capture_limit) is not int or not 0 <= capture_limit <= 2 * 1024 * 1024 + or type(input_bytes) is not bytes or len(input_bytes) > 1024 * 1024 + or threading.active_count() != 1): + raise ChildFailure("invalid cooperative runtime operation") + at, end = self._select_end(timeout, installer) + charge = len(input_bytes) + capture_limit + if self.owner.runtime_io_reserved + charge > 4 * 1024 * 1024: + raise ChildFailure("runtime buffer budget") + nonce = secrets.token_hex(16) + parent, child_end = socket.socketpair() + endpoint = self.owner.endpoint(parent, nonce) + slot = {"label": label, "nonce": nonce, "child": None, "endpoint": endpoint, + "end": end, "started": at, "input": input_bytes, "offset": 0, + "capture_limit": capture_limit, "stdout": bytearray(), "stdout_count": 0, + "stderr_count": 0, "stdout_eof": False, "stderr_eof": False, + "cancel_sent": False, "waited_published": False, "collected": False, + "accepted": None, "retrieved": False, "first_fault": None, + "output_limit_first": None} + slot.update({"stdin_configured": False, "stdout_configured": False, "stderr_configured": False, + "control_closed": False, "cancel_end": None}) + # Reserve history and buffers before Popen. Slot remains even on error. + self.slots.append(slot) + self.io_reserved += charge + self.owner.runtime_io_reserved += charge + env = {**self.environment, **(extra or {})} + for key in ("KEITO_SOURCE_OWNER_FD", "KEITO_SOURCE_OWNER_NONCE"): + env.pop(key, None) + env.update({"KEITO_PROCESS_OWNER_FD": "4", "KEITO_PROCESS_OWNER_NONCE": nonce, + "KEITO_PROCESS_OWNER_PID": str(os.getpid()), "KEITO_PROCESS_OWNER_END_NS": str(end), + "KEITO_PROCESS_OWNER_CONTRACT": "2"}) + # Keep FD4 valid for pass_fds, then map the private endpoint in the + # single-threaded child callback. No child inherits the blocked mask. + placeholder = None + try: + try: + os.fstat(4) + except OSError: + placeholder = os.open("/dev/null", os.O_RDONLY) + if placeholder != 4: + os.dup2(placeholder, 4, inheritable=False) + os.close(placeholder) + placeholder = 4 + source_fd = child_end.fileno() + def attach(): + signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask) + os.dup2(source_fd, 4, inheritable=True) + if source_fd != 4: + os.close(source_fd) + self.spawning = True + previous_mask = signal.pthread_sigmask(signal.SIG_BLOCK, (signal.SIGINT, signal.SIGTERM)) + try: + self.owner.check() + gate_at = self._now() + self.owner.check() + if self.pending_cancel is not None or gate_at >= end: + raise Cancelled(self.pending_cancel or signal.SIGTERM) + child = subprocess.Popen(arguments, cwd=self.cwd, env=env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + close_fds=True, pass_fds=tuple(sorted({4, source_fd})), preexec_fn=attach) + slot["child"] = child # BEFORE flags, endpoint identity or receipt. + finally: + self.spawning = False + signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask) + endpoint.expected_pid = child.pid + if self.pending_cancel is not None: + raise Cancelled(self.pending_cancel) + self._configure_pipes(slot) + self.owner.check() + self.owner.forward([f"REGISTER|{os.getpid()}|{child.pid}|{nonce}|0"]) + # Ordinary exclusive receipt, after actual returned-handle retention. + self._record(label + "-child-started.json", {"pid": child.pid, "launch_nonce": nonce, + "launch_before_monotonic_ns": at, "launch_after_monotonic_ns": self._now()}) + return slot + except BaseException as error: + self._fail(error, "RUNTIME_START_OR_RECEIPT") + self.begin_cleanup(min(end, self._now() + 4_000_000_000)) + raise + finally: + child_end.close() + if placeholder is not None: + os.close(placeholder) + + def _configure_pipes(self, slot): + for name in ("stdin", "stdout", "stderr"): + try: + os.set_blocking(getattr(slot["child"], name).fileno(), False) + slot[name + "_configured"] = True + except BaseException as error: + self._fail(error, "RUNTIME_PIPE_FLAGS") + slot["first_fault"] = slot["first_fault"] or "RUNTIME_PIPE_FLAGS" + if slot["first_fault"]: + raise self.first_error + + def _close_input(self, slot): + child = slot["child"] + if child is not None and child.stdin is not None: + try: + child.stdin.close() + child.stdin = None + except BaseException as error: + slot["first_fault"] = slot["first_fault"] or "RUNTIME_INPUT_CLOSE" + self._fail(error, "RUNTIME_INPUT_CLOSE") + + def _close_control(self, slot): + if not slot.get("control_closed", False): + try: + slot["endpoint"].close() + slot["control_closed"] = True + except BaseException as error: + self._fail(error, "RUNTIME_CONTROL_CLOSE") + + def _poll_slot(self, slot, accepting): + from source_qa_protocol import ProtocolError + child = slot["child"] + if child is None: + self._close_control(slot) + slot["collected"] = slot.get("control_closed", False) + return + endpoint = slot["endpoint"] + try: + if endpoint.first_fault: + self._fail(ProtocolError(endpoint.first_fault), "RUNTIME_ENDPOINT") + endpoint.drain_failed() + else: + endpoint.receive(parent=False) + except ProtocolError as error: + slot["first_fault"] = slot["first_fault"] or str(error) + self._fail(error, "RUNTIME_ENDPOINT") + events, endpoint.events = endpoint.events, [] + if events: + try: + self.owner.forward(events) + except BaseException as error: + self._fail(error, "RUNTIME_FORWARD") + if child.stdin is not None: + if self.cleanup_end is not None or slot["offset"] == len(slot["input"]): + self._close_input(slot) + elif slot.get("stdin_configured", False): + try: + count = os.write(child.stdin.fileno(), memoryview(slot["input"])[slot["offset"]:slot["offset"] + 4096]) + if count <= 0: + raise ChildFailure("runtime input short write") + slot["offset"] += count + except (BlockingIOError, InterruptedError): + pass + except OSError as error: + slot["first_fault"] = slot["first_fault"] or "RUNTIME_INPUT_WRITE" + self._fail(error, "RUNTIME_INPUT_WRITE") + self._close_input(slot) + for name in ("stdout", "stderr"): + pipe = getattr(child, name) + if pipe is None or not slot.get(name + "_configured", False): + continue + for _ in range(8): + try: + block = os.read(pipe.fileno(), 4096) + except (BlockingIOError, InterruptedError): + break + except OSError as error: + slot["first_fault"] = slot["first_fault"] or "RUNTIME_OUTPUT_READ" + self._fail(error, "RUNTIME_OUTPUT_READ") + break + if not block: + slot[name + "_eof"] = True + pipe.close(); setattr(child, name, None) + break + slot[name + "_count"] += len(block) + if name == "stdout": + remaining = max(0, slot["capture_limit"] - len(slot["stdout"])) + slot["stdout"].extend(block[:remaining]) + if slot[name + "_count"] > (slot["capture_limit"] if name == "stdout" else 0): + slot["first_fault"] = slot["first_fault"] or "RUNTIME_OUTPUT_LIMIT" + error = RuntimeOutputLimit() + self._fail(error, "RUNTIME_OUTPUT_LIMIT") + if slot.get("output_limit_first") is None: + observation = {"stream": name, "observed_bytes": slot[name + "_count"], + "allowed_bytes": slot["capture_limit"] if name == "stdout" else 0, + "error_category": None} + slot["output_limit_first"] = observation + # The original failure is already latched. Optional + # classification cannot replace it or retain raw stderr. + if name == "stderr": + try: observation["error_category"] = _stderr_category(block) + except BaseException: pass + else: error.observation = observation.copy() + else: + error.observation = observation.copy() + try: + status = child.poll() + except OSError as error: + status = None + self._fail(error, "RUNTIME_DIRECT_WAIT") + if status is not None and not slot["waited_published"] and (endpoint.settled or endpoint.first_fault): + slot["waited_published"] = True + try: + self.owner.forward([f"WAITED|{os.getpid()}|{child.pid}|{slot['nonce']}|{status}"]) + except BaseException as error: + self._fail(error, "RUNTIME_WAIT_RECEIPT") + slot["collected"] = (status is not None and slot["stdout_eof"] and slot["stderr_eof"] + and child.stdin is None and endpoint.eof) + at = self._now() + if (accepting and slot["accepted"] is None and slot["collected"] and endpoint.settled + and slot["first_fault"] is None and self.owner.first_fault is None + and at < slot["end"]): + slot["accepted"] = at + if slot["collected"]: + self._close_control(slot) + if not slot.get("control_closed", False): slot["collected"] = False + + def poll(self): + try: + self.owner.check() + except BaseException as error: + self._fail(error, "RUNTIME_PARENT_OR_SIGNAL") + if self.owner.first_fault: + self.begin_cleanup(self.hard_end if self.hard_end is not None else self._now()) + for slot in self.slots: + if not slot["collected"]: + try: self._poll_slot(slot, self.owner.first_fault is None) + except BaseException as error: self._fail(error, "RUNTIME_SLOT_POLL") + if self.owner.first_fault: + self.begin_cleanup(self.hard_end if self.hard_end is not None else slot["end"]) + if slot["accepted"] is None and self._now() >= slot["end"]: + self._fail(subprocess.TimeoutExpired(slot["label"], 0), "RUNTIME_DEADLINE") + self.begin_cleanup(self.hard_end if self.hard_end is not None else slot["end"]) + if self.owner.first_fault: + self.begin_cleanup(self.hard_end if self.hard_end is not None else self._now()) + return all(slot["accepted"] is not None for slot in self.slots) + + def begin_cleanup(self, end): + bounds = [end] + if self.cleanup_end is not None: bounds.append(self.cleanup_end) + if self.hard_end is not None: bounds.append(self.hard_end) + bounds.extend(slot["end"] for slot in self.slots if slot["accepted"] is None) + if self.owner.deadline_ns is not None: + bounds.append(self.owner.deadline_ns) + self.cleanup_end = min(bounds) + # Broadcast ALL cancellation/close intents before any wait or drain. + for slot in self.slots: + if slot["child"] is None: + # Close the provisional parent channel even at a zero end. + # The surrounding start finally owns the temporary peer/mask; + # only its later collection turn may mark the slot collected. + self._close_control(slot) + continue + if slot["accepted"] is not None: + continue + child = slot["child"] + self._close_input(slot) + if (not slot["endpoint"].settled and (slot.get("cancel_end") is None or self.cleanup_end < slot["cancel_end"])): + slot["cancel_sent"] = True + slot["cancel_end"] = self.cleanup_end + try: + slot["endpoint"].cancel_tighter(max(1, self.cleanup_end)) + except BaseException as error: + self._fail(error, "RUNTIME_CANCEL_WRITE") + + def poll_cleanup(self, end): + self.owner.pump_parent() + self.begin_cleanup(end) + for slot in self.slots: + if not slot["collected"]: + if self._now() >= self.cleanup_end: + self._fail(ChildFailure("runtime cleanup deadline"), "RUNTIME_CLEANUP_DEADLINE") + self.begin_cleanup(self.cleanup_end) + try: self._poll_slot(slot, False) + except BaseException as error: self._fail(error, "RUNTIME_SLOT_COLLECTION") + if self._now() >= self.cleanup_end: + self._fail(ChildFailure("runtime cleanup deadline"), "RUNTIME_CLEANUP_DEADLINE") + self.begin_cleanup(self.cleanup_end) + return all(slot["collected"] for slot in self.slots) + + def complete(self, slot): + if not any(value is slot for value in self.slots) or slot["retrieved"]: + raise ChildFailure("runtime slot identity") + while slot["accepted"] is None: + self.poll() + if self.first_error is not None: + raise self.first_error + time.sleep(0.001) + slot["retrieved"] = True + child = slot["child"] + result = {"source_fixture_only": True, "pid": child.pid, "waited": child.returncode is not None, + "returncode": child.returncode, "terminal_eof": slot["endpoint"].settled, + "stdout_eof": slot["stdout_eof"], "stderr_eof": slot["stderr_eof"], + "stdout_bytes": slot["stdout_count"], "stderr_bytes": slot["stderr_count"], + "accepted_monotonic_ns": slot["accepted"], "deadline_ns": slot["end"]} + try: + self._record(slot["label"] + "-result.json", result) + except BaseException as error: + self._fail(error, "RUNTIME_RESULT_RECEIPT") + self.begin_cleanup(self._now() + 4_000_000_000) + raise + if child.returncode != 0: + error = ChildFailure("cooperative runtime child failed") + self._fail(error, "RUNTIME_COMMAND_FAILED") + raise error + return bytes(slot["stdout"]) if slot["capture_limit"] else None + + def run(self, label, arguments, timeout, extra=None, capture_limit=0, input_bytes=b""): + return self.complete(self.start(label, arguments, timeout, extra, capture_limit, input_bytes)) diff --git a/tests/support/source_qa_manifest.py b/tests/support/source_qa_manifest.py new file mode 100644 index 0000000..9040150 --- /dev/null +++ b/tests/support/source_qa_manifest.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +"""Outer source collection; import-safe bounded no-Git verification inside policy.""" +from pathlib import Path, PurePosixPath +import datetime +import hashlib +import json +import os +import stat +import subprocess +import sys + +MAX_FILES = 4096 +MAX_FILE_BYTES = 16 * 1024 * 1024 +MAX_TOTAL_BYTES = 64 * 1024 * 1024 +MAX_MANIFEST_BYTES = 2 * 1024 * 1024 +MANIFEST_NAME = "source-qa-manifest.json" +COLLECTOR_NAME = "tests/support/source_qa_manifest.py" +COMPLETENESS = {"tracked": True, "untracked_nonignored": True, "deleted_tracked": True, + "fsmonitor": False, "hooks": False, "global_config": False, + "optional_locks": False} + + +class ManifestError(RuntimeError): + pass + + +def closed_object(pairs): + value = {} + for key, entry in pairs: + if key in value: + raise ManifestError("duplicate source manifest field") + value[key] = entry + return value + + +def canonical_root(path, private=False): + path = Path(path) + metadata = path.lstat() + if (not path.is_absolute() or path.resolve(strict=True) != path or not stat.S_ISDIR(metadata.st_mode) + or metadata.st_uid != os.getuid() or (private and stat.S_IMODE(metadata.st_mode) != 0o700)): + raise ManifestError("invalid owned canonical root") + return path + + +def safe_name(name): + if (not isinstance(name, str) or not name or len(name.encode()) > 2048 or "\\" in name + or any(ord(value) < 32 or ord(value) == 127 for value in name)): + raise ManifestError("unsafe source name") + path = PurePosixPath(name) + if path.is_absolute() or any(part in ("", ".", "..") for part in name.split("/")) or path.parts[0] == ".git": + raise ManifestError("unsafe source name") + if "__pycache__" in path.parts or name.endswith((".pyc", ".pyo")): + raise ManifestError("generated bytecode is not source") + return path.parts + + +def open_parent(repo, name): + parts = safe_name(name) + descriptor = os.open(repo, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC) + try: + for part in parts[:-1]: + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=descriptor) + metadata = os.fstat(child) + if metadata.st_uid != os.getuid(): + os.close(child) + raise ManifestError("foreign source directory") + os.close(descriptor) + descriptor = child + return descriptor, parts[-1] + except BaseException: + os.close(descriptor) + raise + + +def stamp(metadata): + return (metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_mode, + metadata.st_nlink, metadata.st_size, metadata.st_mtime_ns, metadata.st_ctime_ns) + + +def source_record(repo, name): + directory, leaf = open_parent(repo, name) + try: + descriptor = os.open(leaf, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=directory) + try: + before = os.fstat(descriptor) + if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid() or before.st_nlink != 1 + or before.st_size > MAX_FILE_BYTES): + raise ManifestError("unsafe or oversized source") + value = hashlib.sha256() + size = 0 + while True: + block = os.read(descriptor, 64 * 1024) + if not block: + break + size += len(block) + if size > MAX_FILE_BYTES: + raise ManifestError("oversized source") + value.update(block) + named = os.stat(leaf, dir_fd=directory, follow_symlinks=False) + if size != before.st_size or stamp(before) != stamp(os.fstat(descriptor)) or stamp(before) != stamp(named): + raise ManifestError("source changed during snapshot") + return {"sha256": value.hexdigest(), "bytes": size, "mode": stat.S_IMODE(before.st_mode)} + finally: + os.close(descriptor) + finally: + os.close(directory) + + +def require_absent(repo, name): + try: + directory, leaf = open_parent(repo, name) + except FileNotFoundError: + return + try: + try: + os.stat(leaf, dir_fd=directory, follow_symlinks=False) # lstat semantics, no target read. + except FileNotFoundError: + return + raise ManifestError("deleted source path reappeared") + finally: + os.close(directory) + + +def source_set_digest(files, deleted): + return hashlib.sha256(json.dumps({"files": files, "deleted_paths": deleted}, sort_keys=True, + separators=(",", ":")).encode()).hexdigest() + + +def snapshot(repo, names, deleted): + if len(names) + len(deleted) > MAX_FILES or set(names) & set(deleted): + raise ManifestError("invalid source membership") + files = {} + total = 0 + for name in sorted(names): + files[name] = source_record(repo, name) + total += files[name]["bytes"] + if total > MAX_TOTAL_BYTES: + raise ManifestError("source set too large") + for name in deleted: + require_absent(repo, name) + return files + + +def git_members(repo): + """OUTER ONLY. No caller in the inherited runner invokes this function.""" + environment = {"PATH": "/usr/bin:/bin", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0"} + command = ["/usr/bin/git", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", + "-c", "submodule.recurse=false", "-C", str(repo)] + + def query(arguments): + # Git remains in the outer caller's group, with no detached child group. + output = subprocess.check_output(command + arguments, env=environment, timeout=60) + if len(output) > MAX_MANIFEST_BYTES: + raise ManifestError("source Git inventory output too large") + return output + + top = query(["rev-parse", "--show-toplevel"]).decode().strip() + if top != str(repo): + raise ManifestError("Git root mismatch") + head = query(["rev-parse", "HEAD"]).decode().strip() + if len(head) != 40 or any(value not in "0123456789abcdef" for value in head): + raise ManifestError("invalid source head") + names = query(["ls-files", "--cached", "--others", "--exclude-standard", "-z"]).decode().split("\0")[:-1] + deleted = query(["ls-files", "--deleted", "-z"]).decode().split("\0")[:-1] + if len(names) > MAX_FILES or len(deleted) > MAX_FILES: + raise ManifestError("source membership too large") + if len(names) != len(set(names)) or len(deleted) != len(set(deleted)) or not set(deleted) <= set(names): + raise ManifestError("ambiguous source membership") + for name in names: + safe_name(name) + return head, sorted(set(names) - set(deleted)), sorted(deleted) + + +def collect(repo, parent): + repo, parent = canonical_root(repo), canonical_root(parent, private=True) + head, names, deleted = git_members(repo) + files = snapshot(repo, names, deleted) + if COLLECTOR_NAME not in files: + raise ManifestError("collector not included in source set") + value = {"schema_version": 1, "repo": str(repo), "head_sha": head, + "collector": {"name": COLLECTOR_NAME, "sha256": files[COLLECTOR_NAME]["sha256"]}, + "completeness": COMPLETENESS, "files": files, "deleted_paths": deleted, + "source_set_sha256": source_set_digest(files, deleted), + "created_utc": datetime.datetime.now(datetime.timezone.utc).isoformat()} + raw = (json.dumps(value, indent=2, sort_keys=True) + "\n").encode() + if len(raw) > MAX_MANIFEST_BYTES: + raise ManifestError("manifest too large") + descriptor = os.open(parent / MANIFEST_NAME, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600) + with os.fdopen(descriptor, "wb") as output: + output.write(raw) + output.flush() + os.fsync(output.fileno()) + return hashlib.sha256(raw).hexdigest() + + +class ManifestLease: + def __init__(self, repo, parent): + self.repo, self.parent = canonical_root(repo), canonical_root(parent, private=True) + self.descriptor = os.open(self.parent / MANIFEST_NAME, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + try: + metadata = os.fstat(self.descriptor) + if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid() or metadata.st_nlink != 1 + or stat.S_IMODE(metadata.st_mode) != 0o600 or metadata.st_size > MAX_MANIFEST_BYTES): + raise ManifestError("unsafe source manifest") + self.raw = os.read(self.descriptor, MAX_MANIFEST_BYTES + 1) + if len(self.raw) != metadata.st_size or stamp(metadata) != stamp(os.fstat(self.descriptor)): + raise ManifestError("source manifest changed") + self.before = stamp(metadata) + self.raw_sha256 = hashlib.sha256(self.raw).hexdigest() + self.value = json.loads(self.raw, object_pairs_hook=closed_object) + value = self.value + required = {"schema_version", "repo", "head_sha", "collector", "completeness", "files", "deleted_paths", "source_set_sha256", "created_utc"} + if (set(value) != required or value["schema_version"] != 1 or value["repo"] != str(self.repo) + or value["completeness"] != COMPLETENESS or any(type(part) is not bool for part in value["completeness"].values()) + or not isinstance(value["files"], dict) + or not isinstance(value["deleted_paths"], list) or not isinstance(value["head_sha"], str) + or len(value["head_sha"]) != 40 or any(part not in "0123456789abcdef" for part in value["head_sha"])): + raise ManifestError("source manifest schema mismatch") + files, deleted = value["files"], value["deleted_paths"] + if (len(files) + len(deleted) > MAX_FILES or deleted != sorted(set(deleted)) + or set(files) & set(deleted) or value["source_set_sha256"] != source_set_digest(files, deleted)): + raise ManifestError("source manifest membership mismatch") + for name in list(files) + deleted: + safe_name(name) + for entry in files.values(): + if (not isinstance(entry, dict) or set(entry) != {"sha256", "bytes", "mode"} + or type(entry["bytes"]) is not int or not 0 <= entry["bytes"] <= MAX_FILE_BYTES + or type(entry["mode"]) is not int or not 0 <= entry["mode"] <= 0o777 + or not isinstance(entry["sha256"], str) or len(entry["sha256"]) != 64 + or any(value not in "0123456789abcdef" for value in entry["sha256"])): + raise ManifestError("invalid source manifest record") + if (COLLECTOR_NAME not in files or sum(entry["bytes"] for entry in files.values()) > MAX_TOTAL_BYTES + or value["collector"] != {"name": COLLECTOR_NAME, "sha256": files[COLLECTOR_NAME]["sha256"]}): + raise ManifestError("collector identity missing") + if source_record(self.repo, COLLECTOR_NAME)["sha256"] != hashlib.sha256(Path(__file__).read_bytes()).hexdigest(): + raise ManifestError("collector implementation mismatch") + self.verify() + except BaseException: + self.close() + raise + + def verify(self): + named = os.stat(self.parent / MANIFEST_NAME, follow_symlinks=False) + if stamp(named) != self.before or stamp(os.fstat(self.descriptor)) != self.before: + raise ManifestError("source manifest changed") + value = self.value + current = snapshot(self.repo, value["files"], value["deleted_paths"]) + if current != value["files"]: + raise ManifestError("source bytes or mode changed") + return current + + def close(self): + if self.descriptor is not None: + os.close(self.descriptor) + self.descriptor = None + + def __enter__(self): + return self + + def __exit__(self, *_): + self.close() + + +def verify_complete(repo, parent): + with ManifestLease(repo, parent) as lease: + head, names, deleted = git_members(lease.repo) + if head != lease.value["head_sha"] or names != sorted(lease.value["files"]) or deleted != lease.value["deleted_paths"]: + raise ManifestError("outer source completeness changed") + return lease.raw_sha256 + + +if __name__ == "__main__": + assert len(sys.argv) == 4 + if sys.argv[1] == "collect": + print(collect(sys.argv[2], sys.argv[3])) + elif sys.argv[1] == "verify-complete": + print(verify_complete(sys.argv[2], sys.argv[3])) + else: + raise SystemExit("unknown outer source-manifest command") diff --git a/tests/support/source_qa_protocol.py b/tests/support/source_qa_protocol.py new file mode 100644 index 0000000..f1a54dd --- /dev/null +++ b/tests/support/source_qa_protocol.py @@ -0,0 +1,618 @@ +"""Developer-only cancellation/settlement metadata; no capture/auth authority. + +Connected to retained cooperative runtime managers. A clean protocol trace +alone never proves reserved-group absence or an actual direct wait. +""" +import os +import signal +import socket +import time + +FD = "KEITO_SOURCE_OWNER_FD" +NONCE = "KEITO_SOURCE_OWNER_NONCE" +CURRENT = None +MAX_FRAME = 256 # Including newline. +MAX_PENDING = 1024 +MAX_READS = 8 # Attempts, including interrupted reads. +MAX_PARSE = 32 +MAX_REGISTRATIONS = 4096 +MAX_FRAMES = 16384 +MAX_WIRE = 4 * 1024 * 1024 + + +def monotonic_ns(): + # Absolute deadlines cross the Python/Rust boundary. Python 3.9 on macOS + # gives time.monotonic_ns() a process-local origin; Rust uses this POSIX + # clock directly. Never translate/calibrate an inherited deadline. + return time.clock_gettime_ns(time.CLOCK_MONOTONIC) + + +class ProtocolError(RuntimeError): + """Only bounded reason codes, never offending input.""" + + +def nonce_valid(value): + return isinstance(value, str) and len(value) == 32 and all(c in "0123456789abcdef" for c in value) + + +def integer(value, low, high): + digits = value[1:] if value.startswith("-") else value + if not value or len(value) > 21 or not digits.isascii() or not digits.isdigit(): + raise ProtocolError("INTEGER_SCHEMA") + result = int(value) + if str(result) != value: + raise ProtocolError("INTEGER_SCHEMA") + if not low <= result <= high: + raise ProtocolError("INTEGER_RANGE") + return result + + +class Budget: + """Shared send/receive/forwarding and retained-trace budget per operation.""" + def __init__(self): + self.wire = self.frames = self.registrations = 0 + self.first_fault = None + self.owner_fault = None + + def poison_owner(self, reason): + if self.owner_fault is None: + self.owner_fault = reason + + def charge(self, kind, amount, limit): + if self.first_fault: + raise ProtocolError(self.first_fault) + if getattr(self, kind) + amount > limit: + self.first_fault = "LIMIT_" + kind.upper() + raise ProtocolError(self.first_fault) + setattr(self, kind, getattr(self, kind) + amount) + + +class MetadataLedger: + """The same bounded grammar/ledger at an endpoint and at an outer root.""" + def __init__(self, root_pid, budget): + self.root_pid, self.budget = root_pid, budget + self.records = {} + + def observe(self, value): + if (not isinstance(value, str) or len(value) + 34 > MAX_FRAME + or not value.isascii() or "\n" in value or "\r" in value): + raise ProtocolError("METADATA_SCHEMA") + fields = value.split("|") + if len(fields) != 5 or fields[0] not in ("REGISTER", "WAITED") or not nonce_valid(fields[3]): + raise ProtocolError("METADATA_SCHEMA") + owner = integer(fields[1], 1, 2147483647) + child = integer(fields[2], 1, 2147483647) + identity = (owner, child, fields[3]) + if fields[0] == "REGISTER": + integer(fields[4], 0, 18446744073709551615) + if owner != self.root_pid and not any(key[1] == owner and not waited for key, waited in self.records.items()): + raise ProtocolError("OWNER_EDGE") + if (owner == child or child == self.root_pid or identity in self.records + or any(key[1] == child and not waited for key, waited in self.records.items())): + raise ProtocolError("DUPLICATE_REGISTRATION") + self.budget.charge("registrations", 1, MAX_REGISTRATIONS) + self.records[identity] = False + else: + integer(fields[4], -2147483648, 2147483647) + if identity not in self.records or self.records[identity]: + raise ProtocolError("UNMATCHED_WAIT") + self.records[identity] = True + + def complete(self): + return all(self.records.values()) + + +class Endpoint: + def __init__(self, channel, nonce, expected_pid=None, budget=None, on_fault=None): + def reject(reason): + if on_fault is not None: + on_fault(reason) + raise ProtocolError(reason) + if not nonce_valid(nonce): + reject("NONCE_SCHEMA") + if channel.family != socket.AF_UNIX or channel.type != socket.SOCK_STREAM: + reject("SOCKET_SCHEMA") + if expected_pid is not None and (type(expected_pid) is not int or not 1 <= expected_pid <= 2147483647): + reject("PID_SCHEMA") + self.channel, self.nonce, self.expected_pid = channel, nonce, expected_pid + try: + channel.setblocking(False) + channel.set_inheritable(False) + except OSError: + reject("SOCKET_FLAGS") + self.budget = budget if budget is not None else Budget() + self.on_fault = on_fault + self.pending = bytearray() + self.live = self.settled = self.cancelled = False + self.terminal = self.eof = False + self.first_fault = None + self.cancel_deadline_ns = None + self.events = [] + self.registrations = {} + self._parent_role = None + self._sent_live = self._sent_terminal = self._sent_cancel = False + self._sent_cancel_end = None + self._failed_attempted = False + self._sent_ledger = MetadataLedger(os.getpid(), self.budget) + self._sent_registrations = self._sent_ledger.records + + def fail(self, reason): + if self.first_fault is None: + self.first_fault = reason + self.settled = False + self.budget.poison_owner(self.first_fault) + if self.on_fault is not None: + self.on_fault(self.first_fault) + raise ProtocolError(self.first_fault) + + def _check(self): + if self.first_fault: + raise ProtocolError(self.first_fault) + if self.budget.first_fault: + self.fail(self.budget.first_fault) + + def _send(self, value): + if not isinstance(value, str) or len(value) + 34 > MAX_FRAME or "\n" in value or "\r" in value: + self.fail("FRAME_SCHEMA") + try: + frame = (self.nonce + "|" + value + "\n").encode("ascii") + self.budget.charge("wire", len(frame), MAX_WIRE) + self.budget.charge("frames", 1, MAX_FRAMES) + if self.channel.send(frame) != len(frame): + self.fail("SHORT_WRITE") + except (OSError, UnicodeError): + self.fail("WRITE_FAILED") + except ProtocolError as error: + self.fail(str(error)) + + def send(self, tag, deadline_ns=None): + # One bounded FAILED attempt is allowed after a fault. It never repairs + # proof; a broken/exhausted channel instead leaves EOF without settlement. + if tag == "FAILED": + if self._failed_attempted or self._sent_terminal: + self.fail("DUPLICATE_TERMINAL") + self._failed_attempted = self._sent_terminal = True + self._send("FAILED|" + str(os.getpid())) + try: + self.channel.shutdown(socket.SHUT_WR) + except OSError: + self.fail("SHUTDOWN_FAILED") + return + self._check() + if tag == "SETTLED" and self.budget.owner_fault is not None: + self.fail(self.budget.owner_fault) + if self._sent_terminal: + self.fail("POST_TERMINAL_WRITE") + if tag == "LIVE" and not self._sent_live and not self._sent_cancel: + self._sent_live = True + elif tag == "SETTLED" and self._sent_live and all(self._sent_registrations.values()): + self._sent_terminal = True + elif tag == "CANCEL" and not self._sent_cancel and not self._sent_live: + self._sent_cancel = True + if type(deadline_ns) is not int or not 1 <= deadline_ns <= 18446744073709551615: + self.fail("CANCEL_DEADLINE") + self._sent_cancel_end = deadline_ns + self._send("CANCEL|{}|{}".format(os.getpid(), deadline_ns)) + return + else: + self.fail("SEND_STATE") + self._send(tag + "|" + str(os.getpid())) + if self._sent_terminal: + try: + self.channel.shutdown(socket.SHUT_WR) + except OSError: + self.fail("SHUTDOWN_FAILED") + + def cancel_tighter(self, end): + self._check() + if type(end) is not int or not 1 <= end <= 18446744073709551615 or self._sent_terminal or self._sent_live: + self.fail("CANCEL_DEADLINE") + if self._sent_cancel_end is None: + return self.send("CANCEL", deadline_ns=end) + if end < self._sent_cancel_end: + self._sent_cancel_end = end + self._send("CANCEL|{}|{}".format(os.getpid(), end)) + + def metadata(self, value): + self._check() + if not self._sent_live or self._sent_terminal: + self.fail("METADATA_SEND_STATE") + try: + self._sent_ledger.observe(value) + self._send(value) + except ProtocolError as error: + self.fail(str(error)) + + def _frame(self, line, parent): + if self.terminal: + self.fail("POST_TERMINAL_DATA") + if len(line) + 1 > MAX_FRAME: + self.fail("FRAME_LIMIT") + self.budget.charge("frames", 1, MAX_FRAMES) + try: + fields = line.decode("ascii").split("|") + except UnicodeError: + self.fail("FRAME_ENCODING") + if len(fields) not in (3, 4, 6) or fields[0] != self.nonce: + self.fail("NONCE_OR_SCHEMA") + tag = fields[1] + if len(fields) == 6: + if parent or not self.live or tag not in ("REGISTER", "WAITED") or not nonce_valid(fields[4]): + self.fail("METADATA_STATE") + owner = integer(fields[2], 1, 2147483647) + child = integer(fields[3], 1, 2147483647) + identity = (owner, child, fields[4]) + if tag == "REGISTER": + if owner != self.expected_pid and not any(key[1] == owner and not waited for key, waited in self.registrations.items()): + self.fail("OWNER_EDGE") + integer(fields[5], 0, 18446744073709551615) + if (owner == child or child == self.expected_pid or identity in self.registrations + or any(key[1] == child and not waited for key, waited in self.registrations.items())): + self.fail("DUPLICATE_REGISTRATION") + self.budget.charge("registrations", 1, MAX_REGISTRATIONS) + self.registrations[identity] = False + else: + integer(fields[5], -2147483648, 2147483647) + if identity not in self.registrations or self.registrations[identity]: + self.fail("UNMATCHED_WAIT") + self.registrations[identity] = True + self.events.append("|".join(fields[1:])) + return + pid = integer(fields[2], 1, 2147483647) + if self.expected_pid is not None and pid != self.expected_pid: + self.fail("PEER_IDENTITY") + if parent: + if len(fields) != 4 or tag != "CANCEL": + self.fail("PARENT_STATE") + deadline = integer(fields[3], 1, 18446744073709551615) + self.cancel_deadline_ns = min(self.cancel_deadline_ns or deadline, deadline) + self.cancelled = True + self.expected_pid = pid + elif len(fields) != 3: + self.fail("CHILD_SCHEMA") + elif tag == "LIVE" and not self.live: + self.live, self.expected_pid = True, pid + elif tag == "SETTLED" and self.live and all(self.registrations.values()): + self.terminal = True + elif tag == "FAILED": + self.fail("PEER_FAILED") + else: + self.fail("CHILD_STATE") + + def receive(self, parent=False, failure_only=False): + if not failure_only: + self._check() + elif not parent: + return self.drain_failed() + if self._parent_role is None: + self._parent_role = parent + if self._parent_role != parent: + self.fail("ROLE_CHANGED") + if self.eof: + return self.cancelled + reads = parsed = 0 + try: + while True: + while b"\n" in self.pending and parsed < MAX_PARSE: + end = self.pending.index(10) + line = bytes(self.pending[:end]) + del self.pending[:end + 1] + self._frame(line, parent) + parsed += 1 + if self.terminal and self.pending: + self.fail("POST_TERMINAL_DATA") + if b"\n" not in self.pending and len(self.pending) >= MAX_FRAME: + self.fail("FRAME_LIMIT") + if parsed == MAX_PARSE or reads == MAX_READS: + break + reads += 1 + try: + block = self.channel.recv(MAX_FRAME) + except BlockingIOError: + break + except InterruptedError: + continue + if not block: + self.eof = True + if self.pending: + self.fail("TRUNCATED_FRAME") + if parent: + self.cancelled = True + elif not self.terminal: + self.fail("EOF_WITHOUT_TERMINAL") + else: + self.settled = True + break + self.budget.charge("wire", len(block), MAX_WIRE) + if len(self.pending) + len(block) > MAX_PENDING: + self.fail("PENDING_LIMIT") + self.pending.extend(block) + except OSError: + self.fail("READ_FAILED") + except ProtocolError as error: + self.fail(str(error)) + return self.cancelled + + def drain_failed(self): + """Failure-only bounded discard: read-zero alone establishes EOF. + + It cannot parse a terminal, settle, erase a fault or reopen admission. + """ + self.pending.clear() + for _ in range(MAX_READS): + if self.eof: + break + try: + block = self.channel.recv(MAX_FRAME) + except (BlockingIOError, InterruptedError): + break + except OSError: + break + if not block: + self.eof = True + break + return self.eof + + def close(self): + self.channel.close() + + +class SourceOwner: + """Permanent owner fault/admission latch with retained runtime managers.""" + def __init__(self): + self.parent = None + self.managers = [] + self.cancelled = self.unsettled = self.admission_closed = False + self.first_fault = None + self.previous = None + self.deadline_ns = None + self.budget = Budget() + self._forward_ledger = MetadataLedger(os.getpid(), self.budget) + self._finished_managers = set() + # Resource collection after a callback fault is not clean proof. Keep + # both the manager object and this separate terminal fact permanently. + self._failed_managers = set() + self._collected_failed_managers = set() + self._closed = False + self.runtime_io_reserved = 0 + # Immutable observation of first admission, distinct from tighter cleanup. + self._runtime_end_ns = None + self._clock_broadcasting = False + + @property + def runtime_end_ns(self): + return self._runtime_end_ns + + def fail(self, reason): + if self.first_fault is None: + self.first_fault = reason + self.budget.poison_owner(self.first_fault) + self.unsettled = self.admission_closed = True + + def fail_manager(self, manager, reason): + # Physical collection from a failed manager is never clean proof. The + # finalizer already retains/caches these two outcomes independently. + self._failed_managers.add(id(manager)) + self.fail(reason) + + def __enter__(self): + global CURRENT + self.previous = CURRENT + descriptor, nonce = os.environ.pop(FD, None), os.environ.pop(NONCE, None) + try: + keys = ("KEITO_PROCESS_OWNER_FD", "KEITO_PROCESS_OWNER_NONCE", "KEITO_PROCESS_OWNER_PID", + "KEITO_PROCESS_OWNER_END_NS", "KEITO_PROCESS_OWNER_CONTRACT") + values = [os.environ.pop(key, None) for key in keys] + if any(value is not None for value in values): + if not all(value is not None for value in values) or descriptor is not None or nonce is not None: + raise ProtocolError("PARTIAL_ENVIRONMENT") + descriptor, nonce, parent, end, contract = values + if descriptor != "4" or contract != "2" or integer(parent, 1, 2147483647) != os.getppid(): + raise ProtocolError("OWNER_PARENT_IDENTITY") + self.deadline_ns = integer(end, 1, 18446744073709551615) + if self.deadline_ns <= self.now(): + raise ProtocolError("OWNER_DEADLINE") + if (descriptor is None) != (nonce is None): + raise ProtocolError("PARTIAL_ENVIRONMENT") + if descriptor is not None: + fd = integer(descriptor, 4, 1024) + self.parent = Endpoint(socket.socket(fileno=fd), nonce, + expected_pid=os.getppid() if any(value is not None for value in values) else None, + budget=self.budget, on_fault=self.fail) + self.parent.send("LIVE") + except (OSError, ValueError, ProtocolError): + self.fail("OWNER_ADMISSION") + if self.parent: + self.parent.close() + raise ProtocolError(self.first_fault) + CURRENT = self + return self + + def check(self): + self.pump_parent() + if self.first_fault: + raise ProtocolError(self.first_fault) + if self.budget.first_fault or self.budget.owner_fault: + self.fail(self.budget.first_fault or self.budget.owner_fault) + raise ProtocolError(self.first_fault) + if self.admission_closed and not self.cancelled: + self.fail("OWNER_ADMISSION_CLOSED") + raise ProtocolError(self.first_fault) + if self.cancelled: + self.admission_closed = True + from source_qa_children import Cancelled + raise Cancelled(signal.SIGTERM) + + def now(self): + try: + return monotonic_ns() + except BaseException: + self.deadline_ns = 0 + self.fail("OWNER_CLOCK") + if not self._clock_broadcasting: + self._clock_broadcasting = True + try: + for manager in self.managers: + try: manager.begin_cleanup(0) + except BaseException: + self._failed_managers.add(id(manager)) + self.fail("MANAGER_CLEANUP_BEGIN") + finally: + self._clock_broadcasting = False + return 0 + + def limit_end(self, end): + self.deadline_ns = end if self.deadline_ns is None else min(self.deadline_ns, end) + + def pump_parent(self, deadline_reason="OWNER_DEADLINE"): + if self.parent: + try: + if self.first_fault is None: + self.cancelled |= self.parent.receive(parent=True) + else: + self.cancelled |= self.parent.receive(parent=True, failure_only=True) + except ProtocolError as error: + self.fail(str(error)) + if self.budget.first_fault: + self.limit_end(0) + if self.parent.cancel_deadline_ns is not None: + self.limit_end(self.parent.cancel_deadline_ns) + at = self.now() + if self.deadline_ns is not None and at >= self.deadline_ns: + self.fail(deadline_reason) + + def forward(self, events): + try: + if self.first_fault: + raise ProtocolError(self.first_fault) + if self._closed: + raise ProtocolError("OWNER_ALREADY_FINISHED") + for count, event in enumerate(events): + if count >= MAX_FRAMES or not isinstance(event, str) or len(event) + 34 > MAX_FRAME: + raise ProtocolError("FORWARD_LIMIT") + self.budget.charge("wire", len(event) + 34, MAX_WIRE) + self.budget.charge("frames", 1, MAX_FRAMES) + self._forward_ledger.observe(event) + if self.parent: + self.parent.metadata(event) + except ProtocolError as error: + self.fail(str(error)) + raise + + def endpoint(self, channel, nonce, expected_pid=None): + self.check() + try: + return Endpoint(channel, nonce, expected_pid, budget=self.budget, on_fault=self.fail) + except (OSError, ProtocolError) as error: + self.fail(str(error) if isinstance(error, ProtocolError) else "ENDPOINT_ADMISSION") + raise ProtocolError(self.first_fault) + + def register_manager(self, manager): + self.check() + if len(self.managers) >= MAX_REGISTRATIONS or any(value is manager for value in self.managers): + self.fail("MANAGER_LIMIT_OR_DUPLICATE") + raise ProtocolError(self.first_fault) + self.managers.append(manager) + + def finish_managers(self): + self.admission_closed = True + if self.budget.first_fault or self.budget.owner_fault: + self.fail(self.budget.first_fault or self.budget.owner_fault) + self.pump_parent("MANAGER_CLEANUP_DEADLINE") + deadline = self.now() + 4_000_000_000 + self.limit_end(deadline) + if len(self.managers) > MAX_REGISTRATIONS: + self.fail("MANAGER_LIMIT") + raise ProtocolError(self.first_fault) + # Broadcast before waiting. active==None or direct wait is not proof. + pending = [] + for manager in self.managers: + identity = id(manager) + if identity in self._finished_managers or identity in self._collected_failed_managers: + continue + # Retain before invoking begin: an exception cannot erase the next + # opportunity to collect this manager's already-owned resources. + pending.append(manager) + try: + manager.begin_cleanup(self.deadline_ns) + except BaseException: + self._failed_managers.add(identity) + self.fail("MANAGER_CLEANUP_BEGIN") + while pending: + previous_end = self.deadline_ns + self.pump_parent("MANAGER_CLEANUP_DEADLINE") + if self.deadline_ns < previous_end: + for manager in pending: + try: manager.begin_cleanup(self.deadline_ns) + except BaseException: + self._failed_managers.add(id(manager)); self.fail("MANAGER_CLEANUP_BEGIN") + if self.now() >= self.deadline_ns: + self.fail("MANAGER_CLEANUP_DEADLINE") + break + remaining = [] + for manager in pending: + try: + if self.now() >= self.deadline_ns: + self.fail("MANAGER_CLEANUP_DEADLINE") + remaining.append(manager) + continue + result = manager.poll_cleanup(self.deadline_ns) + if self.now() >= self.deadline_ns: + self.fail("MANAGER_CLEANUP_DEADLINE") + remaining.append(manager) + elif result is False: + remaining.append(manager) + elif result is True: + if id(manager) in self._failed_managers: + self._collected_failed_managers.add(id(manager)) + else: + self._finished_managers.add(id(manager)) + else: + self._failed_managers.add(id(manager)) + self.fail("MANAGER_PROOF_SCHEMA") + remaining.append(manager) + except BaseException: + self._failed_managers.add(id(manager)) + self.fail("MANAGER_CLEANUP_POLL") + remaining.append(manager) + pending = remaining + if pending and self.now() >= self.deadline_ns: + self.fail("MANAGER_CLEANUP_DEADLINE") + break + if pending: + time.sleep(0.001) + if not self._forward_ledger.complete(): + self.fail("UNWAITED_FORWARD_REGISTRATION") + self.pump_parent("MANAGER_CLEANUP_DEADLINE") + + def __exit__(self, exception_type, exception, traceback): + global CURRENT + # Any abnormal operation must be latched BEFORE resource finalization + # or terminal emission; do not persist arbitrary exception text. + if isinstance(exception, ProtocolError): + self.fail(str(exception)) + elif exception is not None: + self.fail("OWNER_OPERATION_FAILED") + try: + try: + self.finish_managers() + except BaseException: + self.fail("OWNER_FINALIZATION_FAILED") + if self.parent: + try: + self.pump_parent() + self.parent.send("FAILED" if self.unsettled else "SETTLED") + except BaseException: + self.fail("TERMINAL_WRITE") + finally: + self._closed = True + try: + if self.parent: + self.parent.close() + except BaseException: + self.fail("OWNER_CLOSE_FAILED") + finally: + CURRENT = self.previous + if exception is None and self.first_fault: + raise ProtocolError(self.first_fault) + return False # Preserve the original operation exception/traceback. diff --git a/tests/support/test_guarded_failure_diagnostic.py b/tests/support/test_guarded_failure_diagnostic.py new file mode 100644 index 0000000..0d1def8 --- /dev/null +++ b/tests/support/test_guarded_failure_diagnostic.py @@ -0,0 +1,136 @@ +"""Pure diagnostic fixtures. No subprocess, socket, file, clock or runtime roots.""" +import json +from pathlib import Path +import sys +import unittest +from types import SimpleNamespace +from unittest.mock import patch +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from source_qa_children import diagnosed_owned_operation, owned_failure_snapshot + + +class FakeManager: + def __init__(self): + self.owner = SimpleNamespace(first_fault="RUNTIME_ENDPOINT") + self.child = SimpleNamespace(returncode=None, stdin=object()) + self.endpoint = SimpleNamespace(first_fault="PEER_FAILED", live=True, + terminal=False, eof=False, settled=False) + self.slots = [{"child": self.child, "endpoint": self.endpoint, "accepted": None, + "collected": False, "waited_published": False, "stdout_eof": False, + "stderr_eof": False, "stdout_count": 0, "stderr_count": 0, + "first_fault": "PEER_FAILED", "stdout": b"PRIVATE_PAYLOAD"}] + self.cleanup_calls = 0 + def __enter__(self): + return self + def __exit__(self, kind, error, traceback): + self.cleanup_calls += 1 + self.child.returncode = 1 + self.child.stdin = None + self.endpoint.eof = True + self.slots[0].update(collected=True, stdout_eof=True, stderr_eof=True) + return False + + +CONTEXT = {"namespace": "codex", "matrix_label": "profile-record-changed", + "phase": "pre-mutation-prompt", "event": "prompt"} + + +class FailureDiagnosticTests(unittest.TestCase): + def test_primary_identity_cleanup_then_distinct_first_and_final(self): + manager, rows = FakeManager(), [] + primary = RuntimeError("PRIVATE_ERROR") + def operation(active): + self.assertIs(active, manager) + raise primary + def emit(value): + self.assertEqual(manager.cleanup_calls, 1) + rows.append(value) + with self.assertRaises(RuntimeError) as caught: + diagnosed_owned_operation(manager, operation, CONTEXT, emit) + self.assertIs(caught.exception, primary) + self.assertEqual(manager.cleanup_calls, 1) + self.assertEqual(len(rows), 1) + self.assertFalse(rows[0]["first"]["direct_wait_known"]) + self.assertEqual(rows[0]["after_cleanup"]["direct_returncode"], 1) + self.assertFalse(rows[0]["first"]["stdin_closed"]) + self.assertTrue(rows[0]["after_cleanup"]["stdin_closed"]) + self.assertFalse(rows[0]["first"]["endpoint_eof"]) + self.assertTrue(rows[0]["after_cleanup"]["endpoint_eof"]) + self.assertFalse(rows[0]["after_cleanup"]["endpoint_settled"]) + self.assertEqual(rows[0]["first"]["endpoint_fault"], "PEER_FAILED") + self.assertEqual(rows[0]["phase"], "pre-mutation-prompt") + + def test_success_is_silent_and_cleans_once(self): + manager, rows = FakeManager(), [] + self.assertEqual(diagnosed_owned_operation(manager, lambda _: 42, CONTEXT, rows.append), 42) + self.assertEqual(rows, []) + self.assertEqual(manager.cleanup_calls, 1) + + def test_emitter_failure_does_not_replace_primary(self): + manager = FakeManager() + primary = RuntimeError("PRIVATE_PRIMARY") + def fail(_): + raise primary + def emit(_): + raise ValueError("PRIVATE_DIAGNOSTIC_FAILURE") + with self.assertRaises(RuntimeError) as caught: + diagnosed_owned_operation(manager, fail, CONTEXT, emit) + self.assertIs(caught.exception, primary) + self.assertEqual(manager.cleanup_calls, 1) + + def test_snapshot_failure_does_not_delay_cleanup_or_replace_primary(self): + manager = FakeManager() + primary = RuntimeError("PRIVATE_PRIMARY") + def fail(_): + raise primary + with patch("source_qa_children.owned_failure_snapshot", side_effect=ValueError("PRIVATE")): + with self.assertRaises(RuntimeError) as caught: + diagnosed_owned_operation(manager, fail, CONTEXT, lambda _: None) + self.assertIs(caught.exception, primary) + self.assertEqual(manager.cleanup_calls, 1) + + def test_closed_payload_ignores_free_context_errors_paths_and_raw_output(self): + manager, rows = FakeManager(), [] + manager.endpoint.first_fault = "PRIVATE_ENDPOINT_ERROR" + manager.owner.first_fault = {"PRIVATE_PATH": "/PRIVATE_SECRET"} + manager.slots[0]["first_fault"] = "PRIVATE_SLOT_ERROR" + context = {key: "PRIVATE_CONTEXT" for key in CONTEXT} + def fail(_): + raise RuntimeError("PRIVATE_ERROR") + with self.assertRaises(RuntimeError): + diagnosed_owned_operation(manager, fail, context, rows.append) + self.assertEqual(len(rows), 1) + raw = json.dumps(rows[0]) + self.assertNotIn("PRIVATE", raw) + self.assertLess(len(raw.encode()), 4096) + self.assertEqual(rows[0]["namespace"], "UNKNOWN") + self.assertEqual(rows[0]["after_cleanup"]["owner_fault"], "OTHER") + self.assertEqual(set(rows[0]), {"schema", "source_fixture_only", "namespace", "matrix_label", + "phase", "event", "first", "after_cleanup"}) + + def test_cached_unknown_signal_and_bad_numeric_types_without_poll(self): + manager = FakeManager() + manager.child.returncode = -15 + manager.slots[0]["stdout_count"] = True + manager.slots[0]["stderr_count"] = 2**64 + value = owned_failure_snapshot(manager) + self.assertEqual(value["direct_returncode"], -15) + self.assertTrue(value["direct_wait_known"]) + self.assertIsNone(value["stdout_bytes"]) + self.assertIsNone(value["stderr_bytes"]) + manager.child.returncode = True + self.assertFalse(owned_failure_snapshot(manager)["direct_wait_known"]) + + def test_empty_provisional_slot_is_unknown_without_handle(self): + manager = FakeManager() + manager.slots = [] + value = owned_failure_snapshot(manager) + self.assertEqual(value["slot_count"], 0) + self.assertFalse(value["direct_handle_retained"]) + self.assertFalse(value["direct_wait_known"]) + self.assertIsNone(value["direct_returncode"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/support/test_paired_test_runner.py b/tests/support/test_paired_test_runner.py new file mode 100644 index 0000000..cd86668 --- /dev/null +++ b/tests/support/test_paired_test_runner.py @@ -0,0 +1,82 @@ +"""Dependency-free fixture regressions; never launches Cargo or a native client.""" +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location("paired", Path(__file__).with_name("run_paired_tests.py")) +paired = importlib.util.module_from_spec(spec) +spec.loader.exec_module(paired) + + +class PairFixtures(unittest.TestCase): + def test_default_and_explicit_all_targets_are_passed_exactly_once(self): + for arguments in ([], ["--all-targets"]): + with self.subTest(arguments=arguments), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + run = root / "run" + run.mkdir() + for name in ("git", "guard-bin", "core-bin"): + (root / name).write_bytes(name.encode()) + with patch.dict(paired.os.environ, {"RUSTC": "fixture-inherited-rustup-proxy"}), patch.object(paired.sys, "platform", "linux"), \ + patch.object(paired.tempfile, "mkdtemp", return_value=str(run)), \ + patch.object(paired.shutil, "which", return_value=str(root / "git")), \ + patch.object(paired.subprocess, "check_output", return_value="host: fixture-target\n"), \ + patch.object(paired, "artifact", side_effect=[root / "guard-bin", root / "core-bin"]), \ + patch.object(paired.subprocess, "run") as launch: + paired.main(["fixture-cargo", "fixture-rustc", *arguments]) + command = launch.call_args_list[-1].args[0] + self.assertEqual(command.count("--all-targets"), 1) + # Cargo must use the compiler passed by the caller for every + # phase, never the rustup shim found through PATH. + for call in launch.call_args_list: + self.assertEqual(call.kwargs["env"].get("RUSTC"), "fixture-rustc") + self.assertIn("--all-features", call.args[0]) + for profile in ("DEV", "TEST"): + for key, value in {"OPT_LEVEL": "z", "DEBUG": "0", + "STRIP": "symbols", "LTO": "true", + "CODEGEN_UNITS": "1", "DEBUG_ASSERTIONS": "true", + "OVERFLOW_CHECKS": "true"}.items(): + self.assertEqual(call.kwargs["env"].get( + "CARGO_PROFILE_" + profile + "_" + key), value) + + def test_each_running_image_has_its_own_binding_and_tampering_breaks_it(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for name, content in [("one", b"first-image"), ("two", b"second-image"), + ("guard", b"exact-compiled-guard")]: + (root / name).write_bytes(content) + manifests = [] + for image in ("one", "two"): + core = paired.stage_pair(root / (image + "-pair"), root / image, + root / "guard", "0.2.0", "fixture-target") + manifest = json.loads((core.parent / "capture-runtime-manifest.json").read_text()) + self.assertEqual(manifest["files"]["keito"], paired.digest(root / image)) + self.assertEqual(manifest["files"]["keito-capture-guard"], paired.digest(root / "guard")) + self.assertEqual(core.stat().st_mode & 0o777, 0o700) + manifests.append(manifest) + self.assertNotEqual(manifests[0]["files"]["keito"], manifests[1]["files"]["keito"]) + core.write_bytes(b"changed-image") + self.assertNotEqual(manifest["files"]["keito"], paired.digest(core)) + + def test_only_the_normal_binary_can_supply_the_core_artifact(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "artifacts.jsonl" + rows = [{"reason": "compiler-artifact", "target": {"name": "keito"}, + "executable": name, "profile": {"test": test}} + for name, test in [("unit-test", True), ("core", False)]] + path.write_text("\n".join(map(json.dumps, rows))) + self.assertEqual(paired.artifact(path, "keito"), "core") + path.write_text(json.dumps(rows[0])) + with self.assertRaises(RuntimeError): + paired.artifact(path, "keito") + rows.append({**rows[1], "executable": "ambiguous"}) + path.write_text("\n".join(map(json.dumps, rows))) + with self.assertRaises(RuntimeError): + paired.artifact(path, "keito") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/support/test_runtime_children_finite.py b/tests/support/test_runtime_children_finite.py new file mode 100644 index 0000000..2b9e665 --- /dev/null +++ b/tests/support/test_runtime_children_finite.py @@ -0,0 +1,531 @@ +"""Finite tests of the REAL runtime manager, no Popen/fork/tool execution.""" +import os +from pathlib import Path +import sys +import signal +import tempfile +import unittest +from unittest.mock import patch + +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from source_qa_children import OwnedChildren, Cancelled, ChildFailure +from source_qa_protocol import SourceOwner, ProtocolError + + +class Pipe: + def __init__(self, fd): self.fd, self.closed = fd, False + def fileno(self): return self.fd + def close(self): self.closed = True + + +class Child: + def __init__(self, pid, status=None): + self.pid, self.returncode = pid, status + self.stdin, self.stdout, self.stderr = Pipe(100), Pipe(101), Pipe(102) + def poll(self): return self.returncode + + +class Peer: + def __init__(self, name, events): + self.name, self.trace = name, events + self.settled = self.eof = False + self.first_fault = None + self.events = [] + self.closed = False + def send(self, tag, deadline_ns=None): self.trace.append((self.name, tag, deadline_ns)) + def receive(self, parent=False): + self.trace.append((self.name, "poll")) + if self.first_fault: raise ProtocolError(self.first_fault) + def close(self): self.closed = True + def cancel_tighter(self, end): self.send("CANCEL", deadline_ns=end) + def drain_failed(self): return self.eof + + +def slot(name, pid, trace, end): + return {"label": name, "nonce": name * 32, "child": Child(pid), "endpoint": Peer(name, trace), + "end": end, "started": 1, "input": b"", "offset": 0, + "capture_limit": 8, "stdout": bytearray(), "stdout_count": 0, "stderr_count": 0, + "stdout_eof": False, "stderr_eof": False, "cancel_sent": False, + "waited_published": False, "collected": False, "accepted": None, + "retrieved": False, "first_fault": None} + + +class RuntimeManagerTests(unittest.TestCase): + def setUp(self): + self.root = Path(tempfile.mkdtemp(prefix="finite-manager-", dir=os.environ["TMPDIR"])) + self.owner = SourceOwner() + self.manager = OwnedChildren(self.root, {}, self.root, self.owner) + self.trace = [] + self.end = 10**30 + self.a = slot("a", 101, self.trace, self.end) + self.b = slot("b", 102, self.trace, self.end) + self.manager.slots = [self.a, self.b] + for value in self.manager.slots: + value.update({"stdin_configured": True, "stdout_configured": True, "stderr_configured": True, + "control_closed": False, "cancel_end": None}) + self.owner.forward([f"REGISTER|{os.getpid()}|101|{'a'*32}|0", + f"REGISTER|{os.getpid()}|102|{'b'*32}|0"]) + + def test_output_limit_preserves_first_stream_counts_without_retaining_content(self): + raw = b"PRIVATE_OUTPUT_CANARY" + blocks = [raw, b""] + with patch("os.read", side_effect=lambda fd, count: blocks.pop(0) if fd == 101 else b""): + self.manager._poll_slot(self.a, False) + self.assertEqual(self.a.get("output_limit_first"), { + "stream": "stdout", "observed_bytes": len(raw), "allowed_bytes": 8, + "error_category": None}) + self.assertEqual(self.a["first_fault"], "RUNTIME_OUTPUT_LIMIT") + self.assertEqual(self.owner.first_fault, "RUNTIME_OUTPUT_LIMIT") + self.assertEqual(len(self.a["stdout"]), 8) + self.assertNotIn("PRIVATE", str(self.a.get("output_limit_first"))) + + def test_output_limit_exception_exposes_only_first_sanitized_observation(self): + import json + raw = json.dumps({"error": True, "code": 8, + "message": "Configuration error: Repository command ownership unavailable; capture paused"}).encode() + blocks = [raw, b""] + with patch("os.read", side_effect=lambda fd, count: blocks.pop(0) if fd == 102 else b""): + self.manager._poll_slot(self.a, False) + first = self.manager.first_error + self.assertIn("stream=stderr", str(first)) + self.assertIn("observed_bytes=" + str(len(raw)), str(first)) + self.assertIn("allowed_bytes=0", str(first)) + self.assertIn("category=REPOSITORY_OWNERSHIP", str(first)) + self.assertNotIn("message", str(first)) + blocks = [b"PRIVATE_LATER_CANARY", b""] + with patch("os.read", side_effect=lambda fd, count: blocks.pop(0) if fd == 101 else b""): + self.manager._poll_slot(self.b, False) + self.assertIs(self.manager.first_error, first) + self.assertNotIn("PRIVATE", str(first)) + self.assertIn("stream=stderr", str(first)) + self.assertEqual(self.owner.first_fault, "RUNTIME_OUTPUT_LIMIT") + + def test_output_limit_exception_rejects_unselected_or_malformed_diagnostics(self): + from source_qa_children import RuntimeOutputLimit + valid = {"stream": "stdout", "observed_bytes": 9, "allowed_bytes": 8, "error_category": None} + error = RuntimeOutputLimit() + error.observation = valid + self.assertIn("category=UNKNOWN", str(error)) + for key, value in [("stream", "PRIVATE_CANARY"), ("error_category", "PRIVATE_CANARY"), + ("observed_bytes", True), ("observed_bytes", -1), + ("observed_bytes", 2**64), ("allowed_bytes", "PRIVATE_CANARY"), + ("extra", "PRIVATE_CANARY")]: + error.observation = {**valid, key: value} + self.assertEqual(str(error), "runtime output limit") + error.observation = None + self.assertEqual(str(error), "runtime output limit") + + def test_stderr_limit_stays_zero_and_retains_only_closed_error_category(self): + import json + raw = json.dumps({"error": True, "code": 8, + "message": "Configuration error: Repository command ownership unavailable; capture paused"}).encode() + blocks = [raw, b""] + with patch("os.read", side_effect=lambda fd, count: blocks.pop(0) if fd == 102 else b""): + self.manager._poll_slot(self.a, False) + self.assertEqual(self.a.get("output_limit_first"), { + "stream": "stderr", "observed_bytes": len(raw), "allowed_bytes": 0, + "error_category": "REPOSITORY_OWNERSHIP"}) + self.assertEqual(self.owner.first_fault, "RUNTIME_OUTPUT_LIMIT") + self.assertEqual(self.a["stderr_count"], len(raw)) + self.assertNotIn("message", str(self.a.get("output_limit_first"))) + + def test_failure_categories_reject_unsafe_schema_and_never_copy_private_text(self): + import json + cases = [ + (json.dumps({"error": True, "code": 8, "message": "PRIVATE_MESSAGE_CANARY"}).encode(), "APP_ERROR_8"), + (json.dumps({"error": True, "code": 8, "private": "PRIVATE_EXTRA_CANARY"}).encode(), None), + (json.dumps({"error": True, "code": True}).encode(), None), + (b"PRIVATE_NON_JSON_CANARY", None), + (b"[" * 1200 + b"0" + b"]" * 1200, None), + (json.dumps({"error": True, "code": 8, + "message": "Coding-agent version probe refused: original deadline exceeded", + "details": {"kind": "capture_version_probe", "reason": "deadline", + "cleanup_unverified": False, "cleanup_status": "not_reported"}}).encode(), + "VERSION_PROBE_DEADLINE"), + ] + for raw, expected in cases: + with self.subTest(expected=expected, size=len(raw)): + owner = SourceOwner() + manager = OwnedChildren(self.root, {}, self.root, owner) + value = slot("c", 103, [], self.end) + value.update({"stdin_configured": True, "stdout_configured": True, + "stderr_configured": True, "control_closed": False}) + blocks = [raw, b""] + with patch("os.read", side_effect=lambda fd, count: blocks.pop(0) if fd == 102 else b""): + manager._poll_slot(value, False) + self.assertEqual(value.get("output_limit_first"), { + "stream": "stderr", "observed_bytes": len(raw), "allowed_bytes": 0, + "error_category": expected}) + self.assertEqual(owner.first_fault, "RUNTIME_OUTPUT_LIMIT") + self.assertIsNone(value["accepted"]) + self.assertNotIn("PRIVATE", str(value.get("output_limit_first"))) + + def test_failure_classification_cannot_replace_original_output_fault(self): + blocks = [b"PRIVATE_UNCLASSIFIED", b""] + with patch("source_qa_children._stderr_category", create=True, side_effect=MemoryError), \ + patch("os.read", side_effect=lambda fd, count: blocks.pop(0) if fd == 102 else b""): + self.manager._poll_slot(self.a, False) + self.assertEqual(self.owner.first_fault, "RUNTIME_OUTPUT_LIMIT") + self.assertIsInstance(self.manager.first_error, ChildFailure) + self.assertEqual(str(self.manager.first_error), "runtime output limit") + self.assertEqual(self.a.get("output_limit_first"), { + "stream": "stderr", "observed_bytes": len(b"PRIVATE_UNCLASSIFIED"), + "allowed_bytes": 0, "error_category": None}) + + def test_review_failed_endpoint_is_not_physical_eof(self): + self.a["endpoint"].first_fault = "INERT_ENDPOINT" + self.a["child"].returncode = 0 + with patch("os.read", return_value=b""): + self.manager._poll_slot(self.a, False) + self.assertTrue(self.a["stdout_eof"] and self.a["stderr_eof"]) + self.assertEqual(self.a["child"].returncode, 0) + self.assertFalse(self.a["endpoint"].eof) + self.assertFalse(self.a["collected"]) + + def test_review_known_fault_broadcasts_before_any_sibling_poll(self): + self.owner.fail("ORIGINAL") + def progress(slot, accepting): self.trace.append((slot["label"], "ordinary-poll")) + self.manager._poll_slot = progress + self.manager.poll() + cancel_indices = [i for i, event in enumerate(self.trace) if event[1] == "CANCEL"] + poll_indices = [i for i, event in enumerate(self.trace) if event[1] == "ordinary-poll"] + self.assertEqual(len(cancel_indices), 2) + self.assertLess(max(cancel_indices), min(poll_indices)) + + def test_review_close_error_cannot_skip_sibling_cancel(self): + def fail_close(): raise OSError("inert-close") + self.a["child"].stdin.close = fail_close + try: + self.manager.begin_cleanup(self.end) + except OSError: + pass + self.assertTrue(self.b["cancel_sent"]) + + def test_review_cancel_never_extends_original_slot_and_tightens(self): + self.a["end"] = 1000 + self.b["end"] = 900 + with patch("source_qa_protocol.monotonic_ns", return_value=100): + self.manager.begin_cleanup(5000) + self.manager.begin_cleanup(500) + self.manager.begin_cleanup(6000) + a_ends = [event[2] for event in self.trace if event[:2] == ("a", "CANCEL")] + b_ends = [event[2] for event in self.trace if event[:2] == ("b", "CANCEL")] + self.assertEqual(a_ends, [900, 500]) + self.assertEqual(b_ends, [900, 500]) + + def test_review_unconfigured_output_is_never_read(self): + self.a["stdout_configured"] = False + self.a["stderr_configured"] = True + with patch("os.read", return_value=b"") as read: + self.manager._poll_slot(self.a, False) + self.assertNotIn(101, [call.args[0] for call in read.call_args_list]) + self.assertFalse(self.a["stdout_eof"]) + + def test_review_each_stream_flags_attempted_after_an_independent_failure(self): + for failed in [100, 101, 102]: + owner = SourceOwner() + manager = OwnedChildren(self.root, {}, self.root, owner) + value = slot("a", 101, [], self.end) + value.update({"stdin_configured": False, "stdout_configured": False, "stderr_configured": False}) + attempted = [] + def configure(fd, blocking): + attempted.append(fd) + if fd == failed: raise OSError("inert-flags") + with patch("os.set_blocking", side_effect=configure), self.assertRaises(OSError): + manager._configure_pipes(value) + self.assertEqual(attempted, [100, 101, 102]) + for name, fd in [("stdin",100),("stdout",101),("stderr",102)]: + self.assertEqual(value[name + "_configured"], fd != failed) + + def test_review_latched_cancel_during_preparation_never_calls_popen(self): + owner = SourceOwner() + manager = OwnedChildren(self.root, {}, self.root, owner) + manager.entered = True + def during_preparation(fd): + manager._cancel(signal.SIGTERM, None) + return object() + with patch("os.fstat", side_effect=during_preparation), patch("signal.pthread_sigmask", return_value=set()), patch("subprocess.Popen") as popen: + with self.assertRaises((ProtocolError, Cancelled)): + manager.start("cancelled", ["never-execute"], 1) + popen.assert_not_called() + self.assertEqual(owner.first_fault, "RUNTIME_SIGNAL") + self.assertEqual(len(manager.slots), 1) + self.assertIsNone(manager.slots[0]["child"]) + manager.poll_cleanup(manager.hard_end) + + def test_review_failed_enter_restores_current_and_partial_handlers(self): + import source_qa_protocol as protocol + previous = protocol.CURRENT + manager = OwnedChildren(self.root, {}, self.root) + calls = [] + old = object() + def install(signum, handler): + calls.append((signum, handler)) + if len(calls) == 2: raise OSError("inert-signal-setup") + return old + with patch("signal.signal", side_effect=install), self.assertRaises(OSError): + manager.__enter__() + self.assertIs(protocol.CURRENT, previous) + self.assertEqual(calls[-1], (signal.SIGTERM, old)) + self.assertEqual(len(calls), 3) + + def test_second_review_unspawned_failed_close_remains_unknown(self): + self.a["child"] = None + def cannot_close(): raise OSError("inert-control-close") + self.a["endpoint"].close = cannot_close + self.manager._poll_slot(self.a, False) + self.assertFalse(self.a["control_closed"]) + self.assertFalse(self.a["collected"]) + + def test_second_review_expiry_after_a_poll_broadcasts_before_b_progress(self): + clock = [100] + self.a["end"] = 200 + self.b["end"] = 1000 + def progress(value, accepting): + self.trace.append((value["label"], "ordinary-poll")) + if value is self.a: clock[0] = 200 + self.manager._poll_slot = progress + with patch("source_qa_protocol.monotonic_ns", side_effect=lambda: clock[0]): self.manager.poll() + b_poll = self.trace.index(("b", "ordinary-poll")) + self.assertTrue(all(any(event[:2] == (name, "CANCEL") for event in self.trace[:b_poll]) for name in ["a", "b"])) + + def test_second_review_receipt_clock_failure_preserves_original_and_zeroes_siblings(self): + self.a["accepted"] = 5 + self.a["collected"] = True + self.a["child"].returncode = 0 + (self.root / "a-result.json").write_text("retained") + with patch("source_qa_protocol.monotonic_ns", side_effect=OSError("inert-clock")): + try: + self.manager.complete(self.a) + except BaseException as error: + observed = error + self.assertIsInstance(observed, FileExistsError) + self.assertIs(self.manager.first_error, observed) + self.assertEqual(self.owner.deadline_ns, 0) + self.assertEqual(self.manager.cleanup_end, 0) + self.assertTrue(self.b["cancel_sent"]) + + def test_second_review_failed_rollback_still_exits_owner_and_restores_current(self): + import source_qa_protocol as protocol + previous = protocol.CURRENT + manager = OwnedChildren(self.root, {}, self.root) + original = OSError("inert-install") + calls = [] + def install(signum, handler): + calls.append(signum) + if len(calls) == 2: raise original + if len(calls) == 3: raise OSError("inert-restore") + return object() + with patch("signal.signal", side_effect=install): + try: manager.__enter__() + except BaseException as error: observed = error + self.assertIs(observed, original) + self.assertIs(protocol.CURRENT, previous) + self.assertTrue(manager.owner._closed) + + def test_second_review_late_cleanup_never_becomes_clean_manager_proof(self): + self.owner.managers = [self.manager] + self.owner.deadline_ns = 4000 + self.a["end"] = self.b["end"] = 900 + for value in [self.a, self.b]: + value["endpoint"].settled = value["endpoint"].eof = True + value["child"].returncode = 0 + clock = [800] + original_poll = self.a["child"].poll + def cross_bound(): clock[0] = 901; return original_poll() + self.a["child"].poll = cross_bound + with patch("source_qa_protocol.monotonic_ns", side_effect=lambda: clock[0]), patch("os.read", return_value=b""): + self.owner.finish_managers() + self.assertTrue(self.a["collected"] and self.b["collected"]) + self.assertNotIn(id(self.manager), self.owner._finished_managers) + self.assertTrue(self.owner.unsettled) + + def test_second_review_admission_gate_clock_failure_never_calls_popen(self): + owner = SourceOwner() + manager = OwnedChildren(self.root, {}, self.root, owner) + manager.entered = True + armed = [False] + def mask(*args): armed[0] = True; return set() + def now(): + if armed[0]: + armed[0] = False + raise OSError("inert-gate-clock") + return 100 + # First gate check succeeds. The failure is the following fresh read. + original_check = owner.check + def gate_check(): + if armed[0]: + armed[0] = False + original_check() + armed[0] = True + else: original_check() + with patch("signal.pthread_sigmask", side_effect=mask), patch("source_qa_protocol.monotonic_ns", side_effect=now), patch.object(owner, "check", side_effect=gate_check), patch("subprocess.Popen", side_effect=RuntimeError("POpen must not execute")) as popen: + with self.assertRaises(BaseException): manager.start("clock-gate", ["never-execute"], 1) + popen.assert_not_called() + self.assertEqual(owner.deadline_ns, 0) + self.assertEqual(manager.cleanup_end, 0) + self.assertTrue(manager.slots[0]["control_closed"]) + + def test_review_cached_owner_cannot_finish_clean_at_deadline(self): + owner = SourceOwner() + owner.deadline_ns = 100 + with patch("source_qa_protocol.monotonic_ns", return_value=100): + owner.finish_managers() + self.assertIsNotNone(owner.first_fault) + + def test_review_completed_control_is_explicitly_closed(self): + self.a["endpoint"].settled = self.a["endpoint"].eof = True + self.a["child"].returncode = 0 + with patch("os.read", return_value=b""): + self.manager._poll_slot(self.a, True) + self.assertTrue(self.a["endpoint"].closed) + self.assertTrue(self.a["collected"]) + + def test_review_poll_exception_does_not_starve_sibling_collection(self): + def progress(slot, accepting): + self.trace.append((slot["label"], "poll")) + if slot is self.a: raise OSError("inert-poll") + self.manager._poll_slot = progress + try: + self.manager.poll_cleanup(self.end) + except OSError: + pass + self.assertIn(("b", "poll"), self.trace) + + def test_broadcast_precedes_all_polls_and_sibling_cancel_survives_error(self): + def fail(*args, **kwargs): + self.trace.append(("a", "cancel-failed")); raise OSError("inert") + self.a["endpoint"].send = fail + self.manager.begin_cleanup(self.end) + self.assertEqual([x[0] for x in self.trace], ["a", "b"]) + self.assertTrue(self.a["cancel_sent"] and self.b["cancel_sent"]) + self.assertTrue(self.a["child"].stdin is None and self.b["child"].stdin is None) + self.assertEqual(self.owner.first_fault, "RUNTIME_CANCEL_WRITE") + original = self.manager.cleanup_end + self.manager.begin_cleanup(self.end * 2) + self.assertLessEqual(self.manager.cleanup_end, original) + self.assertEqual(len(self.trace), 2) + + def test_endpoint_failure_still_collects_direct_wait_and_both_real_eofs(self): + self.a["endpoint"].first_fault = "INERT_ENDPOINT" + self.a["child"].returncode = 0 + with patch("os.read", return_value=b""): + self.manager._poll_slot(self.a, False) + # Contract correction AO-04: wait/pipe EOF are retained, but a failed + # endpoint is no longer substituted for physical control EOF. + self.assertFalse(self.a["collected"]) + self.assertTrue(self.a["stdout_eof"] and self.a["stderr_eof"]) + self.assertIsNone(self.a["accepted"]) + self.assertEqual(self.owner.first_fault, "RUNTIME_ENDPOINT") + + def test_successful_a_completion_leaves_b_live_and_history_retained(self): + self.a["endpoint"].settled = self.a["endpoint"].eof = True + self.a["child"].returncode = 0 + with patch("os.read", return_value=b""): + self.manager._poll_slot(self.a, True) + self.assertIsNotNone(self.a["accepted"]) + self.assertIsNone(self.b["child"].returncode) + self.assertFalse(self.b["collected"]) + self.assertIs(self.manager.active, self.b) + self.assertEqual(len(self.manager.slots), 2) + self.assertFalse(self.owner._forward_ledger.complete()) + + def test_actual_result_eexist_cancels_live_sibling_and_preserves_exception(self): + self.a["accepted"] = 5 + self.a["collected"] = True + self.a["child"].returncode = 0 + self.a["endpoint"].settled = self.a["endpoint"].eof = True + (self.root / "a-result.json").write_text("retain collision") + with self.assertRaises(FileExistsError) as raised: + self.manager.complete(self.a) + self.assertIs(self.manager.first_error, raised.exception) + self.assertEqual(self.owner.first_fault, "RUNTIME_RESULT_RECEIPT") + self.assertTrue(self.b["cancel_sent"]) + self.assertIsNone(self.b["child"].returncode) + self.assertEqual((self.root / "a-result.json").read_text(), "retain collision") + self.assertEqual(len(self.manager.slots), 2) + + +class InstallerPolicyTests(unittest.TestCase): + def manager(self, parent=None): + owner = SourceOwner() + owner.deadline_ns = parent + manager = OwnedChildren(Path("/private/synthetic/case"), {}, + Path("/private/synthetic/case"), owner) + owner.register_manager(manager) + manager.entered = True + return manager + + @patch("source_qa_protocol.monotonic_ns", return_value=100_000_000) + def test_installer_original_end_and_cleanup_observation_are_distinct(self, _clock): + manager = self.manager() + self.assertEqual(manager._select_end(30, installer=True), (100_000_000, 30_100_000_000)) + self.assertEqual(manager.owner.runtime_end_ns, 30_100_000_000) + manager.owner.limit_end(4_100_000_000) + self.assertEqual(manager.owner.deadline_ns, 4_100_000_000) + self.assertEqual(manager.owner.runtime_end_ns, 30_100_000_000) + with self.assertRaises(AttributeError): + manager.owner.runtime_end_ns = 90_000_000_000 + with self.assertRaises(ChildFailure): + manager._select_end(30, installer=True) + + @patch("source_qa_protocol.monotonic_ns", return_value=100_000_000) + def test_installer_preserves_earlier_parent_and_cannot_follow_other_runtime(self, _clock): + manager = self.manager(4_000_000_000) + self.assertEqual(manager._select_end(30, installer=True)[1], 4_000_000_000) + ordinary = self.manager() + self.assertEqual(ordinary._select_end(30)[1], 4_100_000_000) + with self.assertRaises(ChildFailure): + ordinary._select_end(30, installer=True) + sibling = OwnedChildren(ordinary.root, {}, ordinary.cwd, ordinary.owner) + ordinary.owner.register_manager(sibling) + with self.assertRaises(ChildFailure): + sibling._select_end(30, installer=True) + + @patch("source_qa_protocol.monotonic_ns", return_value=100_000_000) + def test_ordinary_and_hook_limits_do_not_change(self, _clock): + manager = self.manager() + self.assertEqual(manager._select_end(1)[1], 1_100_000_000) + with patch("source_qa_protocol.monotonic_ns", return_value=200_000_000): + self.assertEqual(manager._select_end(600)[1], 1_100_000_000) + self.assertEqual(manager.owner.runtime_end_ns, 4_100_000_000) + + @patch("source_qa_protocol.monotonic_ns", return_value=100_000_000) + def test_short_slot_retains_actual_owner_admission_and_separate_cleanup(self, _clock): + for parent, original, slot_end in [ + (None, 4_100_000_000, 1_100_000_000), + (3_000_000_000, 3_000_000_000, 1_100_000_000), + (800_000_000, 800_000_000, 800_000_000)]: + with self.subTest(parent=parent): + manager = self.manager(parent) + self.assertEqual(manager._select_end(1)[1], slot_end) + self.assertEqual(manager.hard_end, slot_end) + self.assertEqual(manager.owner.deadline_ns, original) + self.assertEqual(manager.owner.runtime_end_ns, original) + manager.owner.limit_end(700_000_000) + self.assertEqual(manager.owner.deadline_ns, 700_000_000) + self.assertEqual(manager.owner.runtime_end_ns, original) + self.assertEqual(manager._select_end(30)[1], 700_000_000) + self.assertEqual(manager.owner.runtime_end_ns, original) + + @patch("source_qa_protocol.monotonic_ns", return_value=100_000_000) + def test_installer_route_is_closed_before_any_runtime_preparation(self, _clock): + manager = self.manager() + prepared = manager.root.parent + argv = [str(prepared / "natives/codex-inert-source-only"), + "--installer-phases-diagnostic", str(prepared), str(manager.root), + str(prepared / "pair/keito")] + with patch.object(manager, "_start", return_value="selected") as start: + self.assertEqual(manager.start_installer("install", argv), "selected") + self.assertEqual(start.call_args.args[2], 30) + self.assertTrue(start.call_args.kwargs["installer"]) + for bad in [argv[:-1], argv + ["extra"], ["/usr/bin/git"] + argv[1:], + [argv[0], "--cli"] + argv[2:], argv[:-1] + ["relative"]]: + with self.assertRaises(ChildFailure): + manager.start_installer("install", bad) + self.assertEqual(start.call_count, 1) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/support/test_source_clock_domain.py b/tests/support/test_source_clock_domain.py new file mode 100644 index 0000000..ed6c440 --- /dev/null +++ b/tests/support/test_source_clock_domain.py @@ -0,0 +1,50 @@ +"""No child processes: the wire deadline must use Rust's POSIX clock domain.""" +from pathlib import Path +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import source_qa_protocol as protocol + + +class ClockDomainTests(unittest.TestCase): + def test_wire_clock_is_posix_monotonic_not_python_process_epoch(self): + owner = protocol.SourceOwner() + with patch.object(protocol.time, 'monotonic_ns', return_value=7), \ + patch.object(protocol.time, 'clock_gettime_ns', return_value=100) as clock: + self.assertEqual(owner.now(), 100) + clock.assert_called_once_with(protocol.time.CLOCK_MONOTONIC) + self.assertIsNone(owner.first_fault) + + def test_posix_clock_failure_still_zeros_and_broadcasts_every_manager(self): + owner = protocol.SourceOwner() + owner.deadline_ns = 900 + events = [] + + class Manager: + def __init__(self, label): + self.label = label + + def begin_cleanup(self, end): + events.append((self.label, end)) + + owner.managers = [Manager('A'), Manager('B')] + with patch.object(protocol.time, 'monotonic_ns', return_value=7), \ + patch.object(protocol.time, 'clock_gettime_ns', side_effect=OSError('inert-clock')): + self.assertEqual(owner.now(), 0) + self.assertEqual(owner.deadline_ns, 0) + self.assertEqual(owner.first_fault, 'OWNER_CLOCK') + self.assertEqual(events, [('A', 0), ('B', 0)]) + + def test_valid_posix_zero_is_not_clock_failure(self): + owner = protocol.SourceOwner() + with patch.object(protocol.time, 'monotonic_ns', return_value=7), \ + patch.object(protocol.time, 'clock_gettime_ns', return_value=0): + self.assertEqual(owner.now(), 0) + self.assertIsNone(owner.first_fault) + self.assertIsNone(owner.deadline_ns) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/support/test_source_owner_finalizer.py b/tests/support/test_source_owner_finalizer.py new file mode 100644 index 0000000..7682069 --- /dev/null +++ b/tests/support/test_source_owner_finalizer.py @@ -0,0 +1,156 @@ +"""Finite R34 manager-finalizer regressions: objects/fake clocks only. + +No processes, profiles, signals, threads, runtime actors or environment access. +The real SourceOwner is the subject; test managers have no cleanup authority. +""" +from pathlib import Path +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import source_qa_protocol as protocol +from source_qa_protocol import SourceOwner, ProtocolError +from source_qa_children import Cancelled + + +class Parent: + cancel_deadline_ns = None + def receive(self, parent=False, failure_only=False): return False + def __init__(self, close_error=False): + self.sent = [] + self.closed = False + self.close_error = close_error + + def send(self, tag): + self.sent.append(tag) + + def close(self): + self.closed = True + if self.close_error: + raise OSError("PRIVATE_CLOSE_DETAIL") + + +class FinalizerCases(unittest.TestCase): + def test_begin_error_retains_manager_and_broadcasts_siblings_before_poll(self): + owner = SourceOwner() + calls = [] + class Manager: + def __init__(self, name): self.name, self.polls = name, 0 + def begin_cleanup(self, end): + calls.append(("begin", self.name, end)) + if self.name == "a": raise OSError("PRIVATE_BEGIN_DETAIL") + def poll_cleanup(self, end): + self.polls += 1 + calls.append(("poll", self.name, end)) + return self.name == "b" or self.polls == 2 + a, b = Manager("a"), Manager("b") + owner.managers = [a, b] + with patch.object(protocol, "monotonic_ns", return_value=1), patch.object(protocol.time, "sleep"): + owner.finish_managers() + self.assertEqual([(kind, name) for kind, name, _ in calls], + [("begin", "a"), ("begin", "b"), ("poll", "a"), ("poll", "b"), ("poll", "a")]) + self.assertEqual(len({end for _, _, end in calls}), 1) + self.assertEqual(owner.managers, [a, b]) + self.assertEqual(owner.first_fault, "MANAGER_CLEANUP_BEGIN") + self.assertTrue(owner.unsettled) + self.assertNotIn(id(a), owner._finished_managers) + + def test_poll_error_retains_manager_for_later_collection(self): + owner = SourceOwner() + class Manager: + polls = 0 + def begin_cleanup(self, end): pass + def poll_cleanup(self, end): + self.polls += 1 + if self.polls == 1: raise OSError("PRIVATE_POLL_DETAIL") + return True + manager = Manager() + owner.managers = [manager] + with patch.object(protocol, "monotonic_ns", return_value=1), patch.object(protocol.time, "sleep"): + owner.finish_managers() + self.assertEqual(manager.polls, 2) + self.assertEqual(owner.first_fault, "MANAGER_CLEANUP_POLL") + self.assertNotIn(id(manager), owner._finished_managers) + before = manager.polls + with patch.object(protocol, "monotonic_ns", return_value=2): + owner.finish_managers() + self.assertEqual(manager.polls, before) # collected failed facts are cached, never clean proof + self.assertTrue(owner.unsettled) + + def test_bad_schema_does_not_discard_pending_collection(self): + owner = SourceOwner() + class Manager: + polls = 0 + def begin_cleanup(self, end): pass + def poll_cleanup(self, end): + self.polls += 1 + return "NOT_A_PROOF" if self.polls == 1 else True + manager = Manager() + owner.managers = [manager] + with patch.object(protocol, "monotonic_ns", return_value=1), patch.object(protocol.time, "sleep"): + owner.finish_managers() + self.assertEqual(manager.polls, 2) + self.assertEqual(owner.first_fault, "MANAGER_PROOF_SCHEMA") + self.assertNotIn(id(manager), owner._finished_managers) + + def test_generic_receipt_error_and_cancellation_cannot_emit_settled(self): + for original in (OSError("PRIVATE_RECEIPT_DETAIL"), Cancelled(15), KeyboardInterrupt()): + with self.subTest(kind=type(original).__name__): + owner = SourceOwner() + parent = Parent() + owner.parent = parent + with patch.object(protocol, "monotonic_ns", return_value=1): + self.assertFalse(owner.__exit__(type(original), original, None)) + self.assertEqual(parent.sent, ["FAILED"]) + self.assertTrue(parent.closed) + self.assertTrue(owner.admission_closed) + self.assertTrue(owner.unsettled) + self.assertNotIn("PRIVATE", owner.first_fault) + + def test_finish_exception_does_not_replace_original_or_skip_failed_terminal(self): + owner = SourceOwner() + parent = Parent() + owner.parent = parent + original = OSError("PRIVATE_ORIGINAL") + with patch.object(owner, "finish_managers", side_effect=RuntimeError("PRIVATE_CLEANUP")): + self.assertFalse(owner.__exit__(OSError, original, None)) + self.assertEqual(parent.sent, ["FAILED"]) + self.assertTrue(parent.closed) + self.assertEqual(owner.first_fault, "OWNER_OPERATION_FAILED") + + def test_close_exception_preserves_original_and_restores_current(self): + owner = SourceOwner() + owner.parent = Parent(close_error=True) + previous = object() + owner.previous = previous + original = ProtocolError("ORIGINAL") + with patch.object(protocol, "CURRENT", owner), patch.object(protocol, "monotonic_ns", return_value=1): + self.assertFalse(owner.__exit__(ProtocolError, original, None)) + self.assertIs(protocol.CURRENT, previous) + self.assertEqual(owner.first_fault, "ORIGINAL") + self.assertTrue(owner._closed) + + def test_permanent_callback_error_remains_unfinished_at_original_bound(self): + owner = SourceOwner() + owner.deadline_ns = 10 + class Manager: + polls = 0 + def begin_cleanup(self, end): pass + def poll_cleanup(self, end): + self.polls += 1 + raise OSError("PRIVATE_CALLBACK") + manager = Manager() + owner.managers = [manager] + ticks = iter(range(1, 100)) + with patch.object(protocol, "monotonic_ns", side_effect=lambda: next(ticks)), patch.object(protocol.time, "sleep"): + owner.finish_managers() + self.assertGreater(manager.polls, 1) + self.assertEqual(owner.deadline_ns, 10) + self.assertEqual(owner.first_fault, "MANAGER_CLEANUP_POLL") + self.assertNotIn(id(manager), owner._finished_managers) + self.assertEqual(owner.managers, [manager]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/support/test_source_owner_finalizer_review_regressions.py b/tests/support/test_source_owner_finalizer_review_regressions.py new file mode 100644 index 0000000..2a4809a --- /dev/null +++ b/tests/support/test_source_owner_finalizer_review_regressions.py @@ -0,0 +1,169 @@ +"""R35 independent finite finalizer cases. No child, signal, thread or env access.""" +from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import os +import socket +import unittest +from unittest.mock import patch +import source_qa_protocol as p +from source_qa_children import Cancelled + +class Parent: + cancel_deadline_ns = None + def receive(self, parent=False, failure_only=False): return False + def __init__(self, send_error=None, close_error=None): + self.tags=[]; self.closed=False; self.send_error=send_error; self.close_error=close_error + def send(self, tag): + self.tags.append(tag) + if self.send_error is not None: raise self.send_error + def close(self): + self.closed=True + if self.close_error is not None: raise self.close_error + +class ReviewCases(unittest.TestCase): + def test_mixed_clean_failed_collection_is_retained_and_cached(self): + owner=p.SourceOwner(); calls=[] + class Manager: + def __init__(self,name): self.name=name; self.polls=0; self.handle=object(); self.collected=False + def begin_cleanup(self,end): + calls.append(('begin',self.name,end)) + if self.name=='a': raise KeyboardInterrupt() + def poll_cleanup(self,end): + self.polls+=1; calls.append(('poll',self.name,end)) + if self.name=='a' and self.polls==1: return False + if self.name=='b' and self.polls==1: return 1 + self.collected=True; return True + a,b,c=[Manager(x) for x in 'abc']; owner.managers=[a,b,c] + handles=[x.handle for x in owner.managers] + with patch.object(p,'monotonic_ns',return_value=1), patch.object(p.time,'sleep'): + owner.finish_managers() + self.assertEqual([(x[0],x[1]) for x in calls[:3]],[('begin','a'),('begin','b'),('begin','c')]) + self.assertEqual(owner._finished_managers,{id(c)}) + self.assertEqual(owner._failed_managers,{id(a),id(b)}) + self.assertEqual(owner._collected_failed_managers,{id(a),id(b)}) + self.assertTrue(all(x.collected for x in owner.managers)) + self.assertEqual([x.handle for x in owner.managers],handles) + self.assertEqual(len({x[2] for x in calls}),1) + before=list(calls); previous=owner.deadline_ns + with patch.object(p,'monotonic_ns',return_value=previous+1): owner.finish_managers() + self.assertEqual(calls,before); self.assertEqual(owner.deadline_ns,previous) + self.assertEqual(owner.first_fault,'MANAGER_CLEANUP_BEGIN'); self.assertTrue(owner.unsettled) + + def test_permanent_false_and_throwing_callback_keep_unknown_handles(self): + owner=p.SourceOwner(); owner.deadline_ns=30; calls=[] + class Manager: + def __init__(self,name): self.name=name; self.polls=0; self.handle=object() + def begin_cleanup(self,end): + calls.append(('begin',self.name,end)) + if self.name=='error': raise OSError('PRIVATE_BEGIN') + def poll_cleanup(self,end): + self.polls+=1; calls.append(('poll',self.name,end)) + if self.name=='error': raise RuntimeError('PRIVATE_POLL') + return False + a,b=Manager('error'),Manager('false'); owner.managers=[a,b] + ticks=iter(range(1,1000)) + with patch.object(p,'monotonic_ns',side_effect=lambda:next(ticks)), patch.object(p.time,'sleep'): + owner.finish_managers() + self.assertEqual([(x[0],x[1]) for x in calls[:2]],[('begin','error'),('begin','false')]) + self.assertGreater(a.polls,1); self.assertGreater(b.polls,1) + self.assertEqual(owner.managers,[a,b]); self.assertIsNotNone(a.handle); self.assertIsNotNone(b.handle) + self.assertFalse(owner._finished_managers); self.assertFalse(owner._collected_failed_managers) + self.assertEqual(owner.deadline_ns,30); self.assertEqual(owner.first_fault,'MANAGER_CLEANUP_BEGIN') + self.assertTrue(owner.unsettled) + + def test_late_true_stays_unknown_on_repeated_finish(self): + owner=p.SourceOwner(); owner.deadline_ns=10; calls=[] + clock=[1] + class Manager: + def begin_cleanup(self,end): calls.append(('begin',end)) + def poll_cleanup(self,end): calls.append(('poll',end)); clock[0]=10; return True + manager=Manager(); owner.managers=[manager] + # The callback itself crosses the bound; the fixture no longer relies + # on how many fresh-clock observations the owner performs. + with patch.object(p,'monotonic_ns',side_effect=lambda:clock[0]): owner.finish_managers() + with patch.object(p,'monotonic_ns',return_value=12): owner.finish_managers() + self.assertEqual([x[0] for x in calls],['begin','poll','begin']) + self.assertNotIn(id(manager),owner._finished_managers) + self.assertNotIn(id(manager),owner._collected_failed_managers) + self.assertEqual(owner.deadline_ns,10); self.assertEqual(owner.first_fault,'MANAGER_CLEANUP_DEADLINE') + self.assertTrue(owner.unsettled) + + def test_clock_failure_fails_closed_preserves_original_and_current(self): + for has_original in (False,True): + with self.subTest(original=has_original): + owner=p.SourceOwner(); manager=object(); owner.managers=[manager] + parent=Parent(); owner.parent=parent; previous=object(); owner.previous=previous + original=OSError('PRIVATE_OPERATION') if has_original else None + with patch.object(p,'CURRENT',owner), patch.object(p,'monotonic_ns',side_effect=OSError('PRIVATE_CLOCK')): + if has_original: self.assertFalse(owner.__exit__(OSError,original,None)) + else: + with self.assertRaises(p.ProtocolError) as error: owner.__exit__(None,None,None) + self.assertEqual(str(error.exception),'OWNER_CLOCK') + self.assertIs(p.CURRENT,previous) + self.assertEqual(parent.tags,['FAILED']); self.assertTrue(parent.closed) + self.assertEqual(owner.managers,[manager]); self.assertFalse(owner._finished_managers) + self.assertTrue(owner._closed); self.assertTrue(owner.unsettled) + self.assertEqual(owner.first_fault,'OWNER_OPERATION_FAILED' if has_original else 'OWNER_CLOCK') + + def test_terminal_and_close_baseexceptions_keep_first_reason(self): + for original in (None,OSError('PRIVATE_OPERATION'),p.ProtocolError('ORIGINAL')): + with self.subTest(original=type(original).__name__): + owner=p.SourceOwner(); owner.parent=Parent(SystemExit('PRIVATE_SEND'),KeyboardInterrupt()) + previous=object(); owner.previous=previous + with patch.object(p,'CURRENT',owner), patch.object(p,'monotonic_ns',return_value=1): + if original is None: + with self.assertRaises(p.ProtocolError) as error: owner.__exit__(None,None,None) + self.assertEqual(str(error.exception),'TERMINAL_WRITE') + else: self.assertFalse(owner.__exit__(type(original),original,None)) + self.assertIs(p.CURRENT,previous) + self.assertTrue(owner.parent.closed); self.assertTrue(owner._closed) + self.assertEqual(owner.parent.tags,['SETTLED' if original is None else 'FAILED']) + self.assertEqual(owner.first_fault,'TERMINAL_WRITE' if original is None else ('ORIGINAL' if isinstance(original,p.ProtocolError) else 'OWNER_OPERATION_FAILED')) + + def test_real_socket_receives_failed_after_operation_or_cancel(self): + for original in (OSError('PRIVATE_RECEIPT'),Cancelled(15)): + with self.subTest(original=type(original).__name__): + left,right=socket.socketpair() + self.addCleanup(left.close); self.addCleanup(right.close) + owner=p.SourceOwner(); owner.parent=p.Endpoint(left,'a'*32,budget=owner.budget,on_fault=owner.fail) + remote=p.Endpoint(right,'a'*32,os.getpid()); owner.parent.send('LIVE') + remote.receive(); self.assertTrue(remote.live); self.assertFalse(remote.settled) + with patch.object(p,'monotonic_ns',return_value=1): + self.assertFalse(owner.__exit__(type(original),original,None)) + with self.assertRaises(p.ProtocolError) as error: remote.receive() + self.assertEqual(str(error.exception),'PEER_FAILED'); self.assertFalse(remote.settled) + self.assertEqual(owner.first_fault,'OWNER_OPERATION_FAILED') + + def test_unwaited_forward_ledger_cannot_be_hidden_by_manager_true(self): + owner=p.SourceOwner() + child=1 if os.getpid()!=1 else 2 + owner.forward(['REGISTER|{}|{}|{}|1'.format(os.getpid(),child,'b'*32)]) + owner.parent=Parent() + class Manager: + def begin_cleanup(self,end): pass + def poll_cleanup(self,end): return True + manager=Manager(); owner.managers=[manager] + with patch.object(p,'monotonic_ns',return_value=1): + with self.assertRaises(p.ProtocolError) as error: owner.__exit__(None,None,None) + self.assertEqual(str(error.exception),'UNWAITED_FORWARD_REGISTRATION') + self.assertEqual(owner._finished_managers,{id(manager)}) + self.assertEqual(owner.parent.tags,['FAILED']); self.assertFalse(owner._forward_ledger.complete()) + self.assertTrue(owner.parent.closed); self.assertTrue(owner.unsettled) + + def test_local_four_seconds_and_earlier_inherited_bound_never_extend(self): + for inherited,expected in ((None,4_000_000_007),(50,50),(9_000_000_000,4_000_000_007)): + with self.subTest(inherited=inherited): + owner=p.SourceOwner(); owner.deadline_ns=inherited; calls=[] + class Manager: + def begin_cleanup(self,end): calls.append(end) + def poll_cleanup(self,end): calls.append(end); return True + manager=Manager(); owner.managers=[manager] + with patch.object(p,'monotonic_ns',return_value=7): owner.finish_managers() + with patch.object(p,'monotonic_ns',return_value=8): owner.finish_managers() + self.assertEqual(owner.deadline_ns,expected); self.assertEqual(calls,[expected,expected]) + self.assertFalse(owner.unsettled); self.assertEqual(owner.managers,[manager]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/support/test_source_qa_build_owner.py b/tests/support/test_source_qa_build_owner.py new file mode 100644 index 0000000..4286c14 --- /dev/null +++ b/tests/support/test_source_qa_build_owner.py @@ -0,0 +1,766 @@ +"""Pure fake/socket/metadata checks ONLY; no child, group or signal actor.""" +import importlib.util +from pathlib import Path +import signal +import unittest + +spec = importlib.util.spec_from_file_location("build_owner", Path(__file__).with_name("source_qa_build_owner.py")) +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) + + +class Stream: + def __init__(self, actions=()): + self.actions = list(actions) + self.reads = 0 + self.output = bytearray() + self.shutdowns = 0 + + def setblocking(self, _): + pass + + def recv(self, limit): + self.reads += 1 + value = self.actions.pop(0) if self.actions else BlockingIOError() + if isinstance(value, BaseException): + raise value + assert len(value) <= limit + return value + + def send(self, data): + self.output.extend(data) + return len(data) + + def shutdown(self, _): + self.shutdowns += 1 + + +class Group: + def __init__(self): + self.events = [] + self.absent_value = False + self.fail_park = False + self.disabled = False + + def park(self): + assert not self.disabled + self.events.append("park") + if self.fail_park: + raise OSError() + + def absent(self): + assert not self.disabled + self.events.append("query") + return self.absent_value + + def send(self, signum): + assert not self.disabled + self.events.append("term" if signum == signal.SIGTERM else "kill") + + def abandon(self): + assert not self.disabled + self.events.append("self-kill") + self.disabled = True + raise m.Refused("SELF_GROUP_UNPROVEN") + + def disable(self): + self.events.append("disable") + self.disabled = True + + +def wire(*bodies): + return b"".join(("a" * 32 + "|" + b + "\n").encode() for b in bodies) + + +def pair(actions=()): + group = Group() + keeper = m.Keeper(group, 10 * m.CAP) + stream = Stream(actions) + return keeper, group, m.Channel(stream, "a" * 32) + + +class Tests(unittest.TestCase): + def test_timely_park_is_deferred_until_real_quiescence(self): + k, g, c = pair([wire("PARK")] + [InterruptedError() for _ in range(8)]) + self.assertFalse(k.turn(c, lambda: 1)) + self.assertEqual(g.events, []) + self.assertTrue(k.intent) + self.assertFalse(k.turn(c, lambda: 2)) + self.assertEqual(g.events, ["park"]) + self.assertEqual(c.stream.output, wire("PARKED")) + + def test_park_and_self_kill_cannot_precede_buffered_expired_minimum(self): + for failed in [False, True]: + k, g, c = pair([wire("PARK", "CLEAN|100")]) + g.fail_park = failed + with self.assertRaisesRegex(m.Refused, "DEADLINE"): + k.turn(c, lambda: 150) + self.assertEqual(k.end, 100) + self.assertEqual(g.events, []) + self.assertFalse(k.gone) + + def test_partial_wouldblock_is_not_drained(self): + k, g, c = pair([wire("PARK") + ("a" * 32 + "|CLEAN|").encode()]) + self.assertFalse(k.turn(c, lambda: 150)) + self.assertEqual(g.events, []) + c.stream.actions.append(b"100\n") + with self.assertRaisesRegex(m.Refused, "DEADLINE"): + k.turn(c, lambda: 150) + self.assertEqual(g.events, []) + + def test_rejected_line_drains_matching_minimum_before_group_work(self): + k, g, c = pair([b"b" * 32 + b"|PARK\n" + wire("CLEAN|100")]) + with self.assertRaisesRegex(m.Refused, "DEADLINE"): + k.turn(c, lambda: 150) + self.assertEqual(k.first, "CHANNEL") + self.assertEqual(k.end, 100) + self.assertEqual(g.events, []) + + def test_fatal_transport_stops_pending_park_and_stays_failed(self): + k, g, c = pair([wire("PARK"), OSError()]) + with self.assertRaisesRegex(m.Refused, "CHANNEL"): + k.turn(c, lambda: 1) + self.assertEqual(g.events, ["disable"]) + self.assertFalse(k.intent) + for action in [lambda: k.turn(c, lambda: 2), lambda: k.step(lambda: 2), lambda: k.park(lambda: 2)]: + with self.assertRaises(m.Refused): + action() + self.assertEqual(g.events, ["disable"]) + + def test_expiry_has_reserved_cleanup_budget(self): + k, g, c = pair() + self.assertFalse(k.turn(c, lambda: k.operation_end)) + self.assertEqual(k.first, "LIFETIME") + self.assertEqual(g.events, ["park", "query", "term"]) + saved = list(g.events) + with self.assertRaisesRegex(m.Refused, "DEADLINE"): + k.turn(c, lambda: k.hard) + self.assertEqual(g.events, saved) + + def test_first_clean_bound_is_immutable_and_second_request_refused(self): + k, g, c = pair() + k.control("CLEAN|1000", 1) + with self.assertRaisesRegex(m.Refused, "CLEAN_ALREADY_BOUND"): + k.control("CLEAN|500", 2) + self.assertEqual(k.end, 1000) + self.assertEqual(g.events, []) + + def test_first_clean_reduction_after_expiry_does_not_restore_proof(self): + k, g, c = pair() + at = k.operation_end + k.turn(c, lambda: at) + grace = k.term_end + saved = list(g.events) + c.stream.actions.append(wire("CLEAN|" + str(at + 100))) + with self.assertRaisesRegex(m.Refused, "DEADLINE"): + k.turn(c, lambda: at + 150) + self.assertEqual(k.first, "LIFETIME") + self.assertEqual(k.term_end, grace) + self.assertEqual(g.events, saved) + + def test_pre_park_eof_parking_loss_has_one_failure_only_self_kill(self): + k, g, c = pair([b""]) + g.fail_park = True + with self.assertRaisesRegex(m.Refused, "SELF_GROUP_UNPROVEN"): + k.turn(c, lambda: 1) + self.assertEqual(k.first, "OWNER_EOF") + self.assertEqual(g.events, ["park", "self-kill"]) + self.assertFalse(k.gone) + + def test_normal_single_bound_settlement_requires_release_and_eof(self): + k, g, c = pair([wire("PARK", "CLEAN|1000")]) + g.absent_value = True + self.assertFalse(k.turn(c, lambda: 1)) + self.assertEqual(c.stream.output, wire("PARKED", "GONE")) + saved = list(g.events) + c.stream.actions.extend([wire("RELEASE"), b""]) + self.assertTrue(k.turn(c, lambda: 2)) + self.assertEqual(g.events, saved) + + def test_trailing_release_is_sticky_failure_not_success(self): + k, g, c = pair([wire("CLEAN|1000")]) + g.absent_value = True + k.turn(c, lambda: 1) + c.stream.actions.extend([wire("RELEASE", "RELEASE"), b""]) + with self.assertRaises(m.Refused): + k.turn(c, lambda: 2) + self.assertEqual(k.first, "CONTROL") + + def test_parent_collects_both_handles_after_first_fault(self): + state = object.__new__(m.BuildRun) + state.first = "FIRST" + state.secondary = [] + state.keeper, state.child_status, state.keeper_status = 42, None, None + state.release = False + class Child: + def poll(self): + raise OSError() + state.child = Child() + from unittest.mock import patch + with patch.object(m.os, "waitpid", return_value=(42, 0)) as wait: + state.collect() + self.assertEqual(state.first, "FIRST") + self.assertIn("CHILD_WAIT", state.secondary) + self.assertEqual(state.keeper_status, 0) + wait.assert_called_once_with(42, m.os.WNOHANG) + + def test_parent_half_close_is_attempted_once_without_repeated_fault(self): + state = object.__new__(m.BuildRun) + state.channel = m.Channel(Stream(), "a" * 32) + state.writer_attempted = state.writer_shutdown_ok = False + state.first, state.secondary = None, [] + state.close_writer() + state.close_writer() + self.assertEqual(state.channel.stream.shutdowns, 1) + self.assertTrue(state.writer_shutdown_ok) + self.assertIsNone(state.first) + + def test_integer_grammar_is_canonical_and_bounded(self): + for value in ["", "01", "-1", "1.0", "18446744073709551616"]: + with self.assertRaises(m.Refused): + m.integer(value) + self.assertEqual(m.integer("0"), 0) + + def test_missing_kernel_policy_marker_refuses_before_any_actor_or_file(self): + from unittest.mock import patch + with patch.dict(m.os.environ, {}, clear=True), patch.object(m.os, "fork") as fork, patch.object(m, "BuildRun") as owner: + with self.assertRaisesRegex(m.Refused, "POLICY_PREREQUISITE"): + m.run({}) + fork.assert_not_called() + owner.assert_not_called() + + def test_receipt_error_retains_specific_safe_reason(self): + from unittest.mock import patch + state = object.__new__(m.BuildRun) + class Trace: + def write(self, _): + raise OSError("private path must not escape") + state.trace = Trace() + with patch.object(m.time, "monotonic_ns", return_value=1): + with self.assertRaisesRegex(m.Refused, "^RECEIPT$"): + state.event("REGISTERED") + + def test_frame_cap_cannot_trigger_park_before_ninth_minimum(self): + bodies = ["PARK"] + ["CLEAN|1000"] * 7 + ["CLEAN|100"] + # This owner accepts only ONE CLEAN. Duplicates remain control failure; + # neither this different contract nor frame caps permit eager PARK. + data = wire(*bodies) + k, g, c = pair([data[:200], data[200:]]) + self.assertFalse(k.turn(c, lambda: 150)) + self.assertEqual(g.events, []) + self.assertEqual(k.first, "CONTROL") + self.assertEqual(k.end, 1000) + + def test_private_spec_positive_and_negative_metadata_refusal_before_actors(self): + import json + import os + import tempfile + from unittest.mock import patch + with tempfile.TemporaryDirectory(prefix="build-owner-pure-") as temp: + root = Path(temp).resolve() + for relative in ["home", "home/.codex", "home/.claude", "home/capture", "home/config", "home/state", "home/AppData", "tmp", "toolchain", "cargo-cache", "rustup-cache", "target"]: + (root / relative).mkdir(mode=0o700) + image = root / "toolchain/cargo" + image.write_text("INERT MARKER; NEVER EXECUTED\n") + image.chmod(0o700) + env = {"HOME": str(root / "home"), "CODEX_HOME": str(root / "home/.codex"), + "CLAUDE_CONFIG_DIR": str(root / "home/.claude"), "KEITO_CAPTURE_HOME": str(root / "home/capture"), + "XDG_CONFIG_HOME": str(root / "home/config"), "XDG_STATE_HOME": str(root / "home/state"), + "APPDATA": str(root / "home/AppData"), "TMPDIR": str(root / "tmp"), + "PATH": ":".join((str(image.parent), "/usr/bin", "/bin", "/usr/sbin", "/sbin")), + "CARGO_HOME": str(root / "cargo-cache"), "RUSTUP_HOME": str(root / "rustup-cache"), + "CARGO_TARGET_DIR": str(root / "target"), "CARGO_BUILD_JOBS": "2", "CARGO_NET_OFFLINE": "true", + "RUST_TEST_THREADS": "1", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"} + base = {"root": str(root), "cwd": str(root), "argv": [str(image), "build", "--offline", "--locked"], + "env": env, "seconds": 3, "image_sha256": m.file_hash(image), "owner_sha256": m.file_hash(Path(m.__file__).resolve())} + path = root / "spec.json" + def save(value): + path.write_text(json.dumps(value));path.chmod(0o600) + save(base) + with patch.object(m.os, "fork") as fork, patch.object(m.subprocess, "Popen") as popen: + self.assertEqual(m.spec_read(path)["argv"], base["argv"]) + for key, value, expected in [("HOME", "/outside-private-home", "PRIVATE_ENV"), + ("PATH", "/unapproved/tools", "TOOLCHAIN_PATH"), + ("CARGO_NET_OFFLINE", "false", "BUILD_ENV"), + ("CARGO_TARGET_DIR", str(root.parent), "PRIVATE_TARGET")]: + changed = dict(base);changed["env"] = dict(env, **{key:value});save(changed) + with self.assertRaisesRegex(m.Refused, expected): + m.spec_read(path) + changed = dict(base, image_sha256="0" * 64);save(changed) + with self.assertRaisesRegex(m.Refused, "SOURCE_BINDING"): + m.spec_read(path) + changed = dict(base);changed["env"] = dict(env, EXTRA="must-refuse");save(changed) + with self.assertRaisesRegex(m.Refused, "ENV"): + m.spec_read(path) + path.write_text('{"root":"one","root":"two"}');path.chmod(0o600) + with self.assertRaisesRegex(m.Refused, "SPEC_DUPLICATE"): + m.spec_read(path) + fork.assert_not_called();popen.assert_not_called() + + def test_parent_success_requires_actual_both_waits_release_and_eof(self): + from unittest.mock import patch + state = object.__new__(m.BuildRun) + state.first, state.secondary = None, [] + state.keeper, state.keeper_status = 42, None + state.child_status = None + state.end, state.hard = 1000, 2000 + state.gone = state.release = state.proof = False + state.writer_attempted = state.writer_shutdown_ok = False + state.channel = m.Channel(Stream([wire("GONE"), b""]), "a" * 32) + class Child: + def poll(self): + return 0 + state.child = Child() + def waited(pid, flags): + self.assertEqual((pid, flags), (42, m.os.WNOHANG)) + return (42, 0) if state.release else (0, 0) + with patch.object(m.os, "waitpid", side_effect=waited), patch.object(m.time, "monotonic_ns", return_value=1), patch.object(m.time, "sleep"): + state.settle() + self.assertTrue(state.proof) + self.assertEqual((state.child_status, state.keeper_status), (0, 0)) + self.assertEqual(state.channel.stream.output, wire("RELEASE")) + self.assertEqual(state.channel.stream.shutdowns, 1) + + def test_parent_duplicate_terminal_never_rehabilitates_failed_proof(self): + from unittest.mock import patch + state = object.__new__(m.BuildRun) + state.first, state.secondary = None, [] + state.keeper, state.keeper_status = 42, None + state.child_status = None + state.end, state.hard = 1000, 2000 + state.gone = state.release = state.proof = False + state.writer_attempted = state.writer_shutdown_ok = False + state.channel = m.Channel(Stream([wire("GONE", "GONE"), b""]), "a" * 32) + class Child: + def poll(self): + return 0 + state.child = Child() + with patch.object(m.os, "waitpid", side_effect=lambda *_: (42, 0) if state.release else (0, 0)), patch.object(m.time, "monotonic_ns", return_value=1), patch.object(m.time, "sleep"): + state.settle() + self.assertFalse(state.proof) + self.assertEqual(state.first, "TERMINAL") + + def finalizer_case(self, phase): + import io + import json + from contextlib import ExitStack + from unittest.mock import patch + state = object.__new__(m.BuildRun) + state.root = Path("/inert-no-files-opened") + state.first, state.secondary = "ORIGINAL_OPERATION", [] + state.cancelled = False + state.keeper, state.keeper_status = 42, None + state.child_status = None + state.child_attempted = True + state.hard, state.end = 1000, 500 + state.gone = state.release = state.proof = False + state.writer_attempted = state.writer_shutdown_ok = False + calls, packets = [], [] + class Child: + pid = 43 + count = 0 + def poll(self): + self.count += 1 + calls.append("child_wait") + return 0 if phase != "late" or self.count >= 3 else None + state.child = Child() + class ActorStream(Stream): + def shutdown(self, _): + calls.append("shutdown") + if phase == "shutdown": + state.cancel_signal(None, None) + self.shutdowns += 1 + state.channel = m.Channel(ActorStream(), "a" * 32) + class Close: + def __init__(self, name): + self.name = name + def close(self): + calls.append(self.name) + if self.name == "output_close" and phase == "close": + state.cancel_signal(None, None) + raise OSError("synthetic close") + state.output, state.trace = Close("output_close"), Close("trace_close") + parent, child_end = Close("parent_close"), Close("child_end_close") + class Receipt(io.StringIO): + def fileno(self): + return 99 + wait_count = 0 + def wait(*_): + nonlocal wait_count + wait_count += 1 + calls.append("keeper_wait") + return (42, 0) if phase != "late" or wait_count >= 3 else (0, 0) + def sleep(_): + calls.append("late_sleep") + if phase == "late": + state.cancel_signal(None, None) + stderr = object() + def publish(value, **kwargs): + calls.append("stderr_fact" if kwargs.get("file") is stderr else "stdout_fact") + if phase == "fact" and kwargs.get("file") is not stderr: + state.cancel_signal(None, None) + raise OSError("synthetic output") + packets.append(json.loads(value)) + error = None + with ExitStack() as stack: + stack.enter_context(patch.object(m.os, "waitpid", side_effect=wait)) + stack.enter_context(patch.object(m.os, "fsync")) + stack.enter_context(patch.object(m.time, "monotonic_ns", return_value=1)) + stack.enter_context(patch.object(m.time, "sleep", side_effect=sleep)) + stack.enter_context(patch.object(m, "exclusive", side_effect=lambda *_: Receipt())) + stack.enter_context(patch.object(m.signal, "pthread_sigmask", return_value=set())) + stack.enter_context(patch.object(m.signal, "sigpending", return_value=set())) + stack.enter_context(patch.object(m.signal, "signal", side_effect=lambda *args: calls.append("restore_handler"))) + stack.enter_context(patch.object(m.sys, "stderr", stderr)) + stack.enter_context(patch("builtins.print", side_effect=publish)) + try: + state.finalize(parent, child_end, False, {m.signal.SIGINT: None, m.signal.SIGTERM: None}) + except BaseException as caught: + error = caught + self.assertIsNone(error, "catchable cancellation/secondary errors must not escape finalization") + self.assertEqual(state.first, "ORIGINAL_OPERATION") + self.assertEqual((state.child_status, state.keeper_status), (0, 0)) + for name in ["child_wait", "keeper_wait", "child_end_close", "parent_close", "output_close", "trace_close", "restore_handler"]: + self.assertIn(name, calls) + self.assertEqual(calls.count("restore_handler"), 2) + self.assertTrue(packets, "retained facts must reach the bounded fallback") + self.assertEqual(packets[-1]["owner_result"]["first_fault"], "ORIGINAL_OPERATION") + self.assertFalse(packets[-1]["first_saved"]) + if phase == "late": + self.assertGreaterEqual(state.child.count, 3) + self.assertGreaterEqual(wait_count, 3) + self.assertIsNone(packets[-1]["cutpoint"]["child_wait"]) + self.assertEqual(packets[-1]["owner_result"]["child_wait"], 0) + if phase == "fact": + self.assertIn("stderr_fact", calls) + + def test_r24_cancel_at_finalizer_shutdown_retains_both_waits_and_facts(self): + self.finalizer_case("shutdown") + + def test_r24_cancel_during_late_wait_does_not_abort_remaining_collection(self): + self.finalizer_case("late") + + def test_r24_cancel_and_fact_output_failure_still_close_and_publish_fallback(self): + self.finalizer_case("fact") + + def test_r24_secondary_close_failure_cannot_skip_other_owned_resources(self): + self.finalizer_case("close") + + def handoff_case(self, original=None, unmask_error=None, final_stdout_failure=False): + """Actual finalizer, fake waits/IO/masks only; no signal API reaches OS.""" + import io + import json + from contextlib import ExitStack + from unittest.mock import patch + state = object.__new__(m.BuildRun) + state.root = Path("/inert-handoff-no-files-opened") + state.first, state.secondary, state.cancelled = original, [], False + state.keeper, state.keeper_status = 42, 0 + state.child_status, state.child_attempted = 0, True + state.hard, state.end = 1000, 500 + state.gone = state.release = state.proof = True + state.writer_attempted = state.writer_shutdown_ok = True + state.channel = m.Channel(Stream(), "a" * 32) + state.channel.eof = True + calls, packets, saved = [], [], [] + class Child: + pid = 43 + state.child = Child() + class Close: + def __init__(self, name): + self.name = name + def close(self): + calls.append(self.name) + state.output, state.trace = Close("output_close"), Close("trace_close") + class Receipt(io.StringIO): + def fileno(self): + return 99 + def close(self): + saved.append(json.loads(self.getvalue())) + super().close() + def mask(how, _): + calls.append("mask" if how == m.signal.SIG_BLOCK else "unmask") + if how == m.signal.SIG_SETMASK and unmask_error is not None: + raise unmask_error + return set() + def publish(value, **_): + calls.append("packet") + if final_stdout_failure and "unmask" in calls and not _.get("file"): + raise OSError("synthetic final stdout") + packets.append(json.loads(value)) + cutpoint = state.facts() + with ExitStack() as stack: + stack.enter_context(patch.object(m.os, "waitpid", side_effect=AssertionError("already waited"))) + stack.enter_context(patch.object(m.os, "fsync")) + stack.enter_context(patch.object(m, "exclusive", side_effect=lambda *_: Receipt())) + stack.enter_context(patch.object(m.signal, "pthread_sigmask", side_effect=mask)) + stack.enter_context(patch.object(m.signal, "sigpending", return_value=set())) + stack.enter_context(patch.object(m.signal, "signal", side_effect=lambda *_: calls.append("handler"))) + stack.enter_context(patch("builtins.print", side_effect=publish)) + state.finalize(Close("parent_close"), Close("child_end_close"), True, + {m.signal.SIGINT: None, m.signal.SIGTERM: None}, cutpoint) + self.assertEqual((state.child_status, state.keeper_status), (0, 0)) + for name in ["child_end_close", "parent_close", "output_close", "trace_close"]: + self.assertEqual(calls.count(name), 1) + self.assertEqual(calls.count("handler"), 2) + self.assertEqual(calls.count("mask"), 1) + self.assertEqual(calls.count("unmask"), 1, "failed handoff must never retry into success") + self.assertEqual(len(saved), 1, "FINAL is immutable, not rewritten after handoff") + self.assertEqual(saved[0]["cutpoint"], cutpoint) + self.assertTrue(saved[0]["handler_restoration_pending"]) + self.assertTrue(packets) + self.assertEqual(packets[-1]["cutpoint"], cutpoint) + self.assertEqual(calls[-1], "packet", "final report must follow the actual unmask disposition") + last = packets[-1] + self.assertEqual(last["mask_restoration_pending"], unmask_error is not None) + self.assertEqual(last["handoff_complete"], unmask_error is None) + self.assertFalse(last["handler_restoration_pending"]) + if unmask_error is not None: + self.assertEqual(last["owner_result"]["first_fault"], original or "HANDOFF_UNMASK") + if original: + self.assertIn("HANDOFF_UNMASK", last["owner_result"]["secondary_faults"]) + if isinstance(unmask_error, KeyboardInterrupt): + self.assertTrue(last["owner_result"]["cancelled"]) + self.assertIn("CANCELLED", last["owner_result"]["secondary_faults"]) + else: + self.assertIsNone(last["owner_result"]["first_fault"]) + self.assertTrue(last["owner_result"]["cleanup_proof"]) + if final_stdout_failure: + self.assertIn("FACT_STDOUT", last["owner_result"]["secondary_faults"]) + self.assertEqual(cutpoint["first_fault"], original) + self.assertEqual(cutpoint["secondary_faults"], []) + + def test_r25_unmask_oserror_is_published_as_first_fault_with_unknown_mask(self): + self.handoff_case(unmask_error=OSError("synthetic unmask")) + + def test_r25_unmask_oserror_preserves_original_and_publishes_secondary(self): + self.handoff_case(original="ORIGINAL_OPERATION", unmask_error=OSError("synthetic unmask")) + + def test_r25_late_interrupt_at_unmask_retains_cancellation_evidence(self): + self.handoff_case(unmask_error=KeyboardInterrupt()) + + def test_r25_complete_handoff_report_follows_successful_unmask(self): + self.handoff_case() + + def test_r25_failed_unmask_and_final_stdout_use_failure_only_stderr_packet(self): + self.handoff_case(unmask_error=OSError("synthetic unmask"), final_stdout_failure=True) + + def terminal_interrupt_case(self, original=None, stderr_interrupt=False): + import io + import json + from contextlib import ExitStack + from unittest.mock import patch + calls, packets, receipts = [], [], [] + handoff_done = False + class Receipt(io.StringIO): + def fileno(self): + return 99 + def receipt(path): + item = Receipt() + receipts.append(item) + return item + def mask(how, _): + nonlocal handoff_done + if how == m.signal.SIG_SETMASK: + handoff_done = True + return set() + def publish(value, **kwargs): + sink = "stderr" if kwargs.get("file") is not None else "stdout" + calls.append(sink) + if handoff_done: + if sink == "stdout": + raise OSError("synthetic output") if stderr_interrupt else KeyboardInterrupt() + if stderr_interrupt: + raise KeyboardInterrupt() + packets.append(json.loads(value)) + with ExitStack() as stack: + stack.enter_context(patch.object(m, "exclusive", side_effect=receipt)) + stack.enter_context(patch.object(m.os, "fsync")) + stack.enter_context(patch.object(m.os, "waitpid", side_effect=AssertionError("already waited"))) + stack.enter_context(patch.object(m.signal, "pthread_sigmask", side_effect=mask)) + stack.enter_context(patch.object(m.signal, "sigpending", return_value=set())) + stack.enter_context(patch.object(m.signal, "signal", side_effect=lambda *_: calls.append("handler"))) + stack.enter_context(patch("builtins.print", side_effect=publish)) + state = m.BuildRun(Path("/inert-terminal-no-files"), 1000) + state.first = original + state.keeper, state.keeper_status, state.child_status = 42, 0, 0 + state.child = type("Child", (), {"pid": 43})() + state.child_attempted = True + state.gone = state.release = state.proof = True + state.end = 500 + cutpoint = state.facts() + state.finalize(None, None, True, {m.signal.SIGINT: None, m.signal.SIGTERM: None}, cutpoint) + self.assertTrue(state.cancelled, "a caught default INT must retain cancellation provenance") + if original: + self.assertEqual(state.first, original) + self.assertIn("CANCELLED", state.secondary) + elif stderr_interrupt: + self.assertEqual(state.first, "FACT_STDOUT") + self.assertIn("CANCELLED", state.secondary) + else: + self.assertEqual(state.first, "CANCELLED") + self.assertIn("FACT_STDERR" if stderr_interrupt else "FACT_STDOUT", state.secondary) + self.assertEqual((state.child_status, state.keeper_status), (0, 0)) + self.assertEqual(calls.count("handler"), 2) + self.assertTrue(all(item.closed for item in receipts)) + self.assertEqual(cutpoint["first_fault"], original) + self.assertFalse(cutpoint["cancelled"]) + if not stderr_interrupt: + last = packets[-1] + self.assertTrue(last["owner_result"]["cancelled"]) + self.assertEqual(last["owner_result"]["first_fault"], original or "CANCELLED") + self.assertTrue(last["handoff_complete"]) + self.assertFalse(last["mask_restoration_pending"]) + self.assertEqual(last["cutpoint"], cutpoint) + else: + # Both final sinks failed. The earlier pending snapshot is not a + # completed report; failure is retained in state, never upgraded. + self.assertFalse(packets[-1]["handoff_complete"]) + + def test_r26_final_stdout_interrupt_retains_cancelled_first_and_fallback(self): + self.terminal_interrupt_case() + + def test_r26_final_stdout_interrupt_preserves_original_and_cancelled_secondary(self): + self.terminal_interrupt_case(original="ORIGINAL_OPERATION") + + def test_r26_stdout_error_then_stderr_interrupt_keeps_both_failures(self): + self.terminal_interrupt_case(stderr_interrupt=True) + + def keeper_admission_case(self, cancellation): + import io + import json + from contextlib import ExitStack + from unittest.mock import patch + state_ref, handlers, packets, calls, files = [], {}, [], [], [] + class Receipt(io.StringIO): + def fileno(self): + return 99 + class Endpoint(Stream): + def __init__(self): + super().__init__() + self.closed = 0 + def close(self): + self.closed += 1 + parent, child_end = Endpoint(), Endpoint() + def receipt(_): + item = Receipt();files.append(item);return item + actual_build_run = m.BuildRun + def build_run(*args): + state = actual_build_run(*args);state_ref.append(state);return state + def install(signum, handler): + handlers[signum] = handler + return None + def limits(_): + if cancellation == "setup": + handlers[m.signal.SIGINT](None, None) + return (1024, 1024) + first_block, delivered_after_fork = True, False + def mask(how, _): + nonlocal first_block, delivered_after_fork + calls.append("block" if how == m.signal.SIG_BLOCK else "unblock") + if how == m.signal.SIG_BLOCK and first_block: + first_block = False + if cancellation == "before_fork": + handlers[m.signal.SIGINT](None, None) + elif (how == m.signal.SIG_SETMASK and cancellation == "after_fork" + and state_ref[0].keeper and not delivered_after_fork): + delivered_after_fork = True + handlers[m.signal.SIGINT](None, None) + return set() + def fork(): + calls.append("fork") + return 42 + def event(state, _): + state.checkpoint() + # The uncancelled admission control deliberately stops here so + # this test cannot reach a fake or real workload spawn. + raise m.Refused("CONTROL_AFTER_KEEPER") + def begin(state): + state.end = 500 + with ExitStack() as stack: + stack.enter_context(patch.dict(m.os.environ, {"KEITO_BOOTSTRAP_POLICY_CONFIRMED": "source-group-build-only"}, clear=True)) + stack.enter_context(patch.object(m, "BuildRun", side_effect=build_run)) + stack.enter_context(patch.object(m, "exclusive", side_effect=receipt)) + stack.enter_context(patch.object(m.os, "fsync")) + stack.enter_context(patch.object(m.socket, "socketpair", return_value=(parent, child_end))) + stack.enter_context(patch.object(m.os, "urandom", return_value=b"a" * 16)) + stack.enter_context(patch.object(m.resource, "getrlimit", side_effect=limits)) + stack.enter_context(patch.object(m.os, "getpgrp", return_value=99)) + fork_mock = stack.enter_context(patch.object(m.os, "fork", side_effect=fork)) + popen = stack.enter_context(patch.object(m.subprocess, "Popen", side_effect=AssertionError("no workload"))) + waited = stack.enter_context(patch.object(m.os, "waitpid", return_value=(42, 0))) + stack.enter_context(patch.object(m.time, "monotonic_ns", return_value=1)) + stack.enter_context(patch.object(m.time, "sleep", side_effect=AssertionError("no wait loop"))) + stack.enter_context(patch.object(m.signal, "signal", side_effect=install)) + stack.enter_context(patch.object(m.signal, "pthread_sigmask", side_effect=mask)) + stack.enter_context(patch.object(m.signal, "sigpending", return_value=set())) + stack.enter_context(patch.object(actual_build_run, "event", event)) + stack.enter_context(patch.object(actual_build_run, "begin", begin)) + stack.enter_context(patch.object(actual_build_run, "settle", lambda state: None)) + stack.enter_context(patch("builtins.print", side_effect=lambda value, **_: packets.append(json.loads(value)))) + self.assertFalse(m.run({"root": "/inert-admission-no-files", "seconds": 3})) + state = state_ref[0] + self.assertFalse(state.child_attempted) + popen.assert_not_called() + self.assertEqual((parent.closed, child_end.closed), (1, 1)) + self.assertTrue(all(item.closed for item in files)) + self.assertEqual(packets[-1]["owner_result"]["cancelled"], cancellation is not None) + if cancellation in ("setup", "before_fork"): + fork_mock.assert_not_called() + waited.assert_not_called() + self.assertEqual(state.first, "CANCELLED") + self.assertIsNone(state.keeper) + self.assertIsNone(state.keeper_status) + self.assertFalse(packets[-1]["owner_result"]["keeper_spawned"]) + else: + fork_mock.assert_called_once() + waited.assert_called_once_with(42, m.os.WNOHANG) + self.assertEqual((state.keeper, state.keeper_status), (42, 0)) + self.assertLess(calls.index("fork"), calls.index("unblock")) + self.assertEqual(state.first, "CANCELLED" if cancellation else "CONTROL_AFTER_KEEPER") + self.assertEqual(calls.count("block"), calls.count("unblock")) + self.assertNotIn("HANDOFF_UNMASK", state.secondary, "late-cancel control delivers only once") + + def test_r26_setup_cancellation_prevents_first_keeper_admission(self): + self.keeper_admission_case("setup") + + def test_r26_cancel_latched_at_mask_boundary_prevents_first_keeper_admission(self): + self.keeper_admission_case("before_fork") + + def test_r26_no_cancel_control_keeps_admitted_handle_until_wait(self): + self.keeper_admission_case(None) + + def test_r26_unblock_cancellation_keeps_already_admitted_handle_until_wait(self): + self.keeper_admission_case("after_fork") + + def test_r24_cancellation_checkpoint_refuses_admission_without_throwing_in_handler(self): + from unittest.mock import patch + state = object.__new__(m.BuildRun) + state.first, state.secondary, state.cancelled = None, [], False + state.channel = m.Channel(Stream([wire("READY")]), "a" * 32) + self.assertIsNone(state.cancel_signal(None, None)) + with patch.object(m.time, "monotonic_ns", return_value=1): + with self.assertRaisesRegex(m.Refused, "CANCELLED"): + state.wait_frame("READY", 1000) + self.assertEqual(state.first, "CANCELLED") + self.assertEqual(state.channel.stream.reads, 0) + + def test_r24_cutpoint_secondary_errors_are_not_mutated_by_late_observations(self): + state = object.__new__(m.BuildRun) + state.first, state.secondary, state.cancelled = "FIRST", [], False + state.keeper, state.child, state.keeper_status, state.child_status = 42, None, None, None + state.child_attempted = False + state.gone = state.release = state.proof = False + state.writer_shutdown_ok = False + state.channel, state.hard, state.end = None, 1000, 500 + before = state.facts() + state.fail("SECOND") + state.keeper_status = 0 + self.assertEqual(before["secondary_faults"], []) + self.assertIsNone(before["keeper_wait"]) + self.assertEqual(state.facts()["secondary_faults"], ["SECOND"]) + self.assertEqual(state.facts()["keeper_wait"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/support/test_source_qa_contract.py b/tests/support/test_source_qa_contract.py new file mode 100644 index 0000000..3a46567 --- /dev/null +++ b/tests/support/test_source_qa_contract.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +"""Bounded inert-only source QA contracts; never executes compiler/product/service.""" +from pathlib import Path +import json +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import unittest + +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import source_qa_manifest as inventory +from source_qa_children import Cancelled, LegacyDirectChildren as OwnedChildren +from source_qa_cargo import build_script_target + +BASE = None + + +class CargoBuildTargetTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="cargo-layout-", dir=BASE) + self.addCleanup(self.temp.cleanup) + self.profile = Path(self.temp.name) / "debug" + + def output(self, relative, target): + path = self.profile / "build" / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("cargo:rustc-env=KEITO_BUILD_TARGET=" + target + "\n") + + def test_legacy_build_script_layout(self): + self.output("keito-cli-123/output", "x86_64-unknown-linux-gnu") + self.assertEqual(build_script_target(self.profile), "x86_64-unknown-linux-gnu") + + def test_nested_build_script_layout(self): + self.output("keito-cli/123/run/stdout", "x86_64-unknown-linux-gnu") + self.assertEqual(build_script_target(self.profile), "x86_64-unknown-linux-gnu") + + def test_same_target_across_layouts_is_consistent(self): + self.output("keito-cli-123/output", "aarch64-apple-darwin") + self.output("keito-cli/456/run/stdout", "aarch64-apple-darwin") + self.assertEqual(build_script_target(self.profile), "aarch64-apple-darwin") + + def test_conflicting_targets_across_layouts_are_refused(self): + self.output("keito-cli-123/output", "aarch64-apple-darwin") + self.output("keito-cli/456/run/stdout", "x86_64-unknown-linux-gnu") + with self.assertRaisesRegex(RuntimeError, "exactly one source-build target"): + build_script_target(self.profile) + + def test_no_matching_output_is_refused(self): + with self.assertRaisesRegex(RuntimeError, "exactly one source-build target"): + build_script_target(self.profile) + + def test_dependency_output_is_not_target_authority(self): + self.output("dependency/123/run/stdout", "x86_64-unknown-linux-gnu") + with self.assertRaisesRegex(RuntimeError, "exactly one source-build target"): + build_script_target(self.profile) + + +class RetainedDirectory: + # Evidence, including the first failing case, must survive assertions. + def __init__(self, prefix, dir): + self.name = tempfile.mkdtemp(prefix=prefix, dir=dir) + + def cleanup(self): + pass + + +PYTHON = str(Path(sys.executable).resolve(strict=True)) +LEAF = """import json,os,signal,sys,time +from pathlib import Path +mode,marker=sys.argv[1],Path(sys.argv[2]) +if mode=='ignore': signal.signal(signal.SIGTERM,signal.SIG_IGN) +with marker.open('x') as f: json.dump({'pid':os.getpid(),'started_monotonic_ns':time.monotonic_ns(),'term_blocked':signal.SIGTERM in signal.pthread_sigmask(signal.SIG_BLOCK,set())},f) +end=time.monotonic()+8 +while time.monotonic()" + parent = inventory.canonical_root(sys.argv[1], private=True) + BASE = parent / "source-qa-contract-inert" + BASE.mkdir(mode=0o700) + unittest.main(argv=[sys.argv[0]], verbosity=2) diff --git a/tests/support/test_source_qa_protocol.py b/tests/support/test_source_qa_protocol.py new file mode 100644 index 0000000..26c9b8e --- /dev/null +++ b/tests/support/test_source_qa_protocol.py @@ -0,0 +1,495 @@ +#!/usr/bin/env python3 +"""Finite socket-only ownership regressions. No subprocesses or signals.""" +from pathlib import Path +import os +import json +import socket +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from source_qa_protocol import (Endpoint, ProtocolError, SourceOwner, Budget, + MAX_FRAME, MAX_PENDING, MAX_READS, MAX_PARSE, + MAX_REGISTRATIONS, MAX_FRAMES, MAX_WIRE) + +NONCE = "a" * 32 +PEER = 12345 + + +class ProtocolTests(unittest.TestCase): + def test_review_real_cancel_wire_only_moves_to_strictly_earlier_ends(self): + left, right = socket.socketpair() + self.addCleanup(left.close); self.addCleanup(right.close) + sender = Endpoint(left, NONCE, os.getpid()) + receiver = Endpoint(right, NONCE, os.getpid()) + for end, expected in [(1000,1000),(500,500),(1,1),(5000,1),(1,1)]: + sender.cancel_tighter(end) + receiver.receive(parent=True) + self.assertEqual(receiver.cancel_deadline_ns, expected) + self.assertFalse(receiver.settled) + + def test_review_failed_control_writer_stays_unknown_until_actual_read_zero(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "FAILED") + with self.assertRaises(ProtocolError): endpoint.receive() + self.assertFalse(endpoint.eof) + self.assertFalse(endpoint.drain_failed()) + writer.shutdown(socket.SHUT_WR) + self.assertTrue(endpoint.drain_failed()) + self.assertEqual(endpoint.first_fault, "PEER_FAILED") + self.assertFalse(endpoint.settled) + def pair(self): + reader, writer = socket.socketpair() + self.addCleanup(reader.close) + self.addCleanup(writer.close) + return Endpoint(reader, NONCE, PEER), writer + + def frame(self, writer, tag, *fields, nonce=NONCE): + values = fields or (PEER,) + writer.sendall(("|".join((nonce, tag, *(str(v) for v in values))) + "\n").encode()) + + def live(self, endpoint, writer): + self.frame(writer, "LIVE") + endpoint.receive() + + def test_clean_terminal_requires_closed_writer_control(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "REGISTER", PEER, 12346, "b" * 32, 1) + self.frame(writer, "WAITED", PEER, 12346, "b" * 32, 0) + self.frame(writer, "SETTLED") + writer.shutdown(socket.SHUT_WR) + endpoint.receive() + self.assertTrue(endpoint.settled) + + def test_bad_nonce_cannot_be_rehabilitated_by_later_settlement(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "LIVE", nonce="b" * 32) + with self.assertRaises(ProtocolError) as first: + endpoint.receive() + self.frame(writer, "SETTLED") + writer.shutdown(socket.SHUT_WR) + with self.assertRaises(ProtocolError) as later: + endpoint.receive() + self.assertEqual(str(first.exception), str(later.exception)) + self.assertFalse(endpoint.settled) + + def test_unmatched_wait_cannot_be_rehabilitated(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "WAITED", PEER, 12346, "b" * 32, 0) + with self.assertRaises(ProtocolError) as first: + endpoint.receive() + self.frame(writer, "SETTLED") + writer.shutdown(socket.SHUT_WR) + with self.assertRaises(ProtocolError) as later: + endpoint.receive() + self.assertEqual(str(first.exception), str(later.exception)) + self.assertFalse(endpoint.settled) + + def test_terminal_without_eof_is_not_settled(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "SETTLED") + endpoint.receive() + self.assertFalse(endpoint.settled) + writer.shutdown(socket.SHUT_WR) + endpoint.receive() + self.assertTrue(endpoint.settled) + + def test_partial_trailing_frame_poisons_terminal(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "SETTLED") + endpoint.receive() + writer.sendall(b"trailing") + writer.shutdown(socket.SHUT_WR) + with self.assertRaises(ProtocolError): + endpoint.receive() + self.assertFalse(endpoint.settled) + + def test_registration_before_live_is_refused(self): + endpoint, writer = self.pair() + self.frame(writer, "REGISTER", PEER, 12346, "b" * 32, 1) + with self.assertRaises(ProtocolError): + endpoint.receive() + + def test_unregistered_owner_edge_is_refused(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "REGISTER", 9999, 12346, "b" * 32, 1) + with self.assertRaises(ProtocolError): + endpoint.receive() + + def test_truncated_eof_is_refused(self): + endpoint, writer = self.pair() + writer.sendall(b"partial") + writer.shutdown(socket.SHUT_WR) + with self.assertRaises(ProtocolError): + endpoint.receive() + + def test_oversized_complete_frame_is_refused(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "REGISTER", PEER, 12346, "b" * 32, "9" * 300) + with self.assertRaises(ProtocolError): + endpoint.receive() + + def test_source_owner_retains_fault_and_emits_failed_after_cleanup(self): + reader, writer = socket.socketpair() + self.addCleanup(reader.close) + self.addCleanup(writer.close) + owner = SourceOwner() + owner.parent = Endpoint(reader, NONCE, os.getpid()) + owner.parent.send("LIVE") + self.frame(writer, "CANCEL", os.getpid(), nonce="b" * 32) + with self.assertRaises(ProtocolError) as first: + owner.check() + owner.__exit__(ProtocolError, first.exception, None) + writer.settimeout(1) + trace = bytearray() + while True: + block = writer.recv(1024) + if not block: + break + trace.extend(block) + self.assertIn(b"|FAILED|", trace) + self.assertNotIn(b"|SETTLED|", trace) + self.assertTrue(owner.unsettled) + + def test_all_control_faults_remain_sticky(self): + for tag, fields in [("LIVE", (PEER,)), ("FAILED", (PEER,)), + ("LIVE", (PEER + 1,)), ("unknown", (PEER,))]: + with self.subTest(tag=tag, fields=fields): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, tag, *fields) + with self.assertRaises(ProtocolError) as first: + endpoint.receive() + self.frame(writer, "SETTLED") + writer.shutdown(socket.SHUT_WR) + with self.assertRaises(ProtocolError) as later: + endpoint.receive() + self.assertEqual(str(first.exception), str(later.exception)) + self.assertFalse(endpoint.settled) + + def test_post_terminal_full_frames_never_yield_proof(self): + for trailing in ["LIVE", "SETTLED", "REGISTER", "WAITED"]: + with self.subTest(trailing=trailing): + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "SETTLED") + self.frame(writer, trailing) + writer.shutdown(socket.SHUT_WR) + with self.assertRaises(ProtocolError): + endpoint.receive() + self.assertFalse(endpoint.settled) + + def test_parent_eof_cancels_before_live(self): + endpoint, writer = self.pair() + writer.shutdown(socket.SHUT_WR) + self.assertTrue(endpoint.receive(parent=True)) + self.assertTrue(endpoint.cancelled) + self.assertFalse(endpoint.settled) + + def test_cancel_deadline_never_extends(self): + endpoint, writer = self.pair() + for deadline in [100, 200, 50]: + self.frame(writer, "CANCEL", PEER, deadline) + self.assertTrue(endpoint.receive(parent=True)) + self.assertEqual(endpoint.cancel_deadline_ns, 50) + + def test_wrong_role_and_malformed_integer_poison(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + with self.assertRaises(ProtocolError): + endpoint.receive(parent=True) + endpoint, writer = self.pair() + self.live(endpoint, writer) + self.frame(writer, "REGISTER", "--1", 12346, "b" * 32, 1) + with self.assertRaises(ProtocolError): + endpoint.receive() + self.assertIsNotNone(endpoint.first_fault) + + def test_total_budgets_exact_cap_and_cap_plus_one(self): + for kind, maximum in [("wire", MAX_WIRE), ("frames", MAX_FRAMES), + ("registrations", MAX_REGISTRATIONS)]: + with self.subTest(kind=kind): + budget = Budget() + budget.charge(kind, maximum, maximum) + self.assertEqual(getattr(budget, kind), maximum) + with self.assertRaises(ProtocolError) as first: + budget.charge(kind, 1, maximum) + with self.assertRaises(ProtocolError) as later: + budget.charge(kind, 0, maximum) + self.assertEqual(str(first.exception), str(later.exception)) + + def test_shared_budget_counts_send_receive_and_forwarding(self): + budget = Budget() + left, right = socket.socketpair() + self.addCleanup(left.close) + self.addCleanup(right.close) + sender = Endpoint(left, NONCE, budget=budget) + receiver = Endpoint(right, NONCE, os.getpid(), budget=budget) + sender.send("LIVE") + sent = budget.wire + receiver.receive() + self.assertEqual(budget.wire, sent * 2) + self.assertEqual(budget.frames, 2) + sender.metadata("REGISTER|{}|12346|{}|1".format(os.getpid(), "b" * 32)) + receiver.receive() + self.assertEqual(budget.registrations, 2) + self.assertEqual(budget.frames, 4) + with self.assertRaises(ProtocolError): + sender.send("SETTLED") + + def test_send_failure_poison_is_visible_at_owner(self): + class ShortSocket: + family, type = socket.AF_UNIX, socket.SOCK_STREAM + def setblocking(self, value): pass + def set_inheritable(self, value): pass + def send(self, frame): return len(frame) - 1 + owner = SourceOwner() + endpoint = Endpoint(ShortSocket(), NONCE, on_fault=owner.fail) + with self.assertRaises(ProtocolError): + endpoint.send("LIVE") + self.assertTrue(owner.admission_closed) + self.assertTrue(owner.unsettled) + with self.assertRaises(ProtocolError) as later: + owner.check() + self.assertEqual(str(later.exception), "SHORT_WRITE") + + def test_poll_read_attempt_and_parse_work_are_bounded(self): + class BurstSocket: + family, type = socket.AF_UNIX, socket.SOCK_STREAM + def __init__(self, interrupted=False): + self.calls, self.interrupted = 0, interrupted + def setblocking(self, value): pass + def set_inheritable(self, value): pass + def recv(self, size): + self.calls += 1 + if self.interrupted: raise InterruptedError() + return (NONCE + "|CANCEL|12345|100\n").encode() + for interrupted in [False, True]: + channel = BurstSocket(interrupted) + endpoint = Endpoint(channel, NONCE, PEER) + endpoint.receive(parent=True) + self.assertEqual(channel.calls, MAX_READS) + # A finite prebuffer controls parse work independently of read readiness. + channel = BurstSocket() + endpoint = Endpoint(channel, NONCE, PEER) + frame = (NONCE + "|CANCEL|12345|100\n").encode() + endpoint.pending.extend(frame * 20) + endpoint.receive(parent=True) + self.assertLessEqual(endpoint.budget.frames, MAX_PARSE) + self.assertLessEqual(len(endpoint.pending), MAX_PENDING) + self.assertLessEqual(channel.calls, MAX_READS) + + def test_frame_limit_includes_newline_and_errors_hide_input(self): + endpoint, writer = self.pair() + self.live(endpoint, writer) + writer.sendall(b"PRIVATE_CANARY" + b"x" * MAX_FRAME) + with self.assertRaises(ProtocolError) as error: + endpoint.receive() + self.assertNotIn("PRIVATE_CANARY", str(error.exception)) + self.assertEqual(str(error.exception), "FRAME_LIMIT") + + def test_owner_broadcasts_cleanup_before_any_poll(self): + owner = SourceOwner() + observed = [] + class Manager: + def __init__(self, name): self.name = name + def begin_cleanup(self, deadline): observed.append(("begin", self.name, deadline)) + def poll_cleanup(self, deadline): observed.append(("poll", self.name, deadline)); return True + owner.managers = [Manager("a"), Manager("b")] + owner.finish_managers() + self.assertEqual([(kind, name) for kind, name, _ in observed], + [("begin", "a"), ("begin", "b"), ("poll", "a"), ("poll", "b")]) + self.assertEqual(len({deadline for _, _, deadline in observed}), 1) + previous = owner.deadline_ns + owner.finish_managers() + self.assertEqual(owner.deadline_ns, previous) + with self.assertRaises(ProtocolError): + owner.check() + + def test_cleanup_fault_cannot_replace_original_exception(self): + owner = SourceOwner() + class Manager: + def begin_cleanup(self, deadline): raise RuntimeError("SECONDARY") + owner.managers = [Manager()] + original = ProtocolError("ORIGINAL") + owner.__exit__(ProtocolError, original, None) + self.assertEqual(owner.first_fault, "ORIGINAL") + self.assertTrue(owner.unsettled) + + def test_constructor_refusal_and_closed_manager_admission_poison_owner(self): + owner = SourceOwner() + reader, writer = socket.socketpair() + self.addCleanup(reader.close) + self.addCleanup(writer.close) + with self.assertRaises(ProtocolError): + owner.endpoint(reader, "invalid", PEER) + self.assertEqual(owner.first_fault, "NONCE_SCHEMA") + with self.assertRaises(ProtocolError): + owner.register_manager(object()) + self.assertEqual(owner.managers, []) + self.assertTrue(owner.admission_closed) + + def test_shared_wire_contract_vectors(self): + corpus = json.loads((Path(__file__).resolve().parents[1] / "fixtures/source_qa_protocol_vectors.json").read_text()) + self.assertEqual(corpus["schema"], 1) + self.assertEqual(len(corpus["cases"]), 16) + for case in corpus["cases"]: + with self.subTest(case=case["name"]): + endpoint, writer = self.pair() + fault = False + for chunk in case["chunks"]: + writer.sendall(chunk.encode("ascii")) + try: + endpoint.receive(parent=case["parent"]) + except ProtocolError: + fault = True + if case["close_writer"]: + writer.shutdown(socket.SHUT_WR) + try: + endpoint.receive(parent=case["parent"]) + except ProtocolError: + fault = True + expected = case["expected"] + self.assertEqual(fault, expected == "fault") + self.assertEqual(endpoint.settled, expected == "clean") + if expected == "cancel": + self.assertTrue(endpoint.cancelled) + + def test_root_forward_validates_unknown_and_impossible_metadata(self): + for event in ["unknown", "UNKNOWN|1|2|" + "b" * 32 + "|0", + "REGISTER|9999|12346|" + "b" * 32 + "|1", + "REGISTER|{}|12346|{}|1\nPRIVATE_CANARY".format(os.getpid(), "b" * 32)]: + with self.subTest(event=event.split("|", 1)[0]): + owner = SourceOwner() + with self.assertRaises(ProtocolError) as error: + owner.forward([event]) + self.assertTrue(owner.unsettled) + self.assertNotIn("PRIVATE_CANARY", str(error.exception)) + + def test_root_forward_cannot_finish_with_an_unmatched_registration(self): + owner = SourceOwner() + owner.forward(["REGISTER|{}|12346|{}|1".format(os.getpid(), "b" * 32)]) + with self.assertRaises(ProtocolError): + owner.__exit__(None, None, None) + self.assertTrue(owner.unsettled) + + def test_valid_root_forward_closes_ledger_before_finish(self): + owner = SourceOwner() + identity = "{}|12346|{}".format(os.getpid(), "b" * 32) + owner.forward(["REGISTER|" + identity + "|1", "WAITED|" + identity + "|0"]) + self.assertEqual(owner.budget.registrations, 1) + self.assertEqual(owner.budget.frames, 2) + owner.__exit__(None, None, None) + self.assertFalse(owner.unsettled) + + def test_parent_and_root_forwarding_both_refuse_unmatched_wait(self): + for has_parent in [False, True]: + owner = SourceOwner() + if has_parent: + reader, writer = socket.socketpair() + self.addCleanup(reader.close) + self.addCleanup(writer.close) + owner.parent = owner.endpoint(reader, NONCE) + owner.parent.send("LIVE") + with self.assertRaises(ProtocolError): + owner.forward(["WAITED|{}|12346|{}|0".format(os.getpid(), "b" * 32)]) + self.assertTrue(owner.unsettled) + + def test_failed_terminal_shutdown_error_is_sticky_safe_protocol_error(self): + class ShutdownFault: + family, type = socket.AF_UNIX, socket.SOCK_STREAM + def setblocking(self, value): pass + def set_inheritable(self, value): pass + def send(self, frame): return len(frame) + def shutdown(self, how): raise OSError("PRIVATE_CANARY") + owner = SourceOwner() + endpoint = owner.endpoint(ShutdownFault(), NONCE) + with self.assertRaises(ProtocolError) as error: + endpoint.send("FAILED") + self.assertEqual(str(error.exception), "SHUTDOWN_FAILED") + self.assertTrue(owner.unsettled) + self.assertNotIn("PRIVATE_CANARY", owner.first_fault) + + def test_late_cleanup_true_is_not_accepted_as_timely_proof(self): + owner = SourceOwner() + observed = [] + class Manager: + def begin_cleanup(self, deadline): observed.append("begin") + def poll_cleanup(self, deadline): observed.append("poll"); return True + owner.managers = [Manager()] + owner.deadline_ns = 1 + owner.finish_managers() + self.assertTrue(owner.unsettled) + self.assertEqual(observed, ["begin"]) + + def test_accepted_manager_proof_is_not_repolled_after_deadline(self): + owner = SourceOwner() + observed = [] + class Manager: + def begin_cleanup(self, deadline): observed.append("begin") + def poll_cleanup(self, deadline): observed.append("poll"); return True + owner.managers = [Manager()] + owner.finish_managers() + self.assertFalse(owner.unsettled) + owner.deadline_ns = 1 + owner.finish_managers() + # AO-05: accepted manager history is cached, but the containing owner + # cannot emit a fresh clean terminal after its inherited end. + self.assertTrue(owner.unsettled) + self.assertEqual(observed, ["begin", "poll"]) + + def test_owner_fault_yields_failed_not_clean_at_remote_peer(self): + owner = SourceOwner() + up, remote = socket.socketpair() + down, sender = socket.socketpair() + for value in [up, remote, down, sender]: + self.addCleanup(value.close) + upstream = owner.endpoint(up, NONCE) + downstream = owner.endpoint(down, NONCE, PEER) + upstream.send("LIVE") + sender.sendall(("b" * 32 + "|LIVE|12345\n").encode()) + with self.assertRaises(ProtocolError) as first: + downstream.receive() + with self.assertRaises(ProtocolError): + upstream.send("SETTLED") + upstream.send("FAILED") + remote_endpoint = Endpoint(remote, NONCE, os.getpid()) + with self.assertRaises(ProtocolError) as remote_error: + remote_endpoint.receive() + self.assertEqual(str(remote_error.exception), "PEER_FAILED") + self.assertFalse(remote_endpoint.settled) + self.assertEqual(owner.first_fault, str(first.exception)) + + def test_manager_true_returning_after_deadline_is_rejected(self): + from unittest.mock import patch + owner = SourceOwner() + owner.deadline_ns = 100 + class Manager: + def begin_cleanup(self, deadline): pass + def poll_cleanup(self, deadline): return True + manager = Manager() + owner.managers = [manager] + with patch("source_qa_protocol.monotonic_ns", side_effect=[1, 2, 3, 101, 102]): + owner.finish_managers() + self.assertTrue(owner.unsettled) + self.assertEqual(owner.first_fault, "MANAGER_CLEANUP_DEADLINE") + self.assertNotIn(id(manager), owner._finished_managers) + + def test_finished_owner_refuses_further_forwarding(self): + owner = SourceOwner() + owner.__exit__(None, None, None) + with self.assertRaises(ProtocolError): + owner.forward(["REGISTER|{}|12346|{}|1".format(os.getpid(), "b" * 32)]) + self.assertEqual(owner.first_fault, "OWNER_ALREADY_FINISHED") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/support/test_source_qa_protocol_review_regressions.py b/tests/support/test_source_qa_protocol_review_regressions.py new file mode 100644 index 0000000..a121832 --- /dev/null +++ b/tests/support/test_source_qa_protocol_review_regressions.py @@ -0,0 +1,88 @@ +"""R17 independently derived finite cases, promoted unchanged to regression CI. + +Only Unix socketpairs and metadata: no child actors, signals, threads, environment +or profile inspection. These assertions express the requested component contract. +The original reviewer source and first RED are retained in developer evidence. +""" +import os +import socket +import sys +import unittest + +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from source_qa_protocol import Endpoint, SourceOwner, ProtocolError, MAX_REGISTRATIONS + +NONCE = "a" * 32 +PEER = 12345 + + +class IndependentlyDerivedCases(unittest.TestCase): + def sockets(self): + left, right = socket.socketpair() + self.addCleanup(left.close) + self.addCleanup(right.close) + return left, right + + def test_owner_fault_blocks_other_endpoint_clean_terminal(self): + owner = SourceOwner() + up, upstream_peer = self.sockets() + upstream = owner.endpoint(up, NONCE) + upstream.send("LIVE") + down, downstream_peer = self.sockets() + downstream = owner.endpoint(down, NONCE, PEER) + downstream_peer.sendall((("b" * 32) + "|LIVE|12345\n").encode("ascii")) + with self.assertRaises(ProtocolError) as first: + downstream.receive() + self.assertEqual(owner.first_fault, str(first.exception)) + self.assertTrue(owner.unsettled) + # At b2ac4ae2 this does not raise; it writes SETTLED and shuts down. + with self.assertRaises(ProtocolError): + upstream.send("SETTLED") + + def test_root_forward_refuses_unmatched_wait(self): + owner = SourceOwner() + event = "WAITED|{}|12346|{}|0".format(os.getpid(), "b" * 32) + with self.assertRaises(ProtocolError): + owner.forward([event]) + self.assertTrue(owner.unsettled) + self.assertTrue(owner.admission_closed) + + def test_root_forward_registration_cap_is_operation_wide(self): + owner = SourceOwner() + own_pid = os.getpid() + # 8194 frames and less than 1 MiB: only the registration cap is crossed. + with self.assertRaises(ProtocolError) as fault: + for index in range(MAX_REGISTRATIONS + 1): + child = 100000 + index + if child == own_pid: + child += 50000 + suffix = "{}|{}|{}".format(own_pid, child, "b" * 32) + owner.forward(["REGISTER|" + suffix + "|1"]) + owner.forward(["WAITED|" + suffix + "|0"]) + self.assertEqual(str(fault.exception), "LIMIT_REGISTRATIONS") + self.assertTrue(owner.unsettled) + + def test_clean_terminal_every_byte_split_requires_eof(self): + terminal = (NONCE + "|SETTLED|12345\n").encode("ascii") + for split in range(1, len(terminal)): + with self.subTest(split=split): + left, right = self.sockets() + endpoint = Endpoint(left, NONCE, PEER) + right.sendall((NONCE + "|LIVE|12345\n").encode("ascii")) + endpoint.receive() + right.sendall(terminal[:split]) + endpoint.receive() + self.assertFalse(endpoint.settled) + right.sendall(terminal[split:]) + endpoint.receive() + self.assertFalse(endpoint.settled) + right.shutdown(socket.SHUT_WR) + endpoint.receive() + self.assertTrue(endpoint.settled) + left.close() + right.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/table_output_controls.rs b/tests/table_output_controls.rs new file mode 100644 index 0000000..3d36b76 --- /dev/null +++ b/tests/table_output_controls.rs @@ -0,0 +1,15 @@ +//! Human-readable output compatibility controls captured before tabled migration. +#[test] +fn rounded_tables_preserve_headers_values_spacing_and_empty_output() { + let cases: serde_json::Value = + serde_json::from_str(include_str!("fixtures/table-output-controls.json")).unwrap(); + for case in cases.as_array().unwrap() { + let actual = keito_cli::output::table::to_table(case["items"].as_array().unwrap()); + assert_eq!( + actual, + case["expected"].as_str().unwrap(), + "{}", + case["name"] + ); + } +} diff --git a/tests/unit/capture_usage_factory.rs b/tests/unit/capture_usage_factory.rs new file mode 100644 index 0000000..33ba0cf --- /dev/null +++ b/tests/unit/capture_usage_factory.rs @@ -0,0 +1,478 @@ +//! Negative normal-factory admission. No synthetic positive approval or actual +//! process/harness/provider is constructed by this suite. +use super::*; +use crate::capture_usage_consent::ConsentPolicy; +use crate::capture_usage_test_io::Denied; + +const SESSION: &str = "12345678-1234-4234-8234-123456789abc"; +struct Fixture { + _temp: tempfile::TempDir, + store: Store, + repository: Repository, + binding: Binding, + source: &'static str, + version: &'static str, +} +impl Fixture { + fn new(source: &'static str) -> Self { + let temp = tempfile::tempdir().unwrap(); + let mut store = Store::open(&temp.path().join("capture")).unwrap(); + let repository = Repository { + key: hash("repo"), + remote_hash: hash("remote"), + hint_hash: hash("hint"), + linked_without_hint: false, + disabled: false, + }; + let binding = store + .approve(Binding { + repository_key: repository.key.clone(), + remote_hash: repository.remote_hash.clone(), + hint_hash: repository.hint_hash.clone(), + id: String::new(), + version: 0, + workspace_id: "co_synthetic".into(), + owner_id: "owner_synthetic".into(), + origin_hash: hash("origin"), + project_id: "project_synthetic".into(), + task_id: "task_synthetic".into(), + agents: vec![source.into()], + paused: false, + revoked: false, + }) + .unwrap(); + Self { + _temp: temp, + store, + repository, + binding, + source, + version: if source == "codex" { + "0.167.0" + } else { + "2.1.319" + }, + } + } + fn consent(&self) { + let policy = ConsentPolicy { + policy_version: 1, + binding_id: self.binding.id.clone(), + binding_version: self.binding.version, + source_namespace: self.source.into(), + profile_id: "a".repeat(64), + profile_digest: "b".repeat(64), + epoch: 1, + enabled: true, + unavailable_reason: None, + }; + self.store + .connection + .execute( + "INSERT INTO usage_consents(binding_id,namespace,data) VALUES(?1,?2,?3)", + params![ + self.binding.id, + self.source, + serde_json::to_string(&policy).unwrap() + ], + ) + .unwrap(); + } + fn event(&mut self, event: CaptureEvent, n: i64, hook: bool) { + let clock = Clock { + wall: 1_794_067_200 + n, + monotonic: 1000 + n, + boot: "synthetic".into(), + }; + let signal = Signal { + source: self.source, + resumed: false, + source_id: SESSION, + turn_id: Some("turn_synthetic"), + version: self.version, + event, + clock: &clock, + }; + if hook { + self.store + .event_hook( + &self.repository, + signal, + Some(Path::new("/inert/never-open-source")), + None, + ) + .unwrap(); + } else { + self.store.event(&self.repository, signal).unwrap(); + } + } + fn assert_time_only(&self) { + let body: String = self + .store + .connection + .query_row("SELECT body FROM outbox", [], |row| row.get(0)) + .unwrap(); + let body: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(body["segments"][0]["duration_seconds"], 4); + assert_eq!(body["usage"]["status"], "UNAVAILABLE"); + assert!(body["usage"]["records"] + .as_array() + .is_none_or(Vec::is_empty)); + assert!(!body.to_string().contains("/inert/")); + } +} +#[test] +fn default_and_explicitly_disabled_never_consult_numeric_io() { + for source in ["codex", "claude-code"] { + for disabled in [false, true] { + let mut f = Fixture::new(source); + if disabled { + f.store.disable_numeric(&f.repository, source).unwrap(); + } + let denied = Denied::arm(); + f.event(CaptureEvent::Prompt, 0, true); + f.event(CaptureEvent::Stop, 4, true); + assert_eq!(denied.counts(), [0; 3]); + f.assert_time_only(); + } + } +} +#[test] +fn enabled_without_live_guard_keeps_timing_and_never_loads_profile_or_source() { + for source in ["codex", "claude-code"] { + let mut f = Fixture::new(source); + f.consent(); + let denied = Denied::arm(); + f.event(CaptureEvent::Prompt, 0, true); + assert_eq!( + f.store.numeric_status(&f.repository, source).unwrap()["reason"], + "LIVE_GUARD_REQUIRED" + ); + f.event(CaptureEvent::Stop, 4, true); + assert_eq!( + f.store.numeric_status(&f.repository, source).unwrap()["reason"], + "MISSING_QUALIFIED_PROMPT" + ); + assert_eq!(denied.counts(), [0; 3]); + f.assert_time_only(); + } +} +#[test] +fn terminal_cannot_repair_an_unqualified_prompt() { + for source in ["codex", "claude-code"] { + let mut f = Fixture::new(source); + f.event(CaptureEvent::Prompt, 0, false); + f.consent(); + let denied = Denied::arm(); + f.event(CaptureEvent::Stop, 4, true); + assert_eq!( + f.store.numeric_status(&f.repository, source).unwrap()["reason"], + "MISSING_QUALIFIED_PROMPT" + ); + assert_eq!(denied.counts(), [0; 3]); + f.assert_time_only(); + } +} +#[test] +fn committed_revoke_before_hook_wins_without_any_functional_read() { + for source in ["codex", "claude-code"] { + let mut f = Fixture::new(source); + f.consent(); + f.store.disable_numeric(&f.repository, source).unwrap(); + let denied = Denied::arm(); + f.event(CaptureEvent::Prompt, 0, true); + f.event(CaptureEvent::Stop, 4, true); + assert_eq!( + f.store.numeric_status(&f.repository, source).unwrap()["enabled"], + false + ); + assert_eq!(denied.counts(), [0; 3]); + f.assert_time_only(); + } +} +#[test] +fn malformed_or_binding_stale_consent_cannot_trigger_functional_reads() { + for source in ["codex", "claude-code"] { + for malformed in [false, true] { + let mut f = Fixture::new(source); + f.consent(); + f.store + .connection + .execute( + "UPDATE usage_consents SET data=?1", + [if malformed { + "{malformed".to_owned() + } else { + let mut policy = + Store::numeric_policy_in(&f.store.connection, &f.binding, source) + .unwrap() + .unwrap(); + policy.binding_version += 1; + serde_json::to_string(&policy).unwrap() + }], + ) + .unwrap(); + let denied = Denied::arm(); + f.event(CaptureEvent::Prompt, 0, true); + f.event(CaptureEvent::Stop, 4, true); + assert_eq!(denied.counts(), [0; 3]); + f.assert_time_only(); + } + } +} + +fn record(id: &str) -> crate::capture_usage_ledger::UsageRecord { + crate::capture_usage_ledger::UsageRecord { + source_adapter: "CLAUDE_JSONL_2_1_319_V1".into(), + source_record_id: id.into(), + source_turn_id: None, + model: None, + model_provenance: "UNKNOWN".into(), + counter_semantics: "REQUEST_DELTA".into(), + input_basis: "CLAUDE_UNCACHED_INPUT".into(), + input_tokens: Some(5), + cached_input_tokens: None, + cache_write_input_tokens: None, + output_tokens: Some(2), + reasoning_output_tokens: None, + } +} +fn frozen_fixture() -> (Fixture, Session, String, String) { + let mut f = Fixture::new("claude-code"); + f.consent(); + f.event(CaptureEvent::Prompt, 0, false); + f.event(CaptureEvent::Stop, 4, false); + let raw: String = f + .store + .connection + .query_row("SELECT data FROM sessions", [], |row| row.get(0)) + .unwrap(); + let mut session: Session = serde_json::from_str(&raw).unwrap(); + session.usage_ledger.records.push(record("request_frozen")); + session.usage_ledger.record_revisions.push(1); + session.usage_ledger.queued = 1; + let mut body = session.payload(session.segments.clone(), 1).unwrap(); + body.usage = session.usage_ledger.payload(0, 1); + let frozen = serde_json::to_string(&body).unwrap(); + let digest = hash(&frozen); + f.store + .connection + .execute( + "UPDATE outbox SET body=?1,payload_hash=?2", + params![frozen, digest], + ) + .unwrap(); + f.store + .connection + .execute( + "UPDATE sessions SET data=?1", + [serde_json::to_string(&session).unwrap()], + ) + .unwrap(); + let start = Clock { + wall: 1_794_067_206, + monotonic: 1006, + boot: "synthetic".into(), + }; + session.active = Some(ActiveTurn { + key: "turn_second".into(), + clock: Some(start.clone()), + part: 0, + }); + let end = Clock { + wall: start.wall + 4, + monotonic: start.monotonic + 4, + boot: start.boot, + }; + session.close(&end, true).unwrap(); + (f, session, frozen, digest) +} +#[test] +fn late_source_failure_rolls_back_new_numeric_writes_but_preserves_time_and_frozen_evidence() { + // Component-only negative: no runtime/normal approval constructor is added. + // Genuine guarded normal-route acceptance is the separately retained pair QA. + use crate::capture_usage_test_io::AfterWrite; + for replace in [false, true] { + let (mut f, time_only, frozen, digest) = frozen_fixture(); + let home = f._temp.path().canonicalize().unwrap().join("home"); + let path = home.join(format!(".claude/projects/owned/{SESSION}.jsonl")); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, b"").unwrap(); + let approved = + ApprovedActiveSession::new(Harness::ClaudeCode, "2.1.319", &home, &path, SESSION) + .unwrap(); + let (_, lease) = crate::capture_usage::read_request_ids_leased(&approved).unwrap(); + let policy = Store::numeric_policy_in(&f.store.connection, &f.binding, f.source) + .unwrap() + .unwrap(); + let mut factory = NormalFactory { + policy: Some(policy), + runtime: None, + approved: None, + profile: None, + origin: None, + source_lease: Some(lease), + reason: Some("OBSERVED_REQUEST_RECORDS"), + invalidate: false, + }; + let mut candidate = time_only.clone(); + candidate + .usage_ledger + .records + .push(record("request_uncertain")); + candidate.usage_ledger.record_revisions.push(0); + let observed = std::rc::Rc::new(std::cell::Cell::new(false)); + let callback_observed = observed.clone(); + let _fault = AfterWrite::arm(move |connection| { + let written: String = connection + .query_row("SELECT body FROM outbox WHERE revision=2", [], |row| { + row.get(0) + }) + .unwrap(); + let written: serde_json::Value = serde_json::from_str(&written).unwrap(); + assert_eq!(written["usage"]["status"], "PARTIAL"); + assert_eq!( + written["usage"]["records"][0]["source_record_id"], + "request_uncertain" + ); + callback_observed.set(true); + if replace { + fs::rename(&path, path.with_extension("previous")).unwrap(); + } + fs::write(&path, b"PRIVATE_SOURCE_CHANGED_AFTER_QUEUE").unwrap(); + }); + let tx = f.store.transaction().unwrap(); + Store::finalize_normal_event( + &tx, + &mut candidate, + Some(&mut factory), + EventFinalization { + id: &time_only.id, + binding: &f.binding, + source_id: SESSION, + was_refused: false, + time_only: Some(&time_only), + }, + ) + .unwrap(); + tx.commit().unwrap(); + assert!(observed.get()); + let prior: (String, String) = f + .store + .connection + .query_row( + "SELECT body,payload_hash FROM outbox WHERE revision=1", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(prior, (frozen, digest)); + let new: String = f + .store + .connection + .query_row("SELECT body FROM outbox WHERE revision=2", [], |row| { + row.get(0) + }) + .unwrap(); + let new: serde_json::Value = serde_json::from_str(&new).unwrap(); + assert_eq!(new["segments"][0]["duration_seconds"], 4); + assert_eq!(new["usage"]["status"], "UNAVAILABLE"); + let persisted: String = f + .store + .connection + .query_row("SELECT data FROM sessions", [], |row| row.get(0)) + .unwrap(); + let persisted: Session = serde_json::from_str(&persisted).unwrap(); + assert_eq!(persisted.usage_ledger.records.len(), 1); + assert_eq!( + persisted.usage_ledger.records[0].source_record_id, + "request_frozen" + ); + assert!(!persisted.usage_ledger.baseline_ready()); + assert_eq!( + f.store.numeric_status(&f.repository, f.source).unwrap()["reason"], + "SOURCE_CHANGED" + ); + } +} +#[test] +fn self_revocation_keeps_specific_local_reason_and_never_rewrites_a_frozen_numeric_body() { + let (mut f, time_only, frozen, digest) = frozen_fixture(); + let policy = Store::numeric_policy_in(&f.store.connection, &f.binding, f.source) + .unwrap() + .unwrap(); + let mut factory = NormalFactory { + policy: Some(policy), + runtime: None, + approved: None, + profile: None, + origin: None, + source_lease: None, + reason: Some("HARNESS_CHANGED"), + invalidate: true, + }; + let mut candidate = time_only.clone(); + factory.fail(&mut candidate, "HARNESS_CHANGED"); + let tx = f.store.transaction().unwrap(); + Store::finalize_normal_event( + &tx, + &mut candidate, + Some(&mut factory), + EventFinalization { + id: &time_only.id, + binding: &f.binding, + source_id: SESSION, + was_refused: false, + time_only: Some(&time_only), + }, + ) + .unwrap(); + tx.commit().unwrap(); + let prior: (String, String, String) = f + .store + .connection + .query_row( + "SELECT body,payload_hash,state FROM outbox WHERE revision=1", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .unwrap(); + assert_eq!(prior, (frozen, digest, "held".into())); + let status = f.store.numeric_status(&f.repository, f.source).unwrap(); + assert_eq!(status["enabled"], false); + assert_eq!(status["reason"], "HARNESS_CHANGED"); +} + +#[test] +fn repository_observed_usage_status_never_touches_profile_origin_or_source() { + for source in ["claude-code", "codex"] { + for mutation in ["hint", "remote", "disabled"] { + let mut f = Fixture::new(source); + f.consent(); + let original = f.repository.clone(); + let denied = Denied::arm(); + f.store.observe_repository(&original).unwrap(); + assert_eq!( + f.store.numeric_status(&original, source).unwrap()["enabled"], + true + ); + match mutation { + "hint" => f.repository.hint_hash = hash("changed-hint"), + "remote" => f.repository.remote_hash = hash("changed-remote"), + "disabled" => f.repository.disabled = true, + _ => unreachable!(), + } + f.store.observe_repository(&f.repository).unwrap(); + assert_eq!( + f.store.numeric_status(&f.repository, source).unwrap()["enabled"], + false + ); + f.store.observe_repository(&original).unwrap(); + assert_eq!( + f.store.numeric_status(&original, source).unwrap()["enabled"], + false + ); + assert_eq!(denied.counts(), [0; 3], "{source}/{mutation}"); + } + } +} diff --git a/tests/unit/capture_usage_lease.rs b/tests/unit/capture_usage_lease.rs new file mode 100644 index 0000000..e12026f --- /dev/null +++ b/tests/unit/capture_usage_lease.rs @@ -0,0 +1,102 @@ +//! Real private descriptor/source leases; no harness, CLI or process launch. +use super::*; +use std::{ + ffi::CString, + fs, + os::unix::{ + ffi::OsStrExt, + fs::{symlink, PermissionsExt}, + }, +}; +const SESSION: &str = "12345678-1234-4234-8234-123456789abc"; +struct Fixture { + _temp: tempfile::TempDir, + path: PathBuf, + approved: ApprovedActiveSession, +} +impl Fixture { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let home = temp.path().canonicalize().unwrap().join("home"); + let path = home.join(format!(".claude/projects/owned/{SESSION}.jsonl")); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, b"").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + let approved = + ApprovedActiveSession::new(Harness::ClaudeCode, "2.1.319", &home, &path, SESSION) + .unwrap(); + Self { + _temp: temp, + path, + approved, + } + } +} +#[test] +fn source_identity_is_opaque_and_accepts_same_inode_growth_after_prompt() { + let f = Fixture::new(); + let (_, baseline) = read_request_ids_leased(&f.approved).unwrap(); + let identity = baseline.identity().unwrap(); + assert_eq!(identity.len(), 64); + assert!(!identity.contains('/')); + assert!(baseline.valid()); + fs::write( + &f.path, + serde_json::json!({"type":"user","sessionId":SESSION}).to_string() + "\n", + ) + .unwrap(); + assert!(!baseline.valid()); + let (_, current) = read_requests_leased(&f.approved, &BTreeSet::new(), &identity).unwrap(); + assert_eq!(current.identity(), Some(identity)); + assert!(current.valid()); +} +#[test] +fn replaced_source_is_rejected_before_poisoned_bytes_are_decoded_and_new_prompt_can_rebaseline() { + let f = Fixture::new(); + let (_, baseline) = read_request_ids_leased(&f.approved).unwrap(); + let identity = baseline.identity().unwrap(); + fs::rename(&f.path, f.path.with_extension("previous")).unwrap(); + fs::write(&f.path, b"PRIVATE_POISONED_INVALID_BYTES").unwrap(); + assert!(!baseline.valid()); + assert!(matches!( + read_requests_leased(&f.approved, &BTreeSet::new(), &identity), + Err(UsageReadError::SourceChanged) + )); + fs::write(&f.path, b"").unwrap(); + let (_, fresh) = read_request_ids_leased(&f.approved).unwrap(); + assert_ne!(fresh.identity(), Some(identity)); + assert!(fresh.valid()); +} +#[test] +fn named_symlink_fifo_hardlink_or_directory_never_qualifies_as_source() { + for kind in [0, 1, 2, 3] { + let f = Fixture::new(); + let (_, baseline) = read_request_ids_leased(&f.approved).unwrap(); + let old = f.path.with_extension("previous"); + fs::rename(&f.path, &old).unwrap(); + match kind { + 0 => symlink(&old, &f.path).unwrap(), + 1 => { + let name = CString::new(f.path.as_os_str().as_bytes()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); + } + 2 => fs::hard_link(&old, &f.path).unwrap(), + _ => fs::create_dir(&f.path).unwrap(), + } + assert!(!baseline.valid()); + assert!(read_request_ids_leased(&f.approved).is_err()); + } +} +#[test] +fn same_inode_content_or_permissions_change_invalidates_the_commit_held_lease() { + for mode in [false, true] { + let f = Fixture::new(); + let (_, lease) = read_request_ids_leased(&f.approved).unwrap(); + if mode { + fs::set_permissions(&f.path, fs::Permissions::from_mode(0o400)).unwrap(); + } else { + fs::write(&f.path, b"changed").unwrap(); + } + assert!(!lease.valid()); + } +} diff --git a/tests/unit/capture_usage_origin.rs b/tests/unit/capture_usage_origin.rs new file mode 100644 index 0000000..4569a17 --- /dev/null +++ b/tests/unit/capture_usage_origin.rs @@ -0,0 +1,113 @@ +//! Pure bounded metadata contracts; no OS processes are observed here. +use super::*; +fn node(pid: i32) -> Snapshot { + Snapshot { + pid, + parent: pid + 1, + started: (10, 20), + image: PathBuf::from("/inert/owned-image"), + } +} +#[test] +fn first_and_eighth_ancestor_are_the_only_bounded_positive_edges() { + let file = tempfile::tempfile().unwrap(); + for matched in [1, 8] { + let mut calls = 0; + let result = collect_chain( + 1, + |pid| { + calls += 1; + Some((node(pid), file.try_clone().unwrap())) + }, + |node, _| node.pid == matched, + ); + assert!(result.is_some()); + assert_eq!(calls, matched); + } +} +#[test] +fn ninth_ancestor_wrong_image_missing_and_invalid_pid_fail_closed() { + let file = tempfile::tempfile().unwrap(); + for matched in [9, 99] { + let mut calls = 0; + assert!(collect_chain( + 1, + |pid| { + calls += 1; + Some((node(pid), file.try_clone().unwrap())) + }, + |node, _| node.pid == matched + ) + .is_none()); + assert_eq!(calls, 8); + } + assert!(collect_chain(1, |_| None, |_, _| true).is_none()); + for pid in [0, -1] { + assert!(collect_chain(pid, |_| panic!("invalid PID was observed"), |_, _| true).is_none()); + } +} +#[test] +fn observed_pid_zero_start_self_parent_and_cycles_are_refused() { + let file = tempfile::tempfile().unwrap(); + for field in [0, 1, 2] { + assert!(collect_chain( + 1, + |pid| { + let mut value = node(pid); + match field { + 0 => value.pid += 1, + 1 => value.started.0 = 0, + _ => value.parent = pid, + }; + Some((value, file.try_clone().unwrap())) + }, + |_, _| true + ) + .is_none()); + } + let mut calls = 0; + assert!(collect_chain( + 1, + |pid| { + calls += 1; + let mut value = node(pid); + if pid == 2 { + value.parent = 1 + }; + Some((value, file.try_clone().unwrap())) + }, + |_, _| false + ) + .is_none()); + assert_eq!(calls, 2); +} +#[test] +fn revalidation_rejects_changed_pid_start_parent_image_missing_or_chain() { + let file = tempfile::tempfile().unwrap(); + let nodes = vec![node(1), node(2)]; + assert!(stable_chain(&nodes, 1, |pid| Some(( + node(pid), + file.try_clone().unwrap() + )))); + assert!(!stable_chain(&nodes, 9, |_| panic!( + "changed immediate parent was observed" + ))); + assert!(!stable_chain(&nodes, 1, |_| None)); + for field in [0, 1, 2, 3] { + assert!(!stable_chain(&nodes, 1, |pid| { + let mut value = node(pid); + match field { + 0 => value.pid += 10, + 1 => value.started.1 += 1, + 2 => value.parent += 10, + _ => value.image = PathBuf::from("/inert/replaced-image"), + }; + Some((value, file.try_clone().unwrap())) + })); + } + let mut broken = nodes.clone(); + broken[0].parent = 3; + assert!(!stable_chain(&broken, 1, |_| panic!( + "broken stored chain was observed" + ))); +} diff --git a/tests/unit/capture_usage_parser.rs b/tests/unit/capture_usage_parser.rs new file mode 100644 index 0000000..78c694c --- /dev/null +++ b/tests/unit/capture_usage_parser.rs @@ -0,0 +1,843 @@ +//! The numeric shapes/counts below are minimized actual 2026-11-08 probe +//! observations. Envelopes reconstruct allowlisted fields from the initial and +//! envelope-session probes; raw content was discarded. Malformed/stream variants +//! and edge cases are synthetic validation, not harness qualification evidence. +use super::*; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +use std::{fs, path::PathBuf}; + +const SESSION: &str = "59455d61-5c59-4419-9cb8-9fb7143c317d"; +struct Fixture { + _temp: tempfile::TempDir, + home: PathBuf, + path: PathBuf, + harness: Harness, +} +impl Fixture { + fn new(harness: Harness, records: Vec) -> Self { + // /tmp is commonly a symlink on macOS; policy requires resolved HOME. + let temp = tempfile::tempdir().unwrap(); + let home = temp.path().canonicalize().unwrap().join("home"); + let path = match harness { + Harness::ClaudeCode => home.join(format!(".claude/projects/synthetic/{SESSION}.jsonl")), + Harness::Codex => home.join(format!( + ".codex/sessions/2026/11/08/rollout-2026-11-08T12-00-00-{SESSION}.jsonl" + )), + }; + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let this = Self { + _temp: temp, + home, + path, + harness, + }; + this.write(records); + this + } + fn write(&self, records: Vec) { + fs::write( + &self.path, + records + .iter() + .map(|r| format!("{}\n", r)) + .collect::(), + ) + .unwrap(); + } + #[cfg(unix)] + fn approved(&self) -> ApprovedActiveSession { + ApprovedActiveSession::new( + self.harness, + if self.harness == Harness::Codex { + "0.167.0" + } else { + "2.1.319" + }, + &self.home, + &self.path, + SESSION, + ) + .unwrap() + } + fn read(&self) -> Result { + let decoded = parse_snapshot( + &self.decoder_identity(), + &fs::read(&self.path).unwrap(), + &BTreeSet::new(), + ); + #[cfg(unix)] + { + let native = read_active_session(&self.approved()); + assert_eq!(native, decoded, "native/pure decoder parity"); + native + } + #[cfg(not(unix))] + { + decoded + } + } + fn read_request_ids(&self) -> Result { + let decoded = parse_request_ids(&self.decoder_identity(), &fs::read(&self.path).unwrap()); + #[cfg(unix)] + { + let native = read_active_session_request_ids(&self.approved()); + assert_eq!(native, decoded, "native/pure identity decoder parity"); + native + } + #[cfg(not(unix))] + { + decoded + } + } + fn read_excluding(&self, excluded: &BTreeSet) -> Result { + let decoded = parse_snapshot( + &self.decoder_identity(), + &fs::read(&self.path).unwrap(), + excluded, + ); + #[cfg(unix)] + { + let native = read_active_session_excluding_request_ids(&self.approved(), excluded); + assert_eq!(native, decoded, "native/pure excluded decoder parity"); + native + } + #[cfg(not(unix))] + { + decoded + } + } + fn decoder_identity(&self) -> DecoderIdentity<'_> { + DecoderIdentity { + harness: self.harness, + session_id: SESSION, + } + } +} +fn claude(id: &str, output: u64) -> Value { + json!({"type":"assistant","sessionId":SESSION,"message":{"id":id,"model":"claude-opus-5-5","stop_reason":"end_turn","usage":{"input_tokens":2,"cache_creation_input_tokens":2280,"cache_read_input_tokens":0,"output_tokens":output},"content":[{"text":"PRIVATE_PROMPT_CANARY /private/path sk-secret"}]}}) +} +fn meta() -> Value { + json!({"type":"session_meta","payload":{"id":SESSION,"session_id":SESSION,"cli_version":"0.167.0","cwd":"PRIVATE_PATH_CANARY"}}) +} +fn context(turn: &str) -> Value { + json!({"type":"turn_context","payload":{"turn_id":turn,"model":"gpt-6.1-sol","instructions":"PRIVATE_INSTRUCTION_CANARY"}}) +} +fn codex(id: &str, turn: &str, resumed: bool) -> Value { + let (input, cached) = if resumed { + (20333, 20096) + } else { + (20309, 19328) + }; + json!({"type":"token_usage_record","payload":{"thread_id":SESSION,"session_id":SESSION,"turn_id":turn,"root_turn_id":turn,"response_id":id,"usage":{"input_tokens":input,"cached_input_tokens":cached,"cache_write_input_tokens":0,"output_tokens":6,"reasoning_output_tokens":0,"total_tokens":input+6},"thread_token_usage":{"input_tokens":40642,"output_tokens":12},"turn_token_usage":{"input_tokens":999999}}}) +} +fn lifecycle(kind: &str, turn: &str) -> Value { + json!({"type":"event_msg","payload":{"type":kind,"turn_id":turn,"message":"PRIVATE_EVENT_CANARY"}}) +} + +#[test] +fn baseline_keeps_only_ids_including_provisional_or_nonnumeric_history() { + let mut old = claude("msg_old", 81); + old["message"]["stop_reason"] = Value::Null; + old["message"]["model"] = json!("PRIVATE_HISTORICAL_MODEL/path"); + old["message"]["usage"] = json!({"input_tokens":"PRIVATE_HISTORY_COUNTER","output_tokens":-1}); + let missing = json!({"type":"assistant","sessionId":SESSION,"message":{"id":"msg_missing"}}); + let f = Fixture::new(Harness::ClaudeCode, vec![old, missing]); + let baseline = f.read_request_ids().unwrap(); + assert_eq!( + baseline.record_ids, + ["msg_old".to_owned(), "msg_missing".to_owned()] + .into_iter() + .collect() + ); + assert!(baseline.limitations.is_empty()); + let serialized = serde_json::to_string(&baseline).unwrap(); + assert!(!serialized.contains("PRIVATE")); + assert!(!serialized.contains("usage")); + assert!(!serialized.contains("model")); + assert_eq!(baseline.source_adapter, "CLAUDE_JSONL_2_1_319_V1"); +} + +#[test] +fn empty_stable_claude_baseline_is_valid_but_tail_or_missing_identity_is_not_complete() { + let f = Fixture::new(Harness::ClaudeCode, vec![]); + let empty = f.read_request_ids().unwrap(); + assert!(empty.record_ids.is_empty()); + assert!(empty.limitations.is_empty()); + fs::write(&f.path, b"{\"type\":\"assistant\"").unwrap(); + let partial = f.read_request_ids().unwrap(); + assert!(partial.limitations.contains(&"INCOMPLETE_TAIL")); + f.write(vec![ + json!({"type":"assistant","sessionId":SESSION,"message":{}}), + ]); + assert_eq!(f.read_request_ids(), Err(UsageReadError::InvalidRecord)); +} + +#[test] +fn codex_baseline_requires_native_metadata_and_excludes_no_usage_response_ids() { + let mut old = codex("resp_old", "turn_old", false); + old["payload"]["usage"] = Value::Null; + let f = Fixture::new(Harness::Codex, vec![meta(), old.clone()]); + let ids = f.read_request_ids().unwrap(); + assert_eq!( + ids.record_ids, + ["resp_old".to_owned()].into_iter().collect() + ); + f.write(vec![meta()]); + let ids = f.read_request_ids().unwrap(); + assert!(ids.record_ids.is_empty()); + assert!(ids.limitations.is_empty()); + f.write(vec![old]); + assert_eq!(f.read_request_ids(), Err(UsageReadError::InvalidSession)); +} + +#[test] +fn excluded_history_is_skipped_before_counter_model_or_finality_decoding() { + let mut invalid = claude("msg_old", 81); + invalid["message"]["usage"] = json!({"output_tokens":"PRIVATE_INVALID_HISTORY"}); + invalid["message"]["model"] = json!({"PRIVATE_MODEL":"invalid"}); + invalid["message"]["stop_reason"] = json!({"PRIVATE_FINALITY":"invalid"}); + let f = Fixture::new(Harness::ClaudeCode, vec![invalid, claude("msg_new", 7)]); + let excluded: BTreeSet<_> = ["msg_old".to_owned()].into_iter().collect(); + let evidence = f.read_excluding(&excluded).unwrap(); + assert_eq!(evidence.requests.len(), 1); + assert_eq!(evidence.requests[0].source_record_id, "msg_new"); + assert!(!serde_json::to_string(&evidence) + .unwrap() + .contains("PRIVATE")); + let mut old = codex("resp_old", "turn_old", false); + old["payload"]["usage"] = json!({"input_tokens":"PRIVATE_INVALID_HISTORY"}); + let f = Fixture::new( + Harness::Codex, + vec![ + meta(), + old, + context("turn_new"), + codex("resp_new", "turn_new", false), + ], + ); + let excluded: BTreeSet<_> = ["resp_old".to_owned()].into_iter().collect(); + let evidence = f.read_excluding(&excluded).unwrap(); + assert_eq!(evidence.requests.len(), 1); + assert_eq!(evidence.requests[0].source_record_id, "resp_new"); +} + +#[test] +fn exclusion_never_bypasses_session_identity_or_changed_accepted_request_conflicts() { + let mut old = claude("msg_old", 5); + old["sessionId"] = json!("other-session"); + let f = Fixture::new(Harness::ClaudeCode, vec![old]); + let excluded: BTreeSet<_> = ["msg_old".to_owned()].into_iter().collect(); + assert_eq!( + f.read_excluding(&excluded), + Err(UsageReadError::InvalidSession) + ); + f.write(vec![claude("msg_accepted", 5), claude("msg_accepted", 9)]); + let evidence = f.read_excluding(&excluded).unwrap(); + assert!(evidence.requests.is_empty()); + assert!(evidence + .limitations + .contains(&"CONFLICTING_REQUEST_RECORDS")); +} + +#[test] +fn observed_claude_tool_turn_and_model_change_retain_three_request_deltas() { + // Exact observed counts/IDs; the approved test session envelope is synthetic. + let observations = [ + ( + "msg_011CgqR9eX293BGPxqbyYPK6", + "claude-opus-5-5", + "tool_use", + 2, + 4224, + 0, + 81, + ), + ( + "msg_011CgqR9p5zFhFpDa2WMG2VG", + "claude-opus-5-5", + "end_turn", + 2, + 125, + 4224, + 5, + ), + ( + "msg_011CgqR9whPUXYvaWyNJXFaj", + "claude-sonnet-5-5", + "end_turn", + 2, + 4665, + 0, + 7, + ), + ]; + let rows = observations.into_iter().map(|(id,model,stop,input,write,read,output)| { + json!({"type":"assistant","sessionId":SESSION,"message":{"id":id,"model":model,"stop_reason":stop, + "usage":{"input_tokens":input,"cache_creation_input_tokens":write,"cache_read_input_tokens":read,"output_tokens":output}, + "content":[{"type":if stop=="tool_use" {"tool_use"} else {"text"},"text":"PRIVATE_PROSE_CANARY"}]}}) + }).collect(); + let f = Fixture::new(Harness::ClaudeCode, rows); + let e = f.read().unwrap(); + assert_eq!(e.requests.len(), 3); + assert_eq!( + e.requests + .iter() + .map(|r| r.output_tokens.unwrap()) + .sum::(), + 93 + ); + assert_eq!( + e.requests + .iter() + .map(|r| r.cached_input_tokens.unwrap()) + .sum::(), + 4224 + ); + assert_eq!( + e.requests + .iter() + .filter(|r| r.model.as_deref() == Some("claude-sonnet-5-5")) + .count(), + 1 + ); + assert_eq!(e.coverage, "PARTIAL"); + assert!(!serde_json::to_string(&e).unwrap().contains("PRIVATE")); +} + +#[test] +fn stale_or_missing_codex_source_version_and_missing_native_id_are_refused() { + let f = Fixture::new(Harness::Codex, vec![]); + for version in [json!("0.166.0"), Value::Null] { + let mut record = meta(); + record["payload"]["cli_version"] = version; + f.write(vec![ + record, + context("turn_1"), + codex("resp_1", "turn_1", false), + ]); + assert_eq!(f.read(), Err(UsageReadError::UnsupportedVersion)); + } + let mut record = meta(); + record["payload"] + .as_object_mut() + .unwrap() + .remove("session_id"); + f.write(vec![ + record, + context("turn_1"), + codex("resp_1", "turn_1", false), + ]); + assert_eq!(f.read(), Err(UsageReadError::InvalidSession)); +} + +#[test] +fn unsupported_nonnull_claude_finality_remains_explicitly_held() { + for stop in [json!("unknown"), json!("max_tokens")] { + let mut partial = claude("msg_1", 5); + partial["message"]["stop_reason"] = stop; + let f = Fixture::new( + Harness::ClaudeCode, + vec![partial, claude("msg_1", 5), claude("msg_2", 3)], + ); + let e = f.read().unwrap(); + assert_eq!(e.requests.len(), 1); + assert_eq!(e.requests[0].source_record_id, "msg_2"); + assert!(e.limitations.contains(&"UNKNOWN_REQUEST_FINALITY")); + } +} + +#[test] +fn provisional_claude_frames_yield_to_one_qualified_final_record() { + // Synthetic stream ordering exercises the proposed contract; the real + // pinned probe did not observe same-ID provisional-to-final delivery. + for absent in [false, true] { + for final_first in [false, true] { + let mut provisional = claude("msg_1", 1); + provisional["message"]["stop_reason"] = Value::Null; + if absent { + provisional["message"] + .as_object_mut() + .unwrap() + .remove("stop_reason"); + } + let final_record = claude("msg_1", 81); + let rows = if final_first { + vec![ + final_record.clone(), + provisional.clone(), + provisional, + final_record, + ] + } else { + vec![ + provisional.clone(), + provisional, + final_record.clone(), + final_record, + ] + }; + let f = Fixture::new(Harness::ClaudeCode, rows); + let e = f.read().unwrap(); + assert_eq!(e.requests.len(), 1); + assert_eq!(e.requests[0].output_tokens, Some(81)); + assert!(!e.limitations.contains(&"UNKNOWN_REQUEST_FINALITY")); + assert!(!e.limitations.contains(&"PENDING_REQUEST_FINALITY")); + assert!(!e.limitations.contains(&"CONFLICTING_REQUEST_RECORDS")); + assert_eq!(e.coverage, "PARTIAL"); + } + } +} + +#[test] +fn provisional_only_claude_request_is_pending_and_can_resolve_in_a_later_snapshot() { + let mut provisional = claude("msg_1", 1); + provisional["message"]["stop_reason"] = Value::Null; + let f = Fixture::new( + Harness::ClaudeCode, + vec![provisional.clone(), claude("msg_2", 3)], + ); + let pending = f.read().unwrap(); + assert_eq!(pending.requests.len(), 1); + assert_eq!(pending.requests[0].source_record_id, "msg_2"); + assert!(pending.limitations.contains(&"PENDING_REQUEST_FINALITY")); + assert!(!pending.limitations.contains(&"UNKNOWN_REQUEST_FINALITY")); + f.write(vec![provisional, claude("msg_1", 81), claude("msg_2", 3)]); + let resolved = f.read().unwrap(); + assert_eq!(resolved.requests.len(), 2); + assert_eq!( + resolved + .requests + .iter() + .map(|r| r.output_tokens.unwrap()) + .sum::(), + 84 + ); + assert!(!resolved.limitations.contains(&"PENDING_REQUEST_FINALITY")); + assert_eq!(resolved.coverage, "PARTIAL"); +} + +#[test] +fn observed_codex_abort_without_usage_is_unknown_not_zero() { + let mut record = codex( + "resp_08030d9a2a9f256b016af0634fb21487d28fc0d98709899918", + "turn_1", + false, + ); + record["payload"]["usage"]["input_tokens"] = json!(17975); + record["payload"]["usage"]["cached_input_tokens"] = json!(0); + record["payload"]["usage"]["total_tokens"] = json!(17981); + let f = Fixture::new( + Harness::Codex, + vec![ + meta(), + context("turn_1"), + lifecycle("task_started", "turn_1"), + record, + lifecycle("task_complete", "turn_1"), + context("turn_2"), + lifecycle("task_started", "turn_2"), + lifecycle("turn_aborted", "turn_2"), + ], + ); + let e = f.read().unwrap(); + assert_eq!(e.requests.len(), 1); + assert_eq!(e.requests[0].input_tokens, Some(17975)); + assert!(e.limitations.contains(&"INTERRUPTED_TURN")); + assert!(e.limitations.contains(&"MISSING_TURN_USAGE")); + assert_eq!(e.coverage, "PARTIAL"); + assert!(!serde_json::to_string(&e).unwrap().contains("PRIVATE")); +} + +#[test] +fn actual_claude_shape_preserves_raw_input_and_cache_without_prose() { + let f = Fixture::new( + Harness::ClaudeCode, + vec![claude("msg_011CgqP5w7Za31Gd1RKqi4wG", 5)], + ); + let evidence = f.read().unwrap(); + assert_eq!( + (evidence.coverage, evidence.coverage_reason), + ("PARTIAL", "OBSERVED_REQUEST_RECORDS") + ); + assert_eq!(evidence.requests.len(), 1); + let r = &evidence.requests[0]; + assert_eq!(r.input_basis, "CLAUDE_UNCACHED_INPUT"); + assert_eq!( + ( + r.input_tokens, + r.cached_input_tokens, + r.cache_write_input_tokens, + r.output_tokens + ), + (Some(2), Some(0), Some(2280), Some(5)) + ); + assert_eq!(r.reasoning_output_tokens, None); + assert_eq!(r.model_provenance, "RESPONSE_MODEL"); + let serialized = serde_json::to_string(&evidence).unwrap(); + assert!(!serialized.contains("PRIVATE")); + assert!(!serialized.contains("sk-secret")); +} +#[test] +fn codex_resume_uses_response_deltas_not_cumulative_totals() { + let f = Fixture::new( + Harness::Codex, + vec![ + meta(), + context("turn_1"), + codex("resp_1", "turn_1", false), + context("turn_2"), + codex("resp_2", "turn_2", true), + ], + ); + let e = f.read().unwrap(); + assert_eq!(e.requests.len(), 2); + assert_eq!( + e.requests + .iter() + .map(|r| r.input_tokens.unwrap()) + .sum::(), + 40642 + ); + assert_eq!(e.requests[1].cached_input_tokens, Some(20096)); + assert_eq!(e.requests[0].input_basis, "CODEX_TOTAL_INPUT"); + assert_eq!(e.requests[0].model_provenance, "TURN_CONFIG"); + assert!(!serde_json::to_string(&e).unwrap().contains("999999")); +} +#[test] +fn identical_terminal_delivery_is_deduped_but_conflicting_terminal_records_are_held() { + let f = Fixture::new( + Harness::ClaudeCode, + vec![claude("msg_1", 5), claude("msg_1", 5)], + ); + assert_eq!(f.read().unwrap().requests.len(), 1); + f.write(vec![ + claude("msg_1", 1), + claude("msg_1", 5), + claude("msg_2", 3), + ]); + let e = f.read().unwrap(); + assert_eq!(e.requests.len(), 1); + assert_eq!(e.requests[0].source_record_id, "msg_2"); + assert!(e.limitations.contains(&"CONFLICTING_REQUEST_RECORDS")); +} +#[test] +fn incomplete_trailing_json_is_never_an_observation() { + let f = Fixture::new(Harness::ClaudeCode, vec![claude("msg_1", 5)]); + use std::io::Write; + fs::OpenOptions::new() + .append(true) + .open(&f.path) + .unwrap() + .write_all(b"{\"type\":\"assistant\"") + .unwrap(); + let e = f.read().unwrap(); + assert_eq!(e.requests.len(), 1); + assert!(e.limitations.contains(&"INCOMPLETE_TAIL")); +} +#[test] +fn wrong_or_absent_session_identity_fails_closed() { + let mut wrong = claude("msg_1", 5); + wrong["sessionId"] = json!("other-session"); + let f = Fixture::new(Harness::ClaudeCode, vec![wrong]); + assert_eq!(f.read(), Err(UsageReadError::InvalidSession)); + let mut absent = claude("msg_1", 5); + absent.as_object_mut().unwrap().remove("sessionId"); + f.write(vec![absent]); + assert_eq!(f.read(), Err(UsageReadError::InvalidSession)); + let f = Fixture::new( + Harness::Codex, + vec![context("turn_1"), codex("resp_1", "turn_1", false)], + ); + assert_eq!(f.read(), Err(UsageReadError::InvalidSession)); + let mut wrong = codex("resp_1", "turn_1", false); + wrong["payload"]["thread_id"] = json!("other-session"); + f.write(vec![meta(), context("turn_1"), wrong]); + assert_eq!(f.read(), Err(UsageReadError::InvalidSession)); +} +#[test] +fn stale_version_and_repository_controlled_paths_are_refused() { + let f = Fixture::new(Harness::ClaudeCode, vec![]); + assert!(matches!( + ApprovedActiveSession::new(f.harness, "2.1.318", &f.home, &f.path, SESSION), + Err(UsageReadError::UnsupportedVersion) + )); + assert!(matches!( + ApprovedActiveSession::new( + f.harness, + "2.1.319", + &f.home, + &f.home.join(format!("repo/{SESSION}.jsonl")), + SESSION + ), + Err(UsageReadError::UnsafePath) + )); +} + +#[test] +fn absent_counters_stay_unknown_and_explicit_zero_is_preserved() { + let mut record = claude("msg_1", 0); + record["message"]["usage"] + .as_object_mut() + .unwrap() + .remove("cache_read_input_tokens"); + let f = Fixture::new(Harness::ClaudeCode, vec![record]); + let r = f.read().unwrap().requests.remove(0); + assert_eq!(r.cached_input_tokens, None); + assert_eq!(r.output_tokens, Some(0)); + let mut record = codex("resp_1", "turn_1", false); + record["payload"]["usage"] = Value::Null; + let f = Fixture::new(Harness::Codex, vec![meta(), record]); + let e = f.read().unwrap(); + assert!(e.requests.is_empty()); + assert!(e.limitations.contains(&"MISSING_USAGE")); + assert!(e.limitations.contains(&"MISSING_MODEL")); +} + +#[test] +fn invalid_numeric_categories_and_subset_violations_are_refused() { + for value in [ + json!(-1), + json!(1.5), + json!("5"), + json!(1_000_000_000_001u64), + ] { + let mut record = codex("resp_1", "turn_1", false); + record["payload"]["usage"]["input_tokens"] = value; + let f = Fixture::new(Harness::Codex, vec![meta(), record]); + assert_eq!(f.read(), Err(UsageReadError::InvalidRecord)); + } + for (field, value) in [ + ("cached_input_tokens", 20310), + ("reasoning_output_tokens", 7), + ] { + let mut record = codex("resp_1", "turn_1", false); + record["payload"]["usage"][field] = json!(value); + let f = Fixture::new(Harness::Codex, vec![meta(), record]); + assert_eq!(f.read(), Err(UsageReadError::InvalidRecord)); + } + // A real observed shape had reasoning 16 inside output 23. Never sum it. + let mut record = codex("resp_1", "turn_1", false); + record["payload"]["usage"]["output_tokens"] = json!(23); + record["payload"]["usage"]["reasoning_output_tokens"] = json!(16); + let f = Fixture::new(Harness::Codex, vec![meta(), context("turn_1"), record]); + let r = f.read().unwrap().requests.remove(0); + assert_eq!( + (r.output_tokens, r.reasoning_output_tokens), + (Some(23), Some(16)) + ); +} + +#[test] +fn decreasing_thread_snapshots_do_not_reset_request_deltas() { + let first = codex("resp_1", "turn_1", false); + let mut second = codex("resp_2", "turn_2", true); + second["payload"]["thread_token_usage"] = json!({"input_tokens":0}); + second["payload"]["turn_token_usage"] = json!({"input_tokens":0}); + let f = Fixture::new( + Harness::Codex, + vec![meta(), context("turn_1"), first, context("turn_2"), second], + ); + assert_eq!( + f.read() + .unwrap() + .requests + .iter() + .map(|r| r.input_tokens.unwrap()) + .sum::(), + 40642 + ); +} + +#[test] +fn repeated_equal_responses_with_different_ids_remain_distinct() { + let f = Fixture::new( + Harness::Codex, + vec![ + meta(), + context("turn_1"), + codex("resp_1", "turn_1", false), + codex("resp_2", "turn_1", false), + ], + ); + let e = f.read().unwrap(); + assert_eq!(e.requests.len(), 2); + assert_eq!( + e.requests + .iter() + .map(|r| r.output_tokens.unwrap()) + .sum::(), + 12 + ); +} + +#[test] +fn missing_snapshot_for_an_existing_id_is_a_conflict_not_silent_fallback() { + let first = codex("resp_1", "turn_1", false); + let mut missing = first.clone(); + missing["payload"]["usage"] = Value::Null; + let f = Fixture::new( + Harness::Codex, + vec![meta(), context("turn_1"), first, missing], + ); + let e = f.read().unwrap(); + assert!(e.requests.is_empty()); + assert!(e.limitations.contains(&"CONFLICTING_REQUEST_RECORDS")); +} + +#[test] +fn serialized_request_has_only_exact_approved_wire_fields() { + let f = Fixture::new(Harness::ClaudeCode, vec![claude("msg_1", 5)]); + let e = f.read().unwrap(); + let value = serde_json::to_value(&e.requests[0]).unwrap(); + let fields: std::collections::BTreeSet<_> = value + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + assert_eq!( + fields, + [ + "source_adapter", + "source_record_id", + "source_turn_id", + "model", + "model_provenance", + "counter_semantics", + "input_basis", + "input_tokens", + "cached_input_tokens", + "cache_write_input_tokens", + "output_tokens", + "reasoning_output_tokens" + ] + .into_iter() + .collect() + ); + assert_eq!(value["source_adapter"], json!("CLAUDE_JSONL_2_1_319_V1")); + assert!(value.get("total_tokens").is_none()); + assert!(value.get("cost").is_none()); +} + +#[test] +fn same_turn_conflicting_model_never_becomes_a_last_wins_attribution() { + let mut changed = context("turn_1"); + changed["payload"]["model"] = json!("gpt-other"); + let f = Fixture::new( + Harness::Codex, + vec![ + meta(), + context("turn_1"), + codex("resp_1", "turn_1", false), + changed, + context("turn_1"), + ], + ); + let e = f.read().unwrap(); + assert_eq!(e.requests[0].model, None); + assert_eq!(e.requests[0].model_provenance, "UNKNOWN"); + assert!(e.limitations.contains(&"CONFLICTING_TURN_MODELS")); +} + +#[test] +fn duplicate_known_fields_malformed_lines_and_secret_ids_have_static_errors() { + let f = Fixture::new(Harness::ClaudeCode, vec![]); + for content in [ + format!("{{\"type\":\"assistant\",\"sessionId\":\"other\",\"sessionId\":\"{SESSION}\"}}\n"), + "{PRIVATE_RAW_CANARY\n".to_owned(), + format!("{{\"type\":\"assistant\",\"sessionId\":\"{SESSION}\",\"message\":{{\"id\":\"sk-SECRET_CANARY\"}}}}\n"), + ] { + fs::write(&f.path,content).unwrap(); + let error = f.read().unwrap_err(); + assert!(!format!("{error} {error:?}").contains("CANARY")); + assert!(!format!("{error}").contains(&f.home.to_string_lossy().to_string())); + } +} + +#[test] +fn native_metadata_and_context_identity_are_verified() { + let mut bad_meta = meta(); + bad_meta["payload"]["id"] = json!("other-session"); + let f = Fixture::new(Harness::Codex, vec![bad_meta]); + assert_eq!(f.read(), Err(UsageReadError::InvalidSession)); + let mut bad_context = context("turn_1"); + bad_context["payload"]["session_id"] = json!("other-session"); + f.write(vec![meta(), bad_context, codex("resp_1", "turn_1", false)]); + assert_eq!(f.read(), Err(UsageReadError::InvalidSession)); +} + +#[test] +fn size_record_count_and_deep_json_are_bounded() { + let f = Fixture::new(Harness::ClaudeCode, vec![]); + fs::write(&f.path, vec![b' '; MAX_SNAPSHOT_BYTES + 1]).unwrap(); + assert_eq!(f.read(), Err(UsageReadError::TooLarge)); + fs::write(&f.path, b"\n".repeat(4097)).unwrap(); + assert_eq!(f.read(), Err(UsageReadError::TooLarge)); + fs::write( + &f.path, + format!( + "{{\"type\":\"ignored\",\"unknown\":{}0{}}}\n", + "[".repeat(300), + "]".repeat(300) + ), + ) + .unwrap(); + assert_eq!(f.read(), Err(UsageReadError::InvalidRecord)); +} + +#[cfg(unix)] +#[test] +fn symlinked_leaf_and_any_parent_are_refused_without_reading_target() { + use std::os::unix::fs::symlink; + let f = Fixture::new(Harness::ClaudeCode, vec![claude("msg_1", 5)]); + let approved = f.approved(); + let elsewhere = f.home.join("unapproved.jsonl"); + fs::rename(&f.path, &elsewhere).unwrap(); + symlink(&elsewhere, &f.path).unwrap(); + assert_eq!( + read_active_session(&approved), + Err(UsageReadError::UnsafePath) + ); + fs::remove_file(&f.path).unwrap(); + fs::rename(&elsewhere, &f.path).unwrap(); + let original_parent = f.path.parent().unwrap(); + let moved_parent = f.home.join("moved-project"); + fs::rename(original_parent, &moved_parent).unwrap(); + symlink(&moved_parent, original_parent).unwrap(); + assert_eq!( + read_active_session(&approved), + Err(UsageReadError::UnsafePath) + ); +} + +#[cfg(unix)] +#[test] +fn fifo_directory_and_hardlink_are_refused() { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + let f = Fixture::new(Harness::ClaudeCode, vec![]); + let approved = f.approved(); + fs::remove_file(&f.path).unwrap(); + let name = CString::new(f.path.as_os_str().as_bytes()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); + let started = std::time::Instant::now(); + assert_eq!( + read_active_session(&approved), + Err(UsageReadError::UnsafePath) + ); + assert!(started.elapsed() < std::time::Duration::from_secs(1)); + fs::remove_file(&f.path).unwrap(); + fs::create_dir(&f.path).unwrap(); + assert_eq!( + read_active_session(&approved), + Err(UsageReadError::UnsafePath) + ); + fs::remove_dir(&f.path).unwrap(); + f.write(vec![claude("msg_1", 5)]); + fs::hard_link(&f.path, f.home.join("alias.jsonl")).unwrap(); + assert_eq!( + read_active_session(&approved), + Err(UsageReadError::UnsafePath) + ); +} diff --git a/tests/unit/capture_usage_qualification.rs b/tests/unit/capture_usage_qualification.rs new file mode 100644 index 0000000..c9fd625 --- /dev/null +++ b/tests/unit/capture_usage_qualification.rs @@ -0,0 +1,585 @@ +#![cfg(unix)] +// Native consent/store/reader assertions require the supported POSIX authority. +//! Synthetic core qualification only; normal guarded command acceptance is separate. +use crate::capture::{self, Binding, Clock, Repository, Signal, Store, UsageSource}; +use crate::cli::capture::CaptureEvent::{self, *}; +use serde_json::{json, Value}; +use std::fs; +const SESSION: &str = "12345678-1234-4234-8234-123456789abc"; +fn clock(n: i64) -> Clock { + Clock { + wall: 1_794_067_200 + n, + monotonic: 1000 + n, + boot: "fixture".into(), + } +} +fn repo() -> Repository { + Repository { + key: capture::hash("repo"), + remote_hash: capture::hash("remote"), + hint_hash: capture::hash("hint"), + linked_without_hint: false, + disabled: false, + } +} +struct Fixture { + dir: tempfile::TempDir, + home: std::path::PathBuf, + path: std::path::PathBuf, + store: Store, + binding: Binding, + namespace: &'static str, + version: &'static str, +} +impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().canonicalize().unwrap().join("home"); + let path = home.join(format!(".claude/projects/fixture/{SESSION}.jsonl")); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut store = Store::open(&dir.path().join("capture")).unwrap(); + let binding = store + .approve(Binding { + repository_key: repo().key, + remote_hash: repo().remote_hash, + hint_hash: repo().hint_hash, + id: String::new(), + version: 0, + workspace_id: "co_fixture".into(), + owner_id: "user_fixture".into(), + origin_hash: capture::hash("origin"), + project_id: "project_fixture".into(), + task_id: "task_fixture".into(), + agents: vec!["claude-code".into()], + paused: false, + revoked: false, + }) + .unwrap(); + Self { + dir, + home, + path, + store, + binding, + namespace: "claude-code", + version: "2.1.319", + } + } + fn write(&self, records: Vec) { + fs::write( + &self.path, + records + .into_iter() + .map(|v| v.to_string() + "\n") + .collect::(), + ) + .unwrap(); + } + fn event(&mut self, event: CaptureEvent, n: i64, usage: bool) { + self.event_turn(event, n, usage, "prompt_1"); + } + fn event_turn(&mut self, event: CaptureEvent, n: i64, usage: bool, turn: &str) { + let source = UsageSource { + resolved_home: &self.home, + exact_hook_path: &self.path, + qualified_source: self.namespace, + qualified_native_session: SESSION, + }; + self.store + .event_with_usage( + &repo(), + Signal { + source: self.namespace, + resumed: false, + source_id: SESSION, + turn_id: Some(turn), + version: self.version, + event, + clock: &clock(n), + }, + if usage { Some(&source) } else { None }, + ) + .unwrap(); + } + fn start(&mut self, n: i64) { + self.write(vec![]); + self.event(Prompt, n, true); + } + fn usage_ids(&self) -> Vec { + self.bodies() + .into_iter() + .flat_map(|body| { + body["usage"]["records"] + .as_array() + .cloned() + .unwrap_or_default() + }) + .map(|record| record["source_record_id"].as_str().unwrap().to_owned()) + .collect() + } + fn bodies(&self) -> Vec { + let db = + rusqlite::Connection::open(self.dir.path().join("capture/capture.sqlite3")).unwrap(); + let mut s = db + .prepare("SELECT body FROM outbox ORDER BY revision") + .unwrap(); + s.query_map([], |r| r.get::<_, String>(0)) + .unwrap() + .map(|s| serde_json::from_str(&s.unwrap()).unwrap()) + .collect() + } +} +fn request(id: &str, output: u64) -> Value { + json!({"type":"assistant","sessionId":SESSION,"message":{"id":id,"model":"claude-opus-5-5","stop_reason":"end_turn","usage":{"input_tokens":2,"cache_read_input_tokens":null,"cache_creation_input_tokens":2280,"output_tokens":output},"content":[{"text":"PRIVATE_CANARY sk-secret /private/customer"}]}}) +} +#[test] +fn exact_session_usage_and_time_commit_atomically_without_prose_or_paths() { + let mut f = Fixture::new(); + f.start(0); + f.write(vec![request("msg_1", 5)]); + f.event(Stop, 59, true); + let b = &f.bodies()[0]; + assert_eq!(b["segments"][0]["duration_seconds"], 59); + assert_eq!(b["usage"]["status"], "PARTIAL"); + assert_eq!(b["usage"]["records"][0]["cached_input_tokens"], Value::Null); + assert_eq!(b["usage"]["records"][0]["cache_write_input_tokens"], 2280); + let db = fs::read(f.dir.path().join("capture/capture.sqlite3")).unwrap(); + let text = String::from_utf8_lossy(&db); + assert!(!text.contains("PRIVATE_CANARY")); + assert!(!text.contains("sk-secret")); + assert!(!text.contains(f.path.to_str().unwrap())); + assert!(f.store.claim(&f.binding, clock(60).wall).unwrap().is_some()); +} +#[test] +fn late_usage_has_its_own_revision_and_replay_changes_no_frozen_bytes() { + let mut f = Fixture::new(); + f.start(0); + f.event(Stop, 1, false); + let first = f.bodies(); + f.write(vec![request("msg_1", 5)]); + f.event(Stop, 10, true); + f.event(Stop, 11, true); + let b = f.bodies(); + assert_eq!(b.len(), 2); + assert_eq!(b[0], first[0]); + assert_eq!(b[1]["segments"], json!([])); + assert_eq!(b[1]["revision"], 2); + assert_eq!(f.store.preview(SESSION).unwrap()[0].segments.len(), 1); +} +#[test] +fn more_than_25_requests_are_disjoint_bounded_batches_without_truncation() { + let mut f = Fixture::new(); + f.start(0); + f.write( + (0..80) + .map(|n| request(&format!("msg_{n:03}_{}", "a".repeat(110)), 5)) + .collect(), + ); + f.event(Stop, 2, true); + let b = f.bodies(); + assert!(b.len() > 3); + let mut ids = std::collections::BTreeSet::new(); + let mut seconds = 0; + for body in b { + assert!(body.to_string().len() <= capture::MAX_BODY_BYTES); + let r = body["usage"]["records"].as_array().unwrap(); + assert!(r.len() <= 25); + for row in r { + assert!(ids.insert(row["source_record_id"].as_str().unwrap().to_owned())); + } + seconds += body["segments"] + .as_array() + .unwrap() + .iter() + .map(|s| s["duration_seconds"].as_i64().unwrap()) + .sum::(); + } + assert_eq!(ids.len(), 80); + assert_eq!(seconds, 2); +} +#[test] +fn conflicting_request_identity_holds_unsent_evidence_but_preserves_time() { + let mut f = Fixture::new(); + f.start(0); + f.write(vec![request("msg_1", 5)]); + f.event(Stop, 2, true); + let frozen = f.bodies(); + f.write(vec![request("msg_1", 6)]); + f.event(Stop, 3, true); + assert!(f.store.claim(&f.binding, clock(5).wall).unwrap().is_none()); + assert!(f.store.preview(SESSION).unwrap()[0].needs_attention); + assert_eq!(f.bodies(), frozen); + assert_eq!( + f.store.preview(SESSION).unwrap()[0].segments[0].duration_seconds, + 2 + ); + assert!(f + .store + .status() + .unwrap() + .queue + .iter() + .any(|q| q.reason.as_deref() == Some("USAGE_RECORD_CONFLICT"))); +} +#[test] +fn conflict_within_one_snapshot_is_held_instead_of_omitting_conflicted_id() { + let mut f = Fixture::new(); + f.start(0); + f.write(vec![ + request("msg_1", 1), + request("msg_1", 5), + request("msg_2", 3), + ]); + f.event(Stop, 2, true); + assert!(f.store.claim(&f.binding, clock(3).wall).unwrap().is_none()); + assert!(f.store.preview(SESSION).unwrap()[0].needs_attention); + assert_eq!( + f.store.preview(SESSION).unwrap()[0].segments[0].duration_seconds, + 2 + ); +} +#[test] +fn revoked_binding_never_reads_or_accepts_transcript_usage() { + let mut f = Fixture::new(); + f.start(0); + f.store.control(&repo(), "disable", &clock(1)).unwrap(); + f.write(vec![request("msg_1", 5)]); + f.event(Stop, 2, true); + assert!(f + .bodies() + .iter() + .all(|b| b["usage"]["status"] == "UNAVAILABLE")); +} +#[test] +fn missing_unsafe_and_wrong_identity_sources_never_replace_prior_usage() { + let mut f = Fixture::new(); + f.start(0); + f.write(vec![request("msg_1", 5)]); + f.event(Stop, 2, true); + let prior = f.bodies(); + fs::write( + &f.path, + "{\"type\":\"assistant\",\"sessionId\":\"other\"}\n", + ) + .unwrap(); + f.event(Stop, 3, true); + assert_eq!(f.bodies(), prior); + let s = UsageSource { + resolved_home: &f.home, + exact_hook_path: &f.path, + qualified_source: "claude-code", + qualified_native_session: "different-session", + }; + f.store + .event_with_usage( + &repo(), + Signal { + source: "claude-code", + resumed: false, + source_id: SESSION, + turn_id: Some("prompt_1"), + version: "2.1.319", + event: Stop, + clock: &clock(4), + }, + Some(&s), + ) + .unwrap(); + assert_eq!(f.bodies(), prior); +} +#[test] +fn legacy_metadata_capture_never_reads_transcripts_without_explicit_internal_gate() { + let mut f = Fixture::new(); + f.write(vec![request("msg_1", 5)]); + f.event(Prompt, 0, false); + f.event(Stop, 2, false); + assert_eq!(f.bodies()[0]["usage"]["status"], "UNAVAILABLE"); +} + +#[test] +fn provisional_request_does_not_permanently_hold_a_later_final_usage_revision() { + let mut f = Fixture::new(); + f.start(0); + let mut provisional = request("msg_later_final", 0); + provisional["message"]["stop_reason"] = Value::Null; + f.write(vec![provisional]); + f.event(Stop, 2, true); + let initial = f.bodies(); + assert_eq!(initial[0]["usage"]["status"], "UNAVAILABLE"); + assert!(!f.store.preview(SESSION).unwrap()[0].needs_attention); + f.write(vec![request("msg_later_final", 5)]); + f.event(Stop, 4, true); + let bodies = f.bodies(); + assert_eq!(bodies.len(), 2); + assert_eq!(bodies[0], initial[0]); + assert_eq!(bodies[1]["usage"]["records"].as_array().unwrap().len(), 1); + assert_eq!(bodies[1]["segments"], json!([])); + assert!(!f.store.preview(SESSION).unwrap()[0].needs_attention); +} + +#[test] +fn first_enabled_prompt_baseline_excludes_preconsent_history_without_numeric_storage() { + let mut f = Fixture::new(); + let mut old = request("msg_before_consent", 5); + old["message"]["usage"]["input_tokens"] = json!(999123457u64); + f.write(vec![old.clone()]); + f.event(Prompt, 10, true); + let db = fs::read(f.dir.path().join("capture/capture.sqlite3")).unwrap(); + assert!(!String::from_utf8_lossy(&db).contains("999123457")); + f.write(vec![old, request("msg_after_consent", 7)]); + f.event(Stop, 20, true); + assert_eq!(f.usage_ids(), vec!["msg_after_consent"]); +} +#[test] +fn paused_terminals_collect_nothing_and_resume_requires_a_new_prompt_baseline() { + let mut f = Fixture::new(); + f.start(0); + f.store.control(&repo(), "pause", &clock(30)).unwrap(); + let paused = request("msg_created_while_paused", 5); + f.write(vec![paused.clone()]); + f.event(Stop, 100, true); + assert!(f.usage_ids().is_empty()); + let db = fs::read(f.dir.path().join("capture/capture.sqlite3")).unwrap(); + assert!(!String::from_utf8_lossy(&db).contains("msg_created_while_paused")); + f.store.control(&repo(), "resume", &clock(110)).unwrap(); + f.event(Stop, 150, true); + assert!(f.usage_ids().is_empty()); + f.event_turn(Prompt, 200, true, "prompt_2"); + f.write(vec![paused, request("msg_new_enabled_turn", 6)]); + f.event_turn(Stop, 250, true, "prompt_2"); + assert_eq!(f.usage_ids(), vec!["msg_new_enabled_turn"]); +} +#[test] +fn preconsent_provisional_id_stays_excluded_when_its_final_record_arrives() { + let mut f = Fixture::new(); + let mut provisional = request("msg_existing_provisional", 0); + provisional["message"]["stop_reason"] = Value::Null; + f.write(vec![provisional]); + f.event(Prompt, 0, true); + f.write(vec![ + request("msg_existing_provisional", 5), + request("msg_new_request", 6), + ]); + f.event(Stop, 10, true); + assert_eq!(f.usage_ids(), vec!["msg_new_request"]); +} +#[test] +fn missing_prompt_baseline_cannot_be_reconstructed_from_a_later_terminal_snapshot() { + let mut f = Fixture::new(); + f.event(Prompt, 0, true); + f.write(vec![request("msg_unknown_epoch", 5)]); + f.event(Stop, 10, true); + assert!(f.usage_ids().is_empty()); + f.event_turn(Prompt, 20, true, "prompt_2"); + f.write(vec![ + request("msg_unknown_epoch", 5), + request("msg_baselined_epoch", 6), + ]); + f.event_turn(Stop, 30, true, "prompt_2"); + assert_eq!(f.usage_ids(), vec!["msg_baselined_epoch"]); +} +#[test] +fn terminal_capability_without_prompt_capability_never_retroactively_imports_usage() { + let mut f = Fixture::new(); + f.write(vec![]); + f.event(Prompt, 0, false); + f.write(vec![request("msg_not_authorized_at_prompt", 5)]); + f.event(Stop, 10, true); + assert!(f.usage_ids().is_empty()); +} +#[test] +fn incomplete_prompt_baseline_requires_another_new_prompt_not_terminal_repair() { + let mut f = Fixture::new(); + fs::write(&f.path, "{\"type\":\"assistant\",\"sessionId\":").unwrap(); + f.event(Prompt, 0, true); + f.write(vec![request("msg_after_unsafe_baseline", 5)]); + f.event(Stop, 10, true); + assert!(f.usage_ids().is_empty()); + f.event_turn(Prompt, 20, true, "prompt_2"); + f.write(vec![ + request("msg_after_unsafe_baseline", 5), + request("msg_after_complete_baseline", 6), + ]); + f.event_turn(Stop, 30, true, "prompt_2"); + assert_eq!(f.usage_ids(), vec!["msg_after_complete_baseline"]); +} + +#[test] +fn prior_accepted_usage_is_immutable_and_not_duplicated_across_pause_baselines() { + let mut f = Fixture::new(); + f.start(0); + let accepted = request("msg_already_accepted", 5); + f.write(vec![accepted.clone()]); + f.event(Stop, 10, true); + let frozen = f.bodies()[0].clone(); + f.store.control(&repo(), "pause", &clock(20)).unwrap(); + let excluded = request("msg_paused_after_accepted", 6); + f.write(vec![accepted.clone(), excluded.clone()]); + f.event(Stop, 30, true); + assert_eq!(f.bodies()[0], frozen); + f.store.control(&repo(), "resume", &clock(40)).unwrap(); + f.event(Stop, 50, true); + assert_eq!(f.usage_ids(), vec!["msg_already_accepted"]); + f.event_turn(Prompt, 60, true, "prompt_2"); + f.write(vec![ + accepted, + excluded, + request("msg_after_new_baseline", 7), + ]); + f.event_turn(Stop, 70, true, "prompt_2"); + assert_eq!( + f.usage_ids(), + vec!["msg_already_accepted", "msg_after_new_baseline"] + ); + assert_eq!(f.bodies()[0], frozen); +} +#[test] +fn repo_global_and_harness_revocation_reset_usage_even_for_an_already_closed_turn() { + for mode in ["repo", "global", "harness"] { + let mut f = Fixture::new(); + f.start(0); + let first = request("msg_prior_approved", 5); + f.write(vec![first.clone()]); + f.event(Stop, 10, true); + match mode { + "repo" => f.store.control(&repo(), "disable", &clock(20)).unwrap(), + "global" => f.store.disable_all().unwrap(), + _ => { + let mut removed = f.binding.clone(); + removed.agents.clear(); + f.store.approve(removed).unwrap(); + } + } + let excluded = request("msg_revoked_period", 6); + f.write(vec![first.clone(), excluded.clone()]); + f.store.approve(f.binding.clone()).unwrap(); + f.event(Stop, 40, true); + assert_eq!(f.usage_ids(), vec!["msg_prior_approved"], "{mode}"); + f.event_turn(Prompt, 50, true, "prompt_2"); + f.write(vec![first, excluded, request("msg_reapproved_new_turn", 7)]); + f.event_turn(Stop, 60, true, "prompt_2"); + assert_eq!( + f.usage_ids(), + vec!["msg_prior_approved", "msg_reapproved_new_turn"], + "{mode}" + ); + } +} +#[test] +fn a_duplicate_prompt_cannot_retroactively_establish_the_missing_usage_baseline() { + let mut f = Fixture::new(); + f.write(vec![]); + f.event(Prompt, 0, false); + f.write(vec![request("msg_before_late_prompt_replay", 5)]); + f.event(Prompt, 5, true); + f.event(Stop, 10, true); + assert!(f.usage_ids().is_empty()); +} + +#[test] +fn changed_previously_accepted_request_still_holds_after_a_new_consent_baseline() { + let mut f = Fixture::new(); + f.start(0); + f.write(vec![request("msg_accepted_before_pause", 5)]); + f.event(Stop, 10, true); + let frozen = f.bodies()[0].clone(); + f.store.control(&repo(), "pause", &clock(20)).unwrap(); + f.store.control(&repo(), "resume", &clock(30)).unwrap(); + f.event_turn(Prompt, 40, true, "prompt_2"); + f.write(vec![ + request("msg_accepted_before_pause", 6), + request("msg_new_but_conflicted_snapshot", 7), + ]); + f.event_turn(Stop, 50, true, "prompt_2"); + assert!(f.store.preview(SESSION).unwrap()[0].needs_attention); + assert!(f.store.claim(&f.binding, clock(60).wall).unwrap().is_none()); + assert_eq!(f.bodies()[0], frozen); + assert_eq!(f.usage_ids(), vec!["msg_accepted_before_pause"]); +} +#[test] +fn excluded_history_never_decodes_or_stores_old_numeric_model_or_finality_payloads() { + let mut f = Fixture::new(); + let mut old = request("msg_history_identity_only", 5); + old["message"]["usage"]["input_tokens"] = json!("PRIVATE_NON_NUMERIC"); + old["message"]["model"] = json!("/PRIVATE_OLD_MODEL"); + old["message"]["stop_reason"] = json!("unqualified_old_reason"); + f.write(vec![old.clone()]); + f.event(Prompt, 0, true); + f.write(vec![old, request("msg_new_valid_payload", 6)]); + f.event(Stop, 10, true); + assert_eq!(f.usage_ids(), vec!["msg_new_valid_payload"]); + let bytes = fs::read(f.dir.path().join("capture/capture.sqlite3")).unwrap(); + let persisted = String::from_utf8_lossy(&bytes); + assert!(!persisted.contains("PRIVATE_NON_NUMERIC")); + assert!(!persisted.contains("PRIVATE_OLD_MODEL")); +} + +#[test] +fn codex_prompt_baseline_and_pause_epoch_exclude_old_response_ids() { + let mut f = Fixture::new(); + f.namespace = "codex"; + f.version = "0.167.0"; + let mut binding = f.binding.clone(); + binding.agents = vec!["codex".into()]; + f.binding = f.store.approve(binding).unwrap(); + f.path = f.home.join(format!( + ".codex/sessions/2026/11/08/rollout-2026-11-08-{SESSION}.jsonl" + )); + fs::create_dir_all(f.path.parent().unwrap()).unwrap(); + let meta = json!({"type":"session_meta","payload":{"id":SESSION,"session_id":SESSION,"cli_version":"0.167.0"}}); + let context = |turn: &str| json!({"type":"turn_context","payload":{"turn_id":turn,"model":"gpt-6.1-sol"}}); + let response = |id: &str, turn: &str| json!({"type":"token_usage_record","payload":{"thread_id":SESSION,"session_id":SESSION,"turn_id":turn,"root_turn_id":turn,"response_id":id,"usage":{"input_tokens":101,"cached_input_tokens":80,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":2}}}); + let mut provisional = response("resp_before_consent", "old_turn"); + provisional["payload"]["usage"] = Value::Null; + f.write(vec![meta.clone(), context("old_turn"), provisional]); + f.event(Prompt, 0, true); + let old = response("resp_before_consent", "old_turn"); + let accepted = response("resp_after_consent", "prompt_1"); + f.write(vec![ + meta.clone(), + context("old_turn"), + old.clone(), + context("prompt_1"), + accepted.clone(), + ]); + f.event(Stop, 10, true); + assert_eq!(f.usage_ids(), vec!["resp_after_consent"]); + f.store.control(&repo(), "pause", &clock(20)).unwrap(); + let excluded = response("resp_paused", "paused_turn"); + f.write(vec![ + meta.clone(), + context("old_turn"), + old.clone(), + context("prompt_1"), + accepted.clone(), + context("paused_turn"), + excluded.clone(), + ]); + f.event(Stop, 30, true); + f.store.control(&repo(), "resume", &clock(40)).unwrap(); + f.event(Stop, 50, true); + assert_eq!(f.usage_ids(), vec!["resp_after_consent"]); + f.event_turn(Prompt, 60, true, "prompt_2"); + f.write(vec![ + meta, + context("old_turn"), + old, + context("prompt_1"), + accepted, + context("paused_turn"), + excluded, + context("prompt_2"), + response("resp_new_epoch", "prompt_2"), + ]); + f.event_turn(Stop, 70, true, "prompt_2"); + assert_eq!(f.usage_ids(), vec!["resp_after_consent", "resp_new_epoch"]); + let bodies = f.bodies(); + assert_eq!( + bodies.last().unwrap()["usage"]["records"][0]["input_basis"], + "CODEX_TOTAL_INPUT" + ); + assert_eq!( + bodies.last().unwrap()["usage"]["records"][0]["cached_input_tokens"], + 80 + ); +} diff --git a/tests/unit/source_qa_protocol.rs b/tests/unit/source_qa_protocol.rs new file mode 100644 index 0000000..7b9f7a6 --- /dev/null +++ b/tests/unit/source_qa_protocol.rs @@ -0,0 +1,361 @@ +//! Socket-only state-machine acceptance; no processes, signalling or profiles. +use super::*; +use std::net::Shutdown; +const NONCE: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const PEER: u32 = 12345; +#[test] +fn native_repair_cancel_sender_forwards_strictly_decreasing_ends() { + let (socket, mut peer) = UnixStream::pair().unwrap(); + let mut endpoint = Endpoint::new(socket, NONCE.into(), Some(PEER)).unwrap(); + endpoint.send_cancel_tighter(1000).unwrap(); + endpoint.send_cancel_tighter(500).unwrap(); + endpoint.send_cancel_tighter(1).unwrap(); + endpoint.send_cancel_tighter(10000).unwrap(); + let mut expected = String::new(); + for end in [1000, 500, 1] { + expected.push_str(&format!("{NONCE}|CANCEL|{}|{end}\n", std::process::id())); + } + peer.set_nonblocking(true).unwrap(); + let mut bytes = vec![0; expected.len() + 100]; + let count = peer.read(&mut bytes).unwrap(); + assert_eq!(&bytes[..count], expected.as_bytes()); +} + +fn pair() -> (Endpoint, UnixStream) { + let (reader, writer) = UnixStream::pair().unwrap(); + writer + .set_write_timeout(Some(std::time::Duration::from_secs(1))) + .unwrap(); + writer + .set_read_timeout(Some(std::time::Duration::from_secs(1))) + .unwrap(); + ( + Endpoint::new(reader, NONCE.into(), Some(PEER)).unwrap(), + writer, + ) +} +fn frame(writer: &mut UnixStream, nonce: &str, value: &str) { + writeln!(writer, "{nonce}|{value}").unwrap(); +} +fn live(endpoint: &mut Endpoint, writer: &mut UnixStream) { + frame(writer, NONCE, "LIVE|12345"); + endpoint.receive(false).unwrap(); +} +#[test] +fn valid_terminal_and_eof_control() { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame(&mut writer, NONCE, "SETTLED|12345"); + writer.shutdown(Shutdown::Write).unwrap(); + endpoint.receive(false).unwrap(); + assert!(endpoint.settled); +} +#[test] +fn invalid_nonce_is_sticky_across_later_settlement() { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame( + &mut writer, + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "LIVE|12345", + ); + let first = endpoint.receive(false).unwrap_err().to_string(); + frame(&mut writer, NONCE, "SETTLED|12345"); + writer.shutdown(Shutdown::Write).unwrap(); + assert_eq!(endpoint.receive(false).unwrap_err().to_string(), first); + assert!(!endpoint.settled); +} +#[test] +fn unmatched_wait_is_sticky_across_later_settlement() { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame( + &mut writer, + NONCE, + "WAITED|12345|12346|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|0", + ); + let first = endpoint.receive(false).unwrap_err().to_string(); + frame(&mut writer, NONCE, "SETTLED|12345"); + writer.shutdown(Shutdown::Write).unwrap(); + assert_eq!(endpoint.receive(false).unwrap_err().to_string(), first); + assert!(!endpoint.settled); +} +#[test] +fn terminal_requires_eof_before_it_counts_as_settled() { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame(&mut writer, NONCE, "SETTLED|12345"); + endpoint.receive(false).unwrap(); + assert!(!endpoint.settled); + writer.shutdown(Shutdown::Write).unwrap(); + endpoint.receive(false).unwrap(); + assert!(endpoint.settled); +} +#[test] +fn registration_requires_live_owner() { + let (mut endpoint, mut writer) = pair(); + frame( + &mut writer, + NONCE, + "REGISTER|12345|12346|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|1", + ); + assert!(endpoint.receive(false).is_err()); +} +#[test] +fn frame_limit_applies_to_complete_lines() { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame( + &mut writer, + NONCE, + &format!( + "REGISTER|12345|12346|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|{}", + "9".repeat(300) + ), + ); + assert!(endpoint.receive(false).is_err()); +} + +#[test] +fn all_control_faults_poison_owner_and_endpoint() { + for value in ["LIVE|12345", "FAILED|12345", "LIVE|12346", "unknown|12345"] { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame(&mut writer, NONCE, value); + let first = endpoint.receive(false).unwrap_err(); + assert_eq!(endpoint.owner.borrow().first_fault, Some(first)); + assert!(endpoint.owner.borrow().admission_closed); + frame(&mut writer, NONCE, "SETTLED|12345"); + writer.shutdown(Shutdown::Write).unwrap(); + assert_eq!(endpoint.receive(false).unwrap_err(), first); + assert!(!endpoint.is_settled()); + } +} +#[test] +fn trailing_data_never_completes_a_terminal_proof() { + for trailing in [ + "trailing", + "LIVE|12345\n", + "SETTLED|12345\n", + "WAITED|12345\n", + ] { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame(&mut writer, NONCE, "SETTLED|12345"); + endpoint.receive(false).unwrap(); + writer.write_all(trailing.as_bytes()).unwrap(); + writer.shutdown(Shutdown::Write).unwrap(); + assert!(endpoint.receive(false).is_err()); + assert!(!endpoint.is_settled()); + } +} +#[test] +fn eof_before_live_is_cancellation_only_for_parent_role() { + let (mut endpoint, writer) = pair(); + writer.shutdown(Shutdown::Write).unwrap(); + assert!(endpoint.receive(true).unwrap()); + assert!(endpoint.owner.borrow().admission_closed); + assert!(!endpoint.is_settled()); + let (mut endpoint, writer) = pair(); + writer.shutdown(Shutdown::Write).unwrap(); + assert!(endpoint.receive(false).is_err()); +} +#[test] +fn received_cancel_deadline_only_gets_earlier() { + let (mut endpoint, mut writer) = pair(); + for deadline in [100, 200, 50] { + frame(&mut writer, NONCE, &format!("CANCEL|12345|{deadline}")); + assert!(endpoint.receive(true).unwrap()); + } + assert_eq!(endpoint.cancel_deadline_ns(), Some(50)); +} +#[test] +fn shared_owner_fault_blocks_clean_upstream_terminal() { + let owner: SharedOwner = Rc::default(); + let (read, mut peer) = UnixStream::pair().unwrap(); + let mut downstream = + Endpoint::with_owner(read, NONCE.into(), Some(PEER), owner.clone()).unwrap(); + live(&mut downstream, &mut peer); + frame(&mut peer, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "LIVE|12345"); + let first = downstream.receive(false).unwrap_err(); + let (read, mut upstream_peer) = UnixStream::pair().unwrap(); + let mut upstream = Endpoint::with_owner(read, NONCE.into(), None, owner.clone()).unwrap(); + upstream.send_live().unwrap(); + assert!(upstream.send_terminal(true).is_err()); + assert_eq!(owner.borrow().first_fault, Some(first)); + upstream.send_terminal(false).unwrap(); + let mut trace = String::new(); + upstream_peer.read_to_string(&mut trace).unwrap(); + assert!(trace.contains("|FAILED|")); + assert!(!trace.contains("|SETTLED|")); +} +#[test] +fn budgets_are_total_sticky_and_checked_before_increment() { + for (kind, cap) in [ + ("wire", MAX_WIRE), + ("frames", MAX_FRAMES), + ("registrations", MAX_REGISTRATIONS), + ] { + let mut state = OwnerState::default(); + state.charge(kind, cap).unwrap(); + let first = state.charge(kind, 1).unwrap_err(); + assert_eq!(state.charge(kind, 0).unwrap_err(), first); + assert_eq!(state.first_fault, Some(first)); + assert!(state.admission_closed); + } +} +#[test] +fn each_poll_has_fixed_read_and_parse_budgets() { + let (mut endpoint, mut writer) = pair(); + // Exercise a constrained finite transport rather than assuming host socket + // buffering can hold one allocation per small write before the first read. + let bytes: libc::c_int = 8192; + assert_eq!( + unsafe { + libc::setsockopt( + writer.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_SNDBUF, + (&bytes as *const libc::c_int).cast(), + std::mem::size_of_val(&bytes) as libc::socklen_t, + ) + }, + 0 + ); + // One bounded write avoids Linux per-write socket-buffer accounting. All + // 100 frames remain pending before the first receive, as this test requires. + let frames = format!("{NONCE}|CANCEL|12345|100\n").repeat(100); + writer.write_all(frames.as_bytes()).unwrap(); + endpoint.receive(true).unwrap(); + assert!(endpoint.last_poll.reads <= MAX_READS); + assert!(endpoint.last_poll.parsed <= MAX_PARSE); + assert!(endpoint.owner.borrow().frames < 100); + assert!(endpoint.pending.len() <= MAX_PENDING); + // Prove the budget yielded with work left, then consume the complete finite + // input without relaxing the limits or relying on writer packet boundaries. + for _ in 0..100 { + if endpoint.owner.borrow().frames == 100 { + break; + } + endpoint.receive(true).unwrap(); + assert!(endpoint.last_poll.reads <= MAX_READS); + assert!(endpoint.last_poll.parsed <= MAX_PARSE); + assert!(endpoint.pending.len() <= MAX_PENDING); + } + assert_eq!(endpoint.owner.borrow().frames, 100); +} +#[test] +fn live_registration_trace_round_trip_and_shared_budget() { + let owner: SharedOwner = Rc::default(); + let (left, right) = UnixStream::pair().unwrap(); + let mut sender = Endpoint::with_owner(left, NONCE.into(), None, owner.clone()).unwrap(); + let mut receiver = + Endpoint::with_owner(right, NONCE.into(), Some(std::process::id()), owner.clone()).unwrap(); + sender.send_live().unwrap(); + let sent_wire = owner.borrow().wire; + receiver.receive(false).unwrap(); + assert_eq!(owner.borrow().wire, sent_wire * 2); + sender + .metadata(&format!( + "REGISTER|{}|12346|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|1", + std::process::id() + )) + .unwrap(); + receiver.receive(false).unwrap(); + assert_eq!(owner.borrow().registrations, 2); + sender + .metadata(&format!( + "WAITED|{}|12346|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|0", + std::process::id() + )) + .unwrap(); + receiver.receive(false).unwrap(); + assert_eq!(receiver.take_events().len(), 2); + sender.send_terminal(true).unwrap(); + receiver.receive(false).unwrap(); + assert!(receiver.is_settled()); +} +#[test] +fn invalid_or_already_closed_owner_edges_are_refused() { + for owner in ["9999", "12346"] { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame( + &mut writer, + NONCE, + "REGISTER|12345|12346|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|1", + ); + frame( + &mut writer, + NONCE, + "WAITED|12345|12346|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|0", + ); + frame( + &mut writer, + NONCE, + &format!("REGISTER|{owner}|12347|cccccccccccccccccccccccccccccccc|1"), + ); + assert!(endpoint.receive(false).is_err()); + } +} +#[test] +fn malformed_numeric_fields_are_sticky_and_never_echo_raw_input() { + for value in ["--1", "+1", "001", "PRIVATE_CANARY"] { + let (mut endpoint, mut writer) = pair(); + live(&mut endpoint, &mut writer); + frame( + &mut writer, + NONCE, + &format!("REGISTER|{value}|12346|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|1"), + ); + let error = endpoint.receive(false).unwrap_err(); + assert!(!error.to_string().contains(value)); + assert_eq!(endpoint.receive(false).unwrap_err(), error); + } +} + +#[test] +fn constructor_refusal_poisons_supplied_owner() { + let owner: SharedOwner = Rc::default(); + let (left, _right) = UnixStream::pair().unwrap(); + assert!(Endpoint::with_owner(left, "invalid".into(), Some(PEER), owner.clone()).is_err()); + assert_eq!( + owner.borrow().first_fault, + Some(ProtocolError("ENDPOINT_SCHEMA")) + ); + assert!(owner.borrow().check_admission().is_err()); +} + +#[test] +fn shared_wire_contract_vectors() { + let corpus: serde_json::Value = + serde_json::from_str(include_str!("../fixtures/source_qa_protocol_vectors.json")).unwrap(); + assert_eq!(corpus["schema"], 1); + let cases = corpus["cases"].as_array().unwrap(); + assert_eq!(cases.len(), 16); + for case in cases { + let (mut endpoint, mut writer) = pair(); + let parent = case["parent"].as_bool().unwrap(); + let mut fault = false; + for chunk in case["chunks"].as_array().unwrap() { + writer + .write_all(chunk.as_str().unwrap().as_bytes()) + .unwrap(); + fault |= endpoint.receive(parent).is_err(); + } + if case["close_writer"].as_bool().unwrap() { + writer.shutdown(Shutdown::Write).unwrap(); + } + fault |= endpoint.receive(parent).is_err(); + assert_eq!(fault, case["expected"] == "fault", "{}", case["name"]); + assert_eq!( + endpoint.is_settled(), + case["expected"] == "clean", + "{}", + case["name"] + ); + if case["expected"] == "cancel" { + assert!(endpoint.cancelled, "{}", case["name"]); + } + } +} diff --git a/tests/unit/source_qa_scope.rs b/tests/unit/source_qa_scope.rs new file mode 100644 index 0000000..66ec36f --- /dev/null +++ b/tests/unit/source_qa_scope.rs @@ -0,0 +1,456 @@ +use super::*; +use std::cell::RefCell; + +#[test] +fn process_ownership_command_probe_gateway_retains_original_and_inherited_end() { + let mut scope = + crate::process_ownership::scope::Scope::with_owner(Default::default(), 4_000_000_000); + prepare_fixture_scope(&mut scope, || Ok(100_000_000)).unwrap(); + assert_eq!(scope.hard_end(), 1_100_000_000); + prepare_fixture_scope(&mut scope, || Ok(500_000_000)).unwrap(); + assert_eq!(scope.hard_end(), 1_100_000_000); + let mut inherited = + crate::process_ownership::scope::Scope::with_owner(Default::default(), 180_000_000); + prepare_fixture_scope(&mut inherited, || Ok(100_000_000)).unwrap(); + assert_eq!(inherited.hard_end(), 180_000_000); + scope.finish(); + inherited.finish(); +} + +#[test] +fn process_ownership_command_probe_gateway_clock_failure_zeros_and_keeps_first_fault() { + for original in [None, Some(ProtocolError("ORIGINAL"))] { + let mut scope = + crate::process_ownership::scope::Scope::with_owner(Default::default(), 4_000_000_000); + if let Some(fault) = original { + scope.owner_state().borrow_mut().poison(fault); + } + assert!( + prepare_fixture_scope(&mut scope, || Err(io::Error::other("inert clock"))).is_err() + ); + assert_eq!(scope.hard_end(), 0); + assert_eq!( + scope.first_fault(), + original.or(Some(ProtocolError("SCOPE_CLOCK"))) + ); + scope.finish(); + } +} + +#[test] +fn process_ownership_command_probe_gateway_valid_zero_has_positive_original_budget() { + let mut scope = + crate::process_ownership::scope::Scope::with_owner(Default::default(), 4_000_000_000); + prepare_fixture_scope(&mut scope, || Ok(0)).unwrap(); + assert_eq!(scope.hard_end(), 1_000_000_000); + assert_eq!(scope.first_fault(), None); + scope.finish(); +} + +#[derive(Default)] +struct Trace { + calls: Vec<(&'static str, usize, u64)>, +} +struct Fake { + id: usize, + trace: Rc>, + begin_error: bool, + poll_error: bool, + proof: bool, + waited: bool, +} +impl Edge for Fake { + fn begin(&mut self, end: u64) -> io::Result<()> { + self.trace.borrow_mut().calls.push(("begin", self.id, end)); + if self.begin_error { + Err(io::Error::other("synthetic begin")) + } else { + Ok(()) + } + } + fn poll(&mut self) -> io::Result<()> { + self.trace.borrow_mut().calls.push(("poll", self.id, 0)); + if self.poll_error { + Err(io::Error::other("synthetic poll")) + } else { + Ok(()) + } + } + fn proof(&self) -> bool { + self.proof + } + fn waits_known(&self) -> bool { + self.waited + } +} +fn edge(trace: &Rc>, id: usize) -> Fake { + Fake { + id, + trace: trace.clone(), + begin_error: false, + poll_error: false, + proof: false, + waited: false, + } +} +fn registry() -> Registry { + Registry::new(SharedOwner::default(), 10_000_000_000) +} + +#[test] +fn returned_edge_is_registered_before_the_actual_publisher_runs() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let id = r + .admit( + 1, + |_| Ok(edge(&trace, 0)), + |id, slots| { + assert_eq!(slots.len(), 1); + assert_eq!(slots[id.index].id, 0); + Ok(()) + }, + ) + .unwrap(); + assert_eq!(r.slot(&id).unwrap().id, 0); +} + +#[test] +fn failed_publication_keeps_the_real_slot_and_closes_later_admission() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let error = r + .admit( + 1, + |_| Ok(edge(&trace, 0)), + |_, _| Err(io::Error::other("ORIGINAL_RECEIPT")), + ) + .unwrap_err(); + assert_eq!(error.to_string(), "ORIGINAL_RECEIPT"); + assert_eq!(r.slots.len(), 1); + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_PUBLICATION")) + ); + let mut created = false; + assert!(r + .admit( + 2, + |_| { + created = true; + Ok(edge(&trace, 1)) + }, + |_, _| Ok(()) + ) + .is_err()); + assert!(!created); + assert!(trace.borrow().calls.iter().any(|v| v.0 == "begin")); +} + +#[test] +fn broadcasts_every_slot_before_any_poll_even_when_first_begin_fails() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let mut first = edge(&trace, 0); + first.begin_error = true; + r.slots.extend([first, edge(&trace, 1), edge(&trace, 2)]); + r.begin(10, 500); + assert_eq!( + trace.borrow().calls, + [("begin", 0, 500), ("begin", 1, 500), ("begin", 2, 500)] + ); + r.poll(); + assert_eq!( + trace + .borrow() + .calls + .iter() + .filter(|v| v.0 == "poll") + .count(), + 3 + ); +} + +#[test] +fn one_poll_failure_cannot_skip_known_sibling_wait_collection_or_clear_slots() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let mut first = edge(&trace, 0); + first.poll_error = true; + let mut second = edge(&trace, 1); + second.waited = true; + r.slots.extend([first, second]); + r.poll(); + assert_eq!(trace.borrow().calls, [("poll", 0, 0), ("poll", 1, 0)]); + assert_eq!(r.slots.len(), 2); +} + +#[test] +fn cleanup_bound_can_only_decrease_and_begin_does_not_wait() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + r.slots.push(edge(&trace, 0)); + r.begin(1, 500); + r.begin(100, 800); + r.begin(200, 300); + assert_eq!(r.cleanup_end, Some(300)); + assert_eq!(trace.borrow().calls, [("begin", 0, 500), ("begin", 0, 300)]); +} + +#[test] +fn waited_but_unproven_slot_is_retained_for_failed_final_report() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let mut first = edge(&trace, 0); + first.waited = true; + r.slots.push(first); + r.poll(); + assert_eq!(r.slots.len(), 1); + assert!(!r.slots[0].proof()); +} + +#[test] +fn cancelled_owner_never_calls_factory_and_foreign_slot_cannot_target_another_registry() { + let mut a = registry(); + let mut b = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let id = a.admit(1, |_| Ok(edge(&trace, 0)), |_, _| Ok(())).unwrap(); + assert!(b.slot(&id).is_err()); + b.owner.borrow_mut().admission_closed = true; + let mut called = false; + assert!(b + .admit( + 1, + |_| { + called = true; + Ok(edge(&trace, 1)) + }, + |_, _| Ok(()) + ) + .is_err()); + assert!(!called); +} + +#[test] +fn slot_limit_refuses_before_factory_and_preserves_first_owner_fault() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + for id in 0..MAX_REGISTRATIONS { + r.slots.push(edge(&trace, id)); + } + let mut called = false; + assert!(r + .admit( + 1, + |_| { + called = true; + Ok(edge(&trace, 9999)) + }, + |_, _| Ok(()) + ) + .is_err()); + assert!(!called); + assert_eq!(r.slots.len(), MAX_REGISTRATIONS); + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_SLOT_LIMIT")) + ); +} + +#[test] +fn constructor_failure_cancels_already_retained_sibling_without_losing_original_error() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + r.slots.push(edge(&trace, 0)); + let error = r + .admit( + 10, + |_| Err(io::Error::other("ORIGINAL_SPAWN")), + |_, _| Ok(()), + ) + .unwrap_err(); + assert_eq!(error.to_string(), "ORIGINAL_SPAWN"); + assert_eq!(r.slots.len(), 1); + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_SPAWN")) + ); + assert_eq!(trace.borrow().calls[0].0, "begin"); +} + +#[test] +fn successful_finish_needs_proof_and_waits_under_the_same_fresh_bound() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let mut first = edge(&trace, 0); + first.waited = true; + r.slots.push(first); + r.begin(10, 500); + assert!(!r.finish_at(100)); + r.slots[0].proof = true; + assert!(r.finish_at(101)); + let before = trace.borrow().calls.clone(); + r.begin(200, 900); + assert_eq!(trace.borrow().calls, before); + assert_eq!(r.cleanup_end, Some(500)); + assert!(r.owner.borrow().first_fault.is_none()); +} + +#[test] +fn expired_finish_retains_all_slots_and_never_upgrades_on_late_proof() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + r.slots.push(edge(&trace, 0)); + r.begin(10, 500); + assert!(r.finish_at(500)); + r.slots[0].waited = true; + r.slots[0].proof = true; + r.poll(); + assert!(r.finish_at(501)); + assert_eq!(r.slots.len(), 1); + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_CLEANUP_DEADLINE")) + ); +} + +#[test] +fn already_complete_group_facts_do_not_bypass_expired_scope_finish() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let mut first = edge(&trace, 0); + first.waited = true; + first.proof = true; + r.slots.push(first); + r.begin(10, 500); + assert!(r.finish_at(501)); + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_CLEANUP_DEADLINE")) + ); +} + +#[test] +fn prior_owner_cause_survives_all_cleanup_faults_and_secondary_codes_are_bounded() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + r.owner + .borrow_mut() + .poison(ProtocolError("ORIGINAL_RECEIPT")); + let mut first = edge(&trace, 0); + first.begin_error = true; + first.poll_error = true; + r.slots.push(first); + r.begin(10, 500); + r.poll(); + for _ in 0..20 { + r.poison("LATER_CLEANUP"); + } + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("ORIGINAL_RECEIPT")) + ); + assert_eq!( + r.secondary_faults, + [ + ProtocolError("SCOPE_BEGIN"), + ProtocolError("SCOPE_POLL"), + ProtocolError("LATER_CLEANUP") + ] + ); +} + +#[test] +fn expired_admission_is_irreversible_and_broadcasts_to_retained_slots() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + r.slots.push(edge(&trace, 0)); + let mut created = false; + assert!(r + .admit( + r.hard_end, + |_| { + created = true; + Ok(edge(&trace, 1)) + }, + |_, _| Ok(()) + ) + .is_err()); + assert!(!created); + assert!(r.owner.borrow().admission_closed); + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_ADMISSION")) + ); + assert_eq!(trace.borrow().calls[0].0, "begin"); +} + +#[test] +fn sealed_finished_bound_is_not_silently_shortened_or_rebroadcast() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let mut first = edge(&trace, 0); + first.waited = true; + first.proof = true; + r.slots.push(first); + r.begin(10, 500); + assert!(r.finish_at(100)); + let before = trace.borrow().calls.clone(); + r.begin(110, 200); + assert_eq!(trace.borrow().calls, before); + assert_eq!(r.cleanup_end, Some(500)); + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("SCOPE_BOUND_SEALED")) + ); +} + +#[test] +fn ordinary_publisher_unwind_keeps_the_inserted_slot_for_explicit_failure_cleanup() { + let mut r = registry(); + let trace = Rc::new(RefCell::new(Trace::default())); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = r.admit( + 1, + |_| Ok(edge(&trace, 0)), + |_, _| panic!("synthetic publisher"), + ); + })); + assert!(result.is_err()); + assert_eq!(r.slots.len(), 1); + r.poison("PUBLISHER_UNWIND"); + r.begin(2, 500); + r.poll(); + assert_eq!(trace.borrow().calls, [("begin", 0, 500), ("poll", 0, 0)]); + assert_eq!(r.slots.len(), 1); + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("PUBLISHER_UNWIND")) + ); + // This finite seam tests retention across unwind, not actual public Drop + // or a process-cleanup proof. The latter requires the real API OS actor. +} + +#[test] +fn distinct_secondary_faults_stop_at_eight_without_replacing_the_original() { + let mut r = registry(); + r.poison("ORIGINAL"); + let reasons = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]; + for reason in reasons { + r.poison(reason); + } + assert_eq!( + r.owner.borrow().first_fault, + Some(ProtocolError("ORIGINAL")) + ); + assert_eq!( + r.secondary_faults, + reasons[..8] + .iter() + .copied() + .map(ProtocolError) + .collect::>() + ); + r.poison("A"); + assert_eq!(r.secondary_faults.len(), 8); +}