croft-software 0.2.3

VSCode-style TUI written in Rust
name: CI

# The gates that used to exist only as habit on one Mac.
#
# The cross-build jobs are the point. `croft <host>` cross-compiles a static
# binary locally and ships it; when the pinned toolchain lacks a target, that
# path silently degrades to a full `cargo install` on the user's box, with
# nothing but a line in ~/.cache/croft/install.log to say so. Rustup targets
# belong to ONE toolchain, so bumping rust-toolchain.toml orphans every one of
# them - which is what the 1.95.0 -> 1.97.1 bump did, unnoticed for four days.
#
# These jobs run the REAL build (zig for musl, the NDK for Android), not
# `cargo check`: croft's tree-sitter grammars are C, so their build scripts
# need a working cross C compiler and a check alone fails before it can prove
# anything useful.

on:
  push:
    branches: [main]
  pull_request:

# Every job here only reads the checkout; none writes to the repo, its issues
# or its PRs. Without this the token gets the repository default, which can be
# read-write. A job that ever needs more asks for it in its own block.
permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  release-hygiene:
    # Every merge that changes what ships must be a release in its own right
    # (#281): the version increments (two different binaries must never share
    # a version and differ only in commit hash), and src/release_notes/<version>.md
    # exists and says something, so the welcome panel's "IN THIS RELEASE" card
    # describes THIS version instead of silently carrying the previous
    # release's story. One file per version (#399) so two open PRs describing
    # different changes never collide on the same file.
    # Docs / CI / test-only changes ship nothing and are exempt, including a
    # diff confined to a `#[cfg(test)]` module inside a shipped file (#461).
    name: version bump + release notes
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    # This job now runs a SCRIPT from the submitted branch, which the inline
    # shell above it never did, so it takes the same posture the doc-ownership
    # job below documents: only what it needs to read the diff, and no
    # checkout token left in the local git config for that script to reach.
    #
    # Pinning the script to the base revision instead would buy nothing on
    # this trigger: `pull_request` runs the workflow file from the merge of
    # the branch, so a PR that wanted to neuter the gate would edit the job
    # rather than the helper it calls. What is worth removing is the
    # CREDENTIAL, not the ability to run branch code.
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v7
        with:
          # Full history so the merge-base with the PR base resolves.
          fetch-depth: 0
          persist-credentials: false
      - name: Shipped changes must bump the version and replace the notes
        run: |
          set -euo pipefail
          base="$(git merge-base "origin/$GITHUB_BASE_REF" HEAD)"
          # --no-renames: git collapses a rename to its destination alone, so
          # `git mv 0.1.808.md 0.1.809.md` would look like "wrote this
          # version's notes" while destroying the previous release's. Split
          # into a delete plus an add, the stale guard below sees the delete.
          changed="$(git diff --no-renames --name-only "$base" HEAD)"
          # What ships in the binary: sources, baked-in assets, the build
          # script, and the dependency set. src/app/tests.rs and tests/ are
          # compiled out of release builds.
          shipped="$(printf '%s\n' "$changed" \
            | grep -E '^(src/|assets/|build\.rs$|Cargo\.toml$|Cargo\.lock$)' \
            | grep -vE '^(src/app/tests\.rs|tests/)' || true)"
          # A `.rs` file whose diff touches nothing outside a
          # `#[cfg(test)] mod tests` produces a byte-identical binary, and
          # croft keeps most unit tests beside the code they cover, so that
          # is the ordinary shape of a test-only fix here (#461). The path
          # list above only reaches whole test FILES. Anything the parse is
          # unsure about counts as shipped: waiving a bump that was needed
          # puts two binaries on one version, which is what this job exists
          # to prevent.
          # Read the list a line at a time rather than word-splitting it: an
          # unquoted `for f in $shipped` also expands globs, so a path
          # holding `[`, `*` or `?` would reach the filter as a pathspec git
          # cannot resolve, and a path holding a space would arrive as two.
          kept="$(mktemp)"
          trap 'rm -f "$kept"' EXIT
          while IFS= read -r f; do
            [ -n "$f" ] || continue
            if python3 scripts/ships_nothing.py "$base" HEAD "$f"; then
              # The status says "ships nothing"; it does not say why, and the
              # script has more than one way to reach it. Claiming the reason
              # here asserted "confined to #[cfg(test)]" about files that had
              # no test module at all.
              echo "$f: ships nothing."
            else
              printf '%s\n' "$f" >> "$kept"
            fi
          done <<< "$shipped"
          shipped="$(cat "$kept")"
          if [ -z "$shipped" ]; then
            echo "No shipped files changed; no release required."
            exit 0
          fi
          echo "Shipped files changed:"
          printf '  %s\n' "$shipped"
          ver() { git show "$1:Cargo.toml" | sed -n 's/^version *= *"\([0-9.]*\)".*/\1/p' | head -n1; }
          old="$(ver "$base")"
          new="$(ver HEAD)"
          fail=0
          highest="$(printf '%s\n%s\n' "$old" "$new" | sort -t. -k1,1n -k2,2n -k3,3n | tail -n1)"
          if [ "$new" = "$old" ] || [ "$highest" != "$new" ]; then
            echo "::error file=Cargo.toml::This PR changes shipped files but the version is still $old. Bump it (base: $old, head: $new) - two binaries must never share a version and differ only in commit hash."
            fail=1
          fi
          # Versions count like an odometer, the same rule as code-graph-rag:
          # MINOR and PATCH stay below 1000, and a bump that reaches 1000
          # carries into the next component and resets the lower ones, so
          # 0.1.999 is followed by 0.2.0 and never by 0.1.1000. A base already
          # past the cap carries on its next bump the same way.
          if ! python3 scripts/next_version.py --check "$new"; then
            next="$(python3 scripts/next_version.py "$old" 2>/dev/null || true)"
            echo "::error file=Cargo.toml::Version $new has a component at or above 1000. MINOR and PATCH stay below 1000 and carry into the next component, like an odometer; the next version after $old is ${next:-unknown} (python3 scripts/next_version.py $old)."
            fail=1
          fi
          # One notes file per version (#399): the check is that THIS version's
          # file exists and says something, not that a shared file was touched.
          # Two PRs adding different versions' notes then never collide.
          notes="src/release_notes/$new.md"
          # AUTHORSHIP, not merely existence. A file for this version can
          # already be on main - left behind by a revert that dropped the
          # code but not the notes - and a bump onto it would pass while the
          # panel advertised a release the binary does not contain. This PR
          # has to have written it.
          if ! printf '%s\n' "$changed" | grep -qx "$notes"; then
            echo "::error file=$notes::This PR changes shipped files but does not write $notes. Write this version's highlights there, one per line, each prefixed 'feature:' or 'fix:', so the welcome panel describes the binary it is in. A file left on main by an earlier revert does not count."
            fail=1
          elif ! git cat-file -e "HEAD:$notes" 2>/dev/null; then
            echo "::error file=$notes::$notes was changed but does not exist at HEAD. This version's notes cannot be the file the PR deleted."
            fail=1
          elif [ -z "$(git show "HEAD:$notes" | tr -d '[:space:]')" ]; then
            echo "::error file=$notes::$notes is empty. Write this version's highlights there, one per line, each prefixed 'feature:' or 'fix:'."
            fail=1
          fi
          # A shipped release describes itself and nothing else: editing an
          # older version's notes rewrites what a binary already out there
          # claims to be.
          stale="$(printf '%s\n' "$changed" | grep -E '^src/release_notes/[0-9.]+\.md$' | grep -v "^$notes$" || true)"
          if [ -n "$stale" ]; then
            echo "Notes for other versions were modified:"
            printf '  %s\n' $stale
            echo "::error::A release's notes describe that release. Only $notes may change in this PR."
            fail=1
          fi
          exit $fail

  doc-ownership:
    # Rust attaches a `///` block to whatever item FOLLOWS it, so inserting a
    # function between an existing one and its doc silently hands that prose to
    # the newcomer (#314). Nothing else here reports it: the build stays green,
    # clippy is silent, and the rendered rustdoc is confidently WRONG rather
    # than absent - which stops a reader looking, where absent docs would have
    # sent them to the code. It has happened twice on one branch, and a sweep
    # of recent history found four more that had shipped.
    #
    # The snapshot is undetectable (well-formed prose above a plausible
    # function) but the diff is not: a function that had a doc and now has none
    # is the exact fingerprint. Validated against both known instances.
    name: doc comments stay with their function
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    # This job runs a script FROM the submitted branch, so a PR can change what
    # executes here. Give it only what it needs to read the diff, and keep the
    # checkout token out of the local git config where that script could reach
    # it.
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v7
        with:
          # Full history so the merge-base with the PR base resolves.
          fetch-depth: 0
          persist-credentials: false
      - name: No function may lose its doc comment
        run: |
          set -euo pipefail
          base="$(git merge-base "origin/$GITHUB_BASE_REF" HEAD)"
          python3 scripts/check_doc_ownership.py "$base" HEAD
      # ARCHITECTURE.md's tree carries the reasons behind each module, and a
      # rewrite can cut a line's rationale away while the row and its
      # identifiers survive - which is what a row-level or identifier-level
      # check sees as a pass. This one compares per-module description
      # length and asks for a `### <module>` section wherever one shrank.
      - name: No module may lose its reasoning
        run: |
          set -euo pipefail
          base="$(git merge-base "origin/$GITHUB_BASE_REF" HEAD)"
          python3 scripts/check_arch_content.py "$base"

      - name: binstall metadata must match what release.yml builds
        # Cargo.toml's pkg-url and bin-dir are resolved by `cargo binstall` at
        # INSTALL time, so drift between them and the release workflow is
        # invisible to every other job here and lands on users as a 404 or a
        # "corrupt download". Nothing else compares the two files (#376).
        run: python3 scripts/check_binstall_contract.py

  test:
    name: clippy + tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      # The suite's terminal tests drive /bin/zsh (the shim they exist to
      # cover) and the PDF tests rasterise through poppler's pdftoppm - the
      # same binaries croft needs at runtime on a Linux box. The runner
      # ships neither.
      - name: Install suite runtime dependencies
        # The chmod keeps compinit's "insecure directories" interactive
        # prompt from wedging every spawned zsh before its first prompt
        # (croft never calls compinit; the runner's own zsh startup does).
        run: |
          set -euo pipefail
          # `apt-get update && apt-get install` looked equivalent and was not
          # (#549). A command on the LEFT of an `&&` is exempt from `set -e`
          # by design, so when `update` failed on a THIRD-PARTY index the
          # runner image ships and croft does not need (a Chrome repo hash
          # mismatch), the install was skipped, this step still went green,
          # and eight PDF tests failed minutes later with "these tests need a
          # PDF rasteriser" on a PR that touches no PDF code.
          #
          # A partial index failure must not decide whether the install runs:
          # apt resolves these two packages from the indexes it did fetch.
          # A transient mirror hiccup is what set #549 off in the first
          # place, and the install below is what actually gates the step, so
          # retry before giving up on the index refresh.
          for attempt in 1 2 3; do
            sudo apt-get update && break
            echo "::warning::apt-get update failed (attempt $attempt)"
            sleep 5
          done
          sudo apt-get install -y --no-install-recommends zsh poppler-utils
          # Without this the step can only report that it RAN, not that it
          # worked, and those are the same colour.
          #
          # Each tool is probed the way ITS CONSUMER resolves it, which is not
          # the same question for the two of them. `pdf::which` walks PATH, so
          # `command -v` is right (and stricter: it also wants the executable
          # bit). The terminal tests take `/bin/zsh` by literal path and SKIP
          # when it is missing, so a zsh present only elsewhere on PATH would
          # pass a `command -v` probe and leave those tests silently
          # uncovered - the same false green this step exists to remove, moved
          # one level up. It holds today only because usrmerge symlinks /bin.
          command -v pdftoppm >/dev/null \
            || { echo "::error::pdftoppm is missing after the install step"; exit 1; }
          [ -x /bin/zsh ] \
            || { echo "::error::/bin/zsh is missing after the install step"; exit 1; }
          for d in /usr/share/zsh /usr/local/share/zsh; do
            if [ -d "$d" ]; then sudo chmod -R go-w "$d"; fi
          done
      # rust-toolchain.toml is the single source of truth; `rustup show`
      # installs exactly the pinned channel and its components.
      - name: Install the pinned toolchain
        run: rustup show
      - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
      - name: Formatting (pinned rustfmt, zero diffs)
        run: cargo fmt --check
      - name: Clippy (zero warnings)
        run: cargo clippy --all-targets -- -D warnings
      - name: Issue-vetting script tests (stdlib, no venv)
        run: python3 -m unittest discover -s scripts/tests -v
      - name: Tests
        # The suite spawns PTYs and real shells; keep the thread count modest
        # so the timing-sensitive terminal tests are not starved.
        run: cargo test --locked
        env:
          RUST_TEST_THREADS: 4
      - name: fs-sync 200 ms invariant (serial, wall clock)
        # The #[ignore]d wall-clock test (see
        # fs_sync_reflects_external_changes_within_200ms_wall_clock in
        # src/app/tests.rs for why it runs alone, #483). The filter is coupled
        # to that name by nothing but convention, and a filter that selects
        # no test exits 0, so the step requires the bin target to report
        # exactly one test before it counts as run.
        run: |
          set -euo pipefail
          cargo test --locked --bin croft fs_sync_reflects -- --ignored --test-threads=1 2>&1 | tee target/fs-sync.log
          grep -q '^running 1 test$' target/fs-sync.log \
            || { echo "::error::fs_sync_reflects selected no test: the filter and the test name have drifted"; exit 1; }

  cross-musl:
    name: ship-path build (${{ matrix.target }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        # CROSS_TARGETS in src/cli.rs: the triples `croft <host>` ships.
        target:
          - x86_64-unknown-linux-musl
          - aarch64-unknown-linux-musl
    steps:
      - uses: actions/checkout@v7
      - name: Install the pinned toolchain
        run: rustup show
      - name: Add the target to the PINNED toolchain
        # Run from the checkout so rust-toolchain.toml resolves the channel.
        # Adding to the default toolchain instead is precisely the bug this
        # job exists to catch.
        run: rustup target add ${{ matrix.target }}
      - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
        with:
          key: ${{ matrix.target }}
      - name: Install zig and cargo-zigbuild
        # cargo-zigbuild probes `python3 -m ziglang` before looking for a zig
        # binary on PATH. Recent runner images mark the system Python as
        # externally managed, so pip needs the override.
        run: |
          python3 -m pip install --break-system-packages ziglang \
            || python3 -m pip install ziglang
          python3 -m ziglang version
          cargo install cargo-zigbuild --locked
      # Byte-for-byte the command src/remote.rs runs for a remote install.
      - name: cargo zigbuild --profile remote-fast
        run: cargo zigbuild --profile remote-fast --locked --bin croft --target ${{ matrix.target }}
      - name: The shipped artifact must exist and be a Linux ELF for its target
        # The architecture, not only the container format: `ELF 64-bit LSB`
        # is true of both musl legs, so an aarch64 build that fell back to the
        # host would pass as x86-64 (#556). Same recipe as release.yml's check.
        run: |
          set -euo pipefail
          bin="target/${{ matrix.target }}/remote-fast/croft"
          test -x "$bin" || { echo "::error::no artifact at $bin"; exit 1; }
          file "$bin"
          case "${{ matrix.target }}" in
            x86_64-unknown-linux-musl)  file "$bin" | grep -qE 'ELF 64-bit LSB.*x86-64' ;;
            aarch64-unknown-linux-musl) file "$bin" | grep -qE 'ELF 64-bit LSB.*aarch64' ;;
            # A `case` with no match exits 0; a new matrix target must add
            # its own assertion rather than pass unchecked.
            *) echo "::error::no artifact-kind assertion for ${{ matrix.target }}"; exit 1 ;;
          esac

  android:
    name: Android build (aarch64-linux-android)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - name: Install the pinned toolchain
        run: rustup show
      - name: Add the Android target to the PINNED toolchain
        run: rustup target add aarch64-linux-android
      - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
        with:
          key: aarch64-linux-android
      - name: Install cargo-ndk
        run: cargo install cargo-ndk --locked
      # Termux builds croft natively on the phone, so nothing ships this
      # artifact. Compiling it here is what catches code that cannot build on
      # Android at all - otherwise the only way to find out is on the device,
      # by hand, after the fact. cargo-ndk wires the runner's NDK into the C
      # build scripts the tree-sitter grammars need.
      - name: cargo ndk build
        # ANDROID_NDK_LATEST_HOME is exported by the runner image into the
        # process environment, which the `env` context does NOT see - so it
        # has to be expanded by the shell, not by an expression.
        # --platform 24: bionic only exports openpty/forkpty from API 23,
        # and cargo-ndk's default level is older, so the link dies on
        # `undefined symbol: openpty`. 24 is what Termux itself targets.
        run: |
          export ANDROID_NDK_HOME="$ANDROID_NDK_LATEST_HOME"
          echo "Using NDK at $ANDROID_NDK_HOME"
          test -d "$ANDROID_NDK_HOME"
          cargo ndk --target arm64-v8a --platform 24 build --locked --bin croft