#!/usr/bin/env bash
# valley — the S1 integrator's verbs, as a plain shell script.
#
# EVICTION CLAUSE (owner-ratified; the decision node is
# archive/.the-valley/decisions/dcr-74c3158-valley-cli-lifecycle.md).
# This tool is deliberately a shell script: it runs from any checkout with
# nothing but git and coreutils — no machinery, the portability stance of
# ida-b9f646c. It GRADUATES to its own repo and a real language the moment
# ANY tripwire is crossed:
#   - it grows past ~300 lines;
#   - it needs persistent state, config, or a daemon
#     (CROSSED by review's notes, which outlive the session in
#     $XDG_STATE_HOME/valley/notes.);
#   - it needs dependencies beyond git + coreutils
#     (CROSSED by Phase 1's tail/replay, which need the nats CLI, and again
#     by checks, which needs the cue CLI, again by review's [a]pprove, which
#     needs the attest helper, and again by status, ready, unready and
#     withdraw, which are a Go program (status/) this script runs —
#     graduation is now owed; recording the decision node is part of taking it.);
#   - its behavior gets subtle enough to need real tests
#     (CROSSED by checks: glob matching is pinned by the policy-deriver
#     flake check, not by reading the code.);
#   - it needs nontrivial parsing or concurrency
#     (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
# The size tripwire (~300 lines) is crossed too. Which way to take the
# graduation is dcr-2aa1a12, still `proposed`.
# Graduation is a deliberate act, recorded as a decision node.
# Precedent: klaus — born in cosmo, graduated deliberately.

set -euo pipefail

# Every verb reads the repository's own objects. A replacement ref makes one
# object stand in for another wherever git looks it up, so a fetched or
# planted refs/replace/* could change the diff a reviewer reads, the policy
# a derivation composes, and the tree a request is filed for. git is told
# to ignore them, whatever configuration says, and the variables that point
# it at other objects or at another replacement namespace are dropped. What
# chooses the repository and the person's own configuration are kept: a
# fetch of the owning valley needs that configuration, and neither changes
# what an object id reads as once replacement refs are off.
export GIT_NO_REPLACE_OBJECTS=1
unset GIT_REPLACE_REF_BASE GIT_GRAFT_FILE GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES

die() {
  printf 'valley: %s\n' "$*" >&2
  exit 1
}

usage() {
  cat <<'EOF'
valley — S1 integrator verbs for a valley project

usage: valley <verb> [args]

  pending [--all] [--repo <name>] [--owes] [--json]
                   list the ready changes whose active version has not
                   landed, one line each: handle and version | title,
                   then `includes <handle>` when its active head strictly
                   contains another change's that has not landed either
                   (ancestry alone: approving it lands that content too),
                   then `uncertain` when the version may have landed
                   without its evidence being stored. then, under
                   branches, each branch on origin that main does not
                   reach and that is no change's active head, one line
                   each: branch | head subject | age | author | ahead N |
                   diffstat. then, under drafts, the changes whose record
                   says they are drafts, one line each, the same way, for
                   the head of the active version: handle and version,
                   and the branch the version names.
                     --all        every project the serving host
                                  publishes, each headed by its name (see
                                  changes below)
                     --repo NAME  that one project
                     --owes       end each change's line with the checks
                                  it owes under the policy, by cost, as
                                  checks derives them
                     --json       print valley-pending/v1: the
                                  valley-changes/v1 shape, with the
                                  pending changes in changes and the
                                  drafts in drafts
                   needs the valley-go helper.
  changes --json [--all] [--repo <name>]
                   print every change origin holds a record of, in every
                   state, as one JSON object, valley-changes/v1, for front
                   ends to read (docs/architecture.md): each version's
                   head, title and branch, how far it has landed
                   (landed, landed-recorded, uncertain or not-landed),
                   its pending request and its last outcome, and the
                   branches no change is on. handles are unique across
                   everything listed: a change id recorded in more than
                   one repository listed has the handle <repo>:<prefix>
                   in each. without --all it covers this
                   repository. --all covers every project the serving
                   host lists at refs/the-valley/projects in its instance
                   repository, which policy/valley names at main's tip on
                   origin; each project's URL is the instance's with its
                   last path segment replaced, and is read through a clone
                   kept under $XDG_CACHE_HOME/valley/repos. a url that
                   opens with a dash, names a <transport>:: helper such
                   as ext::, or has a scheme other than ssh, git, https or
                   file is refused. a repository that cannot be read is
                   listed with its error. --repo limits it to one
                   project. landed means on main's first-parent history
                   with no merge above it. landed-recorded needs a landed
                   commit with one parent and the integrator's transfer
                   statement for the version's request name, verified;
                   the integrator's outcome record for that name saying
                   land at the version's head; and the integrator's merge
                   of the head onto the landed commit's parent giving the
                   landed tree. the statement is verified with these:
                   VALLEY_KNOWN_SIGNERS names the registry's known-signers
                   file and VALLEY_INTEGRATOR_SIGNER the integrator's
                   signing name, and attest checks the note.
                   needs the valley-go helper.
  review <change>  page through the change's branch: its log and diff vs
                   origin/main. then choose:
                     [a]pprove    file an integration request for the
                                  head shown. runs the
                                  checks the composed policy requires of
                                  this change over a throwaway worktree of
                                  that head, signs each result as an
                                  attestation, and publishes the evidence
                                  and the request ref to origin in ONE
                                  atomic push. this files the request;
                                  it does not wait for integration or
                                  update your local checkout. use status
                                  to read the result. the policy comes
                                  from the target's tip and the owning
                                  valley's, as checks describes below,
                                  so your checkout
                                  can be on any branch. a change the policy
                                  requires no check of is filed too, as a
                                  request with no evidence, and says so.
                                  approving a change already requested is
                                  how it is filed again. at a head rebased
                                  onto a moved main it replaces the request
                                  ref under a lease and names the head it
                                  replaced; at the same head it leaves the
                                  ref alone and publishes only the new
                                  evidence, which the create-only
                                  attestation namespace refuses when this
                                  signer has already attested that tree
                                  (bd-7b7d58f). every write of the request
                                  ref is leased, filing included, so an
                                  approval that lost a race is refused
                                  rather than clobbering the one that won.
                                  needs the attest helper and
                                  VALLEY_ATTEST_KEY, the ed25519 key this
                                  host signs with, whenever a check is
                                  owed; VALLEY_ATTEST_NAME is the name it
                                  signs under, defaulting to this host's.
                     [r]eject     delete the remote branch (confirmed first)
                     [s]kip       do nothing
                   when [a]pprove's checks fail, the prompt says approving
                   needs a new head and stops offering [a]pprove until the
                   change has one. any other refusal keeps the prompt as
                   it was.
                   [a]pprove is the only way a change reaches main from
                   here, and approve below is the same act without the
                   pager.
                   Nothing in this script writes the protected ref: the
                   integrator does, having judged the request.
                   a stale branch (won't fast-forward from main) is first
                   offered:
                     [b]ase       rebase it onto origin/main in a throwaway
                                  worktree, push --force-with-lease, then
                                  re-review the diff that would actually land
                   [a]pprove is offered there too: a stale branch is nothing
                   the integrator cannot apply, so it need not be rebased
                   first.
                   while paging, press v: less opens the diff in $EDITOR.
                   every line you insert there is a note. it is anchored to
                   the file and new-side line it sits on — to the file alone
                   when it sits above the first hunk — then appended to
                   $XDG_STATE_HOME/valley/notes/<branch>.md (default
                   ~/.local/state) and printed after the verdict. notes
                   survive [b]ase. lines you change or delete instead of
                   inserting are ignored, with a warning.
  approve [--head <sha>] <change>
                   do what review's [a]pprove does for the change, without
                   paging it: the same checks, the same refusals, the same
                   leased request write and the same output. exits non-zero
                   when it refuses. a change with a record is approved at
                   exactly one head, and its request is filed as
                   refs/the-valley/integration-requests/main/c-<change id>,
                   at that head:
                     --head SHA   approve exactly this head, which must be
                                  one of the record's version heads,
                                  active or not. a front end passes the
                                  head it showed, so a record that moves
                                  after review cannot change what lands.
                   without --head, approve shows the active version's head
                   and title and asks to confirm them, on a terminal; off
                   one it refuses. a branch no record is on is approved at
                   its tip on origin, which --head must name if it is
                   given, under the branch's request name: the branch with
                   each / replaced by -. a branch whose request name would
                   be c-<change id> is refused, since that name is the
                   change's.
  rebase <change>  do what review's [b]ase does for the change: rebase it
                   onto origin/main in a throwaway worktree and push it
                   with --force-with-lease, then print its new head. for a
                   change with a record, it rebases the active version's
                   head, pushes the branch that version names, and then
                   adds the rebased head as a new version, as
                   valley.principal names, the way ready --if-active does:
                   only while the change is still ready at the head the
                   rebase began with. a version that names no branch is
                   refused. it does not re-review the result. a change
                   that already fast-forwards from main is left as it is.
  status [--json] <change>
                   read the request and the integrator's last decision from
                   origin. distinguish waiting, a decision that needs
                   attention, and a change integrated into origin/main.
                   a change with a record is read at its active version's
                   head, under c-<change id>, and the status says the
                   version, its title, the owner, and how far the version
                   has landed, as changes reads it. a refusal for a record
                   that is not ready, or for a merge in the change's
                   commits, is a state of its own.
                   after integration, show how to update the local checkout.
                   fetches objects without moving local branches or files;
                   no checks run and no request is filed.
                     --json       print the status as one JSON object,
                                  valley-status/v1, for front ends to read
                                  (docs/architecture.md). an error prints
                                  no object: it goes to stderr and the exit
                                  status is non-zero.
                   needs the valley-go helper.
  ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
                   mark a head of the branch ready, as a new version of its
                   change, in the change's record on origin:
                   refs/the-valley/changes/main/<change id>. the branch
                   defaults to the current one. the head is --head, or else
                   origin/<branch>, and it must be on origin already. the
                   first ready of a change makes v1; each later one adds
                   the next version, at a head other than the active
                   version's. a draft or a withdrawn change comes back this
                   way: at the active version's head, it is ready again at
                   that version, and at another head it gains the next
                   version. prints the handle and version, e.g.
                   `cosmo nxvp v2 ready`.
                   the change id is --change, else the head commit's jj
                   change-id header, else a Change-Id: trailer in its
                   message, else a new one, which is printed. a header and
                   a trailer that disagree are refused. so is a change
                   whose commits from its merge base with origin/main hold
                   a merge, or that has more than one merge base.
                     --if-active SHA
                                  add the version only while the change
                                  is ready at an active version whose head
                                  is SHA. the record ref is leased on the
                                  record read, so nothing comes between
                                  that check and the write. rebase readies
                                  the head it rebased this way.
                     --stamp      amend the head of your local branch to
                                  carry the id as a Change-Id: trailer and
                                  push the branch, leased, before marking it
                                  ready. it only starts a new change: it
                                  is refused for a change that has a
                                  record on origin already, and for a head
                                  already on origin.
                   the record names the principal your key pushes as, read
                   from git config valley.principal; the host refuses one
                   naming anyone else. the record ref is pushed leased on
                   the value read. a new change is owned by the principal
                   that readies it, and a later version may come from its
                   owner or the operator, who holds the request grant.
                   a record never makes anything land, and approve is
                   still the only way to main. the integrator reads
                   records only to refuse: it lands no request whose head
                   is a version of a change that is not ready.
                   needs the valley-go helper.
  unready <change>
                   make a ready change a draft in its record on origin, as
                   its owner or the operator. a draft is a pause: it voids
                   nothing, and approvals of its active version stand when
                   it is readied again. ready brings it back. prints e.g.
                   `cosmo nxvp v2 draft`. needs the valley-go helper.
  withdraw <change>
                   mark a ready change or a draft withdrawn in its record
                   on origin, as its owner or the operator. withdrawing
                   voids everything outstanding on the change: its
                   integration requests, and the approvals and reviews of
                   every version, so a change brought back needs fresh
                   approvals. ready brings it back, at the same version
                   or a new one. prints e.g. `cosmo nxvp v2 withdrawn`.
                   needs the valley-go helper.
                   the integrator lands no request at a head of a change
                   that is not ready, so unready and withdraw both stop a
                   pending integration request, under c-<change id> or a
                   branch's request name. each says so when origin holds
                   one. a draft's request stands and lands once the change
                   is ready again. withdraw warns, since the request it
                   voids would land too once the change is ready again:
                   only a holder of the request grant may touch a request
                   ref, so the operator must drop it.
  checks [<base> [<head>]]
                   print the check names the change between two commits owes
                   under the composed verification policy (dcr-f41f718), and
                   which class made each one required. It prints: no check is
                   run, nothing is gated, nothing is written.
                   base defaults to the merge base with main, head to HEAD.
                   by default both layers come from the target's tip
                   (origin/main), never from your checkout: the project's
                   own layer is policy/project there, and the owning valley
                   is named one line at policy/valley there, fetched and
                   read at policy/instance in that repository's integrated
                   tip. a valley's own config repository carries
                   policy/instance and uses it. a target carrying no
                   policy/project is derived under the floor alone; a floor
                   that is not there is refused. this is what the
                   integrator reads, so the answer is the same from any
                   branch, however stale. an option overrides each layer,
                   which is the only way to derive against a layer that
                   does not govern — the worked example under
                   examples/policy/, say:
                     --schema FILE    default $VALLEY_VERIFICATION_SCHEMA
                     --instance DIR   default the owning valley's floor
                     --project DIR    default policy/project at the target
                   naming a layer stops this reading the source it
                   replaced. the schema is the shape a policy is written
                   in rather than a layer, so it ships with this tool: the
                   package sets VALLEY_VERIFICATION_SCHEMA to its own copy.
                   with that unset, as when this script runs straight from
                   a the-valley checkout, it is schema/verification.cue in
                   the checkout.
                   after the report, two lines group the owed checks by
                   the cost the policy declares, `quick` or `slow`. a slow
                   check takes minutes or needs special hardware. the cost
                   changes nothing owed: approving runs every owed check
                   whatever its cost, and the integrator requires evidence
                   for every one.
                     --names          print only the owed check names,
                                      one per line
                     --cost COST      with --names, only the quick or
                                      the slow ones, e.g.
                                      `valley checks --names --cost slow`
  tail [subject]   watch bus events scroll by (default subject: valley.>);
                   the server comes from the nats CLI's own config
                   (NATS_URL or a nats context; default localhost)
  replay [dir]     publish one ref-updated event per current ref of the
                   repo at dir (default: .) — rebuilds the stream's
                   projection, e.g. after nats stream purge valley
  help             show this help

A change is named by its full change id, by its handle — the shortest
prefix of the id, four letters at least, that no other change recorded on
origin shares, written <repo>:<handle> too, with this repository's name —
or by its branch. A name written origin/<branch> is always
a branch. A handle that is also a branch on origin is refused unless the
change is on that branch. review, approve and rebase read a branch name,
written either way, against every record on origin: when exactly one
record's active version is on the branch, the name is that change, as if
its id were given, and when more than one's is, the verb refuses and lists
their ids. A change whose active version has landed — its head is on
main's first-parent history with no merge above it, or the integrator's
outcome record and verified transfer statement record that exact head
landing — is skipped, so a branch can be used again once its change has
landed. unready, withdraw and status read a branch the same way. A
branch no record's active version is on is acted on as a branch. A
change with a record is reviewed, approved and rebased at the
head its active version records, never at its branch's tip: review shows
that head and its [a]pprove approves it, and rebase and review's
[r]eject refuse, naming both, when the branch's tip on origin is another
commit. approve approves the head bound to it, wherever the branch is.
[r]eject deletes the branch under a lease on the recorded head. approve,
rebase, and review's [a]pprove and [b]ase refuse a change whose record is
not ready, naming its state. Each reads the record again just before it
acts, and again before approve files or rebase pushes, and refuses when
the change is no longer ready. rebase also refuses when the active
version has moved to another head since it began, and approve when the
head it approves is no longer a version's. A name that read as a plain
branch is read again before approve files or rebase pushes, and if it
names a change by then, the change must be ready at the head the verb
began with. An approval already past that last check can still file if
the change is unreadied or withdrawn in the moment before its push; the
integrator refuses to land it, since it lands no request whose head is a
version of a change that is not ready, whatever the request is named.

Runs from any checkout of the project; needs only git and coreutils,
except tail and replay, which also need the nats CLI (natscli), checks,
which also needs the cue CLI, review's notes, which need less, approve
and review's [a]pprove, which need both the cue CLI and the attest
helper, and status, ready, unready, withdraw, review, approve and rebase,
which need the valley-go helper, as pending and changes do.
nix run .#valley bundles all of them. Deriving a policy fetches the owning
valley's repository, so checks and approving also need whatever reaching
it takes.
No config but valley.principal, which ready reads; no batch mode; and no
state but the notes file — the judgment stays with the human.
EOF
}

fetch_origin() {
  git fetch --prune --quiet origin
}

# Resolve the pager as git would for a diff: pager.diff first (per-command
# pager configs — e.g. home-manager's delta module — set pager.diff and leave
# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
# less). pager.<cmd> may legally be a boolean; treat true/false — and an
# empty or missing value — as unset and fall back. The value is
# shell-interpreted, hence sh -c.
diff_pager() {
  local pager
  pager="$(git config --get pager.diff || true)"
  case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
  printf '%s' "$pager"
}

# Page a file rather than a pipe, so less's v key has something to hand
# $EDITOR: with a real file open, v runs LESSEDIT, whose default
# `%E ?lm+%lm. %g` is the editor, +<line>, and the file name. That file is
# the review buffer, and editing it is how notes get written (see
# collect_notes). A pipe has no name, so less refuses to edit one — which is
# why review no longer pipes.
#
# The configured diff pager stays the renderer, but as less's input
# preprocessor rather than as the pager. It still reads the buffer on stdin
# exactly as it did when it was the pager, less displays what it emits, and
# less still calls the raw buffer "the current file" — so v edits the diff
# and not the rendering. The alternative was to page the buffer with no
# filter at all: exact, and it throws delta's rendering away, which is the
# worse trade for a verb whose whole job is reading a diff.
#
# What this costs is the line number. A filter that restructures the diff —
# delta's default rendering does — makes %lm a line of the rendered view, so
# the editor opens near the cursor rather than on it. A structure-preserving
# filter (pager.diff = `delta --color-only`) makes it exact. No anchor
# depends on it: a note is anchored by where it was inserted, not by where
# the editor opened.
page_file() {
  local file="$1" pager
  [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
  pager="$(diff_pager)"
  case "${pager%%[[:space:]]*}" in
    less | */less)
      # Already less: give it the file and there is no filter to run.
      sh -c "$pager \"\$1\"" sh "$file"
      return
      ;;
  esac
  # Without less there is no editor key; fall back to filtering into a pipe.
  command -v less > /dev/null 2>&1 || {
    sh -c "$pager" < "$file"
    return
  }
  # -R because the filter's color is the whole point of running it, and no
  # LESSCLOSE because a stray one would run against a buffer we still read.
  LESSOPEN="|$pager < %s" env -u LESSCLOSE less -R -- "$file"
}

# pending is valley-go's (status/pending.go). The fetch first keeps this
# checkout's remote-tracking branches current, as pending always has. The
# helper runs valley checks for --owes, so it is told how this script was
# run.
cmd_pending() {
  command -v valley-go > /dev/null 2>&1 \
    || die "pending needs the valley-go helper; nix run .#valley bundles it"
  fetch_origin
  VALLEY_COMMAND="$0" exec valley-go pending "$@"
}

# For a change with a record, what is rejected is the head its record
# names. So the branch is deleted only while its tip is that head, and the
# delete is leased on it. When the tip is another commit, reject refuses
# and names both, and deletes nothing. A branch no record names is deleted
# as before.
#
# reject runs inside a condition, where bash suspends `set -e`, so the push
# is checked by hand.
reject() {
  local branch="$1" answer
  local -a lease=()
  if [ -n "$CHANGE_HEAD" ]; then
    check_recorded_tip "$branch" "nothing deleted" || return 1
    lease=("--force-with-lease=refs/heads/$branch:$CHANGE_HEAD")
  fi
  printf 'really delete origin/%s? [y/N] ' "$branch"
  read -r answer || answer=""
  case "$answer" in
    y | Y | yes)
      if ! git push --quiet "${lease[@]}" origin --delete "$branch"; then
        refuse "origin did not delete $branch, which may have moved since the fetch; nothing deleted"
        return 1
      fi
      echo "rejected $branch: deleted from origin"
      ;;
    *) echo "kept $branch" ;;
  esac
}

# ----------------------------------------------------------------------
# review notes — the lines the reviewer inserts into the paged diff.
#
# The buffer the reviewer pages is a file, so the pager's editor key can open
# it (page_file). Whatever comes back with lines inserted is read as notes:
# no marker, no syntax, no mode — an inserted line is a note because it was
# not there before. What a note is *about* is where it sits, so each one is
# anchored to the file and the new-side line number of the diff line above
# it, which is the pair a reviewer would otherwise have to copy out by hand.

# The scratch directory holding the buffer and its pristine copy, and the
# notes taken so far in this review — a global because [b]ase pages a second
# time and the notes from the first pass are not thereby withdrawn.
REVIEW_TMP=""
NOTES=()

cleanup_review_tmp() {
  [ -n "$REVIEW_TMP" ] || return 0
  rm -rf "$REVIEW_TMP"
  REVIEW_TMP=""
}

# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
# they are neither config nor cache, and losing them loses judgment.
notes_file() {
  printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
}

# The anchor of every line of the buffer, by line: the file that line belongs
# to, and the new-side line number it sits on. Built in one pass so that
# anchoring a note is a lookup. An empty path means the line is above every
# file (the log); line 0 means the line is a file header, above every hunk.
ANCHOR_PATH=()
ANCHOR_LINE=()

anchor_buffer() {
  local file="$1" line path="" at=0 next=0 inhunk=0 rest
  ANCHOR_PATH=()
  ANCHOR_LINE=()
  while IFS= read -r line; do
    # Header lines are only headers outside a hunk: inside one, every line
    # carries a +/-/space prefix, so a diff of a diff cannot be misread.
    if [ "$inhunk" -eq 1 ]; then
      case "$line" in
        ' '* | '+'* | '')
          at="$next" # this line's own new-side number
          next=$((next + 1))
          ;;
        '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
        *) inhunk=0 ;;
      esac
    fi
    if [ "$inhunk" -eq 0 ]; then
      case "$line" in
        'diff --git '*)
          path=""
          # The b/ side, so a rename anchors to the name it will have.
          if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
            path="${BASH_REMATCH[2]}"
          fi
          at=0
          ;;
        '@@ '*)
          rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
          at="${rest%%[!0-9]*}"
          [ -n "$at" ] || at=0
          next="$at"
          inhunk=1
          ;;
      esac
    fi
    ANCHOR_PATH+=("$path")
    ANCHOR_LINE+=("$at")
  done < "$file"
}

# The anchor for a note inserted after buffer line n, as it is written down.
anchor_of() {
  local n="$1" path line
  [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
  path="${ANCHOR_PATH[n - 1]:-}"
  line="${ANCHOR_LINE[n - 1]:-0}"
  if [ -z "$path" ]; then
    printf '(unanchored)'
  elif [ "$line" -eq 0 ]; then
    printf '%s' "$path"
  else
    printf '%s:%s' "$path" "$line"
  fi
}

# The notes in an edited buffer, one `anchor: text` line each. git says where
# the reviewer's lines landed; a hunk that removes nothing is an insertion,
# and the line it was inserted after is the anchor. A hunk that removes
# something is an edit of the diff itself — it anchors to nothing, since the
# line it would name is the line it changed — so it is dropped with a count.
notes_in() {
  local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
  anchor_buffer "$orig"
  while IFS= read -r line; do
    case "$line" in
      '@@ '*)
        rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
        at="${rest%%[!0-9]*}"
        rest="${rest#"$at"}"
        old=1
        case "$rest" in
          ,*)
            rest="${rest#,}"
            old="${rest%%[!0-9]*}"
            ;;
        esac
        if [ "$old" -eq 0 ]; then
          insert=1
        else
          insert=0
          touched=$((touched + old))
        fi
        ;;
      '+'*)
        # Only inside an insertion hunk: the +++ of git's own header is not
        # a note, and neither is the new side of an edit.
        [ "$insert" -eq 1 ] || continue
        text="${line#+}"
        text="${text#"${text%%[![:space:]]*}"}"
        [ -n "$text" ] || continue # a blank line says nothing
        printf '%s: %s\n' "$(anchor_of "$at")" "$text"
        ;;
    esac
  done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
  [ "$touched" -eq 0 ] || printf \
    'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
    "$touched" >&2
}

# Read the notes out of the paged buffer and keep them: appended to the
# branch's notes file under the commit they were taken against, and held for
# the print that follows the verdict. A notes file that cannot be written is
# a warning, never a failure — the notes are still printed, and a review is
# not undone by a missing directory.
collect_notes() {
  local branch="$1" sha="$2" file dir
  local -a found=()
  mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
  [ "${#found[@]}" -gt 0 ] || return 0
  NOTES+=("${found[@]}")
  file="$(notes_file "$branch")"
  dir="${file%/*}"
  mkdir -p "$dir" 2> /dev/null && {
    printf '## %s at %s\n\n' "$branch" "$sha"
    printf '%s\n' "${found[@]}"
    printf '\n'
  } >> "$file" 2> /dev/null && return 0
  printf 'valley: warning: could not write %s — the notes are printed only\n' \
    "$file" >&2
}

print_notes() {
  local branch="$1"
  [ "${#NOTES[@]}" -gt 0 ] || return 0
  printf '\n%d note(s) on %s, appended to %s:\n' \
    "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
  printf '  %s\n' "${NOTES[@]}"
}

show_review() {
  local branch="$1" head sha
  head="$(change_head "$branch")"
  sha="$(git rev-parse --short "$head")"
  REVIEW_TMP="$(mktemp -d)"
  {
    if [ -n "$CHANGE_HEAD" ]; then
      printf 'change %s v%s at %s, on branch %s, log against origin/main:\n\n' \
        "$CHANGE_HANDLE" "$CHANGE_VERSION" "$sha" "$branch"
    else
      printf 'branch %s, log against origin/main:\n\n' "$branch"
    fi
    git --no-pager log --oneline "origin/main..$head"
    printf '\n'
    git --no-pager diff "origin/main...$head"
  } > "$REVIEW_TMP/review.diff"
  cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
  page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
  collect_notes "$branch" "$sha"
  cleanup_review_tmp
}

# Throwaway worktree for review's [b]ase choice; a global so the traps can
# always clean it up — success, conflict, or ctrl-C. Never a mid-rebase state.
REBASE_WT=""
cleanup_rebase_wt() {
  [ -n "$REBASE_WT" ] || return 0
  git -C "$REBASE_WT" rebase --abort >/dev/null 2>&1 || true
  git worktree remove --force "$REBASE_WT" >/dev/null 2>&1 || true
  rm -rf "$REBASE_WT"
  REBASE_WT=""
}

# Everything review, approve and rebase leave outside the repository: the
# two throwaway worktrees, the paged buffer, the two policy layers read out
# of their tips, and the scratch the policy deriver writes into. One
# handler, installed once by each of those verbs, so that no path through
# them — and no ctrl-C in the pager — leaves any of them behind.
cleanup_scratch() {
  cleanup_rebase_wt
  cleanup_approve_wt
  cleanup_policy_tmp
  cleanup_instance_tmp
  cleanup_project_tmp
  cleanup_review_tmp
}

# Rebase origin/<branch> onto origin/main in an isolated worktree — the
# user's checkout is never touched — and push with a lease so a concurrently
# updated branch is never clobbered. Mechanics only; the judgment on the
# rebased diff stays with the human, back at the review prompt or in
# whatever front end ran the rebase verb.
#
# Every step is checked by hand rather than left to `set -e`, because
# rebase_change runs this inside a condition, where bash suspends `set -e`
# for the whole call. An unchecked step that failed there would leave
# REBASE_WT empty, and `git -C ""` would rebase and push the user's own
# checkout.
#
# The commit rebased is the second argument when given, the head a change's
# record names, and otherwise origin/<branch> as the fetch left it. It is
# read once, and the push is leased on exactly that commit, so a fetch that
# moves origin/<branch> meanwhile changes neither. The rebased head is left
# in REBASED_HEAD.
REBASED_HEAD=""
rebase_onto_main() {
  local branch="$1" from="${2:-}" rebased
  if [ -z "$from" ]; then
    from="$(git rev-parse --verify --quiet "refs/remotes/origin/$branch^{commit}")" \
      || die "no such branch on origin: $branch; nothing changed"
  fi
  REBASE_WT="$(mktemp -d)" && [ -d "$REBASE_WT" ] || {
    REBASE_WT=""
    die "could not make a directory for the rebase; nothing changed"
  }
  git worktree add --quiet --detach "$REBASE_WT" "$from" || {
    cleanup_rebase_wt
    die "could not check out origin/$branch for the rebase; nothing changed"
  }
  if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
    cleanup_rebase_wt
    die "$branch conflicts with main — resolve by hand; nothing changed"
  fi
  rebased="$(git -C "$REBASE_WT" rev-parse HEAD)" || {
    cleanup_rebase_wt
    die "could not read the rebased head of $branch; nothing pushed"
  }
  # A change with a record is read once more, just before the push, and a
  # name that read as a plain branch is read again in case it names a
  # change now.
  #
  # This is the last check, and a window remains between it and the push
  # below. A change unreadied or withdrawn in that window is rebased all
  # the same. git compares only the refs a push changes, and the record ref
  # is not one of them, so no client can make the push conditional on the
  # record. rebase_change then adds the rebased head as a version only
  # while the change is still ready at the head it began with, under a
  # lease on the record, so a change unreadied in that window stays a draft
  # at its old head, and the integrator lands nothing for it.
  if ! check_record "nothing pushed" "$from"; then
    cleanup_rebase_wt
    exit 1
  fi
  if ! git -C "$REBASE_WT" push --quiet "--force-with-lease=refs/heads/$branch:$from" \
    origin "HEAD:refs/heads/$branch"; then
    cleanup_rebase_wt
    die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
  fi
  cleanup_rebase_wt
  REBASED_HEAD="$rebased"
  echo "rebased $branch onto origin/main, pushed with --force-with-lease"
  printf '  head     %s\n' "$rebased"
}

# ----------------------------------------------------------------------
# approve — file an integration request for the branch under review.
#
# This is the one way a change reaches main from here: the checks the
# policy requires are run over the branch's tree and signed, the evidence
# and one request ref are published, and the integrator judges the request
# and lands it (archive/design/integration.md). main is never touched from here.
#
# Nothing in this script writes the protected ref. Whether a given pusher
# may write it is a fact about origin's pre-receive hook, so origin is
# where it is answered, and a verb that merged onto main locally would only
# be asking the same question in a worse place.
#
# What this verb removes is a second push. `attest run --push` publishes
# the branch and the attestation refs in one atomic push and knows nothing
# about a request ref, so filing a request by hand is two beats: the
# evidence, then the request after it. In between, evidence stands
# published for a change nobody has approved. So this verb does not
# use --push at all. `attest run` without it stores each note at its ref in
# the repository and stops, and one `git push --atomic` then carries the
# evidence and the request together — all of it or none of it. Nothing in
# attest had to change for that; the sequencing was the whole of it.
#
# The branch itself is not in that push. What is under review is
# origin/<branch>, so the commit the request names is already on origin and
# the objects with it.

# The tree the checks run over: a throwaway worktree of the branch, as
# [b]ase uses, so that what is checked is the branch's tree and not the
# operator's working copy. A global, so the traps clean it up whatever
# happens.
APPROVE_WT=""
# The head approve last ran the checks over and saw them fail, for the
# review prompt: see approve_failed_at.
CHECKS_FAILED_AT=""
cleanup_approve_wt() {
  [ -n "$APPROVE_WT" ] || return 0
  git worktree remove --force "$APPROVE_WT" > /dev/null 2>&1 || true
  rm -rf "$APPROVE_WT"
  APPROVE_WT=""
}

# Report and fail, without leaving the review. A refusal here is not a
# reason to end the session: the branch is still under review and the
# operator can still answer. die() is for the verbs that have nothing left
# to offer. The approve verb has nothing left to offer either, and turns a
# refusal into its exit status itself.
refuse() {
  printf 'valley: %s\n' "$*" >&2
  return 1
}

# The change segment of a request ref. The integrator reads a request as
# <prefix>/<target>/<change> and refuses a change segment holding a slash
# (integrator/refs.go), so a branch name with one is written with dashes
# instead. The ref that results is printed, never left to be assumed.
#
# The mapping is lossy: `topic/x` and `topic-x` are one change name and so
# one request ref, and this verb cannot tell a sibling's request from its
# own. That is bd-57f7f9f, and what is done about it here is to print the
# subject of any request being replaced, so a collision is visible at the
# moment it happens rather than after it.
change_name() {
  printf '%s' "${1//\//-}"
}

# One line of a commit, for saying which commit is meant. A request being
# replaced is usually this operator's own pre-rebase head and so is in
# this repository; one another operator filed may not be, and saying so is
# better than printing an id alone.
subject_of() {
  local s
  if s="$(git log -1 --format=%s "$1" 2>/dev/null)" && [ -n "$s" ]; then
    printf '%s' "$s"
  else
    printf 'subject not in this repository'
  fi
}

# The value of a ref on origin, as one id or the empty string. Failing to
# read it is not the same as reading that it is absent, so the two are
# separate answers: this returns 1 for a read that did not happen.
remote_ref() {
  local out
  out="$(git ls-remote origin "$1" 2>/dev/null)" || return 1
  printf '%s' "$out" | cut -f1
  return 0
}

# Where the checks this run signed are stored, for every failure that
# happens after they have run. One stanza, so no failure path invents its
# own wording. Called with no refs it says nothing.
report_local_evidence() {
  [ "$#" -gt 0 ] || return 0
  printf 'valley: the evidence is stored locally at:\n' >&2
  printf '  %s\n' "$@" >&2
}

# Whether origin already holds one of these attestation refs at a value
# other than the one being pushed. The namespace admits creations only, so
# that is the one refusal approving again will never clear: it is what a
# re-observation of a tree this signer has already attested runs into
# (bd-7b7d58f).
attestation_stands_elsewhere() {
  local digest="$1" remote spec have want
  shift
  remote="$(git ls-remote origin "refs/the-valley/attestations/$digest/*" 2>/dev/null)" || return 1
  for spec in "$@"; do
    have="$(printf '%s\n' "$remote" | awk -v r="$spec" '$2 == r { print $1 }')"
    [ -n "$have" ] || continue
    want="$(git rev-parse "$spec" 2>/dev/null)" || continue
    [ "$have" = "$want" ] || return 0
  done
  return 1
}

# Why a push carrying the request ref failed, said as precisely as the
# state allows. Every such push is leased, and a lease refuses when the
# ref it named is not where the read before it saw it — which covers three
# different events. Reading the ref again is what tells them apart, and a
# read that does not happen is its own answer rather than a guess.
#
# Anything the lease is not responsible for is origin's own refusal, and
# git has already printed it.
diagnose_request_push() {
  local ref="$1" pending="$2" now
  if ! now="$(remote_ref "$ref")"; then
    refuse "origin refused the push, and $ref could not be read again to say why. Nothing was published there and main is untouched"
    return 0
  fi
  if [ "$now" = "$pending" ]; then
    refuse "origin refused the push; nothing was published there and main is untouched"
  elif [ -z "$now" ]; then
    refuse "the pending request was consumed while this one was being prepared, which is what the integrator does when a change lands. The lease on $ref refused and nothing was published; fetch and review the branch again before approving it a second time"
  elif [ -z "$pending" ]; then
    refuse "a request for this change appeared while this one was being prepared, at $(git rev-parse --short "$now") ($(subject_of "$now")); the lease on $ref refused and nothing was published"
  else
    refuse "the pending request moved from $(git rev-parse --short "$pending") to $(git rev-parse --short "$now") while this one was being prepared; the lease on $ref refused, nothing was published, and the request stands where the other approval put it"
  fi
}

# File the request. Called in a condition, from the review prompt and from
# the approve verb alike, which suspends `set -e` for the whole call — so
# every step below is checked by hand, and the failures say what was
# published before they happened.
approve() {
  local branch="$1" target=main tip change head base digest root ref check spec what
  local key
  local -a signer=() owed=() run=() evidence=()

  root="$(git rev-parse --show-toplevel)" || {
    refuse "not a git repository; nothing published"
    return 1
  }
  tip=refs/remotes/origin/main
  # A change with a record is filed at exactly the head bound to this
  # approval, under its own request name, c-<change ID>, and only while its
  # record says it is ready and lists that head as a version's. Where its
  # branch is does not matter: the request names the head.
  if [ -n "$CHANGE_ID" ]; then
    head="$APPROVE_HEAD"
    [ -n "$head" ] || {
      refuse "no head of change $CHANGE_HANDLE is bound to this approval; nothing published"
      return 1
    }
    check_record "nothing published" "" "$head" || return 1
    change="c-$CHANGE_ID"
    what="$CHANGE_HANDLE v$APPROVE_VERSION"
  else
    head="$(git rev-parse "refs/remotes/origin/$branch")" || {
      refuse "no such branch on origin: $branch; nothing published"
      return 1
    }
    change="$(change_name "$branch")"
    what="$branch"
    # c-<change ID> is the request name of the change with that ID, so a
    # branch is never filed under one.
    if [[ "$change" =~ ^c-[k-z]{32}$ ]]; then
      refuse "the branch $branch would be requested as $change, and that name is reserved for the change with the ID ${change#c-}; rename the branch, or name the change by its ID. Nothing published"
      return 1
    fi
  fi
  base="$(git merge-base "$tip" "$head")" || {
    refuse "$what and main share no history; nothing published"
    return 1
  }
  ref="refs/the-valley/integration-requests/$target/$change"

  # What the change owes, read out of exactly the sources the integrator
  # reads: both layers from the target's tip, which review has just
  # fetched, and the floor from the owning valley's own tip. A change never
  # supplies the policy that gates it, and neither does the checkout this
  # runs from — so the answer here is the same answer the integrator will
  # derive, from whatever branch the operator happens to be on. It is
  # printed for exactly that reason.
  policy_defaults "$root"
  resolve_instance_layer "$root" "$tip" || return 1
  resolve_project_layer "$root" "$tip" || return 1
  derive_owed "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" \
    "$base" "$head" || return 1
  sort_into owed "${!DERIVED_OWED[@]}" || {
    refuse "could not sort the owed checks; nothing published"
    return 1
  }

  # A change the policy asks nothing of is still a change, and approving
  # is how one reaches main. The integrator already lands a request owing no
  # check and records the landing as one that required nothing
  # (archive/design/integration.md), so refusing to file it here would strand
  # exactly the changes the policy requires nothing of. Nothing is owed, so
  # nothing is signed and no key is needed: what gets published is one
  # request ref and no evidence at all.
  if [ "${#owed[@]}" -gt 0 ]; then
    key="${VALLEY_ATTEST_KEY:-}"
    [ -n "$key" ] || {
      refuse "no signing key: set VALLEY_ATTEST_KEY to the ed25519 key this host attests with. The host signs; nothing published"
      return 1
    }
    [ -f "$key" ] || {
      refuse "no signing key at $key; nothing published"
      return 1
    }
    command -v attest > /dev/null 2>&1 || {
      refuse "this choice needs the attest helper; nix run .#valley bundles it. Nothing published"
      return 1
    }
    signer=(--key "$key")
    [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")

    for check in "${owed[@]}"; do
      case "${CHECK_RUNNER[$check]:-}" in
        nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
        command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
        *)
          refuse "the policy requires $check but does not say how to run it; nothing published"
          return 1
          ;;
      esac
    done

    cleanup_approve_wt
    APPROVE_WT="$(mktemp -d)" || {
      refuse "no scratch directory to check $branch in; nothing published"
      return 1
    }
    git worktree add --quiet --detach "$APPROVE_WT" "$head" || {
      cleanup_approve_wt
      refuse "could not check $what out to run its checks; nothing published"
      return 1
    }

    printf '\nchecking %s at %s: %s\n' "$what" "$(git rev-parse --short "$head")" \
      "$(printf '%s\n' "${owed[@]}" | join_lines)"
    if ! attest run --repo "$APPROVE_WT" "${signer[@]}" "${run[@]}"; then
      cleanup_approve_wt
      CHECKS_FAILED_AT="$head"
      refuse "the checks did not pass; nothing published, main untouched"
      return 1
    fi
    digest="$(attest digest --repo "$APPROVE_WT")" || {
      cleanup_approve_wt
      refuse "could not digest the tree that was checked; nothing published"
      return 1
    }
    cleanup_approve_wt
    digest="${digest#*:}"

    # Every attestation stored for this tree, whoever signed it: the
    # evidence for this change is what the subject digest is keyed by, not
    # what this run happened to add to it.
    mapfile -t evidence < <(git for-each-ref --format='%(refname)' \
      "refs/the-valley/attestations/$digest")
    [ "${#evidence[@]}" -gt 0 ] || {
      refuse "no attestation is stored for $digest; nothing published"
      return 1
    }
  else
    printf '\n%s owes no check under %s + %s; filing the request with no evidence\n' \
      "$what" "$POLICY_INSTANCE_LABEL" "$POLICY_PROJECT_LABEL"
  fi

  # What origin already holds for this request, read once and remembered.
  # Approving the same change twice is ordinary: evidence expires, and a
  # change whose input closure moved under it is told to re-attest. So the
  # request ref may already exist, and what to do about it depends on
  # where it points. A read that does not happen is not a read that found
  # nothing, so it ends the verb here.
  local pending
  if ! pending="$(remote_ref "$ref")"; then
    refuse "could not read $ref from origin; nothing published"
    report_local_evidence ${evidence[@]+"${evidence[@]}"}
    return 1
  fi

  # The one push: every evidence ref as it stands, and the request ref
  # wherever it has to go. --atomic, so a hook that refuses any of them
  # leaves origin exactly as it was.
  #
  # Every write of the request ref is leased against exactly what the read
  # above saw, including when it saw nothing: git spells that expectation
  # `--force-with-lease=<ref>:` with an empty value, and it refuses if the
  # ref exists at all. So filing a change for the first time is a
  # compare-and-swap too. Without it, two operators filing one change at
  # once would have the second silently fast-forward the first away.
  #
  # A pending request at this same head is a re-attestation of the tree
  # already approved. The evidence is new and the ref does not move, so
  # the ref is left out of the refspec entirely — a push cannot carry a
  # compare-and-swap on a ref it is not changing, because git leaves an
  # up-to-date ref out of what it sends. Nothing this run does establishes
  # where that ref stands afterwards, so it is read again below.
  #
  # A pending request at a different head is a replacement. This is the
  # shape a change takes when main moved through its checks' input
  # closures: no attestation over the old tree can transfer again, so the
  # cure is a new head rebased onto the moved main — and that head is not
  # a descendant of the old one, which makes replacing the ref a
  # non-fast-forward update that git refuses unless told.
  #
  # The lease is the whole of the force, and the refspec carries no `+`.
  # A leading `+` sets git's per-ref force flag, and that flag defeats
  # every rejection the push rules produce — the lease's stale-info among
  # them. The two together are a plain force wearing a lease's name.
  local -a push=() lease=()
  for spec in ${evidence[@]+"${evidence[@]}"}; do push+=("$spec:$spec"); done
  if [ "$pending" != "$head" ]; then
    lease+=("--force-with-lease=$ref:$pending")
    push+=("$head:$ref")
  fi

  # The checks can take minutes, and the record may have moved meanwhile.
  # So it is read once more, just before anything is filed, and a name that
  # read as a plain branch is read again in case it names a change now.
  #
  # This is the last check, and a window remains between it and the push
  # below. A change unreadied or withdrawn in that window is filed all the
  # same. git compares only the refs a push changes, and the record ref is
  # not one of them, so no client can make the filing conditional on the
  # record. The integrator closes the window: it lands no request whose
  # head is a version of a change that is not ready, whatever the request
  # is named, so a request filed in the window stays until the change is
  # ready again.
  if ! check_record "nothing published" "$head" "$APPROVE_HEAD"; then
    report_local_evidence ${evidence[@]+"${evidence[@]}"}
    return 1
  fi

  # Nothing owed and the request already standing at this head leaves
  # nothing to push at all, and a push assembled with an empty refspec
  # would fall back to origin's default one. So none is made.
  local made_push=no
  if [ "${#push[@]}" -gt 0 ]; then
    made_push=yes
    if ! git push --atomic --quiet ${lease[@]+"${lease[@]}"} origin "${push[@]}"; then
      if [ "${#lease[@]}" -eq 0 ] \
        && attestation_stands_elsewhere "$digest" ${evidence[@]+"${evidence[@]}"}; then
        refuse "origin already holds an attestation for this tree from this signer, and that namespace admits creations only, so a second observation of the same tree has nowhere to go. That is bd-7b7d58f rather than anything approving again will clear. Nothing was published and main is untouched"
      else
        diagnose_request_push "$ref" "$pending"
      fi
      report_local_evidence ${evidence[@]+"${evidence[@]}"}
      return 1
    fi
  fi

  # The lines under the request line, which differ by what was found and
  # what was done about it.
  local -a standing=()

  if [ "$pending" = "$head" ]; then
    # The request ref was not in that push, so where it stands now is not
    # something this run established. Read it again rather than repeat
    # what was read before it: in between, the integrator may have landed
    # the change and consumed the ref, or another approval may have
    # replaced it.
    #
    # Nothing here writes it back. Re-creating a consumed request would
    # file a change already in the stream, which the commit rule calls out
    # as the state it consumes the ref to avoid; replacing a request
    # another approval has just filed would clobber the winner; and
    # either would be a second push behind the one this verb promises. So
    # what this does is say what is true and stop. Approving again is the
    # repair, and by then it takes the create or the replace path against
    # what is actually there.
    local after
    if ! after="$(remote_ref "$ref")"; then
      refuse "$ref could not be read again, so whether the request still stands at this head is not known here"
      report_local_evidence ${evidence[@]+"${evidence[@]}"}
      return 1
    fi
    if [ -z "$after" ]; then
      refuse "the request was consumed while this run was working, which is what the integrator does when a change lands. Nothing here re-filed it: a request for a change already in the stream is judged against an empty delta on every pass. Fetch and review $what again, and approve it once more if it has not landed"
      report_local_evidence ${evidence[@]+"${evidence[@]}"}
      return 1
    fi
    if [ "$after" != "$head" ]; then
      refuse "the request moved to $(git rev-parse --short "$after") ($(subject_of "$after")) while this run was working, so another approval filed it. Nothing here replaced it; approve again to replace it deliberately"
      report_local_evidence ${evidence[@]+"${evidence[@]}"}
      return 1
    fi
    if [ "$made_push" = yes ]; then
      standing+=("the request already stood at this head; the evidence is what was published")
    else
      standing+=("the request already stood at this head and nothing was owed, so nothing needed publishing")
    fi
  elif [ -n "$pending" ]; then
    standing+=("replaced the pending request, which stood at $(git rev-parse --short "$pending") ($(subject_of "$pending"))")
  fi

  printf '\nApproved %s (%s): its integration request for origin/%s is filed.\n' \
    "$what" "$(git rev-parse --short "$head")" "$target"
  printf 'The integrator will decide whether this change can land.\n'
  printf 'Your local checkout has not changed.\n\n'
  local named="$branch"
  [ -z "$CHANGE_ID" ] || named="$CHANGE_HANDLE"
  printf 'Check the result: valley status %q\n\n' "$named"
  printf '  request  %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
  [ "${#standing[@]}" -eq 0 ] || printf '  %s\n' "${standing[@]}"
  if [ "${#evidence[@]}" -eq 0 ]; then
    printf '  evidence none — nothing was owed, so nothing was signed\n'
    printf '  checks   none — the policy requires no check of this change\n'
  else
    printf '  evidence %s\n' "${evidence[@]}"
    printf '  checks   %s\n' "$(printf '%s\n' "${owed[@]}" | join_lines)"
  fi
}

# status, ready, unready and withdraw are a Go program, valley-go
# (status/). status reads a change's request and outcome from origin,
# because what front ends read from it is a JSON contract, and because the
# read is subtle enough to want a real parser: an outcome record it does
# not recognise must read as unknown, never as success. It writes nothing
# and moves no local branch. ready, unready and withdraw write a change's
# record, in the one format the push hook reads it in (change/).
cmd_go() {
  command -v valley-go > /dev/null 2>&1 \
    || die "$1 needs the valley-go helper; nix run .#valley bundles it"
  exec valley-go "$@"
}

# A change is named by its full change ID, its handle, or its branch.
# resolve_change reads the name with the helper and sets CHANGE_BRANCH, the
# branch to act on. When the name is a change's, it also sets the change's
# ID, handle, active version and state, and CHANGE_HEAD, the head that
# version records. A branch name is a change's when exactly one record's
# active version is on that branch, and is refused when more than one's is.
# So whether a change's record is read never depends on how it is named,
# and review, approve and rebase cannot run without the helper.
#
# A change with a record is acted on at a head its record names, and never
# at the branch's tip: review and rebase at CHANGE_HEAD, and approve at the
# head bound to it (bind_head). The branch a record names is only where its
# head is expected to be, and anyone who can push the branch can move it,
# in the same push as the record if they like.
CHANGE_NAME="" CHANGE_ID="" CHANGE_HANDLE="" CHANGE_VERSION="" CHANGE_HEAD="" CHANGE_BRANCH="" CHANGE_STATE=""
resolve_change() {
  local line kind
  CHANGE_NAME="$1"
  command -v valley-go > /dev/null 2>&1 \
    || die "review, approve and rebase read the change's record with the valley-go helper; nix run .#valley bundles it"
  line="$(valley-go resolve "$1")" || return 1
  IFS=$'\t' read -r kind CHANGE_ID CHANGE_HANDLE CHANGE_VERSION CHANGE_HEAD CHANGE_BRANCH CHANGE_STATE <<< "$line"
  case "$kind" in
    branch)
      CHANGE_BRANCH="$CHANGE_ID"
      CHANGE_ID=""
      ;;
    change)
      [[ "$CHANGE_HEAD" =~ ^[0-9a-f]{40}$ ]] \
        || die "valley-go resolve named the head $CHANGE_HEAD, which is no object ID"
      case "$CHANGE_STATE" in
        ready | draft | withdrawn) ;;
        *) die "valley-go resolve named the state $CHANGE_STATE, which this script does not read" ;;
      esac
      ;;
    *) die "valley-go resolve answered $line, which this script does not read" ;;
  esac
}

# The commit review, approve and rebase act on: the recorded head for a
# change with a record, and otherwise the branch's head on origin.
change_head() {
  if [ -n "$CHANGE_HEAD" ]; then
    printf '%s\n' "$CHANGE_HEAD"
  else
    git rev-parse "refs/remotes/origin/$1"
  fi
}

# For a change with a record, refuse unless the branch's tip on origin is
# the recorded head, and name both. rebase and review's [r]eject act on
# the branch itself: rebasing or deleting it while it is elsewhere would
# rebase or delete a commit no version records. approve does not ask this,
# since the request it files names the head it approves and not the
# branch. The second argument is what the refusal leaves undone.
check_recorded_tip() {
  local branch="$1" undone="$2" tip
  [ -n "$CHANGE_HEAD" ] || return 0
  tip="$(git rev-parse "refs/remotes/origin/$branch")" || {
    refuse "no such branch on origin: $branch; $undone"
    return 1
  }
  [ "$tip" = "$CHANGE_HEAD" ] && return 0
  refuse "change $CHANGE_HANDLE v$CHANGE_VERSION records the head $CHANGE_HEAD, and origin/$branch is at $tip; $undone. Ready the branch's head as a new version of $CHANGE_HANDLE to act on it"
}

# For a change with a record, read the record again from origin, and
# refuse unless the change is still ready at the head this run began with.
# A draft is paused and a withdrawn change given up, and neither is
# approved or rebased until it is readied again. The record was read when
# review, approve or rebase began, and another principal may unready,
# withdraw or ready a new version of the change while a review is open or
# the checks run. So approve reads it again before it runs the checks and
# before it files, and rebase before it starts and before it pushes. These
# checks save a run that would come to nothing: the integrator makes the
# same one on origin, and lands no request for a change that is not ready.
#
# A name that read as a plain branch can come to name a change meanwhile:
# someone readies the branch, and perhaps unreadies it, while the review
# is open. So the last check before approve files and before rebase
# pushes reads the original name again too. Those two callers pass the
# head they are about to act on as the second argument. When the name now
# names a change, the same rules hold: the change must be ready, and its
# recorded head must be that head. The first argument is what the refusal
# leaves undone.
#
# approve binds the head it approves (APPROVE_HEAD), and passes it as the
# third argument. For approve the change must be ready, and that head must
# be one of its version heads, whichever version is active by then: a
# record that moves after review cannot change what lands, since the
# request names the head approved.
check_record() {
  local undone="$1" acting="${2:-}" bound="${3:-}" line kind id handle version head branch state
  if [ -z "$CHANGE_ID" ]; then
    [ -n "$acting" ] || return 0
    if ! line="$(valley-go resolve "$CHANGE_NAME")"; then
      refuse "could not read $CHANGE_NAME again against origin's records; $undone"
      return 1
    fi
    IFS=$'\t' read -r kind id handle version head branch state <<< "$line"
    [ "$kind" = change ] || return 0
    if [ "$state" != ready ]; then
      refuse "$CHANGE_NAME is now change $handle v$version, which is $state, not ready; $undone. Ready it first: valley ready --change $id $(printf '%q' "$branch")"
      return 1
    fi
    if [ "$head" != "$acting" ]; then
      refuse "$CHANGE_NAME is now change $handle v$version, which records the head $head, and this run began at $acting; $undone. Review it again by its handle"
      return 1
    fi
    return 0
  fi
  if ! line="$(valley-go resolve "$CHANGE_ID")"; then
    refuse "could not read the record of change $CHANGE_HANDLE again; $undone"
    return 1
  fi
  IFS=$'\t' read -r kind id handle version head branch state <<< "$line"
  if [ "$kind" != change ] || [ "$id" != "$CHANGE_ID" ]; then
    refuse "origin no longer holds a record of change $CHANGE_HANDLE; $undone"
    return 1
  fi
  if [ "$state" != ready ]; then
    refuse "change $CHANGE_HANDLE v$version is $state, not ready; $undone. Ready it first: valley ready --change $CHANGE_ID $(printf '%q' "$branch")"
    return 1
  fi
  if [ -n "$bound" ]; then
    check_version "$undone" "$bound"
    return
  fi
  if [ "$head" != "$CHANGE_HEAD" ]; then
    refuse "change $CHANGE_HANDLE is at v$version, $head, and this run began at v$CHANGE_VERSION, $CHANGE_HEAD; $undone. Review it again at its new head"
    return 1
  fi
}

# For a change with a record, read its versions from origin again, and
# refuse unless the change is ready and the head given is one of its
# versions' heads. Sets APPROVE_VERSION and APPROVE_TITLE to that
# version's number and title. The first argument is what the refusal
# leaves undone.
APPROVE_VERSION="" APPROVE_TITLE=""
check_version() {
  local undone="$1" head="$2" out n vhead vstate title state=""
  local -a known=()
  APPROVE_VERSION="" APPROVE_TITLE=""
  if ! out="$(valley-go versions "$CHANGE_ID")"; then
    refuse "could not read the versions of change $CHANGE_HANDLE; $undone"
    return 1
  fi
  # read empties its variables at the end of its input, so the state is
  # kept apart from them.
  while IFS=$'\t' read -r n vhead vstate title; do
    state="$vstate"
    known+=("v$n at $vhead")
    if [ "$vhead" = "$head" ]; then
      APPROVE_VERSION="$n"
      APPROVE_TITLE="$title"
    fi
  done <<< "$out"
  if [ "$state" != ready ]; then
    refuse "change $CHANGE_HANDLE is $state, not ready; $undone. Ready it first: valley ready --change $CHANGE_ID $(printf '%q' "$CHANGE_BRANCH")"
    return 1
  fi
  if [ -z "$APPROVE_VERSION" ]; then
    refuse "$head is no version of change $CHANGE_HANDLE, whose versions are $(printf '%s\n' "${known[@]}" | join_lines); $undone"
    return 1
  fi
}

# The head approve approves for a change with a record, in APPROVE_HEAD.
# With --head, it is exactly that head, which must be one of the record's
# version heads. A front end that shows the change its own way passes the
# head it showed, so what is approved is what was seen, whichever version
# the record makes active by then. Without --head, the operator is shown
# the active version's head and title and asked to confirm them, which
# needs a terminal; off one, approve refuses. The first argument is
# --head's value, or empty.
APPROVE_HEAD=""
bind_head() {
  local want="$1" sha answer
  APPROVE_HEAD=""
  if [ "$CHANGE_STATE" != ready ]; then
    refuse "change $CHANGE_HANDLE v$CHANGE_VERSION is $CHANGE_STATE, not ready; nothing published. Ready it first: valley ready --change $CHANGE_ID $(printf '%q' "$CHANGE_BRANCH")"
    return 1
  fi
  if [ -n "$want" ]; then
    if ! [[ "$want" =~ ^[0-9a-f]{4,64}$ ]] \
      || ! sha="$(git rev-parse --verify --quiet "$want^{commit}")"; then
      refuse "--head takes the object ID of one of change $CHANGE_HANDLE's version heads, and $want is none here; nothing published"
      return 1
    fi
    check_version "nothing published" "$sha" || return 1
    APPROVE_HEAD="$sha"
    return 0
  fi
  check_version "nothing published" "$CHANGE_HEAD" || return 1
  if [ ! -t 0 ]; then
    refuse "approving change $CHANGE_HANDLE names the head it approves: off a terminal, pass it with --head. Its active version is v$APPROVE_VERSION at $CHANGE_HEAD, $APPROVE_TITLE: valley approve --head $CHANGE_HEAD $CHANGE_HANDLE. Nothing published"
    return 1
  fi
  printf 'approve change %s v%s at %s, %s? [y/N] ' \
    "$CHANGE_HANDLE" "$APPROVE_VERSION" "$CHANGE_HEAD" "$APPROVE_TITLE"
  read -r answer || answer=""
  case "$answer" in
    y | Y | yes) APPROVE_HEAD="$CHANGE_HEAD" ;;
    *)
      refuse "not approved; nothing published"
      return 1
      ;;
  esac
}

# review shows a change with a record at its active version's head, and
# its [a]pprove approves exactly that head.
bind_review() {
  APPROVE_HEAD="" APPROVE_VERSION=""
  if [ -n "$CHANGE_ID" ]; then
    APPROVE_HEAD="$CHANGE_HEAD"
    APPROVE_VERSION="$CHANGE_VERSION"
  fi
}

# rebase for a change with a record rebases the active version's head
# alone, so the branch must still be at it. It pushes the branch with a
# lease, and then adds the rebased head to the record as a new version, as
# the principal git config valley.principal names: the operator, who holds
# the request grant, or the change's owner. The version is added only
# while the change is still ready at the head the rebase began with, under
# a lease on the record (ready --if-active).
rebase_change() {
  local branch="$1"
  check_record "nothing rebased" || return 1
  check_recorded_tip "$branch" "nothing rebased" || return 1
  if [ -n "$CHANGE_ID" ] && [ -z "$(git config valley.principal 2>/dev/null)" ]; then
    refuse "rebasing change $CHANGE_HANDLE adds the rebased head to its record as the principal your key pushes as, and git config valley.principal names none; nothing rebased"
    return 1
  fi
  rebase_onto_main "$branch" "$CHANGE_HEAD"
  [ -n "$CHANGE_ID" ] || return 0
  if ! valley-go ready --head "$REBASED_HEAD" --change "$CHANGE_ID" --if-active "$CHANGE_HEAD" "$branch"; then
    refuse "origin/$branch is rebased to $REBASED_HEAD, and no version of $CHANGE_HANDLE records it. Ready it once the change is ready: valley ready --head $REBASED_HEAD --change $CHANGE_ID $(printf '%q' "$branch")"
    return 1
  fi
}

# The head the checks failed at in this review, short, while the change is
# still at it. Approving that head again would run the same checks over
# the same tree and fail the same way, so the prompt stops offering
# [a]pprove until the change has a new head. Fails when the checks have
# not failed at the head the change is at.
approve_failed_at() {
  if [ -z "$CHECKS_FAILED_AT" ] || [ "$CHECKS_FAILED_AT" != "$(change_head "$1")" ]; then
    return 1
  fi
  git rev-parse --short "$CHECKS_FAILED_AT"
}

# Page the branch and take the verdict. Split out of cmd_review so that
# every way out of it — approve, reject, skip — is followed by the notes.
read_and_decide() {
  local branch="$1" choice failed answers
  show_review "$branch"
  # A stale branch's pre-rebase diff is not what would land; offer to rebase it
  # mechanically, then re-review what actually would. [a]pprove is offered
  # here as well, because the integrator applies a delta to the tip rather
  # than fast-forwarding: a stale branch is a request it can judge, and
  # rebasing first is a convenience rather than a precondition.
  while ! git merge-base --is-ancestor refs/remotes/origin/main \
    "$(change_head "$branch")"; do
    if failed="$(approve_failed_at "$branch")"; then
      printf '%s does not fast-forward from main. Its checks failed at %s, so approving needs a new head: [b]ase onto main, [r]eject, [s]kip? ' \
        "$branch" "$failed"
      answers="b, r, or s"
    else
      printf '%s does not fast-forward from main: [a]pprove, [b]ase onto main, [r]eject, [s]kip? ' \
        "$branch"
      answers="a, b, r, or s"
    fi
    read -r choice || die "stdin closed before an answer; nothing done"
    case "$choice" in
      a)
        if [ -n "$failed" ]; then
          echo "answer $answers"
        elif approve "$branch"; then
          return
        fi
        ;;
      b)
        # A change with a record gains the rebased head as a new version,
        # so the review goes on at that version, as it does at the rebased
        # tip of a plain branch.
        if [ -n "$CHANGE_ID" ]; then
          if rebase_change "$branch"; then
            resolve_change "$CHANGE_ID" || die "could not read change $CHANGE_HANDLE again after the rebase"
            bind_review
            fetch_origin
            show_review "$branch"
          fi
        else
          rebase_onto_main "$branch"
          fetch_origin
          show_review "$branch"
        fi
        ;;
      r) reject "$branch" && return ;;
      s)
        echo "skipped $branch; nothing done"
        return
        ;;
      *) echo "answer $answers" ;;
    esac
  done
  while true; do
    if failed="$(approve_failed_at "$branch")"; then
      printf '%s: its checks failed at %s, so approving needs a new head: [r]eject, [s]kip? ' \
        "$branch" "$failed"
      answers="r or s"
    else
      printf '%s: [a]pprove, [r]eject, [s]kip? ' "$branch"
      answers="a, r, or s"
    fi
    read -r choice || die "stdin closed before an answer; nothing done"
    case "$choice" in
      # A refusal from approve is not a verdict: it says what it did not do
      # and the prompt comes back, so the branch can still be rejected or
      # skipped. When the checks failed, approving the same head again is
      # no longer offered.
      a)
        if [ -n "$failed" ]; then
          echo "answer $answers"
        elif approve "$branch"; then
          return
        fi
        ;;
      r) reject "$branch" && return ;;
      s)
        echo "skipped $branch; nothing done"
        return
        ;;
      *) echo "answer $answers" ;;
    esac
  done
}

cmd_review() {
  [ $# -eq 1 ] || die "usage: valley review <change>"
  resolve_change "$1" || exit 1
  local branch="$CHANGE_BRANCH"
  fetch_origin
  git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
    || die "no such branch on origin: $branch"
  bind_review
  trap cleanup_scratch EXIT
  trap 'exit 130' INT TERM
  read_and_decide "$branch"
  # The verdict disposes of the branch; the notes are what the human made of
  # it, so they are printed whatever the verdict was.
  print_notes "$branch"
}

# approve and rebase are review's [a]pprove and [b]ase without the pager,
# for a front end that has shown the change its own way. Each runs the
# function its key runs, so the verb and the key cannot drift apart. A
# change is named as resolve_change reads it.
#
# approve of a change with a record approves exactly one head (bind_head):
# --head's, or the active version's once the operator confirms it on a
# terminal. A plain branch is approved at its tip on origin, and --head,
# when given, must be that tip.
cmd_approve() {
  local name="" want=""
  local usage="usage: valley approve [--head <sha>] <change>"
  while [ $# -gt 0 ]; do
    case "$1" in
      --head)
        [ $# -ge 2 ] || die "$usage"
        want="$2"
        shift 2
        ;;
      --head=*)
        want="${1#--head=}"
        shift
        ;;
      -*) die "$usage" ;;
      *)
        [ -z "$name" ] || die "$usage"
        name="$1"
        shift
        ;;
    esac
  done
  [ -n "$name" ] || die "$usage"
  resolve_change "$name" || exit 1
  local branch="$CHANGE_BRANCH" tip
  fetch_origin
  trap cleanup_scratch EXIT
  trap 'exit 130' INT TERM
  if [ -n "$CHANGE_ID" ]; then
    bind_head "$want" || exit 1
  else
    tip="$(git rev-parse --verify --quiet "refs/remotes/origin/$branch")" \
      || die "no such branch on origin: $branch"
    if [ -n "$want" ] && [ "$(git rev-parse --verify --quiet "$want^{commit}" || true)" != "$tip" ]; then
      die "origin/$branch is at $tip, not $want; nothing published"
    fi
  fi
  # In a condition, as the review prompt calls it: approve checks each of
  # its own steps, and has already said why when it refuses.
  approve "$branch" || exit 1
}

cmd_rebase() {
  [ $# -eq 1 ] || die "usage: valley rebase <change>"
  resolve_change "$1" || exit 1
  local branch="$CHANGE_BRANCH"
  fetch_origin
  git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
    || die "no such branch on origin: $branch"
  check_record "nothing rebased" || exit 1
  check_recorded_tip "$branch" "nothing rebased" || exit 1
  # review offers [b]ase only to a stale branch. One that fast-forwards
  # already is left alone, rather than rewritten for nothing.
  if git merge-base --is-ancestor refs/remotes/origin/main \
    "refs/remotes/origin/$branch"; then
    echo "$branch already fast-forwards from origin/main; nothing rebased"
    printf '  head     %s\n' "$(git rev-parse "refs/remotes/origin/$branch")"
    return
  fi
  trap cleanup_scratch EXIT
  trap 'exit 130' INT TERM
  rebase_change "$branch" || exit 1
}

# tail and replay are thin wrappers over the nats CLI — anything they do,
# plain nats and git can do. They are the only verbs needing more than git
# and coreutils.
need_nats() {
  command -v nats >/dev/null 2>&1 \
    || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
}

cmd_tail() {
  [ $# -le 1 ] || die "usage: valley tail [subject]"
  need_nats
  exec nats sub "${1:-valley.>}"
}

# One ref-updated event per existing ref, from git for-each-ref alone. A
# ref's prior value is not derivable from the repository, so `old` is the
# all-zero id — the same payload a push creating the ref would produce.
# The payload construction mirrors the host module's publisher hook
# (nix/valley-host.nix); change one only with the other.
cmd_replay() {
  [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
  need_nats
  local dir="${1:-.}" repo sha ref event count=0
  git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
    || die "not a git repository: $dir"
  if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
    repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
  else
    repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
  fi
  while read -r sha ref; do
    # " is the only JSON-significant character a refname can contain (git
    # forbids \ and control characters); names and object ids are safe.
    event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
      "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
    nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
    count=$((count + 1))
  done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
  echo "replayed $count refs of $repo onto the bus"
}

# ----------------------------------------------------------------------
# checks — the verification-policy deriver (dcr-f41f718). It composes the
# instance layer with the project layer, matches every side of a diff
# against the composed classes, and prints the check names the change owes
# with the class or classes that made each one required. It reports: no
# check is run, nothing is gated, nothing is written.
#
# Composition is CUE's, never this script's. The whole of the mandatory-
# versus-overridable distinction is unification, so reimplementing it here
# would be reimplementing the decision. What this script does that CUE
# cannot is glob matching and reading a diff.

need_cue() {
  command -v cue >/dev/null 2>&1 \
    || die "this verb needs the cue CLI; nix run .#valley bundles it"
}

# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
# cross a `/`, and every ERE metacharacter is escaped.
segment_ere() {
  local seg="$1" out="" i c
  for ((i = 0; i < ${#seg}; i++)); do
    c="${seg:i:1}"
    case "$c" in
      '*') out+='[^/]*' ;;
      '?') out+='[^/]' ;;
      '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
      *) out+="$c" ;;
    esac
  done
  printf '%s' "$out"
}

# A path glob as an anchored ERE, segment by segment. A `**` segment matches
# any number of segments including none, so it swallows the separator that
# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
# matches exactly one.
glob_ere() {
  local ere='^' i last
  local -a segs=()
  IFS=/ read -r -a segs <<<"$1"
  last=$((${#segs[@]} - 1))
  for ((i = 0; i <= last; i++)); do
    if [ "${segs[i]}" = '**' ]; then
      if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
    else
      ere+="$(segment_ere "${segs[i]}")"
      [ "$i" -eq "$last" ] || ere+='/'
    fi
  done
  printf '%s$' "$ere"
}

# The composed policy as one tab-separated line per covered pattern, per
# required check, and per field of the check catalogue, so the shell never
# parses CUE. Every line is three fields — a kind, a name, and a value —
# whatever the kind, so one reader takes them all. The field is hidden
# because the schema's sentinel rejects unknown top-level fields, and
# `unclassified` is rendered as a class of that name: it is one more source
# a check can come from.
#
# The catalogue is rendered because a caller that runs a check needs what
# the policy says a check IS — its runner, and the attribute or command
# line that runner takes — and a tool that groups the owed checks needs
# their cost. `checks` reads only the cost, to group the owed checks by
# it; approve turns the rest into the arguments attest is given.
render_cue() {
  cat <<'EOF'
package verification

import (
	"list"
	"strings"
)

_render: strings.Join(list.Concat([[
	for cn, c in policy.classes
	for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
], [
	for cn, c in policy.classes
	for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
], [
	for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
], [
	for n, c in policy.checks {"runner\t\(n)\t\(c.runner)"}
], [
	for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)"}
], [
	for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)"}
], [
	for n, c in policy.checks {"cost\t\(n)\t\(c.cost)"}
]]), "\n")
EOF
}

# The composed layer, and a scratch directory for the documents the
# derivation writes into the composition. Globals so the probe below can
# see them.
POLICY_LAYER=()
POLICY_TMP=""

cleanup_policy_tmp() {
  [ -n "$POLICY_TMP" ] || return 0
  rm -rf "$POLICY_TMP"
  POLICY_TMP=""
}

# Where the schema and the two policy layers come from in a project
# following the convention (dcr-f41f718).
#
# The client derives from exactly the sources the integrator uses
# (integrator/policy.go), and the working tree is not among them. The
# project's own layer is read from the TARGET's tip, the pointer naming the
# owning valley is read from the target's tip, and the floor is read from
# that valley's integrated tip. A change never supplies the policy that
# gates it, and neither does whoever happens to be reviewing it: the
# reviewer's checkout may be any branch, however stale, and derivation
# gives the same answer from all of them.
#
# The schema is not a policy layer. It is the shape a policy is written in,
# and it ships with this tool: the package sets VALLEY_VERIFICATION_SCHEMA
# to the copy it was built with, as the integrator's package does. Only
# the-valley's own tree carries schema/, so this script reads the schema
# there only when it runs straight from such a checkout with the variable
# unset.
#
# Neither layer is ever the worked example under examples/policy/ — a gate
# derived from an example is a gate nobody wrote. `checks` takes an option
# for each, so a reader can point it at the example or anywhere else on
# purpose; approve takes no such option, because a request is filed
# against the policy that governs the project and nowhere else.
#
# Neither layer is a path in this tree, so policy_defaults leaves both
# empty and the two resolvers answer for them. That split is also what
# keeps `checks --instance DIR` from fetching a repository whose layer it
# was told to ignore, and `checks --project DIR` from reading a tip whose
# layer it was told to ignore.
POLICY_SCHEMA=""
POLICY_INSTANCE=""
POLICY_INSTANCE_LABEL=""
POLICY_PROJECT=""
POLICY_PROJECT_LABEL=""
policy_defaults() {
  POLICY_SCHEMA="${VALLEY_VERIFICATION_SCHEMA:-$1/schema/verification.cue}"
  POLICY_INSTANCE=""
  POLICY_INSTANCE_LABEL=""
  POLICY_PROJECT=""
  POLICY_PROJECT_LABEL=""
}

# The floor, copied out of a fetch of the owning valley's repository, and
# the project's own layer, copied out of the target's tip. Globals, so the
# traps clean them up whatever happens.
INSTANCE_TMP=""
cleanup_instance_tmp() {
  [ -n "$INSTANCE_TMP" ] || return 0
  rm -rf "$INSTANCE_TMP"
  INSTANCE_TMP=""
}

PROJECT_TMP=""
cleanup_project_tmp() {
  [ -n "$PROJECT_TMP" ] || return 0
  rm -rf "$PROJECT_TMP"
  PROJECT_TMP=""
}

# The directory each layer lives in, the file naming this project's owning
# valley, and the ref of that valley whose tip carries the floor. The floor
# resolves at the integrated tip, because a floor a project could pin is
# not a floor (dcr-f41f718).
INSTANCE_DIR=policy/instance
PROJECT_DIR=policy/project
VALLEY_POINTER=policy/valley
VALLEY_POINTER_REF=refs/heads/main

# The *.cue documents of one directory at one tree-ish, copied out of a
# repository into a directory on disk. Reading a tip with ls-tree and
# cat-file rather than checking it out is what lets the layers come from
# the target while the checkout stays on whatever branch the reviewer is
# on. 0 copied something, 1 the directory holds no *.cue, 2 the read
# failed.
#
# -z because a path may hold anything but NUL, and *.cue because the layer
# is the directory's documents — the same reading the composer takes.
#
# The listing is written out and its status checked before it is read. A
# listing read straight from a process substitution that failed reads as a
# directory holding nothing, and for the project layer that is the floor
# alone: fewer checks owed, from a read that never happened. The listing's
# name is not a *.cue name, so the composer never reads it.
copy_layer() {
  local gitdir="$1" treeish="$2" dir="$3" dest="$4" path name copied=0
  local listing="$dest/.listing"
  git -C "$gitdir" ls-tree --name-only -z "$treeish" "$dir/" > "$listing" \
    || return 2
  while IFS= read -r -d '' path; do
    case "$path" in *.cue) ;; *) continue ;; esac
    name="${path##*/}"
    git -C "$gitdir" cat-file blob "$treeish:$path" > "$dest/$name" || return 2
    copied=1
  done < "$listing"
  rm -f "$listing"
  [ "$copied" -eq 1 ]
}

# The ref whose tip supplies the policy, printed the way a person names it,
# with the commit it stood at. Staleness in a remote-tracking ref is a real
# thing to see, so the report says which commit the layers came out of
# rather than only which ref. A ref that cannot be read fails, so that no
# report names a tip nobody read.
target_label() {
  local ref="$1" short
  short="$(git rev-parse --short "$ref")" || return 1
  ref="${ref#refs/remotes/}"
  ref="${ref#refs/heads/}"
  printf '%s %s' "$ref" "$short"
}

# Resolve the project's own layer, out of the target's tip, into
# POLICY_PROJECT, and set POLICY_PROJECT_LABEL to where it came from.
#
# A target carrying no layer of its own is derived under the floor alone.
# The project layer only ever adds (dcr-f41f718), so the identity of "adds"
# is "adds nothing"; refusing instead would make a repository underivable
# until its first policy commit, and that commit could not derive either.
# This is the integrator's own reading (integrator/policy.go), and the two
# have to agree about an absent layer as much as about a present one.
#
# Absence is answered with a document that adds nothing rather than with an
# argument left off, because the composer is handed a directory of *.cue
# and has no spelling for "no layer".
#
# It reports and returns rather than dying, for the reason derive_owed
# does: a refusal inside the review loop is not the end of the session.
resolve_project_layer() {
  local root="$1" target="$2" rc at

  at="$(target_label "$target")" || {
    refuse "could not read $target; nothing derived"
    return 1
  }
  cleanup_project_tmp
  PROJECT_TMP="$(mktemp -d)" || {
    refuse "no scratch directory to read the project layer into; nothing derived"
    return 1
  }
  copy_layer "$root" "$target" "$PROJECT_DIR" "$PROJECT_TMP" && rc=0 || rc=$?
  case "$rc" in
    0)
      POLICY_PROJECT="$PROJECT_TMP"
      POLICY_PROJECT_LABEL="$PROJECT_DIR@$at"
      ;;
    1)
      printf 'package verification\n' > "$PROJECT_TMP/adds-nothing.cue" || {
        cleanup_project_tmp
        refuse "could not compose an empty project layer; nothing derived"
        return 1
      }
      POLICY_PROJECT="$PROJECT_TMP"
      POLICY_PROJECT_LABEL="no $PROJECT_DIR@$at — the floor alone"
      ;;
    *)
      cleanup_project_tmp
      refuse "could not read $PROJECT_DIR/ at $at; nothing derived"
      return 1
      ;;
  esac
}

# The first line of the pointer that is neither blank nor a comment. Read
# in the shell so that naming an owning valley needs nothing beyond what
# the rest of this script needs.
pointer_url() {
  local line url=""
  while IFS= read -r line || [ -n "$line" ]; do
    line="${line%%#*}"
    line="${line#"${line%%[![:space:]]*}"}"
    line="${line%"${line##*[![:space:]]}"}"
    [ -n "$line" ] || continue
    url="$line"
    break
  done < "$1"
  printf '%s' "$url"
}

# Resolve the floor to a directory on disk, into POLICY_INSTANCE, and set
# POLICY_INSTANCE_LABEL to where it came from — a temporary directory is
# not an answer a reader can check.
#
# Every project has exactly one owning valley, and the floor is that
# valley's (dcr-9b5da04). It is read from the valley's own repository and
# never from the project's tree, which is the tree under judgment. Two
# shapes, and the first is a special case of the second:
#
#   - a valley's config repository carries policy/instance itself, and is
#     governed by that floor like every other project. It uses its own,
#     and fetches nothing.
#   - every other project names its owning valley at policy/valley. That
#     repository is fetched into scratch and its policy/instance is read
#     at the integrated tip. Fetching is all this needs, and anyone the
#     valley governs necessarily holds fetch on it.
#
# Both the pointer and a valley's own floor are read from the TARGET's tip
# and never from the working tree. The pointer is a file a branch can edit,
# so reading it from the branch would let a change name the valley that
# gates it; reading it from the checkout would let whoever is reviewing
# decide the same thing by accident, which is the failure this fixes. An
# absent floor is refused — that is the direction absence defaults in for
# this layer, because the floor is the minimum (dcr-f41f718).
#
# It reports and returns rather than dying, for the reason derive_owed
# does: a refusal inside the review loop is not the end of the session.
resolve_instance_layer() {
  local root="$1" target="$2" url bare dest rc at
  at="$(target_label "$target")" || {
    refuse "could not read $target; nothing derived"
    return 1
  }
  cleanup_instance_tmp
  INSTANCE_TMP="$(mktemp -d)" || {
    refuse "no scratch directory to read the floor into; nothing derived"
    return 1
  }
  dest="$INSTANCE_TMP/instance"
  mkdir -p "$dest"

  copy_layer "$root" "$target" "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
  case "$rc" in
    0)
      POLICY_INSTANCE="$dest"
      POLICY_INSTANCE_LABEL="$INSTANCE_DIR@$at (this repository is its own valley)"
      return 0
      ;;
    1) ;; # no floor of its own: the pointer names the valley that has one
    *)
      cleanup_instance_tmp
      refuse "could not read $INSTANCE_DIR/ at $at; nothing derived"
      return 1
      ;;
  esac

  git -C "$root" cat-file blob "$target:$VALLEY_POINTER" > "$INSTANCE_TMP/pointer" 2> /dev/null || {
    cleanup_instance_tmp
    refuse "no owning valley: $VALLEY_POINTER names the repository whose $INSTANCE_DIR is this project's floor, and $at carries no such file. A valley's own config repository carries $INSTANCE_DIR instead. Nothing derived"
    return 1
  }
  url="$(pointer_url "$INSTANCE_TMP/pointer")"
  [ -n "$url" ] || {
    cleanup_instance_tmp
    refuse "$VALLEY_POINTER at $at names no repository — it wants one line, the owning valley as git fetch takes it; nothing derived"
    return 1
  }

  bare="$INSTANCE_TMP/valley.git"
  git init --quiet --bare "$bare" || {
    cleanup_instance_tmp
    refuse "no scratch repository to fetch the floor into; nothing derived"
    return 1
  }
  git -C "$bare" fetch --quiet --depth 1 "$url" "$VALLEY_POINTER_REF" || {
    cleanup_instance_tmp
    refuse "could not fetch the owning valley $url at $VALLEY_POINTER_REF (named by $VALLEY_POINTER at $at); nothing derived"
    return 1
  }

  copy_layer "$bare" FETCH_HEAD "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
  case "$rc" in
    0) ;;
    1)
      cleanup_instance_tmp
      refuse "the owning valley $url holds no *.cue in $INSTANCE_DIR/ at $VALLEY_POINTER_REF; nothing derived"
      return 1
      ;;
    *)
      cleanup_instance_tmp
      refuse "could not read $INSTANCE_DIR/ from $url; nothing derived"
      return 1
      ;;
  esac

  POLICY_INSTANCE="$dest"
  POLICY_INSTANCE_LABEL="$url $INSTANCE_DIR@$VALLEY_POINTER_REF"
}

# Is this check mandatory in this class, or a default the project left
# alone? The bit is the form of the composed value, so the test is CUE's
# own: a project supplying `false` either conflicts or unifies cleanly.
# Answering by unifying rather than by inspecting syntax means the script
# cannot disagree with `cue vet`.
#
# This is the one producer whose failure does not end the derivation. A
# probe that fails for any other reason, or that cannot be written, reads as
# mandatory, which is the strict answer, and the bit never changes which
# checks are owed.
check_is_mandatory() {
  local class="$1" check="$2" field
  if [ "$class" = unclassified ]; then
    field="policy: unclassified: \"$check\": false"
  else
    field="policy: classes: \"$class\": requires: \"$check\": false"
  fi
  # A probe that could not be written may leave the last one in its place,
  # and that one answers for another check. Mandatory is the strict answer.
  printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue" \
    || return 0
  ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
}

# Every side of the diff: an added, modified or deleted path, and both the
# old and the new path of a rename or copy. It reads `git diff -z
# --name-status` on stdin, because a path may contain anything but NUL, and
# fails on a record cut short — including one cut inside its status, which
# a plain `while read` would end on quietly, dropping the record. It also
# fails when a write fails: the caller runs without `errexit`, so a lost
# path would otherwise end in a normal EOF and a status of 0.
diff_paths() {
  local status path
  while IFS= read -r -d '' status || { [ -z "$status" ] || return 1; false; }; do
    IFS= read -r -d '' path || return 1
    printf '%s\n' "$path" || return 1
    case "$status" in
      R* | C*)
        IFS= read -r -d '' path || return 1
        printf '%s\n' "$path" || return 1
        ;;
    esac
  done
}

# Lines in, one comma-separated line out.
join_lines() {
  local out="" line
  while IFS= read -r line; do out="${out:+$out, }$line"; done
  printf '%s' "$out"
}

# Arguments in, one comma-separated line out, or `none` when there are none.
join_or_none() {
  if [ $# -eq 0 ]; then echo none; else printf '%s\n' "$@" | join_lines; fi
}

# The remaining arguments, sorted, into the array the first one names. The
# sort is captured and its status returned: a sort read through a process
# substitution that fails reads as a sort of nothing, and for a list of
# owed checks that is a change owing none.
#
# The destination is a nameref, so what is assigned is the caller's array,
# and the linter cannot see that array being read.
# shellcheck disable=SC2034
sort_into() {
  local -n sort_into_dest="$1"
  local sorted
  shift
  sort_into_dest=()
  [ $# -gt 0 ] || return 0
  sorted="$(printf '%s\n' "$@" | sort)" || return 1
  mapfile -t sort_into_dest <<<"$sorted"
}

# The target: the ref a change is derived against, and the tip both policy
# layers are read out of. origin's answer is preferred, because the target
# is the branch as the integrator holds it and not as this checkout last
# built it.
#
# Only a ref that is not there falls through to the next. show-ref says
# "not there" with 1 and fails any other way with another status, so a
# read of origin's ref that failed ends here: falling through would read
# the policy out of the local main, which may be older. 1 no main at all,
# 2 a read failed.
target_ref() {
  local ref rc
  for ref in refs/remotes/origin/main refs/heads/main; do
    git show-ref --verify --quiet "$ref" && rc=0 || rc=$?
    case "$rc" in
      0) echo "$ref"; return 0 ;;
      1) ;;
      *) return 2 ;;
    esac
  done
  return 1
}

# ----------------------------------------------------------------------
# The derivation itself, and the globals it answers with. Everything a
# caller could want from the policy comes out of one pass, because every
# part of it is a function of the same composition: `checks` prints the
# answer, approve runs what it names.
#
# It reports and returns rather than dying, so that a caller inside the
# review loop is refused rather than ended. Its callers are all in a
# condition, which suspends `set -e` for the whole call, so every step is
# checked by hand.
#
# Every producer — git, cue, sort — writes a file or a variable, and its
# status is checked before anything reads what it wrote. A producer read
# through a process substitution loses its status, and a failed one then
# reads as an empty list: no changed paths, no catalogue, no classes. Each
# of those derives a change that owes nothing, which is the one answer a
# failure must never give.
DERIVED_PATHS=()     # every side of the diff, sorted
DERIVED_MATCHED=()   # the class names at least one path matched, sorted
DERIVED_UNCOVERED=() # the paths no class covered
DERIVED_OWES=0       # whether `unclassified` is what owes something
declare -A DERIVED_OWED=()    # check -> the classes that required it
declare -A DERIVED_PINNED=()  # check -> mandatory | default
declare -A CHECK_RUNNER=()    # check -> nix | command
declare -A CHECK_ATTRIBUTE=() # check -> the flake check attribute
declare -A CHECK_COMMAND=()   # check -> the command line
declare -A CHECK_COST=()      # check -> quick | slow

derive_owed() {
  local schema="$1" instance="$2" project="$3" base="$4" head="$5"

  need_cue
  [ -f "$schema" ] || {
    refuse "no policy schema at $schema; nothing derived"
    return 1
  }
  # An unmatched glob stays literal, so the first entry is a real file
  # exactly when the directory holds a document.
  local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
  [ -f "${instance_docs[0]}" ] || {
    refuse "no instance policy layer at $instance; nothing derived"
    return 1
  }
  [ -f "${project_docs[0]}" ] || {
    refuse "no project policy layer at $project: a project's own layer is the *.cue documents under $PROJECT_DIR/ (dcr-f41f718). Nothing derived"
    return 1
  }

  cleanup_policy_tmp
  POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
  POLICY_TMP="$(mktemp -d)" || {
    refuse "no scratch directory to compose the policy in; nothing derived"
    return 1
  }

  git diff --no-relative --name-status -M -z "$base" "$head" > "$POLICY_TMP/diff" || {
    refuse "could not diff $base..$head; nothing derived"
    return 1
  }
  diff_paths < "$POLICY_TMP/diff" > "$POLICY_TMP/paths" || {
    refuse "truncated diff output; nothing derived"
    return 1
  }
  sort -u "$POLICY_TMP/paths" > "$POLICY_TMP/paths.sorted" || {
    refuse "could not sort the changed paths; nothing derived"
    return 1
  }
  DERIVED_PATHS=()
  mapfile -t DERIVED_PATHS < "$POLICY_TMP/paths.sorted"

  render_cue > "$POLICY_TMP/render.cue" || {
    refuse "could not write the policy render; nothing derived"
    return 1
  }
  cue vet -c "${POLICY_LAYER[@]}" || {
    refuse "the policy layers do not compose; nothing derived"
    return 1
  }

  # The render is checked before it is read. A render that fails prints
  # nothing, and an empty render reads as a policy that owes nothing. A
  # schema older than this script fails it, by lacking a field it reads.
  cue eval --out text -e _render "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" \
    > "$POLICY_TMP/rendered" || {
    refuse "the composed policy does not render (a schema older than this script is one cause); nothing derived"
    return 1
  }
  # Sorted once here, so every list below comes out in a stable order.
  sort "$POLICY_TMP/rendered" > "$POLICY_TMP/rendered.sorted" || {
    refuse "could not sort the composed policy; nothing derived"
    return 1
  }
  local -a rendered=()
  mapfile -t rendered < "$POLICY_TMP/rendered.sorted"

  unset CHECK_RUNNER CHECK_ATTRIBUTE CHECK_COMMAND CHECK_COST DERIVED_OWED \
    DERIVED_PINNED
  declare -gA CHECK_RUNNER=() CHECK_ATTRIBUTE=() CHECK_COMMAND=() \
    CHECK_COST=() DERIVED_OWED=() DERIVED_PINNED=()

  # The middle field is a class name for a coverage or requirement line and
  # a check name for a catalogue one; `key` is what both are.
  local -a pat_class=() pat_ere=() req_class=() req_check=()
  local line kind key value
  for line in "${rendered[@]}"; do
    kind="${line%%$'\t'*}"
    key="${line#*$'\t'}"
    value="${key#*$'\t'}"
    key="${key%%$'\t'*}"
    case "$kind" in
      path)
        pat_class+=("$key")
        pat_ere+=("$(glob_ere "$value")")
        ;;
      requires)
        req_class+=("$key")
        req_check+=("$value")
        ;;
      runner) CHECK_RUNNER["$key"]="$value" ;;
      attribute) CHECK_ATTRIBUTE["$key"]="$value" ;;
      command) CHECK_COMMAND["$key"]="$value" ;;
      cost) CHECK_COST["$key"]="$value" ;;
    esac
  done

  # A pattern bash cannot compile answers 2, not 1. Read as "no match", it
  # would drop the pattern's class from every change it covers.
  local -A matched=()
  local path i hit rc
  DERIVED_UNCOVERED=()
  for path in "${DERIVED_PATHS[@]}"; do
    hit=0
    for ((i = 0; i < ${#pat_ere[@]}; i++)); do
      [[ "$path" =~ ${pat_ere[i]} ]] && rc=0 || rc=$?
      case "$rc" in
        0)
          matched["${pat_class[i]}"]=1
          hit=1
          ;;
        1) ;;
        *)
          refuse "class ${pat_class[i]} has a path pattern that does not compile (${pat_ere[i]}); nothing derived"
          return 1
          ;;
      esac
    done
    [ "$hit" -eq 1 ] || DERIVED_UNCOVERED+=("$path")
  done
  # A path no class covers is answered by the policy's `unclassified` set,
  # which is why it is treated as one more matched class rather than as an
  # absence.
  [ "${#DERIVED_UNCOVERED[@]}" -eq 0 ] || matched[unclassified]=1

  local check
  DERIVED_OWES=0
  for ((i = 0; i < ${#req_check[@]}; i++)); do
    key="${req_class[i]}"
    check="${req_check[i]}"
    [ -n "${matched[$key]:-}" ] || continue
    [ "$key" != unclassified ] || DERIVED_OWES=1
    DERIVED_OWED["$check"]="${DERIVED_OWED[$check]:+${DERIVED_OWED[$check]}, }$key"
    if check_is_mandatory "$key" "$check"; then
      DERIVED_PINNED["$check"]=mandatory
    else
      DERIVED_PINNED["$check"]="${DERIVED_PINNED[$check]:-default}"
    fi
  done

  sort_into DERIVED_MATCHED "${!matched[@]}" || {
    refuse "could not sort the matched classes; nothing derived"
    return 1
  }
}

cmd_checks() {
  local root schema instance="" label project="" plabel base head target=""
  local names=0 cost="" costed=0 short_base short_head
  root="$(git rev-parse --show-toplevel 2> /dev/null)" \
    || die "not a git repository"
  policy_defaults "$root"
  schema="$POLICY_SCHEMA"
  while [ $# -gt 0 ]; do
    case "$1" in
      --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
      --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
      --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
      --names) names=1; shift ;;
      --cost) [ $# -ge 2 ] || die "--cost needs quick or slow"; cost="$2"; costed=1; shift 2 ;;
      --) shift; break ;;
      -*) die "unknown option: $1" ;;
      *) break ;;
    esac
  done
  [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
  if [ "$costed" -eq 1 ]; then
    case "$cost" in
      quick | slow) ;;
      *) die "--cost takes quick or slow, not '$cost'" ;;
    esac
    [ "$names" -eq 1 ] || die "--cost filters the --names list; pass --names too"
  fi

  head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
    || die "no such commit: ${2:-HEAD}"
  # The target is what the layers are read out of, so it is needed whenever
  # either layer is left to its default — and it is what an unnamed base
  # is the merge base with.
  if [ -z "$instance" ] || [ -z "$project" ] || [ $# -lt 1 ]; then
    target="$(target_ref)" || {
      [ $? -eq 1 ] || die "could not read the main branch; nothing derived"
      die "no main branch: the target's tip is where the policy layers are read from, and there is none here"
    }
  fi
  if [ $# -ge 1 ]; then
    base="$(git rev-parse --verify --quiet "$1^{commit}")" \
      || die "no such commit: $1"
  else
    base="$(git merge-base "$target" "$head")" \
      || die "$head and ${target#refs/} do not share history — name a base"
  fi

  trap 'cleanup_policy_tmp; cleanup_instance_tmp; cleanup_project_tmp' EXIT
  # Each layer is resolved only when nobody named one. --instance and
  # --project are a reader pointing this at a layer on purpose, and
  # honouring that means not fetching the repository, and not reading the
  # tip, that the named layer replaced.
  if [ -n "$instance" ]; then
    label="${instance#"$root"/}"
  else
    resolve_instance_layer "$root" "$target" || exit 1
    instance="$POLICY_INSTANCE"
    label="$POLICY_INSTANCE_LABEL"
  fi
  if [ -n "$project" ]; then
    plabel="${project#"$root"/}"
  else
    resolve_project_layer "$root" "$target" || exit 1
    project="$POLICY_PROJECT"
    plabel="$POLICY_PROJECT_LABEL"
  fi
  derive_owed "$schema" "$instance" "$project" "$base" "$head" || exit 1

  # The owed checks, sorted, and grouped by the cost the policy declares.
  # The grouping changes nothing owed: approve runs every owed check, and
  # the integrator requires evidence for every one, whatever it costs.
  local check width=0
  local -a owed=() quick=() slow=() listed=()
  sort_into owed "${!DERIVED_OWED[@]}" \
    || die "could not sort the owed checks; nothing derived"
  for check in "${owed[@]}"; do
    [ "${#check}" -le "$width" ] || width="${#check}"
    if [ "${CHECK_COST[$check]}" = slow ]; then
      slow+=("$check")
    else
      quick+=("$check")
    fi
  done

  # The form for agents and scripts: the names alone, one per line.
  if [ "$names" -eq 1 ]; then
    case "$cost" in
      quick) listed=("${quick[@]}") ;;
      slow) listed=("${slow[@]}") ;;
      *) listed=("${owed[@]}") ;;
    esac
    [ "${#listed[@]}" -eq 0 ] || printf '%s\n' "${listed[@]}"
    return
  fi

  # Read before the first line is printed, so a read that fails leaves no
  # partial report behind.
  short_base="$(git rev-parse --short "$base")" \
    || die "could not read $base; nothing derived"
  short_head="$(git rev-parse --short "$head")" \
    || die "could not read $head; nothing derived"

  printf '%s..%s: %d changed path(s)\n' "$short_base" "$short_head" \
    "${#DERIVED_PATHS[@]}"
  printf 'policy: %s + %s\n' "$label" "$plabel"
  if [ "${#DERIVED_MATCHED[@]}" -eq 0 ]; then
    printf 'classes matched: none\n\n'
  else
    printf 'classes matched: %s\n\n' \
      "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
  fi

  if [ "${#DERIVED_OWED[@]}" -eq 0 ]; then
    echo "required checks: none"
  else
    echo "required checks:"
    for check in "${owed[@]}"; do
      printf '  %-*s  %-9s  %s\n' \
        "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_OWED[$check]}"
    done
  fi

  if [ "${#DERIVED_UNCOVERED[@]}" -gt 0 ]; then
    printf '\nunclassified: %d path(s) matched no class\n' "${#DERIVED_UNCOVERED[@]}"
    printf '  %s\n' "${DERIVED_UNCOVERED[@]}"
    # The failure the `unclassified` field exists to prevent: paths outside
    # every class that the policy then asks nothing of.
    [ "$DERIVED_OWES" -eq 1 ] \
      || echo "  the policy requires nothing of them — it is behind the tree"
  fi

  # Below every line the integrator reads (integrator/policy.go), and
  # unindented, so neither line can read as a required check.
  if [ "${#owed[@]}" -gt 0 ]; then
    printf '\nquick: %s\n' "$(join_or_none "${quick[@]}")"
    printf 'slow: %s\n' "$(join_or_none "${slow[@]}")"
  fi
}

main() {
  local verb="${1:-help}"
  if [ $# -gt 0 ]; then shift; fi
  # The verb set is mirrored in completions/ (valley.bash, _valley) —
  # update both when it changes.
  case "$verb" in
    pending) cmd_pending "$@" ;;
    review) cmd_review "$@" ;;
    approve) cmd_approve "$@" ;;
    rebase) cmd_rebase "$@" ;;
    status | ready | unready | withdraw | changes) cmd_go "$verb" "$@" ;;
    checks) cmd_checks "$@" ;;
    tail) cmd_tail "$@" ;;
    replay) cmd_replay "$@" ;;
    help | -h | --help) usage ;;
    *)
      printf 'valley: unknown verb: %s\n\n' "$verb" >&2
      usage >&2
      exit 1
      ;;
  esac
}

main "$@"
