diff --git a/.ci/review-evidence-ijson-jcs.pin b/.ci/review-evidence-ijson-jcs.pin new file mode 100644 index 00000000..b495f03a --- /dev/null +++ b/.ci/review-evidence-ijson-jcs.pin @@ -0,0 +1 @@ +1735d68768920f6f59667c9ba2c84769d8d45336 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b0b4d856..b1f87be4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -361,6 +361,8 @@ jobs: test/workflow_test.exs \ test/review_observation_test.exs \ test/review_github_collector_test.exs \ + test/review_evidence_test.exs \ + test/review_check_run_collector_test.exs \ test/egress_decision_mirror_test.exs \ test/deed_test.exs \ test/kyaml_test.exs \ @@ -582,6 +584,64 @@ jobs: - name: Hold Hypatia.Kyaml to the YAML test suite run: YAML_TEST_SUITE=.yts mix test --only yaml_test_suite + # ============================================================================ + # S-03 review evidence: separately pinned I-JSON/JCS differential + # ============================================================================ + # A restricted ASCII/no-number E0 encoder is only canonical for that subset. + # This gate requires the authoritative parser's strict positive/negative + # tests, library-vs-estate LF distinction and JSONL framing; no silent skip. + review-evidence-jcs: + name: Review evidence JCS differential (pinned) + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + steps: + - name: Checkout Hypatia + uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + + - name: Checkout source-pinned I-JSON/JCS + uses: actions/checkout@v7.0.1 + with: + repository: hyperpolymath/ijson-jcs + ref: 1735d68768920f6f59667c9ba2c84769d8d45336 + path: .ijson-jcs + persist-credentials: false + + - name: Setup source-compatible Rust toolchain + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: '1.99.1' + + - name: Setup Elixir/OTP + uses: erlef/setup-beam@v1.24.1 + with: + elixir-version: '1.19.4' + otp-version: '27.3.4.19' + + - name: Fetch Elixir dependencies + run: mix deps.get + + - name: Compile review admission and evidence encoder + run: mix compile --warnings-as-errors + + # Cargo treats a nested Rust package as part of Hypatia's workspace. + # Copy the already checked-out, pinned Git tree to a temporary sibling: + # no edits to either Cargo.toml, Cargo.lock, or the source checkout. + - name: Isolate pinned canonicaliser from Hypatia Cargo workspace + run: cp -a .ijson-jcs "$RUNNER_TEMP/ijson-jcs-review-source" + + - name: Compile JCS binary from exactly pinned source and lockfile + run: cargo build --release --locked --manifest-path "$RUNNER_TEMP/ijson-jcs-review-source/Cargo.toml" --bin ijson-jcs + + - name: Differential and failure-mode checks + env: + HYPATIA_IJSON_JCS_SOURCE: ${{ runner.temp }}/ijson-jcs-review-source + HYPATIA_IJSON_JCS_BIN: ${{ runner.temp }}/ijson-jcs-review-source/target/release/ijson-jcs + run: bash scripts/check-review-evidence-ijson-jcs.sh + # ============================================================================ # Combined Status Check # ============================================================================ @@ -602,6 +662,7 @@ jobs: - elixir-compile - elixir-format - kyaml-conformance + - review-evidence-jcs if: always() steps: - name: Check all jobs status @@ -610,7 +671,7 @@ jobs: run: | set -euo pipefail mandatory=(rust-check rust-fmt rust-test rust-test-coverage detect-haskell - k9iser-validate elixir-compile elixir-format kyaml-conformance) + k9iser-validate elixir-compile elixir-format kyaml-conformance review-evidence-jcs) for job in "${mandatory[@]}"; do result=$(jq -r --arg job "$job" '.[$job].result // "missing"' <<< "$NEEDS_JSON") if [[ "$result" != success ]]; then diff --git a/README.adoc b/README.adoc index 26e83de9..a05ed0cf 100644 --- a/README.adoc +++ b/README.adoc @@ -76,7 +76,7 @@ PatternRegistry ──> TriangleRouter ──> FleetDispatcher ──> DispatchM [cols="1,3"] |=== -| `lib/` | 176 Elixir source files — pipeline, rules, VCL, neural, safety, web, merge orchestration +| `lib/` | 179 Elixir source files — pipeline, rules, VCL, neural, safety, web, merge orchestration | `lib/rules/` | 44 source files: rule modules and their helpers; see link:docs/rules/catalogue.adoc[the catalogue] | `lib/neural/` | 8 networks + blackboard, coordinator, persistence, rebalancer | `lib/vcl/` | VCL query layer over verisim-data: parser, file executor, cache, federation @@ -153,7 +153,7 @@ hypatia help ---- Mix tasks cover the operational surface — `mix hypatia.rsr_score`, `mix hypatia.recipe_health`, -`mix hypatia.watch`, `mix hypatia.triage_issues` and sixteen more. See the +`mix hypatia.watch`, `mix hypatia.triage_issues` and seventeen more. See the https://github.com/hyperpolymath/hypatia/wiki/Operations[Operations wiki page]. Running the supervision tree also serves an HTML dashboard, an SSE event stream, a Prometheus diff --git a/docs/design/2026-11-23-review-check-run-intake.adoc b/docs/design/2026-11-23-review-check-run-intake.adoc new file mode 100644 index 00000000..33f8f50c --- /dev/null +++ b/docs/design/2026-11-23-review-check-run-intake.adoc @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += S-04: GitHub Checks API intake for pre-commit.ci +:date: 2026-11-23 +:toc: + +== Purpose + +This implements a *read-only, external-check assertion* boundary for +pre-commit.ci and deliberately remains separate from review comments. +The parent is https://github.com/hyperpolymath/hypatia/pull/1220[#1220]. +This adapter **does not** trigger pre-commit.ci, rerun jobs, autofix, +post a comment, approve a merge, or authorise Bayesian learning. + +For an operational, read-only inspection of one PR, run: + +---- +mix hypatia.review_check_collect --repo stuff-of-awe/awesome-zig --pr 20 +---- + +The command reports exact source IDs and native statuses only. It neither +writes receipts nor runs the hooks. A missing check is explicitly +"NOT OBSERVED", not success, compliance or a checked installation. + +The upstream ReviewObservation.admit/2 already permits provider +pre-commit.ci with scope hooks. The new collector emits those observations +through a distinct GitHub native Check Runs API intake. + +== Verified provider identity + +The authenticated GitHub Get App endpoint +(https://docs.github.com/en/rest/apps/apps[GitHub Apps REST]) returned +numeric app ID 68672 for slug pre-commit-ci on 2026-11-23. + +Matching is conjunctive: + +* native check.app.id exactly 68672; +* native check.app.slug exactly pre-commit-ci; +* native check.name exactly pre-commit.ci - pr; +* native check.head_sha equals the current PR head after full validation. + +An arbitrary repository workflow merely named pre-commit.ci - pr +is **not** the provider. An unknown app, renamed run, absent check, +or checks not executed on that commit is unknown, never an inferred pass. + +Only the strict native state and conclusion vocabulary is preserved. +The API-reported source event ID has prefix github:check_run: and the +positive native check-run ID. The source locator is the validated GitHub +PR permalink: the external details_url is untrusted and intentionally +not forwarded as evidence. + +== Retrieval and consistency + +The adapter reads the PR via GitHub REST, checks its number, base repo +and 40-hex head, then retrieves every check-run page using +per_page=100 and filter=all, re-reads the inventory, and validates +the head again. + +The API total_count is reconciled with retrieved count; incomplete +pagination, duplicate IDs, invalid record shapes, API failures, +full final pages at budget, shifted inventories and moved PR heads +all fail closed. + +No GitHub API can supply an atomic cross-endpoint PR/check-run +snapshot. Repeated agreement is observation, not a transaction. + +The default is five 100-item pages and an absolute budget of ten; +no cursor is silently ignored. Even a zero-item response has +coverage_verdict=not_established and provider_observed=false. +This describes *observed* check runs, not installation state. + +== Admitted verdicts + +A completed pre-commit.ci check with conclusion success is a +**provider-reported success**, not independent evidence that every +hook ran or that the repository is defect-free. The native conclusion +is carried separately as check_conclusion. + +The review-observation representation uses has_findings=nil for +all check conclusions because GitHub's Checks API status alone +contains no structured hook finding count. The provider's +completed status does not become a clean review; finding_signal +remains unknown and qualification unqualified. + +Failure/neutral/skipped/cancelled/timed_out/action_required and +startup_failure outcomes are likewise preserved as bounded +external assertions without inventing underlying defects. +All admitted records have learning_eligible=false and +merge_approval=false. + +This adapter is not yet merged into the S-03 JSON evidence envelope. +A future versioned envelope union will need its own strict +check-run schema and pinned JCS differential fixtures. It must +not replace the existing permitted S-03 fields or broaden +the E0 learning receipt as a shortcut. + +== Live availability and tests + +A GET-only reconnaissance of five pilot PR heads across four estate +organisations plus Hypatia #1220 found **no matching pre-commit.ci +check run** as of this check. That is evidence of absence of matching +check-run events *on those heads*, not proof that the provider is +uninstalled or that checks passed. + +test/review_check_run_collector_test.exs contains injected API +fixtures for native app-name spoofing, successful/failed/running +and skipped conclusions, incomplete and shifting pagination, +duplicate or invalid check-run IDs, malformed subjects, +stale/moved heads and absent providers. + +A real positive end-to-end provider check will be required before +classifying this adapter as operationally verified beyond +negative-source cases. Do not generate paid reviews or cause +autofix commits merely to populate a test. diff --git a/docs/design/2026-11-23-review-evidence-envelope.adoc b/docs/design/2026-11-23-review-evidence-envelope.adoc new file mode 100644 index 00000000..5c377d4b --- /dev/null +++ b/docs/design/2026-11-23-review-evidence-envelope.adoc @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += S-03: restricted review-evidence envelope +:author: Jonathan D.A. Jewell +:date: 2026-11-23 +:toc: + +== Purpose + +This is a *separate stage* after external-source admission in +https://github.com/hyperpolymath/hypatia/pull/1216[PR #1216]. It adds an +in-memory, deterministic **evidence envelope**, not an E0 learning receipt +and not a replacement for external code/security review. Programme +https://github.com/hyperpolymath/hypatia/issues/1217[#1217] tracks the +corresponding S-03 work. + +The upstream collector has the following limited promise: + +---- +GitHub REST -> repeated observation -> unqualified admission -> envelope +---- + +Two reads of a paginated REST inventory cannot provide database snapshot +isolation. A stable read is an observation of repeated agreement, not a +cryptographic or transactional guarantee. + +== Profile and byte contract + +Hypatia.ReviewEvidence.build/2 only accepts a complete, versioned +collector map with source github_rest_via_gh, provenance +github_api_observed, coverage bot_comment_and_review_submissions_only, +and collection mode repeated_stable_observation. The caller must provide +a **full lowercase 40-hex collector source revision**. This is a label, +not proof of deployment or attestation of source integrity. + +Every admitted observation is reconstructed and revalidated through +Hypatia.ReviewObservation.admit/2. An extra authority-bearing field, +unrecognised source event, changed subject, forged verdict, duplicate +source-event ID, missing content or contradictory assessment fails the +whole envelope. Only an allowlisted set of evidence fields survives. +No free-text bot content, patches, model instructions or credentials +are copied into the envelope. + +Hypatia.ReviewEvidence.canonical/2 delegates byte generation to the +*existing* E0 Hypatia.Receipt.encode/1, but in its restricted +**ASCII/no-JSON-numbers** profile. It returns separately: + +* library_bytes: deterministic encoded JSON with **no final LF**; +* file_record_bytes: those bytes followed by **exactly one LF**; +* library_sha256: SHA-256 of the **library bytes only**. + +Counters and PR numbers are decimal strings in this profile. +The result is explicitly qualified as +requires_ijson_jcs_differential: output has NOT yet been checked +against the authoritative pinned Rust hyperpolymath/ijson-jcs +implementation. A digest cannot establish producer identity, successful +reviewer execution, a genuine finding or eligibility for learning. + +This stage has **no disk writer, append-only ledger or signature**. +No JSONL file is created and no E0 Receipt.write/3 learning operation is +called. The E0 receipt chain remains separate. + +== Fail-closed semantics + +[cols="2,3",options="header"] +|=== +|Case |Outcome + +|Root map contains unexpected keys, or unsupported collection source +|Error; no envelope + +|Malformed revision, PR number, head SHA, or count +|Error; no envelope + +|Wrong subject/ref, manipulated review approval or qualification +|Error; no envelope + +|Unrecognised observation fields or fake provider completion +|Error; no envelope + +|Two events claim the same source ID +|Error; no envelope + +|Non-ASCII field in envelope +|Restricted encoder error; no canonical bytes + +|A valid envelope has zero admitted observations +|Allowed, but coverage_verdict=not_established: **never clean** + +|A known inline finding, provider-run status unknown +|Preserve the assertion with provider_run_status=unknown + +|A historical review against a non-current head +|Retain stale_head; no fresh clean inference +|=== + +== Canonical profile dependencies and remaining qualification + +Canonical routing is defined by +https://github.com/metadatastician/standards/blob/main/3-practice/DATA-FORMAT-ROUTING.adoc[estate format routing]. +The authoritative ijson-jcs repository implements I-JSON (RFC 7493) +plus JCS (RFC 8785). Its canon command emits library bytes without LF; +check --profile estate-file checks exactly one final LF on disk; and +check-jsonl checks records separately. + +Before persistent bytes or hashes are relied upon across machines, a +separate **pinned differential gate** must compare this restricted +encoder's bytes with ijson-jcs canon for positive, negative and +boundary fixtures. If the binary is missing, its revision unpinned, +or the bytes disagree, fail closed. Do not use plain Jason.encode! +or jq -cS as a general JCS validator outside this restricted profile. +There is no approved kyq executable gate inferred from passing JavaScript +conformance tests. + +The later persistence stage must make both file/record transaction order +and concurrency/deduplication rules explicit; do not simply append a +second JSONL receipt on retry. JSON-LD dataset canonicalisation is +distinct and out of scope. DEED, K9 and coordination documents retain +their separate ANBF/grammar authorities. + +== Verification + +test/review_evidence_test.exs covers stable ordering and byte hashes, +empty-but-not-clean collections, stale historical commits, duplicate +event IDs, forged approval/learning fields, unexpected inputs, +mismatched subjects, malformed provenance and non-ASCII values. +It is added to the existing Elixir CI regression set. + +This branch is stacked on #1216 and must remain draft. The base PR's +unrelated Rust dependency-security blocker is +https://github.com/hyperpolymath/hypatia/issues/1219[#1219]. +Do not weaken or bypass it, and do not merge either branch on the +strength of a passing restricted-envelope test alone. diff --git a/lib/hypatia/review_check_run_collector.ex b/lib/hypatia/review_check_run_collector.ex new file mode 100644 index 00000000..e559f7ed --- /dev/null +++ b/lib/hypatia/review_check_run_collector.ex @@ -0,0 +1,270 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +defmodule Hypatia.ReviewCheckRunCollector do + @moduledoc """ + Read-only GitHub Checks API adapter for positively identified pre-commit.ci + PR runs. This is S-04, separate from GitHub bot review comments. + + A successful check is an external service assertion, not an independently + verified clean repository or an authorisation to merge or learn. No observed + check is UNKNOWN, never PASS. Other CI products cannot impersonate this + provider by naming their check "pre-commit.ci - pr". + + GitHub's REST check runs may be paginated and are not an atomic database + snapshot. The collector reads the full bounded inventory twice and refuses + inconsistent lists or a moving PR head. Only GET requests are issued. + """ + + alias Hypatia.ReviewGithubCollector + alias Hypatia.ReviewObservation + + @page_size 100 + @max_budget 10 + @default_budget 5 + @app_id 68672 + @app_slug "pre-commit-ci" + @check_name "pre-commit.ci - pr" + @sha ~r/\A[0-9a-f]{40}\z/i + @repo ~r/\A[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\z/ + @outcomes ~w(success failure neutral skipped cancelled timed_out action_required startup_failure stale) + + @doc """ + Read the subject PR and all paginated check runs at its exact head. + + The optional :api one-argument callback is solely an injectable GET API + client, returning {:ok, decoded_json} or {:error, reason}. Production + delegates to the GitHub collector's bounded gh CLI GET transport. + """ + @spec collect(String.t(), pos_integer(), keyword()) :: {:ok, map()} | {:error, term()} + def collect(repo, number, opts \\ []) do + api = Keyword.get(opts, :api, &ReviewGithubCollector.gh_get/1) + budget = Keyword.get(opts, :page_budget, @default_budget) + + cond do + not valid_repo?(repo) -> + {:error, :invalid_repository} + + not (is_integer(number) and number > 0) -> + {:error, :invalid_pull_request} + + not is_function(api, 1) -> + {:error, :invalid_api_client} + + not (is_integer(budget) and budget >= 1 and budget <= @max_budget) -> + {:error, :invalid_page_budget} + + true -> + collect_snapshot(repo, number, api, budget) + end + end + + defp collect_snapshot(repo, number, api, budget) do + subject_path = "repos/#{repo}/pulls/#{number}" + + with {:ok, start_pr} <- get_object(api, subject_path), + {:ok, head} <- subject_head(start_pr, repo, number), + path = "repos/#{repo}/commits/#{head}/check-runs", + {:ok, first} <- fetch_check_runs(api, path, budget), + {:ok, second} <- fetch_check_runs(api, path, budget), + :ok <- same_inventory(first, second), + {:ok, end_pr} <- get_object(api, subject_path), + {:ok, ^head} <- subject_head(end_pr, repo, number), + {:ok, observations} <- classify(first, repo, number, head) do + {:ok, + %{ + "repository" => repo, + "pull_request" => number, + "head_sha" => head, + "source" => "github_checks_api_via_gh", + "collection" => "repeated_stable_observation", + "coverage" => "pre_commit_ci_pr_check_runs_only", + "transport_provenance" => "github_api_observed", + "provider" => "pre-commit.ci", + "matching_checks" => length(observations), + "provider_observed" => observations != [], + "coverage_verdict" => "not_established", + "observations" => Enum.sort_by(observations, &get_in(&1, ["source", "event_id"])) + }} + else + {:ok, _other_head} -> {:error, :head_changed_during_collection} + {:error, _reason} = error -> error + end + end + + defp valid_repo?(repo) when is_binary(repo) do + Regex.match?(@repo, repo) and + Enum.all?(String.split(repo, "/"), &(&1 not in [".", ".."])) + end + + defp valid_repo?(_), do: false + + defp subject_head( + %{ + "number" => actual_number, + "head" => %{"sha" => sha}, + "base" => %{"repo" => %{"full_name" => actual_repo}} + }, + repo, + number + ) do + cond do + actual_number != number -> + {:error, :subject_number_mismatch} + + not (is_binary(actual_repo) and String.downcase(actual_repo) == String.downcase(repo)) -> + {:error, :subject_repository_mismatch} + + not (is_binary(sha) and Regex.match?(@sha, sha)) -> + {:error, :invalid_head_sha} + + true -> + {:ok, String.downcase(sha)} + end + end + + defp subject_head(_other, _repo, _number), do: {:error, :invalid_subject_shape} + + defp get_object(api, path) do + case api.(path) do + {:ok, %{} = object} -> {:ok, object} + {:ok, _} -> {:error, {:invalid_api_object, path}} + {:error, _} = error -> error + _ -> {:error, {:invalid_api_result, path}} + end + end + + defp fetch_check_runs(api, path, budget), do: fetch_page(api, path, 1, budget, []) + + defp fetch_page(api, path, page, budget, acc) do + endpoint = "#{path}?per_page=#{@page_size}&page=#{page}&filter=all" + + case api.(endpoint) do + {:ok, %{"total_count" => total, "check_runs" => batch}} + when is_integer(total) and total >= 0 and is_list(batch) and + length(batch) <= @page_size -> + accumulated = [batch | acc] + received = Enum.reduce(accumulated, 0, fn x, count -> count + length(x) end) + + cond do + received > total -> + {:error, {:inconsistent_total_count, path}} + + length(batch) == @page_size and page >= budget -> + {:error, {:page_budget_exhausted, path}} + + length(batch) == @page_size -> + fetch_page(api, path, page + 1, budget, accumulated) + + received != total -> + {:error, {:incomplete_check_inventory, path}} + + true -> + records = accumulated |> Enum.reverse() |> List.flatten() + + ids = + Enum.map(records, fn + %{"id" => id} when is_integer(id) and id > 0 -> id + _ -> nil + end) + + if Enum.all?(ids, &is_integer/1) and length(ids) == length(Enum.uniq(ids)) do + {:ok, records} + else + {:error, {:invalid_or_duplicate_check_ids, path}} + end + end + + {:ok, _other} -> + {:error, {:invalid_check_runs_shape, endpoint}} + + {:error, _} = error -> + error + + _ -> + {:error, {:invalid_check_runs_result, endpoint}} + end + end + + defp same_inventory(left, right) when left == right, do: :ok + defp same_inventory(_left, _right), do: {:error, :check_inventory_changed} + + defp classify(runs, repo, number, head) do + Enum.reduce_while(runs, {:ok, []}, fn run, {:ok, accepted} -> + case from_run(run, repo, number, head) do + {:ok, record} -> {:cont, {:ok, [record | accepted]}} + :ignore -> {:cont, {:ok, accepted}} + {:error, reason} -> {:halt, {:error, {:invalid_provider_check, reason}}} + end + end) + |> case do + {:ok, items} -> {:ok, Enum.reverse(items)} + error -> error + end + end + + defp from_run( + %{"name" => @check_name, "app" => %{"id" => @app_id, "slug" => @app_slug}} = run, + repo, + number, + head + ) do + with {:ok, id} <- positive_id(run["id"]), + :ok <- matching_sha(run["head_sha"], head), + {:ok, status, conclusion} <- check_state(run["status"], run["conclusion"]), + {:ok, observation} <- + ReviewObservation.admit( + %{ + "provider" => "pre-commit.ci", + "scope" => "hooks", + "repo" => repo, + "pr_number" => number, + "reviewed_sha" => head, + "source_event_id" => "github:check_run:#{id}", + "source_url" => "https://github.com/#{repo}/pull/#{number}", + "status" => status, + # Native conclusion is a provider claim, not a count of + # independently reproduced hook findings. + "has_findings" => nil + }, + head + ) do + {:ok, + Map.merge(observation, %{ + "check_conclusion" => conclusion, + "check_status" => run["status"], + "provider_run_status" => "github_check_observed", + "provider_app_id" => Integer.to_string(@app_id) + })} + else + {:error, reason} -> {:error, reason} + end + end + + # The app identity and exact PR check name must BOTH match. A renamed check + # or unrecognised app is unknown, not evidence of success. + defp from_run(_other, _repo, _number, _head), do: :ignore + + defp positive_id(id) when is_integer(id) and id > 0, do: {:ok, id} + defp positive_id(_), do: {:error, :invalid_check_id} + + defp matching_sha(value, head) when is_binary(value) do + if Regex.match?(@sha, value) and String.downcase(value) == head, + do: :ok, + else: {:error, :check_head_mismatch} + end + + defp matching_sha(_value, _head), do: {:error, :missing_check_head} + + defp check_state(state, conclusion) when state in ~w(queued in_progress pending) do + if is_nil(conclusion), + do: {:ok, "running", "unknown"}, + else: {:error, :running_with_conclusion} + end + + defp check_state("completed", conclusion) when conclusion in @outcomes do + {:ok, "completed", conclusion} + end + + defp check_state(_state, _conclusion), do: {:error, :unsupported_check_state} +end diff --git a/lib/hypatia/review_evidence.ex b/lib/hypatia/review_evidence.ex new file mode 100644 index 00000000..b935cd12 --- /dev/null +++ b/lib/hypatia/review_evidence.ex @@ -0,0 +1,254 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +defmodule Hypatia.ReviewEvidence do + @moduledoc """ + Restricted, *non-authorising* evidence envelope for external review intake. + + This is the S-03 boundary after ReviewGithubCollector and ReviewObservation, + not Hypatia's E0 learning receipt. It validates the admitted observation + against ReviewObservation again and constructs a minimal ASCII/no-JSON-number + body for Hypatia.Receipt.encode/1. No raw bot text, prompts, or patches enter. + + The E0 encoder's restricted profile is suitable for these deterministic + bytes; nevertheless a future pinned ijson-jcs differential gate is REQUIRED + before representing this output as a fully qualified estate JCS receipt. + The SHA-256 is a content checksum, NOT a producer signature or proof. + + No file, API, bot, learning state or merge state is modified by this module. + """ + + alias Hypatia.Receipt + alias Hypatia.ReviewObservation + + @schema "hypatia.external-review-evidence/1" + @snapshot_keys Enum.sort( + ~w(collection coverage head_sha ignored_source_events observations pull_request repository source transport_provenance) + ) + @observation_keys Enum.sort( + ~w(assessment authenticity evidence_class finding_signal learning_eligible merge_approval missing_evidence qualification review_status schema source subject) + ) + @sha ~r/\A[0-9a-f]{40}\z/ + @event_id ~r/\A[A-Za-z0-9][A-Za-z0-9_.:\/-]{0,255}\z/ + + @doc """ + Return a validated, deterministic **in-memory** envelope. + + collector_revision must be a lowercase 40-hex commit identifying the + collector source. It does not establish that source was deployed or signed. + """ + @spec build(map(), String.t()) :: {:ok, map()} | {:error, atom()} + def build(snapshot, collector_revision) + when is_map(snapshot) and is_binary(collector_revision) do + with :ok <- check_snapshot(snapshot, collector_revision), + {:ok, observations} <- check_observations(snapshot["observations"], snapshot) do + {:ok, + %{ + "schema" => @schema, + "canonical_profile" => "ascii_no_json_numbers_subset/1", + "collector_revision" => collector_revision, + "collection" => %{ + "mode" => "repeated_stable_observation", + "source" => "github_rest_via_gh", + "coverage" => "bot_comment_and_review_submissions_only", + "ignored_source_events" => Integer.to_string(snapshot["ignored_source_events"]), + "observation_count" => Integer.to_string(length(observations)) + }, + "subject" => %{ + "repo" => snapshot["repository"], + "pull_request" => Integer.to_string(snapshot["pull_request"]), + "current_head_sha" => snapshot["head_sha"] + }, + "assurance" => %{ + "source_authenticity" => "unverified", + "learning_credit" => "none", + "merge_authority" => "none", + "coverage_verdict" => "not_established" + }, + "observations" => observations + }} + end + end + + def build(_snapshot, _collector_revision), do: {:error, :invalid_input} + + @doc """ + Produce a deterministic hash of the exact no-final-LF JSON bytes and a + separate single-LF file record. Does not write to disk or sign anything. + """ + @spec canonical(map(), String.t()) :: {:ok, map()} | {:error, term()} + def canonical(snapshot, collector_revision) do + with {:ok, envelope} <- build(snapshot, collector_revision), + {:ok, bytes} <- Receipt.encode(envelope) do + {:ok, + %{ + "body" => envelope, + "library_bytes" => bytes, + "file_record_bytes" => bytes <> "\n", + "library_sha256" => :crypto.hash(:sha256, bytes) |> Base.encode16(case: :lower), + "canonicaliser" => "Hypatia.Receipt.restricted_encoder", + "qualification" => "requires_ijson_jcs_differential" + }} + end + end + + defp check_snapshot(snapshot, revision) do + cond do + Enum.sort(Map.keys(snapshot)) != @snapshot_keys -> + {:error, :unexpected_snapshot_fields} + + not Regex.match?(@sha, revision) -> + {:error, :invalid_collector_revision} + + not (is_binary(snapshot["head_sha"]) and Regex.match?(@sha, snapshot["head_sha"])) -> + {:error, :invalid_head_sha} + + not valid_repo?(snapshot["repository"]) -> + {:error, :invalid_repository} + + not (is_integer(snapshot["pull_request"]) and snapshot["pull_request"] > 0) -> + {:error, :invalid_pull_request} + + not (is_integer(snapshot["ignored_source_events"]) and + snapshot["ignored_source_events"] >= 0) -> + {:error, :invalid_ignored_count} + + snapshot["collection"] != "repeated_stable_observation" -> + {:error, :unsupported_collection} + + snapshot["source"] != "github_rest_via_gh" or + snapshot["transport_provenance"] != "github_api_observed" or + snapshot["coverage"] != "bot_comment_and_review_submissions_only" -> + {:error, :unsupported_source} + + not is_list(snapshot["observations"]) -> + {:error, :invalid_observations} + + true -> + :ok + end + end + + # Match ReviewObservation's owner/repository component rules, including + # for zero-event snapshots (which never reach observation re-admission). + defp valid_repo?(repo) when is_binary(repo) do + Regex.match?(~r/\A[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\z/, repo) and + Enum.all?(String.split(repo, "/"), &(&1 not in [".", ".."])) + end + + defp valid_repo?(_), do: false + + defp check_observations(observations, snapshot) do + with {:ok, records} <- check_each(observations, snapshot) do + ids = Enum.map(records, &get_in(&1, ["source", "event_id"])) + + if Enum.uniq(ids) == ids do + {:ok, Enum.sort_by(records, &get_in(&1, ["source", "event_id"]))} + else + {:error, :duplicate_source_event_id} + end + end + end + + defp check_each(records, snapshot) do + result = + Enum.reduce_while(records, {:ok, []}, fn observation, {:ok, accepted} -> + case validated_observation(observation, snapshot) do + {:ok, record} -> {:cont, {:ok, [record | accepted]}} + {:error, reason} -> {:halt, {:error, reason}} + end + end) + + case result do + {:ok, reversed} -> {:ok, Enum.reverse(reversed)} + error -> error + end + end + + defp validated_observation(observation, snapshot) when is_map(observation) do + source = observation["source"] + subject = observation["subject"] + + cond do + Enum.sort(Map.keys(observation)) not in [ + @observation_keys, + Enum.sort(["provider_run_status" | @observation_keys]) + ] -> + {:error, :unexpected_observation_fields} + + not (is_map(source) and is_map(subject)) -> + {:error, :invalid_observation_shape} + + Map.has_key?(observation, "provider_run_status") and + observation["provider_run_status"] != "unknown" -> + {:error, :unverified_provider_completion} + + not (is_binary(source["event_id"]) and Regex.match?(@event_id, source["event_id"])) -> + {:error, :invalid_source_event_id} + + subject["repo"] != snapshot["repository"] or + subject["pull_request"] != snapshot["pull_request"] or + subject["current_head_sha"] != snapshot["head_sha"] -> + {:error, :subject_mismatch} + + true -> + revalidate(observation, snapshot) + end + end + + defp validated_observation(_invalid, _snapshot), do: {:error, :invalid_observation_shape} + + defp revalidate(observation, snapshot) do + source = observation["source"] + subject = observation["subject"] + + reported_findings = + case observation["finding_signal"] do + "reported_present" -> true + "reported_absent" -> false + "unknown" -> nil + _ -> :invalid + end + + input = %{ + "provider" => source["provider"], + "scope" => source["scope"], + "repo" => subject["repo"], + "pr_number" => subject["pull_request"], + "reviewed_sha" => subject["reviewed_sha"], + "source_event_id" => source["event_id"], + "source_url" => source["url"], + "status" => observation["review_status"], + "has_findings" => reported_findings + } + + case ReviewObservation.admit(input, snapshot["head_sha"]) do + {:ok, expected} -> + if expected == Map.delete(observation, "provider_run_status") do + {:ok, + %{ + "source" => %{ + "provider" => source["provider"], + "scope" => source["scope"], + "event_id" => source["event_id"], + "url" => source["url"] + }, + "reviewed_sha" => subject["reviewed_sha"], + "assessment" => observation["assessment"], + "review_status" => observation["review_status"], + "finding_signal" => observation["finding_signal"], + "missing_evidence" => observation["missing_evidence"], + "provider_run_status" => "unknown", + "qualification" => "unqualified", + "learning_credit" => "none", + "merge_authority" => "none" + }} + else + {:error, :observation_contract_mismatch} + end + + {:error, _} -> + {:error, :invalid_admitted_observation} + end + end +end diff --git a/lib/mix/tasks/hypatia.review_check_collect.ex b/lib/mix/tasks/hypatia.review_check_collect.ex new file mode 100644 index 00000000..38784956 --- /dev/null +++ b/lib/mix/tasks/hypatia.review_check_collect.ex @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +defmodule Mix.Tasks.Hypatia.ReviewCheckCollect do + @moduledoc """ + Read-only summary of GitHub Check Runs emitted by pre-commit.ci. + + mix hypatia.review_check_collect --repo OWNER/REPO --pr NUMBER + + Requires authenticated read access to GitHub through gh CLI. There is no + check-run re-request, auto-fix, bot dispatch, issue comment, learning + event, merge approval, or receipt write. Missing provider events are + UNKNOWN, never a clean review. + """ + + use Mix.Task + + alias Hypatia.ReviewCheckRunCollector + + @shortdoc "Read one PR's pre-commit.ci check-run assertions (not merge approval)" + @switches [repo: :string, pr: :integer, page_budget: :integer] + + @impl Mix.Task + def run(argv) do + {opts, rest, invalid} = OptionParser.parse(argv, strict: @switches) + + if rest != [] or invalid != [] or is_nil(opts[:repo]) or is_nil(opts[:pr]) do + Mix.raise("Usage: mix hypatia.review_check_collect --repo OWNER/REPO --pr NUMBER") + end + + budget = if is_nil(opts[:page_budget]), do: [], else: [page_budget: opts[:page_budget]] + + case ReviewCheckRunCollector.collect(opts[:repo], opts[:pr], budget) do + {:ok, report} -> + IO.puts("External Check Run intake: #{report["repository"]}##{report["pull_request"]}") + IO.puts("Head: #{report["head_sha"]}") + IO.puts("Provider: pre-commit.ci") + IO.puts("Matching current-head PR checks: #{report["matching_checks"]}") + IO.puts("Coverage verdict: #{report["coverage_verdict"]} (not a clean certificate)") + + if not report["provider_observed"] do + IO.puts("State: NOT OBSERVED; not proof of pass, absence, or installation") + end + + Enum.each(report["observations"], fn item -> + IO.puts( + " #{item["source"]["event_id"]}: " <> + "status=#{item["check_status"]} conclusion=#{item["check_conclusion"]} " <> + "[external assertion, unqualified, no merge authority]" + ) + end) + + {:error, reason} -> + Mix.shell().error("Check Run intake unavailable; not a clean result: #{inspect(reason)}") + exit({:shutdown, 2}) + end + end +end diff --git a/scripts/check-review-evidence-ijson-jcs.sh b/scripts/check-review-evidence-ijson-jcs.sh new file mode 100644 index 00000000..6dea1ceb --- /dev/null +++ b/scripts/check-review-evidence-ijson-jcs.sh @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Pinned, read-only differential gate for the restricted review-evidence +# envelope. Does not run any GitHub API call, review bot, merge or learning job. +set -euo pipefail + +cd "$(dirname "$0")/.." + +pin_file=".ci/review-evidence-ijson-jcs.pin" +[ -f "$pin_file" ] || { echo "::error::missing canonicaliser pin"; exit 2; } +pin="$(tr -d '\r\n' < "$pin_file")" +[[ "$pin" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::invalid canonicaliser pin"; exit 2; } + +source_dir="${HYPATIA_IJSON_JCS_SOURCE:?source checkout required}" +binary="${HYPATIA_IJSON_JCS_BIN:?canonicaliser executable required}" +[ -x "$binary" ] || { echo "::error::missing pinned canonicaliser executable"; exit 2; } + +actual="$(git -C "$source_dir" rev-parse HEAD)" || + { echo "::error::canonicaliser checkout inaccessible"; exit 2; } +[ "$actual" = "$pin" ] || + { echo "::error::canonicaliser revision differs from declared pin"; exit 2; } + +# Consume the entire help output before testing it. A quiet grep pipeline +# can exit early, SIGPIPE its producer under pipefail and mask a sound CLI. +help_text="$("$binary" --help)" || + { echo "::error::canonicaliser help probe failed"; exit 2; } +case "$help_text" in + *--profile*) ;; + *) echo "::error::pinned CLI lacks strict file profiles"; exit 2 ;; +esac +case "$help_text" in + *check-jsonl*) ;; + *) echo "::error::pinned CLI lacks JSONL framing check"; exit 2 ;; +esac + +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT + +mix run --no-start scripts/review-evidence-jcs-fixtures.exs "$scratch" + +expect_exit() { + local expected="$1" + shift + local actual_status + if "$@" >/dev/null 2>&1; then + actual_status=0 + else + actual_status="$?" + fi + + if [ "$actual_status" -ne "$expected" ]; then + echo "::error::canonicaliser exit $actual_status instead of $expected" + return 1 + fi +} + +count=0 +for f in "$scratch"/library_*.json; do + [ -f "$f" ] || { echo "::error::no library fixture generated"; exit 2; } + + # Canonicalising the raw byte stream must yield exactly the source bytes. + "$binary" canon < "$f" | cmp -s - "$f" || + { echo "::error::JCS canonical bytes differ"; exit 1; } + + expect_exit 0 "$binary" check --profile library "$f" + expect_exit 1 "$binary" check --profile estate-file "$f" + + estate="$scratch/${f##*/}" + estate="$scratch/estate_${estate##*/library_}" + [ -f "$estate" ] || { echo "::error::missing estate file profile fixture"; exit 2; } + + expect_exit 0 "$binary" check --profile estate-file "$estate" + expect_exit 1 "$binary" check --profile library "$estate" + + count=$((count + 1)) +done +[ "$count" -eq 6 ] || { echo "::error::unexpected fixture denominator: $count"; exit 1; } + +expect_exit 0 "$binary" check-jsonl "$scratch/records_ok.jsonl" +expect_exit 1 "$binary" check-jsonl "$scratch/records_missing_lf.jsonl" +expect_exit 2 "$binary" check-jsonl "$scratch/records_blank.jsonl" +expect_exit 1 "$binary" check-jsonl "$scratch/records_not_sorted.jsonl" + +invalid=0 +for f in "$scratch"/invalid_*.json; do + [ -f "$f" ] || { echo "::error::no invalid fixture generated"; exit 2; } + + # Parsing raw text is essential: decoding to a map first would remove + # duplicated object keys and defeat the negative controls. + expect_exit 2 "$binary" check --profile library "$f" + expect_exit 2 "$binary" canon < "$f" + invalid=$((invalid + 1)) +done +[ "$invalid" -eq 5 ] || + { echo "::error::unexpected invalid fixture denominator: $invalid"; exit 1; } + +echo "review evidence I-JSON/JCS differential: $count canonical examples, $invalid strict negative examples, four JSONL framing controls" +echo "ijson-jcs source pin: $pin" +echo "ijson-jcs built binary SHA-256: $(sha256sum "$binary" | cut -d' ' -f1)" +echo "qualification: restricted ASCII/no-JSON-number profile tested; no signatures, learning or merge authority" diff --git a/scripts/review-evidence-jcs-fixtures.exs b/scripts/review-evidence-jcs-fixtures.exs new file mode 100644 index 00000000..d4c651ab --- /dev/null +++ b/scripts/review-evidence-jcs-fixtures.exs @@ -0,0 +1,120 @@ +# SPDX-License-Identifier: MPL-2.0 +# Review evidence ASCII/JCS differential corpus. Writes fixtures only in the +# caller-supplied scratch directory; no GitHub API, bots or learning changes. + +defmodule Hypatia.ReviewEvidenceJcsFixtures do + alias Hypatia.ReviewEvidence + alias Hypatia.ReviewObservation + + @repo "stuff-of-awe/awesome-zig" + @current String.duplicate("a", 40) + @historical String.duplicate("b", 40) + @collector String.duplicate("c", 40) + + defp observation(id, provider, scope, reviewed_sha, status, findings) do + row = %{ + "provider" => provider, + "scope" => scope, + "repo" => @repo, + "pr_number" => 20, + "reviewed_sha" => reviewed_sha, + "source_event_id" => "github:review_comment:#{id}", + "source_url" => + "https://github.com/stuff-of-awe/awesome-zig/pull/20#discussion_r#{id}", + "status" => status, + "has_findings" => findings + } + + {:ok, admitted} = ReviewObservation.admit(row, @current) + Map.put(admitted, "provider_run_status", "unknown") + end + + defp snapshot(observations, ignored) do + %{ + "repository" => @repo, + "pull_request" => 20, + "head_sha" => @current, + "collection" => "repeated_stable_observation", + "source" => "github_rest_via_gh", + "transport_provenance" => "github_api_observed", + "coverage" => "bot_comment_and_review_submissions_only", + "ignored_source_events" => ignored, + "observations" => observations + } + end + + def emit(directory) do + File.mkdir_p!(directory) + + fixtures = [ + {"empty_unknown", snapshot([], 0)}, + {"current_code", + snapshot([observation(101, "codex", "code", @current, "completed", true)], 0)}, + {"stale_historical", + snapshot([observation(102, "coderabbit", "code", @historical, "completed", true)], 1)}, + {"security_scope", + snapshot([observation(103, "codex", "security", @current, "completed", true)], 0)}, + {"unavailable_review", + snapshot([observation(104, "codex", "security", @current, "unavailable", nil)], 2)}, + {"mixed_sorted", + snapshot( + [ + observation(107, "codex", "security", @current, "completed", true), + observation(105, "coderabbit", "code", @current, "completed", true), + observation(106, "codex", "code", @historical, "completed", true) + ], + 3 + )} + ] + + records = + Enum.map(fixtures, fn {name, data} -> + {:ok, result} = ReviewEvidence.canonical(data, @collector) + body = result["body"] + bytes = result["library_bytes"] + file_record = result["file_record_bytes"] + + unless body["assurance"]["merge_authority"] == "none" and + body["assurance"]["learning_credit"] == "none" and + body["assurance"]["coverage_verdict"] == "not_established" and + result["qualification"] == "requires_ijson_jcs_differential" and + file_record == bytes <> "\n" do + raise "source admission assurance changed" + end + + File.write!(Path.join(directory, "library_#{name}.json"), bytes) + File.write!(Path.join(directory, "estate_#{name}.json"), file_record) + bytes + end) + + [first, second | _] = records + File.write!(Path.join(directory, "records_ok.jsonl"), first <> "\n" <> second <> "\n") + File.write!(Path.join(directory, "records_missing_lf.jsonl"), first <> "\n" <> second) + File.write!(Path.join(directory, "records_blank.jsonl"), first <> "\n\n" <> second <> "\n") + File.write!(Path.join(directory, "records_not_sorted.jsonl"), "{ \"a\":1}\n") + + # These are intentionally *text* fixtures: parsing to a generic map first + # would erase duplicate keys and corrupt the test of strict I-JSON parsing. + negative = [ + {"duplicate_keys", ~S({"a":1,"a":2})}, + {"unsafe_integer", ~S({"x":9007199254740992})}, + {"lone_surrogate", ~S({"x":"\uD800"})}, + {"noncharacter", ~S({"x":"\uFDD0"})}, + {"malformed", ~S({"x":})} + ] + + Enum.each(negative, fn {name, bytes} -> + File.write!(Path.join(directory, "invalid_#{name}.json"), bytes) + end) + + IO.puts("REVIEW_JCS_FIXTURES=#{length(fixtures)}") + end +end + +case System.argv() do + [directory] -> + Hypatia.ReviewEvidenceJcsFixtures.emit(directory) + + _ -> + raise "usage: mix run --no-start scripts/review-evidence-jcs-fixtures.exs SCRATCH_DIR" +end diff --git a/test/review_check_run_collector_test.exs b/test/review_check_run_collector_test.exs new file mode 100644 index 00000000..7da2f3c0 --- /dev/null +++ b/test/review_check_run_collector_test.exs @@ -0,0 +1,247 @@ +# SPDX-License-Identifier: MPL-2.0 + +defmodule Hypatia.ReviewCheckRunCollectorTest do + use ExUnit.Case, async: true + + alias Hypatia.ReviewCheckRunCollector, as: Collector + + @repo "stuff-of-awe/awesome-zig" + @number 20 + @sha String.duplicate("a", 40) + @other String.duplicate("b", 40) + @path "repos/stuff-of-awe/awesome-zig/pulls/20" + @checks "repos/stuff-of-awe/awesome-zig/commits/#{@sha}/check-runs" + @first_page @checks <> "?per_page=100&page=1&filter=all" + @second_page @checks <> "?per_page=100&page=2&filter=all" + + defp pr do + %{ + "number" => @number, + "head" => %{"sha" => @sha}, + "base" => %{"repo" => %{"full_name" => @repo}} + } + end + + defp check(overrides \\ %{}) do + Map.merge( + %{ + "id" => 101, + "name" => "pre-commit.ci - pr", + "app" => %{"id" => 68672, "slug" => "pre-commit-ci"}, + "head_sha" => @sha, + "status" => "completed", + "conclusion" => "success", + "html_url" => "https://results.pre-commit.ci/run/github/irrelevant" + }, + overrides + ) + end + + defp response(runs \\ []) do + %{ + @path => {:ok, pr()}, + @first_page => {:ok, %{"total_count" => length(runs), "check_runs" => runs}} + } + end + + defp api(responses) do + fn endpoint -> Map.get(responses, endpoint, {:error, :unexpected_endpoint}) end + end + + test "missing pre-commit.ci is not a pass even when all other checks succeeded" do + generic = check(%{"app" => %{"id" => 99, "slug" => "github-actions"}}) + + assert {:ok, snapshot} = + Collector.collect(@repo, @number, api: api(response([generic]))) + + assert snapshot["provider_observed"] == false + assert snapshot["matching_checks"] == 0 + assert snapshot["observations"] == [] + assert snapshot["coverage_verdict"] == "not_established" + end + + test "a native successful pre-commit.ci check remains an unverified assertion" do + assert {:ok, snapshot} = + Collector.collect(@repo, @number, api: api(response([check()]))) + + assert snapshot["provider_observed"] + assert snapshot["matching_checks"] == 1 + assert [observation] = snapshot["observations"] + assert observation["source"]["provider"] == "pre-commit.ci" + assert observation["source"]["scope"] == "hooks" + assert observation["source"]["event_id"] == "github:check_run:101" + assert observation["source"]["url"] == "https://github.com/#{@repo}/pull/#{@number}" + assert observation["review_status"] == "completed" + assert observation["check_conclusion"] == "success" + assert observation["finding_signal"] == "unknown" + assert observation["assessment"] == "finding_summary_missing" + assert observation["qualification"] == "unqualified" + assert observation["learning_eligible"] == false + assert observation["merge_approval"] == false + assert snapshot["coverage_verdict"] == "not_established" + end + + test "failed and skipped checks do not turn into independent findings" do + runs = [ + check(%{"id" => 102, "conclusion" => "failure"}), + check(%{"id" => 103, "conclusion" => "skipped"}) + ] + + assert {:ok, snapshot} = Collector.collect(@repo, @number, api: api(response(runs))) + assert length(snapshot["observations"]) == 2 + + assert Enum.map(snapshot["observations"], & &1["check_conclusion"]) == [ + "failure", + "skipped" + ] + + assert Enum.all?(snapshot["observations"], fn item -> + item["finding_signal"] == "unknown" and + item["learning_eligible"] == false and item["merge_approval"] == false + end) + end + + test "pending check has unknown conclusion and cannot declare clean" do + waiting = check(%{"status" => "in_progress", "conclusion" => nil}) + + assert {:ok, snapshot} = + Collector.collect(@repo, @number, api: api(response([waiting]))) + + assert [item] = snapshot["observations"] + assert item["review_status"] == "running" + assert item["check_conclusion"] == "unknown" + assert item["assessment"] == "review_pending" + end + + test "forged check name, slug or numeric app identifier never authenticates" do + spoofed = [ + check(%{"app" => %{"id" => 42, "slug" => "pre-commit-ci"}}), + check(%{"app" => %{"id" => 68672, "slug" => "other-ci"}}), + check(%{"name" => "pre-commit.ci - push"}), + check(%{"name" => "pre-commit.ci - pr ", "id" => 103}) + ] + + spoofed = + spoofed + |> Enum.with_index(201) + |> Enum.map(fn {run, id} -> Map.put(run, "id", id) end) + + assert {:ok, snapshot} = Collector.collect(@repo, @number, api: api(response(spoofed))) + assert snapshot["observations"] == [] + refute snapshot["provider_observed"] + end + + test "positively identified check with invalid state or SHA fails the inventory" do + for invalid <- [ + check(%{"head_sha" => @other}), + check(%{"status" => "completed", "conclusion" => nil}), + check(%{"status" => "in_progress", "conclusion" => "success"}), + check(%{"status" => "completed", "conclusion" => "some_future_state"}) + ] do + assert {:error, {:invalid_provider_check, _}} = + Collector.collect(@repo, @number, api: api(response([invalid]))) + end + end + + test "empty or incomplete pagination never yields clean coverage" do + assert {:ok, empty} = Collector.collect(@repo, @number, api: api(response())) + refute empty["provider_observed"] + + incomplete = + Map.put(response(), @first_page, {:ok, %{"total_count" => 2, "check_runs" => []}}) + + assert {:error, {:incomplete_check_inventory, _}} = + Collector.collect(@repo, @number, api: api(incomplete)) + end + + test "duplicate or malformed source ids fail closed" do + for malformed <- [ + [check(%{"id" => 101}), check(%{"id" => 101})], + [check(%{"id" => nil})], + [%{"name" => "Unrelated check"}] + ] do + assert {:error, {:invalid_or_duplicate_check_ids, _}} = + Collector.collect(@repo, @number, api: api(response(malformed))) + end + end + + test "page budget exhaustion fails, even if the last page was full" do + full = Enum.map(1..100, fn id -> check(%{"id" => id}) end) + + responses = + Map.put(response(), @first_page, {:ok, %{"total_count" => 100, "check_runs" => full}}) + + assert {:error, {:page_budget_exhausted, _}} = + Collector.collect(@repo, @number, api: api(responses), page_budget: 1) + + responses = + responses + |> Map.put(@second_page, {:ok, %{"total_count" => 100, "check_runs" => []}}) + + assert {:ok, snapshot} = + Collector.collect(@repo, @number, api: api(responses), page_budget: 2) + + assert length(snapshot["observations"]) == 100 + end + + test "changed inventory between reads is rejected despite constant PR head" do + {:ok, counter} = Agent.start_link(fn -> 0 end) + + varying = fn endpoint -> + if endpoint == @path do + {:ok, pr()} + else + count = Agent.get_and_update(counter, fn index -> {index, index + 1} end) + {:ok, %{"total_count" => 1, "check_runs" => [check(%{"id" => 101 + count})]}} + end + end + + assert {:error, :check_inventory_changed} = + Collector.collect(@repo, @number, api: varying) + end + + test "moved PR head, bad PR shape, API error or malformed checks refuse collection" do + {:ok, counter} = Agent.start_link(fn -> 0 end) + + moved = fn endpoint -> + if endpoint == @path do + count = Agent.get_and_update(counter, fn index -> {index, index + 1} end) + if count == 0, do: {:ok, pr()}, else: {:ok, put_in(pr(), ["head", "sha"], @other)} + else + {:ok, %{"total_count" => 0, "check_runs" => []}} + end + end + + assert {:error, :head_changed_during_collection} = + Collector.collect(@repo, @number, api: moved) + + assert {:error, :invalid_subject_shape} = + Collector.collect(@repo, @number, + api: api(Map.put(response(), @path, {:ok, %{"head" => []}})) + ) + + assert {:error, :network_failure} = + Collector.collect(@repo, @number, + api: api(Map.put(response(), @path, {:error, :network_failure})) + ) + + assert {:error, {:invalid_check_runs_shape, _}} = + Collector.collect( + @repo, + @number, + api: api(Map.put(response(), @first_page, {:ok, %{"check_runs" => []}})) + ) + end + + test "subject validation rejects path tricks and invalid limits" do + for invalid <- ["../repo", "owner/..", "owner//repo"] do + assert {:error, :invalid_repository} = + Collector.collect(invalid, @number, api: api(response())) + end + + assert {:error, :invalid_pull_request} = Collector.collect(@repo, -1, api: api(response())) + + assert {:error, :invalid_page_budget} = + Collector.collect(@repo, @number, api: api(response()), page_budget: 0) + end +end diff --git a/test/review_evidence_test.exs b/test/review_evidence_test.exs new file mode 100644 index 00000000..bf011367 --- /dev/null +++ b/test/review_evidence_test.exs @@ -0,0 +1,187 @@ +# SPDX-License-Identifier: MPL-2.0 + +defmodule Hypatia.ReviewEvidenceTest do + use ExUnit.Case, async: true + + alias Hypatia.ReviewEvidence + alias Hypatia.ReviewObservation + + @repo "stuff-of-awe/awesome-zig" + @sha String.duplicate("a", 40) + @older String.duplicate("b", 40) + @revision String.duplicate("c", 40) + + defp observation(id, opts \\ []) do + {:ok, admitted} = + ReviewObservation.admit( + %{ + "provider" => Keyword.get(opts, :provider, "codex"), + "scope" => Keyword.get(opts, :scope, "code"), + "repo" => @repo, + "pr_number" => 20, + "reviewed_sha" => Keyword.get(opts, :reviewed_sha, @sha), + "source_event_id" => "github:review_comment:#{id}", + "source_url" => "https://github.com/stuff-of-awe/awesome-zig/pull/20#discussion_r#{id}", + "status" => Keyword.get(opts, :status, "completed"), + "has_findings" => Keyword.get(opts, :has_findings, true) + }, + @sha + ) + + Map.put(admitted, "provider_run_status", "unknown") + end + + defp snapshot(observations \\ [observation(301)]) do + %{ + "repository" => @repo, + "pull_request" => 20, + "head_sha" => @sha, + "collection" => "repeated_stable_observation", + "source" => "github_rest_via_gh", + "transport_provenance" => "github_api_observed", + "coverage" => "bot_comment_and_review_submissions_only", + "ignored_source_events" => 0, + "observations" => observations + } + end + + test "encodes a non-authorising envelope without changing E0 receipt semantics" do + assert {:ok, result} = ReviewEvidence.canonical(snapshot(), @revision) + assert %{"schema" => "hypatia.external-review-evidence/1"} = result["body"] + assert result["qualification"] == "requires_ijson_jcs_differential" + assert result["body"]["assurance"]["merge_authority"] == "none" + assert result["body"]["assurance"]["learning_credit"] == "none" + assert result["body"]["assurance"]["coverage_verdict"] == "not_established" + assert length(result["body"]["observations"]) == 1 + + bytes = result["library_bytes"] + assert String.starts_with?(bytes, "{\"assurance\":") + assert result["file_record_bytes"] == bytes <> "\n" + refute String.ends_with?(bytes, "\n") + assert byte_size(result["library_sha256"]) == 64 + + assert result["library_sha256"] == + :crypto.hash(:sha256, bytes) |> Base.encode16(case: :lower) + + refute String.contains?(bytes, "Potential bad lock") + end + + test "sorts source identities deterministically independently of API page order" do + first = snapshot([observation(302), observation(301)]) + second = snapshot([observation(301), observation(302)]) + + assert {:ok, a} = ReviewEvidence.canonical(first, @revision) + assert {:ok, b} = ReviewEvidence.canonical(second, @revision) + assert a["library_bytes"] == b["library_bytes"] + + assert Enum.map(a["body"]["observations"], &get_in(&1, ["source", "event_id"])) == + ["github:review_comment:301", "github:review_comment:302"] + end + + test "empty observation collection is never a clean-review certificate" do + assert {:ok, result} = ReviewEvidence.canonical(snapshot([]), @revision) + assert result["body"]["collection"]["observation_count"] == "0" + assert result["body"]["observations"] == [] + assert result["body"]["assurance"]["coverage_verdict"] == "not_established" + end + + test "rejects invalid repository dot components with zero observations" do + for repo <- ["../repo", "owner/..", "./repo", "owner/.", "owner//repo"] do + assert {:error, :invalid_repository} = + ReviewEvidence.build(Map.put(snapshot([]), "repository", repo), @revision) + end + + assert {:ok, _} = + ReviewEvidence.build(snapshot([]), @revision) + end + + test "retains exact historical reviewed SHA and stale verdict" do + historical = observation(303, reviewed_sha: @older) + + assert {:ok, result} = ReviewEvidence.build(snapshot([historical]), @revision) + assert [record] = result["observations"] + assert record["reviewed_sha"] == @older + assert record["assessment"] == "stale_head" + end + + test "rejects a manufactured merger approval or learning qualification" do + for changed <- [ + Map.put(observation(301), "merge_approval", true), + Map.put(observation(301), "learning_eligible", true), + Map.put(observation(301), "qualification", "verified"), + Map.put(observation(301), "evidence_class", "proof"), + Map.put(observation(301), "assessment", "reported_no_findings") + ] do + assert {:error, :observation_contract_mismatch} = + ReviewEvidence.build(snapshot([changed]), @revision) + end + end + + test "refuses unverified provider execution completion and unknown fields" do + changed = Map.put(observation(301), "provider_run_status", "completed") + + assert {:error, :unverified_provider_completion} = + ReviewEvidence.build(snapshot([changed]), @revision) + + injected = Map.put(observation(301), "fix_command", "delete all checks") + + assert {:error, :unexpected_observation_fields} = + ReviewEvidence.build(snapshot([injected]), @revision) + end + + test "refuses malformed or mismatched collector snapshots" do + for broken <- [ + Map.put(snapshot(), "collection", "complete_bounded_snapshot"), + Map.put(snapshot(), "source", "unknown"), + Map.put(snapshot(), "transport_provenance", "unauthenticated"), + Map.put(snapshot(), "head_sha", @older), + Map.put(snapshot(), "ignored_source_events", -1), + Map.put(snapshot(), "new_unverified_flag", true), + Map.put(snapshot(), "observations", nil) + ] do + assert {:error, _} = ReviewEvidence.build(broken, @revision) + end + end + + test "refuses duplicate event IDs, malformed provenance and wrong subject" do + assert {:error, :duplicate_source_event_id} = + ReviewEvidence.build(snapshot([observation(301), observation(301)]), @revision) + + changed_source = put_in(observation(301), ["source", "url"], "https://evil.invalid") + + assert {:error, :invalid_admitted_observation} = + ReviewEvidence.build(snapshot([changed_source]), @revision) + + changed_subject = put_in(observation(301), ["subject", "repo"], "other/thing") + + assert {:error, :subject_mismatch} = + ReviewEvidence.build(snapshot([changed_subject]), @revision) + end + + test "bad source revision cannot pose as an immutable collector identity" do + assert {:error, :invalid_collector_revision} = + ReviewEvidence.build(snapshot(), "moving-main") + + assert {:error, :invalid_collector_revision} = + ReviewEvidence.build(snapshot(), String.upcase(@revision)) + + assert {:error, :invalid_input} = ReviewEvidence.build(nil, @revision) + end + + test "non-ASCII in the permitted source locator fails the restricted encoder" do + changed = + put_in( + observation(301), + ["source", "url"], + "https://github.com/stuff-of-awe/awesome-zig/pull/20#caf\u00E9" + ) + + # If the upstream URI parser admits this fragment, the restricted output + # still rejects Unicode rather than claiming the ASCII-only JCS subset. + case ReviewEvidence.canonical(snapshot([changed]), @revision) do + {:error, {:not_canonical, {:not_ascii, _}}} -> :ok + {:error, :invalid_admitted_observation} -> :ok + other -> flunk("Expected rejection of a non-ASCII locator, got #{inspect(other)}") + end + end +end